MCP server on the official SDK, over stdio or HTTP

scripts/mcp.js registers the same tools on @modelcontextprotocol/server (2.4.0, with
@modelcontextprotocol/node 2.1.2 for node:http; dev dependencies, pinned) instead of its own JSON-RPC
loop. stdio works as before; --http [HOST:]PORT serves Streamable HTTP at /mcp, on loopback unless
told otherwise.

Over HTTP every request's Host must be an address of this machine (or --allow-host), an Origin other
than localhost is refused, and a bearer token (SOT_MCP_TOKEN or --token-file) is optional; bound
beyond loopback without one, the server warns. load_save and export_save take JSON only there, or files
under --save-dir and nowhere else. Calls from every client run one at a time, in order.
This commit is contained in:
Wolfgang Nagele 2026-11-03 15:00:08 -05:00
parent 5b76685e5c
commit 2526dd458d
11 changed files with 467 additions and 63 deletions

View file

@ -33,7 +33,21 @@ function pageCall(g, tool, args = {}) {
return JSON.parse(g.ev('JSON.stringify(TUBES.call(__mcpTool,__mcpArgs))') || 'null');
}
// Where load_save and export_save may touch files. stdio (saveDir undefined): anywhere, as the operator's own client
// asks. Over HTTP the client may be another machine: nowhere (null), or only under one directory, symlinks included.
function savePath(s, p, write) {
if (s.saveDir === undefined) return path.resolve(p);
if (s.saveDir === null) throw new Error('This server takes saves as JSON only: give json instead of path (the server can allow a directory with --save-dir).');
const root = s.saveDir, full = path.resolve(root, String(p));
let real;
try { real = write ? path.join(fs.realpathSync(path.dirname(full)), path.basename(full)) : fs.realpathSync(full); } catch (e) { throw new Error(`${p}: no such file or directory under the save directory`); }
if (!real.startsWith(root + path.sep)) throw new Error(`${p} is outside the save directory.`);
if (write && fs.existsSync(real) && fs.lstatSync(real).isSymbolicLink()) throw new Error(`${p} is a symbolic link: write to a plain file.`);
return real;
}
// opts.seed, opts.file as tests/harness.js takes them (a file must be a development page: it carries the facade).
// opts.saveDir: see savePath.
function createSession(opts = {}) {
let game = null;
const boot = () => {
@ -44,6 +58,7 @@ function createSession(opts = {}) {
return g;
};
const session = {
saveDir: opts.saveDir,
get game() { return game || (game = boot()); },
// The page's own tools (TUBES.call).
call(name, args) { return pageCall(session.game, name, args); },
@ -79,7 +94,7 @@ const TOOLS = [
inputSchema: obj({ path: str('Path to a .json save file.'), json: str('The save itself, as JSON text.') }),
run: (s, a) => {
if (!a.path === !a.json) throw new Error('Give either path or json.');
const txt = a.path ? fs.readFileSync(path.resolve(a.path), 'utf8') : a.json;
const txt = a.path ? fs.readFileSync(savePath(s, a.path, false), 'utf8') : a.json;
return s.loadSave(txt);
},
},
@ -89,7 +104,7 @@ const TOOLS = [
inputSchema: obj({ path: str('Where to write the .json file.') }),
run: (s, a) => {
const txt = s.headless('exportSave', require('../../package.json').version);
if (a.path) { fs.writeFileSync(path.resolve(a.path), txt); return { wrote: path.resolve(a.path), bytes: Buffer.byteLength(txt) }; }
if (a.path) { const f = savePath(s, a.path, true); fs.writeFileSync(f, txt); return { wrote: f, bytes: Buffer.byteLength(txt) }; }
if (txt.length > MAX_INLINE_SAVE) throw new Error(`The save is ${txt.length} characters; give a path to write it to.`);
return JSON.parse(txt);
},
@ -215,4 +230,4 @@ const TOOLS = [
},
];
module.exports = { createSession, TOOLS, actArgs };
module.exports = { createSession, TOOLS, actArgs, savePath };

View file

@ -1,70 +1,180 @@
#!/usr/bin/env node
// Series of Tubes as an MCP server: an AI client can play, inspect and debug the game through typed tools.
// It runs locally over stdio and loads the game from this checkout's src/ (scripts/lib/mcp-game.js); nothing is
// hosted, and the game page itself does not change. Register it with a client, for example:
// It loads the game from this checkout's src/ (scripts/lib/mcp-game.js) and speaks MCP through the official SDK
// (@modelcontextprotocol/server), over stdio or over HTTP. Nothing is hosted: this is a local tool, like npm run dev,
// and the game page players get does not change.
//
// node scripts/mcp.js # stdio, for a client that starts the server itself
// node scripts/mcp.js --http 7777 # Streamable HTTP on http://127.0.0.1:7777/mcp
// node scripts/mcp.js --http 0.0.0.0:7777 # the same on every interface: anyone who can reach it can play
//
// claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
// claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp
//
// Protocol: JSON-RPC 2.0, one message per line on stdin and stdout (MCP stdio transport). stdout carries only
// protocol messages; anything else goes to stderr.
const readline = require('node:readline');
// stdout carries only protocol messages in stdio mode; anything else goes to stderr.
const crypto = require('node:crypto');
const fs = require('node:fs');
const http = require('node:http');
const os = require('node:os');
const path = require('node:path');
const { McpServer, fromJsonSchema, createMcpHandler, validateHostHeader, validateOriginHeader, localhostAllowedHostnames, localhostAllowedOrigins } = require('@modelcontextprotocol/server');
const { createSession, TOOLS } = require('./lib/mcp-game');
const { version } = require('../package.json');
const VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
const INSTRUCTIONS = `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. A game is always loaded (a fresh On-call game in Frankfurt until you start or load another).
Read with status, network, city, find, traceroute, peering_check and hot_spots, or raw with state, results and catalog; schema is the typed contract of every action. Change things with act (arguments are checked, outcome says what happened, dryRun prices a move first), or with screen, panel and click, which show the game's own panels and windows as text with numbered buttons. Time moves only with advance. Games are seeded: the same seed and moves give the same game.
To look into a bug report: load_save with the attached save, then status, hot_spots, and advance with timings.`;
const MCP_PATH = '/mcp';
const session = createSession();
const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n');
const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
const error = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
const usage = () => `Usage: node scripts/mcp.js [options]
function handle(msg) {
const { id, method, params = {} } = msg;
const isRequest = id !== undefined && id !== null;
switch (method) {
case 'initialize':
return reply(id, {
protocolVersion: VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : VERSIONS[0],
capabilities: { tools: { listChanged: false } },
serverInfo: { name: 'seriesoftubes', title: 'Series of Tubes', version },
instructions: INSTRUCTIONS,
});
case 'ping':
return reply(id, {});
case 'tools/list':
return reply(id, { tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
case 'tools/call': {
const tool = TOOLS.find((t) => t.name === params.name);
if (!tool) return error(id, -32602, `Unknown tool: ${params.name}`);
try {
const out = tool.run(session, params.arguments || {});
const errs = session.errors();
return reply(id, { content: [{ type: 'text', text: JSON.stringify(out, null, 1) }], ...(errs.length ? { _meta: { pageErrors: errs.slice(-5) } } : {}) });
} catch (e) {
return reply(id, { content: [{ type: 'text', text: String(e && e.message || e) }], isError: true });
}
}
default:
if (method && method.startsWith('notifications/')) return undefined;
if (isRequest) return error(id, -32601, `Method not found: ${method}`);
return undefined;
(no options) stdio: the client starts this process and talks over stdin and stdout
--http [HOST:]PORT Streamable HTTP at http://HOST:PORT${MCP_PATH} instead (HOST defaults to 127.0.0.1)
--token-file FILE HTTP: require "Authorization: Bearer <the file's contents>" (or set SOT_MCP_TOKEN)
--allow-host NAME HTTP: also accept this Host name (repeatable), e.g. for a tunnel or a LAN name
--save-dir DIR HTTP: load_save and export_save may read and write files under DIR (otherwise no files)
--help`;
// Valueless flags are true; repeated ones collect; --kebab-case becomes camelCase.
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith('--')) continue;
const k = a.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase()), v = argv[i + 1];
const val = v === undefined || v.startsWith('--') ? true : (i++, v);
out[k] = k in out ? [].concat(out[k], val) : val;
}
return out;
}
if (require.main === module) {
// The game page logs nothing to stdout, but a stray console.log anywhere must not break the protocol.
console.log = console.info = (...a) => console.error(...a);
const rl = readline.createInterface({ input: process.stdin });
rl.on('line', (line) => {
if (!line.trim()) return;
let msg;
try { msg = JSON.parse(line); } catch (e) { return error(null, -32700, 'Parse error'); }
if (Array.isArray(msg)) { for (const m of msg) handle(m); return; }
handle(msg);
// Tool calls run one at a time, in the order they arrived, from every client: one game, one move at a time.
function serial() {
let chain = Promise.resolve();
return (f) => { const p = chain.then(f); chain = p.catch(() => {}); return p; };
}
// One MCP server definition over the game session: the SDK asks for a fresh one per connection (stdio) or per request
// (HTTP); they all share the session and its queue.
function serverFactory(session) {
const queue = serial();
const schemas = new Map(TOOLS.map((t) => [t.name, fromJsonSchema(t.inputSchema)]));
return () => {
const server = new McpServer({ name: 'seriesoftubes', title: 'Series of Tubes', version }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
for (const tool of TOOLS) {
server.registerTool(tool.name, { description: tool.description, inputSchema: schemas.get(tool.name) }, (args) => queue(async () => {
try {
const out = await tool.run(session, args || {});
const errs = session.errors();
return { content: [{ type: 'text', text: JSON.stringify(out, null, 1) }], ...(errs.length ? { _meta: { pageErrors: errs.slice(-5) } } : {}) };
} catch (e) {
return { content: [{ type: 'text', text: String(e && e.message || e) }], isError: true };
}
}));
}
return server;
};
}
// --http [HOST:]PORT, with IPv6 hosts in brackets ([::1]:7777).
function parseListen(v) {
const s = String(v === true ? '' : v);
const m = /^(?:\[([^\]]+)\]|([^:]+)):(\d+)$/.exec(s) || /^()()(\d+)$/.exec(s);
// Port 0 picks a free one (the banner says which).
if (!m || +m[3] > 65535) throw new Error(`--http takes [HOST:]PORT, e.g. 7777 or 0.0.0.0:7777, not "${s}"`);
return { host: m[1] || m[2] || '127.0.0.1', port: +m[3] };
}
const isLoopback = (h) => h === 'localhost' || h === '::1' || /^127\.\d+\.\d+\.\d+$/.test(h);
const isWildcard = (h) => h === '0.0.0.0' || h === '::';
const bracket = (h) => (h.includes(':') && !h.startsWith('[') ? `[${h}]` : h);
// The names a request's Host may carry: this machine by loopback, the address the server is bound to (every local
// address when bound to all of them), and names the operator allowed. Anything else is a name someone else's DNS
// points here (DNS rebinding) and is refused.
function allowedHosts(host, extra = []) {
const out = new Set([...localhostAllowedHostnames(), ...extra.map(String)]);
if (isWildcard(host)) for (const list of Object.values(os.networkInterfaces())) for (const a of list || []) out.add(bracket(a.address.split('%')[0]));
else out.add(bracket(host));
return [...out];
}
// Constant-time token check (hashing first makes the lengths equal, so the length does not leak either).
const sameToken = (a, b) => crypto.timingSafeEqual(crypto.createHash('sha256').update(String(a)).digest(), crypto.createHash('sha256').update(String(b)).digest());
// The HTTP side: Host and Origin checked on every request (browsers cannot be talked into driving the game from a
// website), the token when there is one, then the SDK's Streamable HTTP handler.
function createHttpServer(factory, { host, allow = [], token = null } = {}) {
const { toNodeHandler } = require('@modelcontextprotocol/node');
const handle = toNodeHandler(createMcpHandler(factory));
const hosts = allowedHosts(host, allow), origins = localhostAllowedOrigins();
const deny = (res, code, message, headers = {}) => {
res.writeHead(code, { 'content-type': 'application/json', ...headers });
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32000, message } }));
};
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname !== MCP_PATH) return deny(res, 404, `The MCP endpoint is ${MCP_PATH}.`);
const h = validateHostHeader(req.headers.host, hosts);
if (!h.ok) return deny(res, 403, `Host not allowed: ${h.message}. Use an address of this machine, or start the server with --allow-host.`);
const o = validateOriginHeader(req.headers.origin, origins);
if (!o.ok) return deny(res, 403, 'Origin not allowed: a web page may not drive this server.');
if (token) {
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization || '');
if (!m || !sameToken(m[1].trim(), token)) return deny(res, 401, 'A bearer token is required.', { 'www-authenticate': 'Bearer realm="seriesoftubes"' });
}
handle(req, res);
});
// advance over thousands of days on a big network takes minutes; Node's default would cut it off at five.
server.requestTimeout = 30 * 60 * 1000;
return server;
}
module.exports = { handle, TOOLS };
function readToken(args) {
if (args.tokenFile) {
const t = fs.readFileSync(path.resolve(String(args.tokenFile)), 'utf8').trim();
if (!t) throw new Error(`${args.tokenFile} is empty`);
return t;
}
return process.env.SOT_MCP_TOKEN ? String(process.env.SOT_MCP_TOKEN).trim() || null : null;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help) { console.error(usage()); process.exit(0); }
const say = (m) => console.error(`[series-of-tubes] ${m}`);
const die = (m) => { console.error(`error: ${m}`); process.exit(1); };
// The game page logs nothing to stdout, but a stray console.log anywhere must not break the stdio protocol.
console.log = console.info = (...a) => console.error(...a);
if (!args.http) {
for (const k of ['tokenFile', 'allowHost', 'saveDir']) if (args[k] !== undefined) die(`--${k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase())} is an --http option`);
const { serveStdio } = require('@modelcontextprotocol/server/stdio');
const session = createSession();
serveStdio(serverFactory(session));
return;
}
let listen, token;
try { listen = parseListen(args.http); token = readToken(args); } catch (e) { die(e.message); }
// Over HTTP the client may be another machine: files only under --save-dir, never anywhere on this one.
let saveDir = null;
if (args.saveDir !== undefined) {
try { saveDir = fs.realpathSync(path.resolve(String(args.saveDir))); } catch (e) { die(`--save-dir ${args.saveDir}: ${e.message}`); }
if (!fs.statSync(saveDir).isDirectory()) die(`--save-dir ${args.saveDir} is not a directory`);
}
const session = createSession({ saveDir });
const server = createHttpServer(serverFactory(session), { host: listen.host, allow: [].concat(args.allowHost || []), token });
server.on('error', (e) => die(`could not listen on ${bracket(listen.host)}:${listen.port}: ${e.message}`));
server.listen(listen.port, listen.host, () => {
const ad = server.address(), at = `${bracket(ad.address)}:${ad.port}`;
say(`MCP server ${version} on http://${at}${MCP_PATH} (one game, shared by every client; calls run one at a time)`);
say(token ? 'a bearer token is required' : 'no token: anything that can reach this address may play');
if (!isLoopback(listen.host) && !token) say(`WARNING: bound to ${listen.host}, beyond this machine, without a token. Set SOT_MCP_TOKEN or --token-file to require one.`);
say(saveDir ? `load_save and export_save files: under ${saveDir}` : 'load_save and export_save take JSON only (no files: --save-dir DIR allows some)');
});
const shutdown = () => server.close(() => process.exit(0));
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
}
if (require.main === module) main();
module.exports = { serverFactory, createHttpServer, serial, parseArgs, parseListen, allowedHosts, INSTRUCTIONS, MCP_PATH };