Spaces:
Running
Running
Download tools/mcp/server.mjs from VectorW/xlerobot-sim: direct link, hf CLI and curl.
- Browser
- Download file 23.6 kB
-
https://huggingface.co/spaces/VectorW/xlerobot-sim/resolve/main/tools/mcp/server.mjs
- Command line
-
hf download hf://spaces/VectorW/xlerobot-sim/tools/mcp/server.mjs
-
curl -L -o server.mjs https://huggingface.co/spaces/VectorW/xlerobot-sim/resolve/main/tools/mcp/server.mjs
23.6 kB
| // XLeRobot Sim's MCP server: Claude Code, or another MCP client, drives XLeRobot in the simulation running in | |
| // a browser tab on this computer. It speaks MCP over stdio to the client and serves a WebSocket on 127.0.0.1 | |
| // that the page connects to (opened with ?bridge in its URL, or by the Connect button in its Agent tab); each | |
| // tool call goes to the page, which runs it with the tools its own agent uses (src/agent/bridge.js, tools.js). | |
| // No dependencies (Node 18 or later), so this one file also runs on its own, downloaded from the Space. | |
| // | |
| // claude mcp add xlerobot-sim -- node /path/to/server.mjs (in this folder, .mcp.json has it) | |
| // | |
| // open_sim opens the page from this server, http://127.0.0.1:8770/: a copy of the Space's, fetched from it as | |
| // the browser asks, so that the page and the WebSocket share an origin. A tab of the Space itself (https) | |
| // may connect too, once the person lets it reach apps on this computer: browsers keep a public page from | |
| // reaching 127.0.0.1 unless allowed (Chrome's local network access checks). | |
| // | |
| // Environment: | |
| // XLEROBOT_SIM_PORT the port (8770; a free one if that is taken) | |
| // XLEROBOT_SIM_URL the page open_sim opens (the Space, through this server; a local one, such as | |
| // http://127.0.0.1:5173/ from `npm run dev`, directly) | |
| // XLEROBOT_SIM_ORIGINS more page origins to accept, comma-separated (the Space's and localhost's are) | |
| // GEMINI_API_KEY a Gemini API key for locate (Gemini 4 Hydrogen), as the Gemini Robotics plugin's | |
| // skills take it: handed to the connected page, which asks Gemini with it | |
| import { createHash } from "node:crypto"; | |
| import { spawn } from "node:child_process"; | |
| import { createServer } from "node:http"; | |
| import { Readable } from "node:stream"; | |
| const VERSION = "0.4.0"; | |
| const SPACE_URL = "https://vectorw-xlerobot-sim.static.hf.space/index.html"; | |
| const PAGE_URL = process.env.XLEROBOT_SIM_URL || SPACE_URL; | |
| const PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]; // MCP versions this server speaks, newest first | |
| const MAX_MESSAGE = 32 * 2 ** 20; // bytes, from the page | |
| const log = (...args) => console.error("[xlerobot-sim]", ...args); // stdout carries the protocol | |
| const originOf = (s) => { | |
| try { | |
| return new URL(s.trim()).origin; | |
| } catch { | |
| if (s.trim()) log(`not an origin: ${s}`); | |
| return null; | |
| } | |
| }; | |
| const ORIGINS = new Set([SPACE_URL, PAGE_URL, ...(process.env.XLEROBOT_SIM_ORIGINS ?? "").split(",")].map(originOf).filter((o) => o && o !== "null")); | |
| const LOOPBACK = ["127.0.0.1", "localhost", "[::1]"]; | |
| const GEMINI_KEY = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY || ""; | |
| // The page's own site, which this server stands in for (none when the page is on this computer already). | |
| const UPSTREAM = LOOPBACK.includes(new URL(PAGE_URL).hostname) ? null : new URL(PAGE_URL).origin; | |
| let port = Number(process.env.XLEROBOT_SIM_PORT) || 8770; // the one listened on, once it listens | |
| let page = null; // the connected page: {conn, origin, info} | |
| let client = null; // the MCP client's name, for the page's panel | |
| let initialized = false; // the client said so: notifications may go out | |
| process.on("unhandledRejection", (error) => log(error)); | |
| // --------------------------------------------------------------------------------------------- | |
| // Tools: two of the server's own, and the page's (src/agent/specs.js; read here when this file is in the | |
| // repository, else told by the page when it connects, which updates the list) | |
| const SERVER_TOOLS = [ | |
| { | |
| name: "status", | |
| description: | |
| "Whether the simulation page is connected; if it is, its scene, the scenes it has, the robot, the renderer, the cameras, the skill running, the household task in progress and the tasks the scene has.", | |
| inputSchema: { type: "object", properties: {} }, | |
| annotations: { readOnlyHint: true }, | |
| }, | |
| { | |
| name: "open_sim", | |
| description: | |
| "Open the simulation in the default web browser, connected to this server, and wait until it has loaded (up to two minutes). Call it when status says no page is connected. scene: the one to open (kitchen unless given, e.g. tabletop); url: another copy of the page (a local dev server such as http://127.0.0.1:5173/).", | |
| inputSchema: { type: "object", properties: { scene: { type: "string" }, url: { type: "string" } } }, | |
| }, | |
| ]; | |
| const LOOKING = new Set(["status", "observe", "task", "camera", "locate"]); | |
| const SKIPPED = new Set(["look"]); // the in-page agent's head camera: camera covers it | |
| let pageSpecs = []; | |
| let guide = ""; // how to work with the tools: in the instructions when read here | |
| let pageGuide = null; // else the page's, given with the first status or open_sim after it connects | |
| let guideGiven = false; | |
| try { | |
| const specs = await import(new URL("../../src/agent/specs.js", import.meta.url)); | |
| pageSpecs = [...specs.TOOL_SPECS, ...specs.BRIDGE_SPECS]; | |
| guide = specs.TOOL_GUIDE; | |
| } catch { | |
| // on its own: the page tells its tools (and how to use them) when it connects | |
| } | |
| function toolList() { | |
| const fromPage = pageSpecs | |
| .filter((t) => t?.name && !SKIPPED.has(t.name) && !SERVER_TOOLS.some((s) => s.name === t.name)) | |
| .map((t) => ({ | |
| name: t.name, | |
| description: t.description ?? "", | |
| inputSchema: t.parameters ?? { type: "object", properties: {} }, | |
| ...(LOOKING.has(t.name) ? { annotations: { readOnlyHint: true } } : {}), | |
| })); | |
| return [...SERVER_TOOLS, ...fromPage]; | |
| } | |
| const INSTRUCTIONS = `XLeRobot Sim is a MuJoCo physics simulation of XLeRobot that runs in a web page on this computer; these tools drive the robot there. XLeRobot has a two-wheel base (it drives forward/backward and turns in place, not sideways), two SO-101 arms with grippers (left and right) and a pan-tilt head camera. | |
| - If status says no page is connected, call open_sim: it opens the page in the browser and waits until it is ready (the person watching sees the robot move there). | |
| - Positions are in the robot frame: forward, left and up in metres from its base; turns are in degrees, positive to the left. | |
| - camera shows a picture from a robot camera (head, left_wrist, right_wrist) or the page's main view. | |
| - locate finds objects in a robot camera's picture with Gemini 4 Hydrogen${GEMINI_KEY ? " (this server has GEMINI_API_KEY)" : " when GEMINI_API_KEY is set for this server or a key is in the page"}; without one, give it the points you see in the camera's last picture ([y, x] on a 0-1000 grid) and it maps them to positions. | |
| - The kitchen has household tasks (status lists them): start_task sets one up, task tells its goal conditions, its score and the time left. | |
| ${guide}`.trim(); | |
| // --------------------------------------------------------------------------------------------- | |
| // MCP over stdio: JSON-RPC 2.0, one message per line | |
| const running = new Map(); // request id -> AbortController of a tools/call | |
| const CANCELLED = Symbol("cancelled"); | |
| const write = (message) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`); | |
| const notify = (method, params) => write(params === undefined ? { method } : { method, params }); | |
| function receive(line) { | |
| let message; | |
| try { | |
| message = JSON.parse(line); | |
| } catch { | |
| return write({ id: null, error: { code: -32700, message: "Parse error" } }); | |
| } | |
| for (const m of Array.isArray(message) ? message : [message]) if (m && typeof m === "object") handle(m); | |
| } | |
| async function handle({ id, method, params }) { | |
| if (typeof method !== "string") return; // a response: this server sends no requests | |
| if (id === undefined || id === null) return notification(method, params ?? {}); | |
| try { | |
| const result = await request(method, params ?? {}, id); | |
| if (result !== CANCELLED) write({ id, result }); | |
| } catch (error) { | |
| write({ id, error: { code: error.code ?? -32603, message: error.message } }); | |
| } | |
| } | |
| function notification(method, params) { | |
| if (method === "notifications/initialized") initialized = true; | |
| else if (method === "notifications/cancelled") running.get(params.requestId)?.abort(); | |
| } | |
| async function request(method, params, id) { | |
| if (method === "initialize") { | |
| client = params.clientInfo?.name ?? null; | |
| page?.conn.send({ type: "client", name: client }); | |
| return { | |
| protocolVersion: PROTOCOLS.includes(params.protocolVersion) ? params.protocolVersion : PROTOCOLS[0], | |
| capabilities: { tools: { listChanged: true } }, | |
| serverInfo: { name: "xlerobot-sim", title: "XLeRobot Sim", version: VERSION }, | |
| instructions: INSTRUCTIONS, | |
| }; | |
| } | |
| if (method === "ping") return {}; | |
| if (method === "tools/list") return { tools: toolList() }; | |
| if (method === "tools/call") { | |
| const controller = new AbortController(); | |
| running.set(id, controller); | |
| try { | |
| const result = await callTool(params, controller.signal); | |
| return controller.signal.aborted ? CANCELLED : result; | |
| } finally { | |
| running.delete(id); | |
| } | |
| } | |
| throw Object.assign(new Error(`Method not found: ${method}`), { code: -32601 }); | |
| } | |
| // --------------------------------------------------------------------------------------------- | |
| // Tool calls | |
| const text = (value, isError = false) => ({ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }], ...(isError ? { isError: true } : {}) }); | |
| /** A page's result as MCP content: its JSON, and the picture it carries, if any. */ | |
| function content(result) { | |
| const { image, ...rest } = result ?? {}; | |
| const out = text(rest, rest.ok === false); | |
| const data = typeof image === "string" && /^data:(image\/(?:jpeg|png|webp|gif));base64,(.+)$/s.exec(image); | |
| if (data) out.content.push({ type: "image", mimeType: data[1], data: data[2] }); | |
| return out; | |
| } | |
| async function callTool({ name, arguments: args, _meta } = {}, signal) { | |
| const token = _meta?.progressToken; | |
| let steps = 0; | |
| const progress = token === undefined ? () => {} : (message) => notify("notifications/progress", { progressToken: token, progress: ++steps, message }); | |
| try { | |
| if (name === "open_sim") return await openSim(args ?? {}, { signal, progress }); | |
| if (!page) return name === "status" ? text({ connected: false, bridge_port: port, open: pageUrl(), note: "call open_sim, or open that URL in a browser" }) : text(notConnected(), true); | |
| const result = await pageCall(name, args ?? {}, { signal, progress }); | |
| return name === "status" ? content(withGuide({ connected: true, bridge_port: port, ...result })) : content(result); | |
| } catch (error) { | |
| return text(error.message, true); | |
| } | |
| } | |
| /** A status for the client, with the page's guide the first time when the instructions lacked it. */ | |
| function withGuide(status) { | |
| if (!pageGuide) return status; | |
| const how_to_work = pageGuide; | |
| pageGuide = null; | |
| return { ...status, how_to_work }; | |
| } | |
| const notConnected = () => `No simulation page is connected. Call open_sim to open it in the browser, or open ${pageUrl()} yourself (or press Connect in the page's Agent tab, under Claude Code).`; | |
| /** The page's URL with the bridge's port: PAGE_URL, through this server when it is another site's. */ | |
| function pageUrl(base, scene) { | |
| let url = new URL(base ?? PAGE_URL); | |
| if (!base && UPSTREAM) url = new URL(`${url.pathname}${url.search}`, `http://127.0.0.1:${port}`); | |
| url.searchParams.set("bridge", String(port)); | |
| if (scene) url.searchParams.set("env", scene); | |
| return url.href; | |
| } | |
| async function openSim({ scene, url }, { signal, progress }) { | |
| if (page) return content(withGuide({ ok: true, message: "the simulation page is connected already", ...(await pageCall("status", {})) })); | |
| let href; | |
| try { | |
| href = pageUrl(url || undefined, scene); | |
| } catch { | |
| return text(`not a URL: ${url}`, true); | |
| } | |
| const origin = new URL(href).origin; | |
| if (!originAllowed(origin)) return text(`This server accepts pages from ${[...ORIGINS].join(", ")} and from localhost; set XLEROBOT_SIM_ORIGINS to add ${origin}.`, true); | |
| openBrowser(href); | |
| progress("opened the page in the browser; waiting for it to load and connect"); | |
| if (!(await waitForPage(120_000, signal))) { | |
| return text(`Opened ${href} in the default browser, but it has not connected within two minutes. If the browser asks whether the page may reach apps or devices on this computer (local network access), allow it; then call status.`, true); | |
| } | |
| return content(withGuide({ ok: true, message: "the simulation page is connected", ...(await pageCall("status", {})) })); | |
| } | |
| function openBrowser(href) { | |
| const [command, args] = process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", href]] : process.platform === "darwin" ? ["open", [href]] : ["xdg-open", [href]]; | |
| try { | |
| spawn(command, args, { stdio: "ignore", detached: true }).on("error", (error) => log(`could not open a browser: ${error.message}`)).unref(); | |
| } catch (error) { | |
| log(`could not open a browser: ${error.message}`); | |
| } | |
| } | |
| // --------------------------------------------------------------------------------------------- | |
| // The page: one at a time (the newest connection wins), calls by id | |
| let nextId = 1; | |
| const pending = new Map(); // call id -> {conn, resolve, reject, progress} | |
| const waiting = new Set(); // resolvers of waitForPage | |
| let ticker = null; | |
| function pageCall(name, args, { signal, progress } = {}) { | |
| const conn = page?.conn; | |
| if (!conn) return Promise.reject(new Error(notConnected())); | |
| return new Promise((resolve, reject) => { | |
| const id = nextId++; | |
| pending.set(id, { conn, resolve, reject, progress }); | |
| conn.send({ type: "call", id, name, args }); | |
| signal?.addEventListener("abort", () => conn.send({ type: "cancel", id }), { once: true }); | |
| // ticks step the physics of a hidden tab while a call runs (src/agent/bridge.js) | |
| ticker ??= setInterval(() => { | |
| if (pending.size) return page?.conn.send({ type: "tick" }); | |
| clearInterval(ticker); | |
| ticker = null; | |
| }, 250); | |
| }); | |
| } | |
| function waitForPage(ms, signal) { | |
| if (page) return Promise.resolve(true); | |
| return new Promise((resolve) => { | |
| const done = (ok) => { | |
| clearTimeout(timer); | |
| waiting.delete(done); | |
| resolve(ok); | |
| }; | |
| const timer = setTimeout(() => done(false), ms); | |
| signal?.addEventListener("abort", () => done(false), { once: true }); | |
| waiting.add(done); | |
| }); | |
| } | |
| function pageMessage(conn, origin, raw) { | |
| let m; | |
| try { | |
| m = JSON.parse(raw); | |
| } catch { | |
| return; | |
| } | |
| if (m?.type === "hello") { | |
| if (page && page.conn !== conn) { | |
| page.conn.send({ type: "replaced" }); | |
| page.conn.close(4000, "replaced"); | |
| } | |
| page = { conn, origin, info: m.info ?? {} }; | |
| if (client) conn.send({ type: "client", name: client }); | |
| if (GEMINI_KEY) conn.send({ type: "perception", gemini_key: GEMINI_KEY }); // to this checked origin only | |
| if (!guide && typeof m.guide === "string" && !guideGiven) { | |
| pageGuide = m.guide; | |
| guideGiven = true; // once per session | |
| } | |
| log(`page connected from ${origin}: ${m.info?.scene?.name ?? "?"}`); | |
| if (Array.isArray(m.tools)) { | |
| const before = JSON.stringify(toolList()); | |
| pageSpecs = m.tools; | |
| if (initialized && JSON.stringify(toolList()) !== before) notify("notifications/tools/list_changed"); | |
| } | |
| for (const done of [...waiting]) done(true); | |
| } else if (m?.type === "result") { | |
| const call = pending.get(m.id); | |
| if (!call) return; | |
| pending.delete(m.id); | |
| call.resolve(m.result); | |
| } else if (m?.type === "progress") { | |
| pending.get(m.id)?.progress?.(m.message); | |
| } | |
| } | |
| function pageClosed(conn) { | |
| if (page?.conn === conn) { | |
| page = null; | |
| log("page disconnected"); | |
| } | |
| for (const [id, call] of pending) { | |
| if (call.conn !== conn) continue; | |
| pending.delete(id); | |
| call.reject(new Error("The page disconnected (reloaded or closed) before the call finished. Call status, or open_sim.")); | |
| } | |
| } | |
| // --------------------------------------------------------------------------------------------- | |
| // WebSocket server (RFC 6455): text messages from an origin-checked browser page | |
| function originAllowed(origin) { | |
| if (ORIGINS.has(origin)) return true; | |
| try { | |
| const { protocol, hostname } = new URL(origin); | |
| return protocol === "http:" && LOOPBACK.includes(hostname); | |
| } catch { | |
| return false; | |
| } | |
| } | |
| class Connection { | |
| constructor(socket, onMessage, onClose) { | |
| this.socket = socket; | |
| this.onMessage = onMessage; | |
| this.buffer = Buffer.alloc(0); | |
| this.parts = []; | |
| this.size = 0; | |
| this.closed = false; | |
| this.seen = Date.now(); | |
| socket.setNoDelay(true); | |
| socket.on("data", (chunk) => this.#data(chunk)); | |
| socket.on("error", () => {}); | |
| socket.on("close", () => { | |
| this.closed = true; | |
| clearInterval(this.alive); | |
| onClose(this); | |
| }); | |
| // a ping every 15 s (the browser answers it, even from a hidden tab); a minute of silence: gone | |
| this.alive = setInterval(() => { | |
| if (this.closed) return; | |
| if (Date.now() - this.seen > 60_000) return void this.socket.destroy(); | |
| this.#frame(0x9, Buffer.alloc(0)); | |
| }, 15_000); | |
| } | |
| send(message) { | |
| if (!this.closed) this.#frame(0x1, Buffer.from(JSON.stringify(message), "utf8")); | |
| } | |
| close(code = 1000, reason = "") { | |
| if (this.closed) return; | |
| const body = Buffer.alloc(2 + Buffer.byteLength(reason)); | |
| body.writeUInt16BE(code, 0); | |
| body.write(reason, 2); | |
| this.#frame(0x8, body); | |
| this.closed = true; | |
| this.socket.end(); | |
| } | |
| #frame(opcode, payload) { | |
| const n = payload.length; | |
| let head; | |
| if (n < 126) head = Buffer.from([0x80 | opcode, n]); | |
| else if (n < 65536) head = Buffer.from([0x80 | opcode, 126, n >> 8, n & 255]); | |
| else { | |
| head = Buffer.alloc(10); | |
| head[0] = 0x80 | opcode; | |
| head[1] = 127; | |
| head.writeBigUInt64BE(BigInt(n), 2); | |
| } | |
| this.socket.write(Buffer.concat([head, payload])); | |
| } | |
| #data(chunk) { | |
| if (this.closed) return; | |
| this.seen = Date.now(); | |
| this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk; | |
| for (;;) { | |
| const b = this.buffer; | |
| if (b.length < 2) return; | |
| const fin = (b[0] & 0x80) !== 0; | |
| const opcode = b[0] & 0x0f; | |
| if ((b[1] & 0x80) === 0) return this.close(1002, "unmasked frame"); // a browser masks what it sends | |
| let length = b[1] & 0x7f; | |
| let at = 2; | |
| if (length === 126) { | |
| if (b.length < 4) return; | |
| length = b.readUInt16BE(2); | |
| at = 4; | |
| } else if (length === 127) { | |
| if (b.length < 10) return; | |
| const big = b.readBigUInt64BE(2); | |
| if (big > BigInt(MAX_MESSAGE)) return this.close(1009, "message too big"); | |
| length = Number(big); | |
| at = 10; | |
| } | |
| if (length > MAX_MESSAGE) return this.close(1009, "message too big"); | |
| if (b.length < at + 4 + length) return; // the rest is still coming | |
| const mask = b.subarray(at, at + 4); | |
| const payload = Buffer.from(b.subarray(at + 4, at + 4 + length)); | |
| for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3]; | |
| this.buffer = b.subarray(at + 4 + length); | |
| if (opcode === 0x8) return this.close(); // the page closes: answer and end | |
| if (opcode === 0x9) this.#frame(0xa, payload); // ping: pong | |
| else if (opcode === 0x0 || opcode === 0x1 || opcode === 0x2) { | |
| this.parts.push(payload); | |
| this.size += payload.length; | |
| if (this.size > MAX_MESSAGE) return this.close(1009, "message too big"); | |
| if (fin) { | |
| const message = Buffer.concat(this.parts).toString("utf8"); | |
| this.parts = []; | |
| this.size = 0; | |
| this.onMessage(message); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| // HTTP: /mcp-status says whether a page is connected; any other path is the page's file, fetched from its site. | |
| const http = createServer((req, res) => { | |
| if (req.url === "/mcp-status" || !UPSTREAM) { | |
| res.writeHead(req.url === "/mcp-status" ? 200 : 404, { "content-type": "text/plain; charset=utf-8" }); | |
| return res.end(`XLeRobot Sim MCP server ${VERSION}: ${page ? `a page is connected (${page.origin})` : "no page connected"}.\n`); | |
| } | |
| relay(req, res).catch((error) => { | |
| log(`could not serve ${req.url}: ${error.message}`); | |
| res.destroy(); | |
| }); | |
| }); | |
| const RELAYED = ["content-type", "content-length", "content-range", "accept-ranges", "etag", "last-modified", "cache-control"]; | |
| /** One of the page's files, from its site: the browser's conditional and range requests go along. */ | |
| async function relay(req, res) { | |
| if (req.method !== "GET" && req.method !== "HEAD") { | |
| res.writeHead(405, { allow: "GET, HEAD" }); | |
| return res.end(); | |
| } | |
| const target = new URL(req.url, UPSTREAM); | |
| if (target.origin !== UPSTREAM) { | |
| res.writeHead(400); | |
| return res.end(); | |
| } | |
| const headers = { "accept-encoding": "identity" }; | |
| for (const h of ["range", "if-none-match", "if-modified-since", "accept"]) if (req.headers[h]) headers[h] = req.headers[h]; | |
| let upstream; | |
| try { | |
| upstream = await fetch(target, { method: req.method, headers, redirect: "follow" }); | |
| } catch (error) { | |
| res.writeHead(502, { "content-type": "text/plain; charset=utf-8" }); | |
| return res.end(`Could not reach ${UPSTREAM}: ${error.message}\n`); | |
| } | |
| const out = {}; | |
| for (const h of RELAYED) { | |
| const value = upstream.headers.get(h); | |
| if (value) out[h] = value; | |
| } | |
| if (upstream.headers.get("content-encoding")) delete out["content-length"]; // fetch inflated the body | |
| res.writeHead(upstream.status, out); | |
| if (req.method === "HEAD" || !upstream.body) return res.end(); | |
| Readable.fromWeb(upstream.body).on("error", () => res.destroy()).pipe(res); | |
| } | |
| http.on("upgrade", (req, socket) => { | |
| const origin = req.headers.origin ?? ""; | |
| const key = req.headers["sec-websocket-key"]; | |
| if (!originAllowed(origin) || req.headers.upgrade?.toLowerCase() !== "websocket" || !key) { | |
| log(`refused a connection from ${origin || "no origin"}`); | |
| socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); | |
| return; | |
| } | |
| const accept = createHash("sha1").update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64"); | |
| socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); | |
| const conn = new Connection(socket, (raw) => pageMessage(conn, origin, raw), pageClosed); | |
| }); | |
| // Listen first, then read the client's messages (their answers name the port). | |
| await new Promise((resolve) => { | |
| const wanted = port; | |
| const failed = (error) => { | |
| if (error.code !== "EADDRINUSE") { | |
| log(`cannot listen on 127.0.0.1:${wanted}: ${error.message}`); | |
| return resolve(); | |
| } | |
| // another session's server, most likely: take a free port (open_sim's URL names it) | |
| http.listen(0, "127.0.0.1", () => { | |
| port = http.address().port; | |
| log(`port ${wanted} is taken; listening on ${port}`); | |
| resolve(); | |
| }); | |
| }; | |
| http.once("error", failed); | |
| http.listen(wanted, "127.0.0.1", () => { | |
| http.off("error", failed); | |
| resolve(); | |
| }); | |
| }); | |
| http.on("error", (error) => log(error.message)); | |
| log(`XLeRobot Sim MCP server ${VERSION}: waiting for the page on ws://127.0.0.1:${port}`); | |
| let input = ""; | |
| process.stdin.setEncoding("utf8"); | |
| process.stdin.on("data", (chunk) => { | |
| input += chunk; | |
| for (let end = input.indexOf("\n"); end >= 0; end = input.indexOf("\n")) { | |
| const line = input.slice(0, end).trim(); | |
| input = input.slice(end + 1); | |
| if (line) receive(line); | |
| } | |
| }); | |
| process.stdin.on("end", () => process.exit(0)); // the client went away | |