The game as a local MCP server: play, inspect and debug it from an AI client
scripts/mcp.js speaks MCP over stdio and loads the game from src/ in jsdom, seeded, like the tests. Tools: new_game, load_save, export_save, status, advance (with per-day timings), network, city, find, traceroute, peering_check, hot_spots, actions, act, screen, panel, click, open_link. Actions go through ACT as buttons do; files, slots, settings and the clock stay out of reach, and nothing evaluates code in the page. Nothing is hosted and the page is unchanged. See docs/MCP.md.
This commit is contained in:
parent
935c08839f
commit
37def9dd6b
9 changed files with 733 additions and 1 deletions
|
|
@ -28,6 +28,7 @@ npm run build # builds _site/ for GitHub Pages (assembles src/, s
|
|||
npm run serve # build and serve the production site locally
|
||||
npm run perf -- --base-ref origin/main # big-network benchmark vs main (see `performance`)
|
||||
npm run perf -- --base-ref origin/main --browser # the same, also in real Chromium (desktop and phone)
|
||||
npm run mcp # the game as a local MCP server for AI clients (docs/MCP.md)
|
||||
```
|
||||
|
||||
## Hard rules
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ npm run dev # development server: assembles src/ on every request, reloads on
|
|||
npm test # headless tests: boot, geography, a year of play, every incident, every panel
|
||||
npm run build # writes the site for GitHub Pages to _site/, with version and date stamped in
|
||||
npm run i18n:check # lists text missing from (or stale in) the translations
|
||||
npm run mcp # the game as an MCP server, so an AI client can play and debug it (docs/MCP.md)
|
||||
```
|
||||
|
||||
## Community
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ Development runs on `npm run dev` (assembles on every request, reloads on save);
|
|||
| `scripts/test.js` | `npm test`: runs every `tests/*.test.js` |
|
||||
| `scripts/release-notes.js` | Extracts a version's CHANGELOG bullets |
|
||||
| `scripts/perf-bench.js`, `perf-browser.js`, `perf-stats.js`, `perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` |
|
||||
| `scripts/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-page.js` | The game as a local MCP server: typed tools to play, inspect and debug it from an AI client ([MCP.md](MCP.md)) |
|
||||
| `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries |
|
||||
| `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over |
|
||||
| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas |
|
||||
|
|
|
|||
54
docs/MCP.md
Normal file
54
docs/MCP.md
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
# Series of Tubes as an MCP server
|
||||
|
||||
`scripts/mcp.js` lets an AI client (Claude Code, Claude Desktop, any MCP client) play, inspect and debug the game
|
||||
through typed tools. It runs on your machine over stdio and loads the game from this checkout's `src/`, the way the
|
||||
tests do: one page in jsdom, seeded, with no animation loop. Nothing is hosted and the game page does not change, so
|
||||
it stays within [ADR 0001](adr/0001-github-pages-only.md): it is a local tool, like `npm run dev`.
|
||||
|
||||
## Set it up
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
|
||||
```
|
||||
|
||||
Other clients take the same command (`node /path/to/seriesoftubes/scripts/mcp.js`) in their MCP server settings.
|
||||
`npm run mcp` starts it by hand; clients should use the `node` command, because `npm run` prints a line of its own first.
|
||||
|
||||
A game is always loaded: a fresh On-call game in Frankfurt until you start or load another. Every game is seeded, so
|
||||
the same seed and the same moves give the same game.
|
||||
|
||||
## Tools
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `new_game` | Start a network in any home city with a preset (`freeze`, `oncall`, `bgp`, `sandbox`) and a seed |
|
||||
| `load_save`, `export_save` | Load an exported save (a path or JSON text, migrated as the game does) or write one the real game can import |
|
||||
| `status` | Date, cash, revenue and costs by kind, level, tier and why it is not Tier 1, the goal, traffic, reach, POPs, incidents |
|
||||
| `advance` | Run N days through `dayTick()`. Stops when a window needs an answer or the network goes bankrupt. Returns the log, new incidents, cash and the time each day took |
|
||||
| `network`, `city`, `find` | The world: policies and what a network asks for, its PoPs, cone and price; a city's exchanges, transit sellers, cables; search by name, id or ASN |
|
||||
| `traceroute` | The looking glass: which exit wins to a network and why, with the AS path |
|
||||
| `peering_check` | Would this network peer with you over a PNI or at an exchange, and the game's reason if not |
|
||||
| `hot_spots` | The fullest links, transit ports and PNIs, the transit bill by carrier, and the biggest traffic still on transit with the way off it |
|
||||
| `actions`, `act` | Every game action with its arguments, and running one as a button would |
|
||||
| `screen`, `panel`, `click`, `open_link` | The game's own windows and panels as text with numbered buttons; press one; open a link's build window |
|
||||
|
||||
`act` and `click` run the same `ACT` actions the buttons dispatch, so the game's rules, prices and messages apply.
|
||||
They never reach files, save slots, settings, the title screen or the game speed (time moves only with `advance`).
|
||||
There is no tool that evaluates code in the page.
|
||||
|
||||
## Looking into a bug report
|
||||
|
||||
1. `load_save` with the save attached to the issue.
|
||||
2. `status` and `hot_spots` for the picture, `traceroute` and `peering_check` for one network's traffic.
|
||||
3. `advance` a few days and read `timing.slowestDays` for lag, or the log for what went wrong.
|
||||
|
||||
## Code
|
||||
|
||||
- `scripts/mcp.js`: the stdio transport (JSON-RPC 2.0, one message per line) and the protocol methods.
|
||||
- `scripts/lib/mcp-game.js`: the session (one game page) and the tool list with input schemas.
|
||||
- `scripts/lib/mcp-page.js`: runs inside the page and reads or drives the game through its own globals.
|
||||
- `tests/mcp.test.js`: the protocol, a game played through the tools, determinism, saves, and what stays out of reach.
|
||||
|
||||
The tools read the game's internals (`S`, `R`, `ACT`, `NETS`…), which are not a stable API: a refactor in `src/` can
|
||||
break a tool, and `tests/mcp.test.js` is there to catch that in CI.
|
||||
|
|
@ -18,7 +18,8 @@
|
|||
"dev": "node scripts/dev.js",
|
||||
"page": "node scripts/lib/page.js",
|
||||
"serve": "npm run build && npx --yes serve@14.2.4 _site",
|
||||
"perf": "node scripts/perf-bench.js"
|
||||
"perf": "node scripts/perf-bench.js",
|
||||
"mcp": "node scripts/mcp.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
|
|
|
|||
167
scripts/lib/mcp-game.js
Normal file
167
scripts/lib/mcp-game.js
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
// The game behind the MCP server (scripts/mcp.js): one game page from src/, loaded in jsdom like the tests load it
|
||||
// (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-page.js added to read and drive it.
|
||||
// TOOLS is the list the server offers; each run() gets the session and the tool's arguments and returns JSON.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('../../tests/harness');
|
||||
|
||||
const PAGE_JS = fs.readFileSync(path.join(__dirname, 'mcp-page.js'), 'utf8');
|
||||
const ACT_DIR = path.join(__dirname, '..', '..', 'src', 'game', '90-actions');
|
||||
|
||||
// The arguments each action takes, read from its source (`buyTransit:({city,net,tier})=>`): in the page the
|
||||
// actions are wrapped for puzzle mode, so their own parameter lists are not visible there.
|
||||
let ACT_ARGS = null;
|
||||
function actArgs() {
|
||||
if (ACT_ARGS) return ACT_ARGS;
|
||||
ACT_ARGS = {};
|
||||
const re = /(?:^|[\s,{])([A-Za-z]\w*):\s*(?:async\s*)?\(\s*\{([^}]*)\}\s*\)\s*=>/g;
|
||||
for (const f of fs.readdirSync(ACT_DIR).filter((f) => f.endsWith('.js')).sort()) {
|
||||
const src = fs.readFileSync(path.join(ACT_DIR, f), 'utf8');
|
||||
for (const m of src.matchAll(re)) if (!ACT_ARGS[m[1]]) ACT_ARGS[m[1]] = m[2].split(',').map((a) => a.split('=')[0].trim()).filter(Boolean);
|
||||
}
|
||||
return ACT_ARGS;
|
||||
}
|
||||
const MAX_INLINE_SAVE = 200000;
|
||||
|
||||
function createSession(opts = {}) {
|
||||
let game = null;
|
||||
const boot = () => {
|
||||
const g = load({ seed: opts.seed || 12345, file: opts.file });
|
||||
g.ev(PAGE_JS);
|
||||
g.call = (fn, ...args) => {
|
||||
g.dom.window.__mcpArgs = JSON.parse(JSON.stringify(args));
|
||||
return JSON.parse(g.ev(`JSON.stringify(__mcp.${fn}(...window.__mcpArgs))`) || 'null');
|
||||
};
|
||||
g.call('newGame', { city: 'fra', name: 'Scratch Networks', preset: 'oncall' });
|
||||
return g;
|
||||
};
|
||||
const session = {
|
||||
get game() { return game || (game = boot()); },
|
||||
call(fn, ...args) { return session.game.call(fn, ...args); },
|
||||
// Text into the page without building a giant eval string (saves run to megabytes).
|
||||
loadSave(txt) { session.game.dom.window.__mcpSave = txt; return JSON.parse(session.game.ev('JSON.stringify(__mcp.loadSave(window.__mcpSave))')); },
|
||||
errors() { return game ? game.errors.slice() : []; },
|
||||
};
|
||||
return session;
|
||||
}
|
||||
|
||||
const str = (description, extra = {}) => ({ type: 'string', description, ...extra });
|
||||
const num = (description, extra = {}) => ({ type: 'number', description, ...extra });
|
||||
const obj = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: 'new_game',
|
||||
description: 'Start a new network, replacing the current one. Presets: freeze (Change Freeze, gentle), oncall (On-call, the classic game), bgp (BGP at 3 a.m., harsh), sandbox (endless money, every level, no chaos). Seeded, so the same seed and the same moves give the same game.',
|
||||
inputSchema: obj({ city: str('Home city: id (fra) or name (Frankfurt). Default Frankfurt.'), name: str('Network name (24 characters at most). Default: a random pun.'),
|
||||
preset: str('Rules preset', { enum: ['freeze', 'oncall', 'bgp', 'sandbox'] }), seed: num('Random seed, default 12345.') }),
|
||||
run: (s, a) => s.call('newGame', a),
|
||||
},
|
||||
{
|
||||
name: 'load_save',
|
||||
description: 'Load a saved game: a file exported from the game (Menu → Export save, the series-of-tubes-*.json from a bug report) or a raw save, as a path or as JSON text. Old saves are migrated exactly as the game does.',
|
||||
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;
|
||||
return s.loadSave(txt);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'export_save',
|
||||
description: 'Export the current game as a save file the real game can import (Menu → Import save). Writes it to path, or returns it when it is small.',
|
||||
inputSchema: obj({ path: str('Where to write the .json file.') }),
|
||||
run: (s, a) => {
|
||||
const txt = s.call('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 (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);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
description: 'The network at a glance: date, cash, monthly revenue and costs by kind, level, tier and why it is not Tier 1 yet, the current goal, traffic, reach, counts, POPs and open incidents.',
|
||||
inputSchema: obj(),
|
||||
run: (s) => s.call('status'),
|
||||
},
|
||||
{
|
||||
name: 'advance',
|
||||
description: 'Run the game forward day by day, as the game loop does. Stops early when a window opens that needs an answer (then answer it with screen and click) or the network goes bankrupt. Returns what happened: log, toasts, new incidents, cash, and how long each simulated day took.',
|
||||
inputSchema: obj({ days: num('Days to run, 1 to 3650. Default 1.') }),
|
||||
run: (s, a) => s.call('advance', a.days),
|
||||
},
|
||||
{
|
||||
name: 'network',
|
||||
description: 'Everything about one network (a carrier, eyeball network, CDN…): type, peering policy and what it asks for, traffic share, transit price, PoPs, exchanges, upstreams and customer cone, whether Tier 1 needs it, and for you: demand, how its traffic leaves you (egress by kind), your PNIs and sessions with it, and how to move it to peering.',
|
||||
inputSchema: obj({ network: str('Id (dtk), name (Doitsche Telekomm) or ASN.') }, ['network']),
|
||||
run: (s, a) => s.call('network', a.network),
|
||||
},
|
||||
{
|
||||
name: 'city',
|
||||
description: 'One city: country, exchanges and their member counts, data center, who sells transit there and at what price, the networks present, the cables that land there, and your POP if you have one.',
|
||||
inputSchema: obj({ city: str('Id (fra) or name (Frankfurt).') }, ['city']),
|
||||
run: (s, a) => s.call('city', a.city),
|
||||
},
|
||||
{
|
||||
name: 'find',
|
||||
description: 'Search cities, networks, cables and exchanges by name, id or ASN. Use it to get the ids other tools and actions take.',
|
||||
inputSchema: obj({ query: str('Part of a name, an id or an ASN.'), kind: str('Only this kind', { enum: ['city', 'network', 'cable', 'exchange'] }) }, ['query']),
|
||||
run: (s, a) => s.call('find', a.query, a.kind),
|
||||
},
|
||||
{
|
||||
name: 'traceroute',
|
||||
description: 'The game\'s looking glass: the path traffic takes from one of your POPs to a network (which exit wins and why, with the AS path) or to another of your POPs (prefix it city:).',
|
||||
inputSchema: obj({ from: str('One of your POPs: id or name.'), to: str('A network (id, name or ASN), or city:<one of your POPs>.') }, ['from', 'to']),
|
||||
run: (s, a) => s.call('trace', a.from, a.to),
|
||||
},
|
||||
{
|
||||
name: 'peering_check',
|
||||
description: 'Would this network peer with you, and if not, why not? Checks a PNI at each of your POPs where it is, and a session at each exchange you are on where it is a member, with the game\'s own reasons (traffic it wants, paid peering, the Tier 1 club…).',
|
||||
inputSchema: obj({ network: str('Id, name or ASN.'), city: str('Only this city.'), via: str('Only this way', { enum: ['pni', 'ix'] }) }, ['network']),
|
||||
run: (s, a) => s.call('peering', a.network, a.city, a.via),
|
||||
},
|
||||
{
|
||||
name: 'hot_spots',
|
||||
description: 'Where it hurts: the fullest links, transit ports and PNIs, the transit bill by carrier, and the networks with the most traffic still over transit, each with the cheapest way to peer with it.',
|
||||
inputSchema: obj({ limit: num('How many of each, default 10.') }),
|
||||
run: (s, a) => s.call('hotSpots', a.limit || 10),
|
||||
},
|
||||
{
|
||||
name: 'actions',
|
||||
description: 'Every game action act can run, with the arguments it takes, e.g. buildPop(city), buyTransit(city,net,tier), buyIx(city,tier), pni(city,net,tier). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=<exchange id>.',
|
||||
inputSchema: obj(),
|
||||
run: (s) => { const a = actArgs(); return s.call('actions').map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k)); },
|
||||
},
|
||||
{
|
||||
name: 'act',
|
||||
description: 'Do something in the game, as a button would: run one action with its arguments (see actions). Returns the game\'s messages, the change in cash, and what is on screen now: an open window (a quote, a choice) with its numbered buttons, or the side panel.',
|
||||
inputSchema: obj({ action: str('Action name, e.g. buildPop.'), args: { type: 'object', description: 'Its arguments, e.g. {"city":"ams"}.' } }, ['action']),
|
||||
run: (s, a) => s.call('run', a.action, a.args || {}),
|
||||
},
|
||||
{
|
||||
name: 'screen',
|
||||
description: 'What the player sees now: the open window, or else the side panel, as text with numbered buttons for click.',
|
||||
inputSchema: obj(),
|
||||
run: (s) => s.call('screen'),
|
||||
},
|
||||
{
|
||||
name: 'panel',
|
||||
description: 'Open the side panel of a city or a link, or a network in the network list, optionally on a tab (a city has cust, up, peer, infra…), and show it as text with numbered buttons.',
|
||||
inputSchema: obj({ city: str('City id or name.'), link: str('Link id (from status or hot_spots).'), network: str('Network id or name.'), tab: str('Tab id, as the tab buttons name it.') }),
|
||||
run: (s, a) => s.call('panel', a),
|
||||
},
|
||||
{
|
||||
name: 'click',
|
||||
description: 'Press a numbered button from the last screen, panel or act result.',
|
||||
inputSchema: obj({ button: num('The button\'s n.') }, ['button']),
|
||||
run: (s, a) => s.call('click', a.button),
|
||||
},
|
||||
{
|
||||
name: 'open_link',
|
||||
description: 'Open the build window for a link (a leased wave, dark fiber or your own cable) from one of your POPs to any city. Then pick the route and size with click (buildLink takes the tier).',
|
||||
inputSchema: obj({ from: str('One of your POPs.'), to: str('Any city.') }, ['from', 'to']),
|
||||
run: (s, a) => s.call('openLink', a.from, a.to),
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = { createSession, TOOLS };
|
||||
273
scripts/lib/mcp-page.js
Normal file
273
scripts/lib/mcp-page.js
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
// Runs inside the game page (see scripts/lib/mcp-game.js), in the game's own global scope, so it reads S, R, NET,
|
||||
// CITY… directly. Every function takes and returns plain JSON. It only reads the game, except act(), click(),
|
||||
// panel(), advance() and the game loaders, which go through the same ACT actions and dayTick() the page uses.
|
||||
(() => {
|
||||
const BLOCK = /^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/;
|
||||
// Text as a player would read it: one line per block, no runs of spaces. jsdom has no innerText.
|
||||
const text = (x, max = 8000) => {
|
||||
let el = x;
|
||||
if (typeof x === 'string') { el = document.createElement('div'); el.innerHTML = x; }
|
||||
if (!el) return '';
|
||||
const out = [];
|
||||
const walk = (n) => {
|
||||
if (n.nodeType === 3) { out.push(n.nodeValue); return; }
|
||||
if (n.nodeType !== 1 || n.hidden || /^(SCRIPT|STYLE|SVG|CANVAS)$/i.test(n.tagName)) return;
|
||||
if (n.tagName === 'BR') { out.push('\n'); return; }
|
||||
// Blocks get their own line; inline tags a space, so "Revenue<b>$2k</b>" does not read as one word.
|
||||
const sep = BLOCK.test(n.tagName) ? '\n' : ' ';
|
||||
out.push(sep);
|
||||
for (const c of n.childNodes) walk(c);
|
||||
out.push(sep);
|
||||
};
|
||||
walk(el);
|
||||
const s = out.join('').split('\n').map((l) => l.replace(/\s+/g, ' ').replace(/ ([.,;:!?)])/g, '$1').replace(/\( /g, '(').trim()).filter(Boolean).join('\n');
|
||||
return s.length > max ? s.slice(0, max) + '\n…' : s;
|
||||
};
|
||||
const r1 = (v) => (typeof v === 'number' && isFinite(v) ? Math.round(v * 10) / 10 : v);
|
||||
const fail = (msg) => { throw new Error(msg); };
|
||||
const norm = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').trim();
|
||||
|
||||
// ---------- finding things by id or by name ----------
|
||||
const best = (list, q, keys) => {
|
||||
const n = norm(q);
|
||||
if (!n) return null;
|
||||
for (const test of [(v) => v === n, (v) => v.startsWith(n), (v) => v.includes(n)]) {
|
||||
const hit = list.find((x) => keys(x).some((k) => test(norm(k))));
|
||||
if (hit) return hit;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const netOf = (q) => NET[q] || best(NETS, q, (n) => [n.id, n.name, 'as' + n.asn, String(n.asn)]) || fail(`No network matches "${q}". Try find.`);
|
||||
const cityOf = (q) => CITY[q] || best(CITIES, q, (c) => [c.id, c.name]) || fail(`No city matches "${q}". Try find.`);
|
||||
const allIx = () => {
|
||||
const o = [];
|
||||
for (const c of CITIES) for (const x of ixStatic(c.id)) o.push(x);
|
||||
for (const c of Object.keys(S.myIx || {})) if (!o.includes(c)) o.push(c);
|
||||
return o;
|
||||
};
|
||||
const ixOf = (q) => (XIXM[q] || (CITY[q] && CITY[q].ix) || (S.myIx && S.myIx[q]) ? q : best(allIx(), q, (x) => [x, ixName(x)])) || fail(`No exchange matches "${q}".`);
|
||||
const cityName = (c) => (CITY[c] ? CITY[c].name : c);
|
||||
const incText = (i) => text(i.msg || incTitle(i), 400);
|
||||
|
||||
// ---------- toasts: what the game tells the player ----------
|
||||
let toasts = [];
|
||||
const t0 = toast;
|
||||
toast = function (h, kind) { toasts.push((kind ? kind + ': ' : '') + text(String(h), 600)); return t0.apply(this, arguments); };
|
||||
const takeToasts = () => { const t = toasts; toasts = []; return t; };
|
||||
|
||||
// ---------- what is on screen ----------
|
||||
let last = [];
|
||||
const buttons = (root) => [...root.querySelectorAll('[data-act]')].map((b) => {
|
||||
let args = {};
|
||||
try { args = JSON.parse(b.dataset.args || '{}'); } catch (e) {}
|
||||
return { label: text(b, 200).replace(/\n/g, ' ') || b.getAttribute('aria-label') || b.dataset.act, act: b.dataset.act, args, disabled: !!b.disabled };
|
||||
});
|
||||
const screen = (where) => {
|
||||
const modal = !$('modal').hidden;
|
||||
if (modal && !where) {
|
||||
last = buttons($('modal'));
|
||||
return { where: 'modal', text: text($('modal')), buttons: last.map((b, i) => ({ n: i, ...b })) };
|
||||
}
|
||||
const p = where === 'left' ? $('leftBody') : $('panel');
|
||||
last = p ? buttons(p) : [];
|
||||
return { where: where === 'left' ? 'network list' : 'panel', modalOpen: modal, selected: UI.sel, tab: UI.tab, text: p ? text(p) : '', buttons: last.map((b, i) => ({ n: i, ...b })) };
|
||||
};
|
||||
|
||||
// ---------- starting and loading ----------
|
||||
const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); compute(); renderAll(); takeToasts(); };
|
||||
const newGame = ({ city = 'fra', name, preset = 'oncall', seed }) => {
|
||||
const c = cityOf(city).id;
|
||||
if (!homeOk(c)) fail(`${cityName(c)} cannot be a home city.`);
|
||||
if (!['freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) fail('preset is one of freeze, oncall, bgp, sandbox');
|
||||
if (seed !== undefined && window.__reseed) window.__reseed(Math.max(1, Math.floor(+seed) || 1));
|
||||
if (UI.pendGame) UI.pendGame = null;
|
||||
UI.pitched = true;
|
||||
const nm = String(name || randomNetworkName()).slice(0, 24);
|
||||
beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: 'none' } } : { mode: 'normal', preset });
|
||||
settle();
|
||||
return status();
|
||||
};
|
||||
const loadSave = (txt) => {
|
||||
const r = parseSave(txt);
|
||||
if (r.err) fail(text(r.err));
|
||||
S = migrate(JSON.parse(JSON.stringify(r.s)));
|
||||
settle();
|
||||
return { savedBy: r.ver, ...status() };
|
||||
};
|
||||
const exportSave = (version) => JSON.stringify({ app: 'series-of-tubes', version: /^\d/.test(APP_VERSION) ? APP_VERSION : version, exported: new Date().toISOString(), S: packSave(S) });
|
||||
|
||||
// ---------- reading the network ----------
|
||||
const status = () => {
|
||||
const goal = GOALS.find((g) => S.done[g.id] === undefined);
|
||||
const t1 = isTier1();
|
||||
return {
|
||||
name: S.name, asn: S.asn, home: cityName(S.home), mode: S.mode, rules: S.rules && S.rules.preset,
|
||||
day: S.day, date: dateStr(S.day), cash: Math.round(S.cash), level: S.lvl || 0,
|
||||
tier: tierLabel(), whyNotTier1: t1 ? null : text(t1Why()),
|
||||
goal: goal ? { title: text(goal.t), what: text(goal.d) } : null,
|
||||
monthly: { revenue: Math.round(R.revMo), cost: Math.round(R.costMo), profit: Math.round(R.revMo - R.costMo),
|
||||
revenueBy: Object.fromEntries(Object.entries(R.rev || {}).map(([k, v]) => [k, Math.round(v)]).filter(([, v]) => v)),
|
||||
costBy: Object.fromEntries(Object.entries(R.cost || {}).map(([k, v]) => [k, Math.round(v)]).filter(([, v]) => v)) },
|
||||
traffic: { demandGbps: r1(R.demand), servedGbps: r1(R.served), reach: r1((R.reach || 0) * 100) + '%', peeringSessions: R.sessions },
|
||||
counts: { pops: Object.keys(S.pops).length, links: S.links.length, transitPorts: S.transit.length, exchangePorts: Object.keys(S.ixp).length,
|
||||
pnis: S.pni.length, cacheBoxes: S.caches.length, customers: S.biz.length, offers: S.offers.length },
|
||||
pops: Object.keys(S.pops).map(cityName),
|
||||
incidents: S.inc.map((i) => ({ id: i.id, type: i.type, what: incText(i), until: i.until !== undefined ? dateStr(i.until) : undefined, rushRepairCost: i.cost || undefined })),
|
||||
lost: !!S.lost, won: !!S.won,
|
||||
};
|
||||
};
|
||||
|
||||
const network = (q) => {
|
||||
const n = netOf(q), id = n.id, eg = R.netEg && R.netEg[id];
|
||||
return {
|
||||
id, name: n.name, asn: n.asn, type: TYPE_L[n.type], policy: n.pol,
|
||||
requirements: { minIxGbps: n.minIx, minPniGbps: n.minPni, paidFeePerMonth: n.paidFee, freeFromLevel: n.freeLv },
|
||||
trafficShare: r1(NSH[id] * 100) + '%', transitPerGbps: n.price ? r1(n.price * S.priceMul) : null,
|
||||
homeMarkets: n.cc ? [].concat(n.cc) : [], pops: n.pops.map(cityName),
|
||||
exchanges: n.ix === 'ALL' ? 'most exchanges where it has a PoP' : (n.ix || []).map((x) => ixName(x)),
|
||||
upstreams: (n.up || []).map((u) => NET[u] ? NET[u].name : u), customerCone: (DOWN[id] || []).length,
|
||||
neededForTier1: t1Need().some((x) => x.id === id), mergedInto: merged(id) ? (MERGERS.find((m) => m.id === id) || {}).into : undefined,
|
||||
about: text(n.blurb),
|
||||
you: {
|
||||
reachable: !!(R.reachable && R.reachable[id]), demandGbps: r1((R.demTo && R.demTo[id]) || 0),
|
||||
egressGbps: eg ? Object.fromEntries(Object.entries(eg).map(([k, v]) => [k, r1(v)])) : null,
|
||||
pnis: S.pni.filter((p) => p.net === id).map((p) => ({ id: p.id, city: cityName(p.city), port: pniPN(p), count: p.n || 1, ready: pniOn(p) })),
|
||||
exchangeSessions: Object.keys(S.ixp).filter((x) => ixSessions(x).has(id)).map(ixName),
|
||||
howToPeer: text(offTransitHint(id, S.home)),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const city = (q) => {
|
||||
const C = cityOf(q), c = C.id, P = S.pops[c];
|
||||
const cab = CABLE_PAIRS.filter((p) => p.a === c || p.b === c).map((p) => ({ cable: CAB[p.cid] ? CAB[p.cid].name : p.cid, to: cityName(p.a === c ? p.b : p.a), km: p.km }));
|
||||
const here = NETS.filter((n) => n.pops.includes(c) && !n.tail).sort((a, b) => b.share - a.share);
|
||||
return {
|
||||
id: c, name: C.name, country: C.cc, region: C.reg, about: C.note ? text(C.note) : undefined, dataCenter: C.dc,
|
||||
canBeHome: homeOk(c),
|
||||
exchanges: ixIdsIn(c).map((x) => ({ id: x, name: ixName(x), members: ixMembers(x).length, yourPort: S.ixp[x] !== undefined })),
|
||||
transit: NETS.filter((n) => sellsAt(n, c)).map((n) => ({ id: n.id, name: n.name, type: TYPE_L[n.type], perGbps: r1(transitPerG(n, c, false) * S.priceMul) })).sort((a, b) => a.perGbps - b.perGbps),
|
||||
networksHere: here.length, biggestNetworksHere: here.slice(0, 15).map((n) => n.name), cables: cab,
|
||||
you: P ? { demandGbps: r1((R.cityDem || {})[c] || 0), servedGbps: r1((R.citySrv || {})[c] || 0), routers: P.routers, down: P.down > S.day ? dateStr(P.down) : false,
|
||||
broadband: !!P.bb, links: S.links.filter((l) => l.a === c || l.b === c).length } : null,
|
||||
};
|
||||
};
|
||||
|
||||
const find = (q, kind) => {
|
||||
const n = norm(q), hit = (...k) => k.some((v) => norm(v).includes(n)), out = {};
|
||||
if (!n) fail('Give a word to search for.');
|
||||
if (!kind || kind === 'city') out.cities = CITIES.filter((c) => hit(c.id, c.name)).slice(0, 20).map((c) => ({ id: c.id, name: c.name, country: c.cc }));
|
||||
if (!kind || kind === 'network') out.networks = NETS.filter((x) => hit(x.id, x.name, String(x.asn))).slice(0, 20).map((x) => ({ id: x.id, name: x.name, asn: x.asn, type: TYPE_L[x.type] }));
|
||||
if (!kind || kind === 'cable') out.cables = Object.values(CAB).filter((x) => hit(x.id, x.name)).slice(0, 20).map((x) => ({ id: x.id, name: x.name, lands: [...new Set(x.pairs.flatMap((p) => [p[0], p[1]]))].map(cityName) }));
|
||||
if (!kind || kind === 'exchange') out.exchanges = allIx().filter((x) => hit(x, ixName(x))).slice(0, 20).map((x) => ({ id: x, name: ixName(x), city: cityName(ixCity(x)) }));
|
||||
return out;
|
||||
};
|
||||
|
||||
const trace = (from, to) => {
|
||||
const src = cityOf(from).id;
|
||||
if (!S.pops[src]) fail(`You have no POP in ${cityName(src)}. Yours: ${Object.keys(S.pops).map(cityName).join(', ')}.`);
|
||||
let target = null;
|
||||
if (typeof to === 'string' && /^city:/i.test(to)) target = { city: cityOf(to.slice(5)).id };
|
||||
else { try { target = { net: netOf(to).id }; } catch (e) { target = { city: cityOf(to).id }; } }
|
||||
if (target.city && !S.pops[target.city]) fail(`A traceroute to a city goes to one of your POPs: ${Object.keys(S.pops).map(cityName).join(', ')}.`);
|
||||
const r = traceroute(src, target);
|
||||
return { text: r.text, why: text(r.why || ''), asPath: r.asPath || null };
|
||||
};
|
||||
|
||||
const peering = (q, where, via) => {
|
||||
const n = netOf(q), id = n.id, out = [];
|
||||
if (!via || via === 'pni') for (const c of (where ? [cityOf(where).id] : Object.keys(S.pops).filter((c) => n.pops.includes(c)))) {
|
||||
const r = peerOk(id, 'pni', c);
|
||||
out.push({ via: 'pni', city: cityName(c), ok: !!r.ok, why: r.why ? text(r.why) : undefined, feePerMonth: r.fee, free: r.free, minimumPort: PORT[pniMin(id)].n });
|
||||
}
|
||||
if (!via || via === 'ix') for (const x of Object.keys(S.ixp).filter((x) => ixMembers(x).includes(id) && (!where || ixCity(x) === cityOf(where).id))) {
|
||||
const r = peerOk(id, 'ix', x);
|
||||
out.push({ via: 'ix', exchange: ixName(x), ok: !!r.ok, why: r.why ? text(r.why) : undefined, session: ixSessions(x).has(id) });
|
||||
}
|
||||
return { network: n.name, policy: n.pol, hint: text(offTransitHint(id, where ? cityOf(where).id : S.home)),
|
||||
checks: out, note: out.length ? undefined : 'No POP or exchange port of yours is where this network is. Build one first: see network.' };
|
||||
};
|
||||
|
||||
const hotSpots = (limit = 10) => {
|
||||
const top = (a) => a.sort((x, y) => y.util - x.util).slice(0, limit);
|
||||
const pct = (u, c) => (c > 0 ? r1((u / c) * 100) : null);
|
||||
const links = S.links.map((l) => { const cap = capOf(l), u = (R.load || {})[l.id] || 0; return { id: l.id, between: cityName(l.a) + ' – ' + cityName(l.b), kind: l.kind, capacity: capName(l), usedGbps: r1(u), util: pct(u, cap), down: linkDown(l) }; });
|
||||
const transit = S.transit.map((t) => { const cap = lagCap(PORT[t.tier].g, t.n), u = (R.useT || {})[t.id] || 0, q = (R.p95 && R.p95[t.id]) || u;
|
||||
return { id: t.id, city: cityName(t.city), carrier: NET[t.net].name, port: lagName(t.tier, t.n), usedGbps: r1(u), util: pct(u, cap), billPerMonth: Math.round(transitMo(t, q)) }; });
|
||||
const pnis = S.pni.filter(pniOn).map((p) => { const cap = pniG(p) * (p.n || 1), u = (R.usePni || {})[p.id] || 0; return { id: p.id, network: NET[p.net].name, city: cityName(p.city), port: pniPN(p), usedGbps: r1(u), util: pct(u, cap) }; });
|
||||
const viaTransit = NETS.filter((n) => R.netEg && R.netEg[n.id] && R.netEg[n.id].t > 0.05).sort((a, b) => R.netEg[b.id].t - R.netEg[a.id].t).slice(0, limit)
|
||||
.map((n) => ({ id: n.id, network: n.name, overTransitGbps: r1(R.netEg[n.id].t), howToPeer: text(offTransitHint(n.id, S.home)) }));
|
||||
const bill = {};
|
||||
for (const t of transit) bill[t.carrier] = (bill[t.carrier] || 0) + t.billPerMonth;
|
||||
return { links: top(links), transitPorts: top(transit), pnis: top(pnis), transitBillByCarrier: bill, biggestTrafficStillOnTransit: viaTransit };
|
||||
};
|
||||
|
||||
// ---------- doing things ----------
|
||||
// Actions the server never runs: files, storage slots, settings and the title screen are not the game's, and time
|
||||
// only moves through advance.
|
||||
const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed',
|
||||
'prefSet', 'pzShare', 'resetAsk', 'settings', 'settingsClose', 'share', 'shareDl', 'shareGo', 'slotBack', 'slotDel', 'slotDelGo', 'slotExport', 'slotMenu',
|
||||
'slotRetry', 'slotSpace', 'slotSwitch', 'slotTake', 'soundSet', 'speed', 'start', 'toTitle', 'traceCopy', 'updateLater', 'updateNow', 'vpSet', 'wsShare']);
|
||||
const run = (name, args) => {
|
||||
if (DENY.has(name)) fail(`${name} is not available here${name === 'speed' ? ': use advance to move time' : name === 'start' || name === 'newgame' ? ': use new_game' : ''}.`);
|
||||
const fn = ACT[name];
|
||||
if (typeof fn !== 'function') fail(`There is no action "${name}". See the actions list.`);
|
||||
takeToasts();
|
||||
const cash = S.cash;
|
||||
fn(args && typeof args === 'object' ? args : {});
|
||||
return { toasts: takeToasts(), cashChange: Math.round(S.cash - cash), screen: screen() };
|
||||
};
|
||||
const click = (n) => {
|
||||
const b = last[n];
|
||||
if (!b) fail(`No button ${n} on the last screen. Call screen first.`);
|
||||
if (b.disabled) fail(`"${b.label}" is greyed out.`);
|
||||
return { clicked: b.label, ...run(b.act, b.args) };
|
||||
};
|
||||
const panel = ({ city: c, link, network: q, tab }) => {
|
||||
if (c) UI.sel = { type: 'city', id: cityOf(c).id };
|
||||
else if (link) { if (!S.links.some((l) => l.id === link)) fail(`No link ${link}. See status or hot_spots for link ids.`); UI.sel = { type: 'link', id: link }; }
|
||||
else if (q) ACT.netFocus({ id: netOf(q).id });
|
||||
if (tab) UI.tab = tab;
|
||||
renderAll();
|
||||
return screen(q ? 'left' : 'panel');
|
||||
};
|
||||
const openLink = (a, b) => {
|
||||
const x = cityOf(a).id, y = cityOf(b).id;
|
||||
if (!S.pops[x]) fail(`A link starts at one of your POPs: ${Object.keys(S.pops).map(cityName).join(', ')}.`);
|
||||
takeToasts();
|
||||
openLinkModal(x, y);
|
||||
return { toasts: takeToasts(), screen: screen() };
|
||||
};
|
||||
const actions = () => Object.keys(ACT).filter((k) => !DENY.has(k)).sort();
|
||||
|
||||
// ---------- time ----------
|
||||
const advance = (days = 1) => {
|
||||
days = Math.max(1, Math.min(3650, Math.floor(+days) || 1));
|
||||
if (!$('modal').hidden) fail('A window is open. Answer it first (screen, click), the game does not run days behind it.');
|
||||
const start = S.day, cash = S.cash, inc0 = new Set(S.inc.map((i) => i.id)), times = [];
|
||||
takeToasts();
|
||||
let ran = 0, stop = null;
|
||||
while (ran < days) {
|
||||
if (S.lost) { stop = 'bankrupt'; break; }
|
||||
const t = performance.now();
|
||||
dayTick();
|
||||
times.push({ day: S.day, ms: r1(performance.now() - t) });
|
||||
ran++;
|
||||
if (!$('modal').hidden) { stop = 'a window opened'; break; }
|
||||
}
|
||||
renderAll();
|
||||
// The log keeps what mattered; toasts that only repeat a log line are left out.
|
||||
const entries = (S.log || []).filter((e) => e.d > start).slice(-60), logged = entries.map((e) => norm(text(e.t, 400)));
|
||||
const log = entries.map((e) => `${dateStr(e.d)}: ${text(e.t, 400)}`);
|
||||
const total = times.reduce((a, x) => a + x.ms, 0);
|
||||
return {
|
||||
from: dateStr(start), to: dateStr(S.day), daysRun: ran, stoppedBecause: stop, cash: Math.round(S.cash), cashChange: Math.round(S.cash - cash),
|
||||
newIncidents: S.inc.filter((i) => !inc0.has(i.id)).map(incText),
|
||||
log, toasts: [...new Set(takeToasts())].filter((t) => { const f = norm(t.replace(/^\w+: /, '').split('\n')[0]); return !logged.some((l) => l.startsWith(f)); }).slice(-40),
|
||||
timing: { totalMs: r1(total), perDayMs: r1(total / (ran || 1)), slowestDays: times.slice().sort((a, b) => b.ms - a.ms).slice(0, 5).map((x) => ({ date: dateStr(x.day), ms: x.ms })) },
|
||||
screen: stop === 'a window opened' ? screen() : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
window.__mcp = { newGame, loadSave, exportSave, status, network, city, find, trace, peering, hotSpots, run, click, panel, openLink, actions, advance, screen };
|
||||
})();
|
||||
70
scripts/mcp.js
Normal file
70
scripts/mcp.js
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
#!/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:
|
||||
//
|
||||
// claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
|
||||
//
|
||||
// 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');
|
||||
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. Change things with act (see actions), 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 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 } });
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { handle, TOOLS };
|
||||
164
tests/mcp.test.js
Normal file
164
tests/mcp.test.js
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
// The MCP server (scripts/mcp.js): an AI client plays, inspects and debugs the game through typed tools.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
const { createSession, TOOLS } = require('../scripts/lib/mcp-game');
|
||||
|
||||
const tools = (s) => (name, args = {}) => TOOLS.find((t) => t.name === name).run(s, args);
|
||||
|
||||
test('speaks MCP over stdio: initialize, list tools, call one, and errors as errors', async () => {
|
||||
const child = spawn(process.execPath, [path.join(__dirname, '..', 'scripts', 'mcp.js')], { stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
const lines = [];
|
||||
let buf = '';
|
||||
const waiters = [];
|
||||
child.stdout.on('data', (d) => { buf += d; let i; while ((i = buf.indexOf('\n')) >= 0) { lines.push(JSON.parse(buf.slice(0, i))); buf = buf.slice(i + 1); waiters.splice(0).forEach((w) => w()); } });
|
||||
const ask = async (msg) => {
|
||||
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...msg }) + '\n');
|
||||
if (msg.id === undefined) return null;
|
||||
const found = () => lines.find((l) => l.id === msg.id);
|
||||
while (!found()) await new Promise((r) => waiters.push(r));
|
||||
return found();
|
||||
};
|
||||
try {
|
||||
const init = await ask({ id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } } });
|
||||
assert.equal(init.result.protocolVersion, '2025-06-18');
|
||||
assert.equal(init.result.serverInfo.name, 'seriesoftubes');
|
||||
assert.ok(init.result.capabilities.tools);
|
||||
assert.equal((await ask({ id: 9, method: 'initialize', params: { protocolVersion: '1999-01-01' } })).result.protocolVersion, '2025-11-25', 'an unknown version gets the newest');
|
||||
await ask({ method: 'notifications/initialized' });
|
||||
const list = await ask({ id: 2, method: 'tools/list' });
|
||||
const names = list.result.tools.map((t) => t.name);
|
||||
for (const n of ['new_game', 'load_save', 'export_save', 'status', 'advance', 'network', 'city', 'find', 'traceroute', 'peering_check', 'hot_spots', 'actions', 'act', 'screen', 'panel', 'click', 'open_link']) assert.ok(names.includes(n), n);
|
||||
assert.ok(list.result.tools.every((t) => t.description && t.inputSchema && t.inputSchema.type === 'object'));
|
||||
const st = await ask({ id: 3, method: 'tools/call', params: { name: 'status', arguments: {} } });
|
||||
assert.equal(st.result.isError, undefined);
|
||||
assert.equal(JSON.parse(st.result.content[0].text).home, 'Frankfurt', 'a game is loaded from the start');
|
||||
const bad = await ask({ id: 4, method: 'tools/call', params: { name: 'network', arguments: { network: 'no such thing at all' } } });
|
||||
assert.equal(bad.result.isError, true);
|
||||
assert.match(bad.result.content[0].text, /No network matches/);
|
||||
assert.equal((await ask({ id: 5, method: 'tools/call', params: { name: 'nope' } })).error.code, -32602);
|
||||
assert.equal((await ask({ id: 6, method: 'resources/list' })).error.code, -32601);
|
||||
assert.equal(lines.filter((l) => l.id === undefined).length, 0, 'notifications get no answer');
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
|
||||
test('plays like a player: buy, answer the quote by its button, and run time forward', () => {
|
||||
const s = createSession(), T = tools(s);
|
||||
T('new_game', { city: 'fra', name: 'Test Tubes', seed: 7 });
|
||||
T('act', { action: 'launchBB', args: { city: 'fra' } });
|
||||
const tr = T('act', { action: 'buyTransit', args: { city: 'fra', net: 'cog', tier: 1 } });
|
||||
assert.ok(tr.toasts.some((t) => /Cogentle transit is live/.test(t)));
|
||||
const ix = T('act', { action: 'buyIx', args: { city: 'fra', tier: 1 } });
|
||||
assert.equal(ix.screen.where, 'modal', 'the DE-KICKS quote opens');
|
||||
const sign = ix.screen.buttons.find((b) => b.act === 'dkAccept');
|
||||
assert.ok(sign, 'with a Sign button');
|
||||
assert.throws(() => T('advance', { days: 1 }), /window is open/, 'no days pass behind an open window');
|
||||
const signed = T('click', { button: sign.n });
|
||||
assert.ok(signed.toasts.some((t) => /Port up at DE-KICKS/.test(t)));
|
||||
assert.equal(T('city', { city: 'fra' }).exchanges.find((x) => x.id === 'fra').yourPort, true);
|
||||
const a = T('advance', { days: 30 });
|
||||
assert.equal(a.daysRun, 30);
|
||||
assert.equal(T('status').day, 30);
|
||||
assert.ok(a.log.length > 0 && a.timing.totalMs > 0);
|
||||
// links go through the game's own build window
|
||||
const w = T('open_link', { from: 'fra', to: 'Amsterdam' });
|
||||
const b100 = w.screen.buttons.find((b) => b.act === 'buildLink' && b.args.tier === 1);
|
||||
T('click', { button: b100.n });
|
||||
assert.ok(T('status').pops.includes('Amsterdam'));
|
||||
assert.deepEqual(s.errors(), []);
|
||||
});
|
||||
|
||||
test('the same seed and the same moves give the same game', () => {
|
||||
const run = () => {
|
||||
const s = createSession(), T = tools(s);
|
||||
T('new_game', { city: 'sin', seed: 42, name: 'Twin' });
|
||||
T('act', { action: 'launchBB', args: { city: 'sin' } });
|
||||
T('act', { action: 'buyTransit', args: { city: 'sin', net: 'ntt', tier: 1 } });
|
||||
T('advance', { days: 90 });
|
||||
const st = T('status');
|
||||
return [st.cash, st.traffic.servedGbps, st.incidents.length];
|
||||
};
|
||||
assert.deepEqual(run(), run());
|
||||
});
|
||||
|
||||
test('reads the world and the network: networks, cities, search, traceroute, peering and hot spots', () => {
|
||||
const s = createSession(), T = tools(s);
|
||||
T('act', { action: 'launchBB', args: { city: 'fra' } });
|
||||
T('act', { action: 'buyTransit', args: { city: 'fra', net: 'cog', tier: 1 } });
|
||||
const dt = T('network', { network: 'Doitsche' });
|
||||
assert.equal(dt.type, 'Tier 1');
|
||||
assert.equal(dt.neededForTier1, true);
|
||||
assert.match(dt.you.howToPeer, /Paid peering only/);
|
||||
assert.equal(T('network', { network: '3203' }).id, 'dtk', 'by ASN too');
|
||||
const ams = T('city', { city: 'Amsterdam' });
|
||||
assert.ok(ams.exchanges.length >= 2 && ams.transit.length > 3);
|
||||
assert.deepEqual(ams.transit.map((x) => x.perGbps), ams.transit.map((x) => x.perGbps).slice().sort((x, y) => x - y), 'cheapest transit first');
|
||||
assert.ok(T('find', { query: 'marea' }).cables.length >= 1);
|
||||
assert.ok(T('find', { query: 'kicks', kind: 'exchange' }).exchanges.some((x) => x.id === 'fra'));
|
||||
const t = T('traceroute', { from: 'Frankfurt', to: 'ggl' });
|
||||
assert.match(t.text, /traceroute to www\.goggle/);
|
||||
assert.equal(t.asPath[1], 714, 'out through Cogentle');
|
||||
assert.throws(() => T('traceroute', { from: 'Tokyo', to: 'ggl' }), /no POP in Tokyo/);
|
||||
const p = T('peering_check', { network: 'nfx' });
|
||||
assert.ok(p.checks.some((c) => c.via === 'pni' && c.ok === false && /Gbps/.test(c.why)));
|
||||
const h = T('hot_spots', { limit: 3 });
|
||||
assert.equal(h.transitPorts[0].carrier, 'Cogentle');
|
||||
assert.ok(h.biggestTrafficStillOnTransit.length > 0);
|
||||
const st = T('status');
|
||||
assert.match(st.whyNotTier1, /you buy transit/);
|
||||
assert.ok(st.monthly.costBy.transit > 0);
|
||||
assert.deepEqual(s.errors(), []);
|
||||
});
|
||||
|
||||
test('panels and the network list read as text with buttons', () => {
|
||||
const s = createSession(), T = tools(s);
|
||||
const p = T('panel', { city: 'fra', tab: 'peer' });
|
||||
assert.equal(p.where, 'panel');
|
||||
assert.match(p.text, /DE-KICKS/);
|
||||
assert.ok(p.buttons.some((b) => b.act === 'tab'));
|
||||
const l = T('panel', { network: 'ggl' });
|
||||
assert.equal(l.where, 'network list');
|
||||
assert.match(l.text, /Goggle/);
|
||||
assert.deepEqual(s.errors(), []);
|
||||
});
|
||||
|
||||
test('saves go out and come back, and a bug report save loads as the game loads it', () => {
|
||||
const s = createSession(), T = tools(s);
|
||||
T('act', { action: 'launchBB', args: { city: 'fra' } });
|
||||
T('advance', { days: 12 });
|
||||
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mcp-')), 'save.json');
|
||||
const out = T('export_save', { path: file });
|
||||
assert.ok(out.bytes > 1000);
|
||||
const j = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
assert.equal(j.app, 'series-of-tubes');
|
||||
assert.match(j.version, /^\d+\.\d+\.\d+$/, 'stamped with the version, like a real export');
|
||||
const cash = T('status').cash;
|
||||
T('new_game', { city: 'nyc' });
|
||||
const back = T('load_save', { path: file });
|
||||
assert.equal(back.day, 12);
|
||||
assert.equal(back.cash, cash);
|
||||
assert.throws(() => T('load_save', { json: '{"nope":1}' }), /does not look like/);
|
||||
assert.throws(() => T('load_save', {}), /either path or json/);
|
||||
// the big benchmark network, as a stand-in for a player's late-game save
|
||||
const big = T('load_save', { path: path.join(__dirname, 'fixtures', 'big-network.json') });
|
||||
assert.equal(big.name, 'Shinternet');
|
||||
assert.ok(T('hot_spots', { limit: 2 }).transitPorts.length === 2);
|
||||
assert.deepEqual(s.errors(), []);
|
||||
});
|
||||
|
||||
test('only game actions: files, slots, settings and the clock stay out of reach', () => {
|
||||
const s = createSession(), T = tools(s);
|
||||
const acts = T('actions');
|
||||
assert.ok(acts.includes('buyTransit(city,net,tier)'), 'with their arguments');
|
||||
assert.ok(acts.includes('pni(city,net,tier)'));
|
||||
for (const no of ['slotDel', 'exportSave', 'importPick', 'langSet', 'speed', 'resetAsk']) assert.ok(!acts.some((a) => a.split('(')[0] === no), no);
|
||||
assert.throws(() => T('act', { action: 'slotDelGo' }), /not available/);
|
||||
assert.throws(() => T('act', { action: 'speed', args: { s: 4 } }), /use advance/);
|
||||
assert.throws(() => T('act', { action: 'noSuchThing' }), /no action/);
|
||||
assert.throws(() => T('click', { button: 99 }), /No button 99/);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue