@mavonengine/cli 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -157,7 +157,7 @@ npx @mavonengine/cli dashboard --sim
157
157
  | `--transparent` | | Let a transparent terminal background show through. Text can be hard to read over a light wallpaper |
158
158
  | `--sim` | | Simulated data instead of a server |
159
159
 
160
- Keys: `q` quits, `r` refreshes now, `o` opens the game the server serves in the browser, `1`–`7` switch between the Overview, Players, Logs, HTTP, Network, Routes and Plugins tabs. The mouse wheel scrolls the players table, the logs, the requests, the packets and the routes; scroll the logs back to the bottom, or the requests and packets back to the top, to follow new ones again.
160
+ Keys: `q` quits, `r` refreshes now, `o` opens the game the server serves in the browser, `1`–`7` switch between the Overview, Players, Logs, HTTP, Network, Routes and Plugins tabs, and `8` to the Database tab when the server has a database plugin. The mouse wheel scrolls the players table, the logs, the requests, the packets and the routes; scroll the logs back to the bottom, or the requests and packets back to the top, to follow new ones again.
161
161
 
162
162
  The HTTP tab lists every request the game server's HTTP server received, newest first: the client (static files or Vite in dev), your own `onHttp` routes, the geckos.io signaling requests and WebSocket upgrades such as Vite's HMR socket, each with status, duration, size and client address. Query strings are left out since they can hold tokens, and the dashboard's own polling is not recorded. The game traffic itself is WebRTC, not HTTP, so it shows on the Players tab instead; with a separate `socketPort` the signaling requests go to that port and don't show up either.
163
163
 
@@ -169,6 +169,8 @@ The Plugins tab lists the plugins in the project's `mavonengine.json` with their
169
169
 
170
170
  Below it, "Available to install" lists the plugins from [`mavonengine plugins`](#mavonengine-plugins) that the project doesn't have yet. The dashboard reads that list from GitHub itself, the first time the tab is shown and again on `r`; a dashboard that never opens the tab never asks for it.
171
171
 
172
+ The Database tab looks into the server's database. It only shows up when the server runs a database plugin such as [`@mavonengine/sqlite`](https://github.com/MavonEngine/Core/tree/main/packages/plugins/sqlite), which it marks in `GET /api/game/plugins`. It lists the tables with the plugin each belongs to (by its table prefix, `game` for the rest) and their number of rows, shows the rows of the selected table and, below, the migrations each plugin ran. `↑`/`↓` (or `j`/`k`, or a click) pick a table, `←`/`→` (or page up / page down) page through its rows. It only reads, and only while the tab shows, every 5 seconds. The database holds what players did, so the server only shows it with its admin token: start the dashboard with `--token <admin token>` for a server that has one; without one it only answers on the server's own machine. It needs a server on a `@mavonengine/core` release with `GET /api/game/database`.
173
+
172
174
  Under [`mavonengine dev`](#mavonengine-dev) a plugin from that list can be installed right there: select it with `↓` and press `i`. The dashboard first asks whether you checked its source, because installing a package runs its code on your machine; `y` installs it with the project's package manager, adds it to `mavonengine.json` and restarts the dev servers, `n` cancels. A dashboard started on its own with `mavonengine dashboard` only shows the command, since it can't restart servers it didn't start.
173
175
 
174
176
  ### Server access
@@ -263,6 +265,15 @@ Plugin tools:
263
265
 
264
266
  With these an assistant can suggest a plugin instead of building what one already does, and set it up from its readme. It can't install one: every tool is read-only, so it hands you the command. `available_plugins` and `plugin_readme` read the list and the readmes from GitHub when they are used; `--plugins-url` or `MAVONENGINE_PLUGINS_URL` points them at another list and `--no-plugin-list` leaves them out.
265
267
 
268
+ Database tools, for the project's database plugin such as [`@mavonengine/sqlite`](https://github.com/MavonEngine/Core/tree/main/packages/plugins/sqlite):
269
+
270
+ | Tool | |
271
+ | --- | --- |
272
+ | `database_overview` | Which plugin gives the database, every table with the plugin it belongs to, its columns and row count, and the migrations each plugin ran |
273
+ | `database_rows` | A page of one table's rows, with the total |
274
+
275
+ They read through the server's `GET /api/game/database` endpoints, so they work with any database plugin and only read. Like the dashboard's Database tab they need the server's [admin token](#admin-token) as `--token`, unless the server runs on the same machine without one. What a tool returns goes to the assistant's model, so `database_rows` replaces the values of columns that look secret, such as password and session token hashes, with `[redacted]` and lists them in `redacted`.
276
+
266
277
  Documentation tools, passed through to the MCP server of [mavonengine.com](https://mavonengine.com) (`https://mavonengine.com/mcp`), so answers come from the current docs:
267
278
 
268
279
  | Tool | |
@@ -367,6 +378,42 @@ export default defineServerPlugin({
367
378
 
368
379
  A plugin that takes the token some other way, such as the password of a login, checks it with `ctx.adminToken.matches(candidate)`, without ever seeing the token.
369
380
 
381
+ ### Authenticating players
382
+
383
+ An auth plugin decides who may connect, before a client gets a player. [`@mavonengine/auth`](https://github.com/MavonEngine/Core/tree/main/packages/plugins/auth) is one, with accounts, passwords and sessions; write your own for anything else. Its client entry gives the token the game connects with, and its server entry's `authorize()` checks it:
384
+
385
+ ```ts
386
+ // client.ts: sent as the Authorization header of the connection request
387
+ export default defineClientPlugin({
388
+ authorization: () => {
389
+ const token = localStorage.getItem('session')
390
+ return token ? `Bearer ${token}` : undefined
391
+ },
392
+ })
393
+ ```
394
+
395
+ ```ts
396
+ // server.ts
397
+ export default defineServerPlugin({
398
+ async authorize(authorization, request, ctx) {
399
+ const account = await findSession(ctx.db, authorization)
400
+ if (!account)
401
+ return false // 401
402
+ if (account.banned)
403
+ return 403
404
+ return { id: account.id, name: account.username }
405
+ },
406
+ })
407
+ ```
408
+
409
+ `authorize()` returns an identity (`{ id, name?, … }`) to let the client in as that account, `true` to let it in without one (a guest), or `false` or an HTTP status from 400 to 599 to turn it away. The identity is also sent to the client, so keep it to what the player may see. A throw or any other result turns that one client away with 500, and the next client is still asked.
410
+
411
+ Other plugins read the identity with `ctx.identity(channel)`, and the game with `player.identity` on the server or `network.identity` on the client. Key anything that should outlast a connection, such as a mute or a score, on `identity.id`: `channel.id` changes every time the player reconnects.
412
+
413
+ On the client, a refusal arrives as the `connectError` event of the `NetworkManager` (and its `onConnectError()`), with the `status` the server answered. The token is read when a `NetworkManager` is made, so to connect again after logging in, make a new one. A game that handles the token itself passes `authorization` to the `NetworkManager` instead.
414
+
415
+ Only one auth plugin is asked: with more than one enabled, set `"auth": "<package>"` in mavonengine.json. When the project has an auth plugin that doesn't run, for example because one of its migrations failed or the package named in `auth` isn't enabled, the server turns every client away with 503 instead of letting them in unchecked. The editor connects like a client too, so with an auth plugin it needs a token as well: when the server turns it away, the editor's status bar and Network panel say why. A server in production (`NODE_ENV=production`) ignores clients that ask to attach the editor, since the editor is sent every entity in the world.
416
+
370
417
  Projects made with `mavonengine create` are already set up for plugins. To set up an existing project:
371
418
 
372
419
  ```ts
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  DEFAULT_DOCS_URL,
4
4
  version
5
- } from "./chunk-TGGH7KA4.js";
5
+ } from "./chunk-WOOU36T7.js";
6
6
 
7
7
  // src/mcp/docs.ts
8
8
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // package.json
4
- var version = "0.0.4";
4
+ var version = "0.0.5";
5
5
 
6
6
  // src/mcp/config.ts
7
7
  import { existsSync, readFileSync, writeFileSync } from "fs";
@@ -2,10 +2,10 @@
2
2
  import {
3
3
  DocsClient,
4
4
  registerDocsTools
5
- } from "./chunk-KHC2RAKX.js";
5
+ } from "./chunk-WDETVETJ.js";
6
6
  import {
7
7
  DEFAULT_DOCS_URL
8
- } from "./chunk-TGGH7KA4.js";
8
+ } from "./chunk-WOOU36T7.js";
9
9
  export {
10
10
  DEFAULT_DOCS_URL,
11
11
  DocsClient,
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  MCP_CONFIG_FILE,
12
12
  version,
13
13
  writeMcpConfig
14
- } from "./chunk-TGGH7KA4.js";
14
+ } from "./chunk-WOOU36T7.js";
15
15
 
16
16
  // src/index.ts
17
17
  import process11 from "process";
@@ -287,6 +287,11 @@ function tickSample(t) {
287
287
  maxCommandsPerTick: num(t.maxCommandsPerTick)
288
288
  };
289
289
  }
290
+ function accountFrom(value) {
291
+ if (!isRecord(value) || typeof value.id !== "string" || !value.id)
292
+ return null;
293
+ return { id: value.id, name: strOrNull(value.name), guest: value.guest === true };
294
+ }
290
295
  function normalizeSnapshot(raw) {
291
296
  const s = section(raw);
292
297
  const world = section(s.world);
@@ -320,7 +325,9 @@ function normalizeSnapshot(raw) {
320
325
  rttMs: numOrNull(connection.rttMs),
321
326
  bytesSent: num(connection.bytesSent),
322
327
  bytesReceived: num(connection.bytesReceived)
323
- } : null
328
+ } : null,
329
+ // Older servers, and servers without an auth plugin, have none
330
+ account: accountFrom(p.account)
324
331
  };
325
332
  }),
326
333
  world: {
@@ -412,7 +419,8 @@ function normalizeSync(raw) {
412
419
  displayName: str(p.displayName, str(p.id)),
413
420
  tracked: Array.isArray(p.tracked) ? p.tracked.length : 0,
414
421
  ack: num(p.ack),
415
- lastState: lastState && { tick: num(lastState.tick), bytes: num(lastState.bytes), entities: num(lastState.entities) }
422
+ lastState: lastState && { tick: num(lastState.tick), bytes: num(lastState.bytes), entities: num(lastState.entities) },
423
+ account: accountFrom(p.account)
416
424
  };
417
425
  });
418
426
  const entities = arr(r.entities, (e) => ({ player: e.player === true, trackedBy: num(e.trackedBy) }));
@@ -473,6 +481,7 @@ function normalizePlugins(raw) {
473
481
  enabled: p.enabled !== false,
474
482
  installed: p.installed !== false,
475
483
  runningOnServer: p.runningOnServer === true,
484
+ ...p.database === true ? { database: true } : {},
476
485
  declaredPrefabs: strings(p.declaredPrefabs),
477
486
  usedPrefabs: strings(p.usedPrefabs),
478
487
  ...target ? { target } : {},
@@ -480,11 +489,52 @@ function normalizePlugins(raw) {
480
489
  };
481
490
  });
482
491
  }
492
+ function columns(value) {
493
+ return arr(value, (c) => ({
494
+ name: str(c.name, "?"),
495
+ type: str(c.type),
496
+ nullable: c.nullable !== false,
497
+ autoIncrement: c.autoIncrement === true,
498
+ hasDefault: c.hasDefault === true
499
+ }));
500
+ }
501
+ function normalizeDatabase(raw) {
502
+ const data = section(raw);
503
+ return {
504
+ provider: strOrNull(data.provider),
505
+ tables: arr(data.tables, (t) => ({ name: str(t.name, "?"), plugin: strOrNull(t.plugin), rows: numOrNull(t.rows), columns: columns(t.columns) })),
506
+ migrations: arr(data.migrations, (m) => ({
507
+ plugin: strOrNull(m.plugin),
508
+ table: str(m.table, "?"),
509
+ applied: arr(m.applied, (a) => ({ name: str(a.name, "?"), executedAt: strOrNull(a.executedAt) }))
510
+ }))
511
+ };
512
+ }
513
+ function normalizeTablePage(raw) {
514
+ const data = section(raw);
515
+ const rows = arr(data.rows, (row) => row);
516
+ return {
517
+ table: str(data.table, "?"),
518
+ columns: columns(data.columns),
519
+ rows,
520
+ total: num(data.total, rows.length),
521
+ offset: num(data.offset),
522
+ limit: num(data.limit, rows.length)
523
+ };
524
+ }
483
525
 
484
526
  // src/dashboard/MetricsClient.ts
485
527
  var MAX_LOG_LINES = 1e3;
486
528
  var MAX_REQUEST_LINES = 1e3;
487
529
  var MAX_PACKET_LINES = 2e3;
530
+ var TABLE_PAGE_ROWS = 50;
531
+ function tableError(err) {
532
+ if (err instanceof MetricsSourceError && err.status === "unauthorized")
533
+ return "The database needs the server's admin token: start the dashboard with --token <admin token>";
534
+ if (err instanceof MetricsSourceError && err.status === "forbidden")
535
+ return "The database is only shown on the server's own machine unless the server has an admin token";
536
+ return err.message;
537
+ }
488
538
  var MetricsSourceError = class extends Error {
489
539
  constructor(message, status) {
490
540
  super(message);
@@ -500,6 +550,7 @@ function httpSource({ url, token, timeoutMs = 3e3, fetch = globalThis.fetch }) {
500
550
  const syncUrl = new URL("dev/net/sync", url);
501
551
  const routesUrl = new URL("routes", url);
502
552
  const pluginsUrl = new URL("plugins", url);
553
+ const databaseUrl = new URL("database", url);
503
554
  async function request(target) {
504
555
  let res;
505
556
  try {
@@ -538,7 +589,14 @@ function httpSource({ url, token, timeoutMs = 3e3, fetch = globalThis.fetch }) {
538
589
  fetchSync: () => request(syncUrl.toString()),
539
590
  fetchPacket: (id) => request(new URL(`dev/net/packets/${id}`, url).toString()),
540
591
  fetchRoutes: () => request(routesUrl.toString()),
541
- fetchPlugins: () => request(pluginsUrl.toString())
592
+ fetchPlugins: () => request(pluginsUrl.toString()),
593
+ fetchDatabase: () => request(databaseUrl.toString()),
594
+ fetchTable: (name, offset, limit) => {
595
+ const tableUrl = new URL(`database/tables/${encodeURIComponent(name)}`, url);
596
+ tableUrl.searchParams.set("offset", String(offset));
597
+ tableUrl.searchParams.set("limit", String(limit));
598
+ return request(tableUrl.toString());
599
+ }
542
600
  };
543
601
  }
544
602
  var Feed = class {
@@ -605,7 +663,11 @@ var MetricsClient = class {
605
663
  routes: [],
606
664
  routesAvailable: source.fetchRoutes ? null : false,
607
665
  plugins: [],
608
- pluginsAvailable: source.fetchPlugins ? null : false
666
+ pluginsAvailable: source.fetchPlugins ? null : false,
667
+ database: null,
668
+ databaseAvailable: source.fetchDatabase ? null : false,
669
+ databaseError: null,
670
+ tableDetail: null
609
671
  };
610
672
  }
611
673
  source;
@@ -625,9 +687,42 @@ var MetricsClient = class {
625
687
  * so the dashboard only turns it on while its Network tab is shown.
626
688
  */
627
689
  watchNetwork = false;
690
+ /** Follow the database too. Off by default, as counting every table's rows isn't free: only while the Database tab is shown */
691
+ watchDatabase = false;
692
+ databaseFetchedAt = null;
628
693
  routesIntervalMs;
629
694
  /** Date.now() the endpoints and plugins were last fetched, null to fetch them with the next poll */
630
695
  projectFetchedAt = null;
696
+ /**
697
+ * Load a page of a table's rows into `state.tableDetail`, or close it with null.
698
+ */
699
+ async inspectTable(table, offset = 0, limit = TABLE_PAGE_ROWS) {
700
+ if (table === null) {
701
+ this.state.tableDetail = null;
702
+ this.notify();
703
+ return;
704
+ }
705
+ const previous = this.state.tableDetail?.table === table ? this.state.tableDetail.page : void 0;
706
+ if (!this.source.fetchTable) {
707
+ this.state.tableDetail = { table, offset, status: "error", error: "This source does not serve database tables" };
708
+ this.notify();
709
+ return;
710
+ }
711
+ this.state.tableDetail = { table, offset, status: "loading", page: previous };
712
+ this.notify();
713
+ let detail;
714
+ try {
715
+ detail = { table, offset, status: "ready", page: normalizeTablePage(await this.source.fetchTable(table, offset, limit)) };
716
+ } catch (err) {
717
+ const gone = err instanceof MetricsSourceError && err.status === "disabled";
718
+ detail = { table, offset, status: "error", page: previous, error: gone ? `The database has no table ${table} (any more)` : tableError(err) };
719
+ }
720
+ const current = this.state.tableDetail;
721
+ if (current?.table !== table || current.offset !== offset)
722
+ return;
723
+ this.state.tableDetail = detail;
724
+ this.notify();
725
+ }
631
726
  /**
632
727
  * Load the content of one packet into `state.packetDetail`, or close it with null.
633
728
  */
@@ -682,6 +777,7 @@ var MetricsClient = class {
682
777
  clearTimeout(this.timer);
683
778
  this.timer = null;
684
779
  this.projectFetchedAt = null;
780
+ this.databaseFetchedAt = null;
685
781
  await this.loop();
686
782
  }
687
783
  /**
@@ -705,6 +801,8 @@ var MetricsClient = class {
705
801
  this.state.packets = this.packets.entries;
706
802
  this.state.packetsAvailable = this.packets.available;
707
803
  }
804
+ if (this.watchDatabase)
805
+ await this.pollDatabase();
708
806
  } catch (err) {
709
807
  this.state.status = err instanceof MetricsSourceError ? err.status : "unreachable";
710
808
  this.state.error = err.message;
@@ -724,6 +822,35 @@ var MetricsClient = class {
724
822
  }
725
823
  }
726
824
  }
825
+ /**
826
+ * Fetch the database's tables, and the rows that are open again, unless they were fetched a moment ago.
827
+ * Its own errors stay its own: a dashboard without the admin token still shows everything else.
828
+ */
829
+ async pollDatabase(now = Date.now()) {
830
+ const { source, state } = this;
831
+ if (!source.fetchDatabase || state.databaseAvailable === false)
832
+ return;
833
+ if (this.databaseFetchedAt !== null && now - this.databaseFetchedAt < this.routesIntervalMs)
834
+ return;
835
+ try {
836
+ state.database = normalizeDatabase(await source.fetchDatabase());
837
+ state.databaseAvailable = true;
838
+ state.databaseError = null;
839
+ this.databaseFetchedAt = now;
840
+ } catch (err) {
841
+ if (err instanceof MetricsSourceError && err.status === "disabled") {
842
+ state.databaseAvailable = false;
843
+ return;
844
+ }
845
+ state.databaseError = tableError(err);
846
+ if (err instanceof MetricsSourceError && (err.status === "unauthorized" || err.status === "forbidden"))
847
+ this.databaseFetchedAt = now;
848
+ return;
849
+ }
850
+ const open = state.tableDetail;
851
+ if (open)
852
+ void this.inspectTable(open.table, open.offset);
853
+ }
727
854
  /**
728
855
  * Fetch the server's HTTP endpoints and plugins, unless they were fetched a moment ago
729
856
  */
@@ -813,7 +940,48 @@ var SIMULATED_PLUGINS = [
813
940
  declaredPrefabs: ["Tree", "Rock"],
814
941
  usedPrefabs: ["Tree"]
815
942
  },
816
- { package: "chat", enabled: false, installed: true, runningOnServer: false, version: "1.0.0", target: "both", declaredPrefabs: [], usedPrefabs: [] }
943
+ { package: "chat", enabled: false, installed: true, runningOnServer: false, version: "1.0.0", target: "both", declaredPrefabs: [], usedPrefabs: [] },
944
+ {
945
+ package: "@mavonengine/sqlite",
946
+ enabled: true,
947
+ installed: true,
948
+ runningOnServer: true,
949
+ database: true,
950
+ version: "0.0.1",
951
+ description: "A SQLite database for the game server and its plugins, on Node's built-in node:sqlite",
952
+ license: "MIT",
953
+ target: "server",
954
+ engine: ">=0.0.24",
955
+ declaredPrefabs: [],
956
+ usedPrefabs: []
957
+ }
958
+ ];
959
+ var SIMULATED_TABLES = [
960
+ {
961
+ name: "chat_messages",
962
+ plugin: "@mavonengine/chat",
963
+ columns: [
964
+ { name: "id", type: "INTEGER", nullable: false, autoIncrement: true, hasDefault: false },
965
+ { name: "player", type: "TEXT", nullable: false, autoIncrement: false, hasDefault: false },
966
+ { name: "text", type: "TEXT", nullable: false, autoIncrement: false, hasDefault: false },
967
+ { name: "sent_at", type: "TEXT", nullable: false, autoIncrement: false, hasDefault: false }
968
+ ],
969
+ rows: Array.from({ length: 137 }, (_, i) => ({ id: i + 1, player: `sim-0${i % 3 + 1}`, text: ["gg", "anyone near the tower?", "brb"][i % 3], sent_at: new Date(Date.UTC(2026, 10, 14, 12, 0, i * 7)).toISOString() }))
970
+ },
971
+ {
972
+ name: "game_scores",
973
+ plugin: null,
974
+ columns: [
975
+ { name: "player", type: "TEXT", nullable: false, autoIncrement: false, hasDefault: false },
976
+ { name: "score", type: "INTEGER", nullable: false, autoIncrement: false, hasDefault: true },
977
+ { name: "guild", type: "TEXT", nullable: true, autoIncrement: false, hasDefault: false }
978
+ ],
979
+ rows: [
980
+ { player: "sim-01", score: 1200, guild: "Wolves" },
981
+ { player: "sim-02", score: 950, guild: null },
982
+ { player: "sim-03", score: 400, guild: "Bears" }
983
+ ]
984
+ }
817
985
  ];
818
986
  var SIMULATED_ROUTES = [
819
987
  { method: "GET", path: "/api/game/health", source: "engine", params: {}, devOnly: false, summary: "Whether the server is up" },
@@ -897,7 +1065,9 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
897
1065
  rttMs: Math.round(20 + i * 8 + random() * 10),
898
1066
  bytesSent: Math.round((now - joinedAt[i]) * (25 + i)),
899
1067
  bytesReceived: Math.round((now - joinedAt[i]) * (4 + i / 2))
900
- }
1068
+ },
1069
+ // As with an auth plugin: most have accounts, some play as guests, one in five got in without either
1070
+ account: i % 5 === 4 ? null : i % 3 === 2 ? { id: `guest-${i + 1}`, name: `Guest-${4800 + i}`, guest: true } : { id: `acc-${(i + 1).toString().padStart(4, "0")}`, name: `player${i + 1}`, guest: false }
901
1071
  }));
902
1072
  for (let i = previousPlayers; i < playerCount; i++) {
903
1073
  const address = players[i].connection.address;
@@ -947,7 +1117,8 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
947
1117
  position: player.position,
948
1118
  ack: player.lastProcessedSequenceId,
949
1119
  tracked: Array.from({ length: player.trackedEntities }, (_, i) => `entity-${i}`),
950
- lastState: lastStates.get(player.id) ?? null
1120
+ lastState: lastStates.get(player.id) ?? null,
1121
+ account: player.account
951
1122
  }));
952
1123
  if (step % 10 === 0)
953
1124
  request("GET", "/api/game/health", 200, 180, "198.51.100.7");
@@ -1062,6 +1233,19 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
1062
1233
  },
1063
1234
  async fetchPlugins() {
1064
1235
  return { plugins: SIMULATED_PLUGINS };
1236
+ },
1237
+ async fetchDatabase() {
1238
+ return {
1239
+ provider: "@mavonengine/sqlite",
1240
+ tables: SIMULATED_TABLES.map(({ rows, ...table }) => ({ ...table, rows: rows.length })),
1241
+ migrations: [{ plugin: "@mavonengine/chat", table: "chat__migrations", applied: [{ name: "001_init", executedAt: "2026-11-14T12:00:00.000Z" }] }]
1242
+ };
1243
+ },
1244
+ async fetchTable(name, offset, limit) {
1245
+ const table = SIMULATED_TABLES.find((t) => t.name === name);
1246
+ if (!table)
1247
+ throw new MetricsSourceError(`No table ${name}`, "disabled");
1248
+ return { table: name, columns: table.columns, rows: table.rows.slice(offset, offset + limit), total: table.rows.length, offset, limit };
1065
1249
  }
1066
1250
  };
1067
1251
  }
@@ -1228,7 +1412,49 @@ var LOGO_SIZES = [
1228
1412
  function initialViewState() {
1229
1413
  return { tab: 0, playerOffset: 0, logFromEnd: 0, requestTopId: null, selectedPlayerId: null, followSelectedPlayer: true, packetTopId: null, showPings: false, eventsOnly: false, selectedPacketId: null, followSelectedPacket: true, payloadOffset: 0 };
1230
1414
  }
1231
- var DASHBOARD_TABS = ["Overview", "Players", "Logs", "HTTP", "Network", "Routes", "Plugins"];
1415
+ function accountLabel(account) {
1416
+ if (!account)
1417
+ return "\u2014";
1418
+ const name = account.name ?? account.id;
1419
+ return account.guest ? `${name} (guest)` : name;
1420
+ }
1421
+ var DASHBOARD_TABS = ["Overview", "Players", "Logs", "HTTP", "Network", "Routes", "Plugins", "Database"];
1422
+ var DEFAULT_VISIBLE_ROWS = 20;
1423
+ function showsDatabase(view) {
1424
+ return DASHBOARD_TABS[view.tab] === "Database";
1425
+ }
1426
+ function selectedTable(view, database) {
1427
+ const tables = database?.tables ?? [];
1428
+ return tables.find((t) => t.name === view.selectedTable) ?? tables[0];
1429
+ }
1430
+ function handleDatabaseKey(view, database, key, pageRows = view.tableVisibleRows || DEFAULT_VISIBLE_ROWS) {
1431
+ if (!showsDatabase(view))
1432
+ return false;
1433
+ const tables = database?.tables ?? [];
1434
+ const shown = selectedTable(view, database);
1435
+ if (!shown)
1436
+ return false;
1437
+ const delta = key === "down" || key === "j" ? 1 : key === "up" || key === "k" ? -1 : 0;
1438
+ if (delta !== 0) {
1439
+ const next2 = tables[Math.max(0, Math.min(tables.length - 1, tables.indexOf(shown) + delta))];
1440
+ if (next2.name === shown.name)
1441
+ return false;
1442
+ view.selectedTable = next2.name;
1443
+ view.tableOffset = 0;
1444
+ return true;
1445
+ }
1446
+ const page = key === "right" || key === "pagedown" ? 1 : key === "left" || key === "pageup" ? -1 : 0;
1447
+ if (page === 0)
1448
+ return false;
1449
+ const offset = view.tableOffset ?? 0;
1450
+ const last = shown.rows === null ? Infinity : Math.max(0, shown.rows - pageRows);
1451
+ const next = Math.max(0, Math.min(last, offset + page * pageRows));
1452
+ if (next === offset)
1453
+ return false;
1454
+ view.selectedTable = shown.name;
1455
+ view.tableOffset = next;
1456
+ return true;
1457
+ }
1232
1458
  function showsNetwork(view) {
1233
1459
  return DASHBOARD_TABS[view.tab] === "Network";
1234
1460
  }
@@ -1243,9 +1469,12 @@ var STATUS_LABELS = {
1243
1469
  forbidden: "FORBIDDEN",
1244
1470
  disabled: "METRICS DISABLED"
1245
1471
  };
1246
- function tabForKey(key) {
1472
+ function dashboardTabs(state) {
1473
+ return state.plugins.some((plugin) => plugin.database) ? DASHBOARD_TABS : DASHBOARD_TABS.filter((tab) => tab !== "Database");
1474
+ }
1475
+ function tabForKey(key, tabCount = DASHBOARD_TABS.length) {
1247
1476
  const index = Number(key) - 1;
1248
- return Number.isInteger(index) && index >= 0 && index < DASHBOARD_TABS.length ? index : null;
1477
+ return Number.isInteger(index) && index >= 0 && index < Math.min(tabCount, DASHBOARD_TABS.length) ? index : null;
1249
1478
  }
1250
1479
  function sortedPlayers(players) {
1251
1480
  return [...players].sort((a, b) => a.id.localeCompare(b.id));
@@ -1395,6 +1624,7 @@ function statusColor(status, theme) {
1395
1624
  function renderDashboard(ui, theme, state, view, { transparent = false, startup, openKey = false, available, installer } = {}) {
1396
1625
  const { snapshot } = state;
1397
1626
  const starting = !snapshot && !!startup && (state.status === "connecting" || state.status === "unreachable");
1627
+ const tabs = dashboardTabs(state);
1398
1628
  ui.column({}, (root) => {
1399
1629
  header(root, theme, state);
1400
1630
  if (snapshot?.latencySimulation)
@@ -1406,8 +1636,10 @@ function renderDashboard(ui, theme, state, view, { transparent = false, startup,
1406
1636
  } else if (!snapshot) {
1407
1637
  waiting(root, theme, state);
1408
1638
  } else {
1639
+ if (view.tab >= tabs.length)
1640
+ view.tab = 0;
1409
1641
  root.tabs({
1410
- tabs: DASHBOARD_TABS.map((name, i) => `${i + 1} ${name}`),
1642
+ tabs: tabs.map((name, i) => `${i + 1} ${name}`),
1411
1643
  active: view.tab,
1412
1644
  size: 1,
1413
1645
  onSelect: (index) => {
@@ -1428,6 +1660,8 @@ function renderDashboard(ui, theme, state, view, { transparent = false, startup,
1428
1660
  routesPanel(root, theme, state, view, transparent);
1429
1661
  } else if (tab === "Plugins") {
1430
1662
  pluginsTab(root, theme, state, view, transparent, available, installer);
1663
+ } else if (tab === "Database") {
1664
+ databaseTab(root, theme, state, view, transparent);
1431
1665
  } else {
1432
1666
  root.responsive({
1433
1667
  [WIDE_LAYOUT]: (c) => wideLayout(c, theme, state, snapshot, view, transparent),
@@ -1441,7 +1675,7 @@ function renderDashboard(ui, theme, state, view, { transparent = false, startup,
1441
1675
  items: [
1442
1676
  { key: "q", label: "Quit" },
1443
1677
  { key: "r", label: "Refresh" },
1444
- { key: `1-${DASHBOARD_TABS.length}`, label: "Tabs" },
1678
+ { key: `1-${tabs.length}`, label: "Tabs" },
1445
1679
  ...openKey && snapshot ? [{ key: "o", label: "Open game" }] : [],
1446
1680
  ...snapshot && DASHBOARD_TABS[view.tab] === "Players" ? [{ key: "\u2191\u2193", label: "Select player" }, ...view.selectedPlayerId ? [{ key: "esc", label: "Close" }] : []] : [],
1447
1681
  ...snapshot && showsNetwork(view) ? [
@@ -1450,7 +1684,8 @@ function renderDashboard(ui, theme, state, view, { transparent = false, startup,
1450
1684
  { key: "\u2191\u2193", label: "Open packet" },
1451
1685
  ...view.selectedPacketId !== null ? [{ key: "esc", label: "Close" }] : []
1452
1686
  ] : [],
1453
- ...snapshot && DASHBOARD_TABS[view.tab] === "Plugins" ? pluginKeys(state, view, available, installer) : []
1687
+ ...snapshot && DASHBOARD_TABS[view.tab] === "Plugins" ? pluginKeys(state, view, available, installer) : [],
1688
+ ...snapshot && showsDatabase(view) && state.database?.tables.length ? [...state.database.tables.length > 1 ? [{ key: "\u2191\u2193", label: "Select table" }] : [], { key: "\u2190\u2192", label: "Page rows" }] : []
1454
1689
  ],
1455
1690
  right: [starting ? { label: "STARTING", color: statusColor("connecting", theme) } : { label: STATUS_LABELS[state.status], color: statusColor(state.status, theme), active: state.status === "live" }]
1456
1691
  });
@@ -1669,6 +1904,7 @@ function playerDetails(ui, theme, player, size) {
1669
1904
  ui.panel({ title: player.displayName, size }, (panel) => {
1670
1905
  panel.keyValues([
1671
1906
  { label: "ID", value: player.id },
1907
+ { label: "Account", value: player.account ? `${accountLabel(player.account)} \xB7 ${player.account.id}` : "none", color: player.account?.guest ? theme.warning : void 0 },
1672
1908
  { label: "Connected", value: formatDuration(player.connectedFor) },
1673
1909
  { label: "IP", value: connection ? connection.address ?? "pending" : "\u2014", color: theme.primary },
1674
1910
  { label: "RTT", value: connection?.rttMs != null ? formatMs(connection.rttMs) : "\u2014" },
@@ -1687,6 +1923,7 @@ function playersPanel(ui, theme, { players }, view, transparent, selectable = fa
1687
1923
  const maxOffset = Math.max(0, rows.length - 1);
1688
1924
  view.playerOffset = Math.min(view.playerOffset, maxOffset);
1689
1925
  const showNames = rows.some((p) => p.displayName !== p.id);
1926
+ const showAccounts = rows.some((p) => p.account);
1690
1927
  ui.panel({ title: `Players (${rows.length})`, size: "1fr" }, (panel) => {
1691
1928
  if (rows.length === 0) {
1692
1929
  panel.label("No players connected");
@@ -1720,6 +1957,7 @@ function playersPanel(ui, theme, { players }, view, transparent, selectable = fa
1720
1957
  },
1721
1958
  columns: [
1722
1959
  ...showNames ? [{ key: "displayName", title: "Name" }] : [],
1960
+ ...showAccounts ? [{ key: "account", title: "Account", render: (p) => accountLabel(p.account), color: (p) => p.account?.guest ? theme.warning : void 0 }] : [],
1723
1961
  { key: "id", title: "ID" },
1724
1962
  { key: "x", title: "X", width: 9, align: "right", render: (p) => p.position.x.toFixed(2) },
1725
1963
  { key: "y", title: "Y", width: 9, align: "right", render: (p) => p.position.y.toFixed(2) },
@@ -1932,6 +2170,7 @@ function syncPanel(ui, theme, { sync }, transparent, size = "1fr") {
1932
2170
  size: "1fr",
1933
2171
  columns: [
1934
2172
  { key: "displayName", title: "Player" },
2173
+ ...sync.players.some((p) => p.account) ? [{ key: "account", title: "Account", render: (p) => accountLabel(p.account) }] : [],
1935
2174
  { key: "tracked", title: "Tracked", width: 8, align: "right" },
1936
2175
  { key: "ack", title: "Ack", width: 9, align: "right" },
1937
2176
  { key: "bytes", title: "State", width: 10, align: "right", render: (p) => p.lastState ? formatBytes(p.lastState.bytes) : "\u2014" },
@@ -2306,6 +2545,117 @@ function pluginDetails(ui, theme, state, plugin, endpoints, size, transparent) {
2306
2545
  });
2307
2546
  });
2308
2547
  }
2548
+ var MAX_CELL_CHARS = 60;
2549
+ var LINE_BREAKS_RE = /\r?\n/g;
2550
+ function formatCell(value) {
2551
+ let text;
2552
+ if (value === null || value === void 0)
2553
+ text = "NULL";
2554
+ else if (typeof value === "object")
2555
+ text = JSON.stringify(value);
2556
+ else
2557
+ text = String(value).replace(LINE_BREAKS_RE, " \u23CE ");
2558
+ return text.length > MAX_CELL_CHARS ? `${text.slice(0, MAX_CELL_CHARS - 1)}\u2026` : text;
2559
+ }
2560
+ function tableOwner(table) {
2561
+ return table.plugin ?? "game";
2562
+ }
2563
+ function databaseTab(ui, theme, state, view, transparent) {
2564
+ const { database } = state;
2565
+ const notice = state.databaseAvailable === false ? "Not available: the server runs a @mavonengine/core release without GET /api/game/database" : !database ? state.databaseError ?? "Asking the server for its database\u2026" : !database.provider ? "The project has no database plugin. Add one with: mavonengine install @mavonengine/sqlite" : database.tables.length === 0 ? `No tables yet in the database of ${database.provider}` : null;
2566
+ if (notice) {
2567
+ ui.panel({ title: "Database", size: "1fr" }, (panel) => {
2568
+ panel.text([{ text: notice, fg: state.databaseError && !database ? theme.danger : theme.muted }]);
2569
+ });
2570
+ return;
2571
+ }
2572
+ const { tables, migrations } = database;
2573
+ const shown = selectedTable(view, database);
2574
+ let top = 0;
2575
+ if (state.databaseError)
2576
+ ui.text([{ text: ` ${state.databaseError} \u2014 showing what was read last`, fg: theme.danger }], { size: 1 });
2577
+ ui.panel({ title: `Tables in ${database.provider} (${tables.length})`, size: Math.min(tables.length, 8) + 3 }, (panel) => {
2578
+ panel.table({
2579
+ rows: tables,
2580
+ selected: tables.indexOf(shown),
2581
+ followSelection: true,
2582
+ onRow: (_row, index, y) => {
2583
+ if (y === 1)
2584
+ top = index;
2585
+ },
2586
+ onSelectRow: (visibleRow) => {
2587
+ const row = tables[top + visibleRow];
2588
+ if (!row)
2589
+ return;
2590
+ view.selectedTable = row.name;
2591
+ view.tableOffset = 0;
2592
+ ui.ctx.invalidate();
2593
+ },
2594
+ scrollbar: true,
2595
+ // Zebra stripes are solid fills, which would break transparency
2596
+ zebra: !transparent,
2597
+ size: "1fr",
2598
+ columns: [
2599
+ { key: "name", title: "Table" },
2600
+ { key: "plugin", title: "Plugin", color: (t) => t.plugin ? theme.primary : theme.muted, render: tableOwner },
2601
+ { key: "rows", title: "Rows", width: 10, align: "right", render: (t) => t.rows === null ? "?" : t.rows.toLocaleString("en-US") },
2602
+ { key: "columns", title: "Columns", width: 7, align: "right", render: (t) => String(t.columns.length) }
2603
+ ]
2604
+ });
2605
+ });
2606
+ tableRowsPanel(ui, theme, state, view, shown, transparent);
2607
+ if (migrations.length) {
2608
+ ui.panel({ title: "Migrations", size: Math.min(migrations.length, 4) + 2 }, (panel) => {
2609
+ for (const m of migrations.slice(0, 4)) {
2610
+ const names = m.applied.map((a) => a.name).join(", ") || "none";
2611
+ panel.text([
2612
+ { text: `${m.plugin ?? m.table} `, fg: m.plugin ? theme.primary : theme.muted },
2613
+ { text: `${m.applied.length} ran: `, fg: theme.muted },
2614
+ { text: names }
2615
+ ]);
2616
+ }
2617
+ });
2618
+ }
2619
+ }
2620
+ function tableRowsPanel(ui, theme, state, view, table, transparent) {
2621
+ const detail = state.tableDetail?.table === table.name ? state.tableDetail : null;
2622
+ const page = detail?.page;
2623
+ const total = page?.total ?? table.rows ?? 0;
2624
+ const shownRows = page ? Math.min(page.rows.length, view.tableVisibleRows || page.rows.length) : 0;
2625
+ const range = page && shownRows ? `rows ${(page.offset + 1).toLocaleString("en-US")}\u2013${(page.offset + shownRows).toLocaleString("en-US")} of ${total.toLocaleString("en-US")}` : `${total.toLocaleString("en-US")} rows`;
2626
+ ui.panel({ title: `${table.name} \xB7 ${range}${detail?.status === "loading" ? " \xB7 loading\u2026" : ""}`, size: "1fr" }, (panel) => {
2627
+ if (detail?.status === "error")
2628
+ panel.text([{ text: detail.error ?? "Could not load the rows", fg: theme.danger }], { size: 1 });
2629
+ if (!page) {
2630
+ if (detail?.status !== "error")
2631
+ panel.label("Loading the rows\u2026");
2632
+ return;
2633
+ }
2634
+ if (page.rows.length === 0) {
2635
+ panel.label("The table is empty");
2636
+ return;
2637
+ }
2638
+ const columns2 = page.columns.length ? page.columns.map((c) => c.name) : Object.keys(page.rows[0]);
2639
+ let visible = 0;
2640
+ panel.table({
2641
+ rows: page.rows,
2642
+ // Counts the rows that fit, so paging moves by a screenful
2643
+ onRow: (_row, _index, y) => {
2644
+ visible = Math.max(visible, y);
2645
+ view.tableVisibleRows = visible;
2646
+ },
2647
+ scrollbar: true,
2648
+ zebra: !transparent,
2649
+ size: "1fr",
2650
+ columns: columns2.map((name) => ({
2651
+ key: name,
2652
+ title: name,
2653
+ color: (row) => row[name] === null || row[name] === void 0 ? theme.muted : void 0,
2654
+ render: (row) => formatCell(row[name])
2655
+ }))
2656
+ });
2657
+ });
2658
+ }
2309
2659
 
2310
2660
  // src/commands/dashboard.ts
2311
2661
  var DASHBOARD_HELP = `Usage: mavonengine dashboard [options]
@@ -2399,6 +2749,16 @@ async function runDashboard(options, signal) {
2399
2749
  void client.refresh();
2400
2750
  }
2401
2751
  client.watchNetwork = watch;
2752
+ const watchDatabase = showsDatabase(view);
2753
+ if (watchDatabase && !client.watchDatabase) {
2754
+ client.watchDatabase = true;
2755
+ void client.refresh();
2756
+ }
2757
+ client.watchDatabase = watchDatabase;
2758
+ const table = watchDatabase ? selectedTable(view, client.state.database) : void 0;
2759
+ const detail = client.state.tableDetail;
2760
+ if (table && (detail?.table !== table.name || detail.offset !== (view.tableOffset ?? 0)))
2761
+ void client.inspectTable(table.name, view.tableOffset ?? 0);
2402
2762
  if ((client.state.packetDetail?.id ?? null) !== view.selectedPacketId)
2403
2763
  void client.inspectPacket(view.selectedPacketId);
2404
2764
  });
@@ -2428,12 +2788,12 @@ async function runDashboard(options, signal) {
2428
2788
  }
2429
2789
  if (event.key === "o" && options.clientUrl)
2430
2790
  openBrowser(options.clientUrl);
2431
- const tab = tabForKey(event.key);
2791
+ const tab = tabForKey(event.key, dashboardTabs(client.state).length);
2432
2792
  if (tab !== null) {
2433
2793
  view.tab = tab;
2434
2794
  app.invalidate();
2435
2795
  }
2436
- if (handlePlayersKey(view, client.state.snapshot, event.key) || handleNetworkKey(view, event.key, client.state.packets) || handlePluginsKey(view, client.state.plugins, event.key, installable2()))
2796
+ if (handlePlayersKey(view, client.state.snapshot, event.key) || handleNetworkKey(view, event.key, client.state.packets) || handlePluginsKey(view, client.state.plugins, event.key, installable2()) || handleDatabaseKey(view, client.state.database, event.key))
2437
2797
  app.invalidate();
2438
2798
  });
2439
2799
  app.on("exit", () => client.stop());
@@ -2495,7 +2855,7 @@ import process4 from "process";
2495
2855
  import { Readable, Transform } from "stream";
2496
2856
  import { pipeline } from "stream/promises";
2497
2857
  import AdmZip from "adm-zip";
2498
- var TEMPLATE_URL = "https://github.com/MavonEngine/Core/archive/refs/tags/0.0.18-alpha.zip";
2858
+ var TEMPLATE_URL = "https://github.com/MavonEngine/Core/archive/refs/tags/0.0.19-alpha.zip";
2499
2859
  var TEMPLATE_SUBPATH = "packages/multiplayer-template";
2500
2860
  var PROJECT_NAME_RE = /^[\w@./-][\w@./\- ]*$/;
2501
2861
  function projectDirFor(projectName, parentDir) {
@@ -3484,6 +3844,8 @@ var NET_UNAVAILABLE = "The network debug endpoints are not available: the game s
3484
3844
  function packetParams(query) {
3485
3845
  return Object.fromEntries(Object.entries(query).filter(([, value]) => value !== void 0 && value !== "").map(([key, value]) => [key, String(value)]));
3486
3846
  }
3847
+ var DATABASE_UNAVAILABLE = "The game server doesn't show its database: it runs a @mavonengine/core release without GET /api/game/database";
3848
+ var DATABASE_DENIED = "The database is only shown with the server's admin token, since it holds what players did: pass it with --token (or MAVONENGINE_METRICS_TOKEN), or run the server on this machine without one";
3487
3849
  var DEV_UNAVAILABLE = "The dev endpoints are not available: the game server runs with NODE_ENV=production (they are never served there), or it uses a @mavonengine/core release without them";
3488
3850
  var GameServerClient = class {
3489
3851
  url;
@@ -3540,6 +3902,14 @@ var GameServerClient = class {
3540
3902
  routes() {
3541
3903
  return this.get("api/game/routes", {}, "The game server doesn't list its endpoints: it runs a @mavonengine/core release without GET /api/game/routes, or its metrics endpoints are off");
3542
3904
  }
3905
+ /** The database plugin, the tables with whose they are, their columns and row counts, and the migrations that ran */
3906
+ database() {
3907
+ return this.get("api/game/database", {}, DATABASE_UNAVAILABLE, DATABASE_DENIED);
3908
+ }
3909
+ /** A page of a table's rows */
3910
+ tableRows(table, offset = 0, limit = 50) {
3911
+ return this.get(`api/game/database/tables/${encodeURIComponent(table)}`, { offset: String(offset), limit: String(limit) }, `There is no table "${table}". database_overview lists them`, DATABASE_DENIED);
3912
+ }
3543
3913
  /** Packets and network events the server recorded, oldest first */
3544
3914
  packets(query = {}) {
3545
3915
  return this.get("api/game/dev/net/packets", packetParams(query), NET_UNAVAILABLE);
@@ -3588,7 +3958,7 @@ var GameServerClient = class {
3588
3958
  throw new GameServerError(body?.error ?? `Client dev server responded ${res.status} ${res.statusText}`);
3589
3959
  return body;
3590
3960
  }
3591
- async get(path, params = {}, notFound) {
3961
+ async get(path, params = {}, notFound, denied) {
3592
3962
  const target = new URL(path, this.base);
3593
3963
  for (const [key, value] of Object.entries(params))
3594
3964
  target.searchParams.set(key, value);
@@ -3601,10 +3971,16 @@ var GameServerClient = class {
3601
3971
  } catch (err) {
3602
3972
  throw new GameServerError(`Can't reach the game server at ${this.url}: ${err.message}. Is it running?`);
3603
3973
  }
3974
+ if (denied && (res.status === 401 || res.status === 403))
3975
+ throw new GameServerError(denied);
3604
3976
  if (res.status === 401)
3605
3977
  throw new GameServerError("Metrics token missing or wrong: pass --token or set MAVONENGINE_METRICS_TOKEN");
3606
3978
  if (res.status === 403)
3607
3979
  throw new GameServerError("The game server only answers localhost without a token: pass --token or set MAVONENGINE_METRICS_TOKEN");
3980
+ if (res.status === 500 && denied) {
3981
+ const body = await res.json().catch(() => null);
3982
+ throw new GameServerError(body?.error ?? "The game server could not read its database");
3983
+ }
3608
3984
  if (res.status === 404)
3609
3985
  throw new GameServerError(notFound ?? "Metrics endpoints not found: they are turned off in the server options, or it runs in production without a metrics token");
3610
3986
  if (res.status === 400)
@@ -3697,8 +4073,8 @@ function parseMcpArgs(args, env = process9.env) {
3697
4073
  async function runMcpCommand({ client, docsUrl, pluginsUrl }) {
3698
4074
  const [{ StdioServerTransport }, { createMcpServer }, { DocsClient }] = await Promise.all([
3699
4075
  import("@modelcontextprotocol/sdk/server/stdio.js"),
3700
- import("./server-QSZHAYK2.js"),
3701
- import("./docs-QCI5VKET.js")
4076
+ import("./server-GC2XXFIG.js"),
4077
+ import("./docs-WADOFPOK.js")
3702
4078
  ]);
3703
4079
  const docs = docsUrl ? new DocsClient(docsUrl) : void 0;
3704
4080
  const server = createMcpServer(client, docs, pluginsUrl ? { url: pluginsUrl } : void 0);
@@ -9,14 +9,14 @@ import {
9
9
  registerDocsTools,
10
10
  run,
11
11
  vec3
12
- } from "./chunk-KHC2RAKX.js";
12
+ } from "./chunk-WDETVETJ.js";
13
13
  import {
14
14
  version
15
- } from "./chunk-TGGH7KA4.js";
15
+ } from "./chunk-WOOU36T7.js";
16
16
 
17
17
  // src/mcp/server.ts
18
18
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
19
- import { z as z4 } from "zod";
19
+ import { z as z5 } from "zod";
20
20
 
21
21
  // src/mcp/clientTools.ts
22
22
  import { mkdir, writeFile } from "fs/promises";
@@ -599,15 +599,77 @@ function registerClientTools(server, client) {
599
599
  }));
600
600
  }
601
601
 
602
- // src/mcp/networkTools.ts
602
+ // src/mcp/databaseTools.ts
603
603
  import { z as z2 } from "zod";
604
- var clientId2 = z2.string().optional().describe("Tab id from list_clients. Default: the only open tab, or the only one not running the editor");
604
+ var SECRET_COLUMN_RE = /secret|password|passwd|token|hash|salt|api_?key|private/i;
605
+ var MAX_ROWS = 500;
606
+ function redactRows(columns, rows) {
607
+ const secret = new Set(columns.map((column) => column.name).filter((name) => SECRET_COLUMN_RE.test(name)));
608
+ for (const row of rows) {
609
+ for (const key of Object.keys(row)) {
610
+ if (SECRET_COLUMN_RE.test(key))
611
+ secret.add(key);
612
+ }
613
+ }
614
+ return {
615
+ redacted: [...secret],
616
+ rows: secret.size === 0 ? rows : rows.map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, secret.has(key) && value !== null ? "[redacted]" : value])))
617
+ };
618
+ }
619
+ function registerDatabaseTools(server, client) {
620
+ server.registerTool("database_overview", {
621
+ title: "Database tables",
622
+ description: `The game server's database, from the project's database plugin (e.g. @mavonengine/sqlite): which plugin gives it, every table with the plugin it belongs to (by its table prefix, "game" for the game's own), its columns and row count, and the migrations each plugin ran. Use database_rows to read a table. Needs the server's admin token (--token) unless the server runs on this machine without one.`,
623
+ inputSchema: {
624
+ table: z2.string().optional().describe("Only tables whose name contains this, case-insensitive")
625
+ },
626
+ annotations: READ_ONLY
627
+ }, ({ table }) => run(async () => {
628
+ const overview = await client.database();
629
+ if (!overview.provider) {
630
+ return {
631
+ provider: null,
632
+ tables: [],
633
+ note: "The project has no database plugin. Install one, e.g. `npx @mavonengine/cli install @mavonengine/sqlite`, and plugins get ctx.db and their migrations run"
634
+ };
635
+ }
636
+ const needle = table?.toLowerCase();
637
+ const tables = (overview.tables ?? []).filter((t) => !needle || t.name.toLowerCase().includes(needle));
638
+ return { provider: overview.provider, tables, migrations: overview.migrations ?? [] };
639
+ }));
640
+ server.registerTool("database_rows", {
641
+ title: "Rows of a database table",
642
+ description: 'A page of rows of one table of the game server\'s database, as database_overview lists them, with the total row count. Values of columns that look secret (password and token hashes, keys) are replaced with "[redacted]" and listed in `redacted`. Page with offset and limit.',
643
+ inputSchema: {
644
+ table: z2.string().min(1).describe("Table name, e.g. chat_mutes"),
645
+ offset: z2.number().int().min(0).default(0),
646
+ limit: z2.number().int().min(1).max(MAX_ROWS).default(50)
647
+ },
648
+ annotations: READ_ONLY
649
+ }, ({ table, offset, limit }) => run(async () => {
650
+ const page = await client.tableRows(table, offset, limit);
651
+ const { rows, redacted } = redactRows(page.columns ?? [], page.rows ?? []);
652
+ return {
653
+ table: page.table,
654
+ total: page.total,
655
+ offset: page.offset,
656
+ limit: page.limit,
657
+ columns: page.columns ?? [],
658
+ ...redacted.length ? { redacted } : {},
659
+ rows
660
+ };
661
+ }));
662
+ }
663
+
664
+ // src/mcp/networkTools.ts
665
+ import { z as z3 } from "zod";
666
+ var clientId2 = z3.string().optional().describe("Tab id from list_clients. Default: the only open tab, or the only one not running the editor");
605
667
  var packetFilters = {
606
- kind: z2.enum(["packet", "event"]).optional().describe("packet: messages on the wire. event: connect, disconnect, sync_enter, sync_leave, dropped, state_gap\u2026"),
607
- direction: z2.enum(["in", "out"]).optional().describe("Seen from the side that recorded it: out was sent, in was received"),
608
- type: z2.string().optional().describe("Message or event name, e.g. sv_state or command. Several separated by commas"),
609
- afterId: z2.number().int().min(0).default(0),
610
- limit: z2.number().int().min(1).max(2e3).default(50).describe("Newest records kept when more match")
668
+ kind: z3.enum(["packet", "event"]).optional().describe("packet: messages on the wire. event: connect, disconnect, sync_enter, sync_leave, dropped, state_gap\u2026"),
669
+ direction: z3.enum(["in", "out"]).optional().describe("Seen from the side that recorded it: out was sent, in was received"),
670
+ type: z3.string().optional().describe("Message or event name, e.g. sv_state or command. Several separated by commas"),
671
+ afterId: z3.number().int().min(0).default(0),
672
+ limit: z3.number().int().min(1).max(2e3).default(50).describe("Newest records kept when more match")
611
673
  };
612
674
  function withTime({ timestamp, ...record }) {
613
675
  return { ...record, time: new Date(timestamp).toISOString() };
@@ -630,13 +692,13 @@ function registerNetworkTools(server, client) {
630
692
  server.registerTool("network_packets", {
631
693
  title: "Packets on the server",
632
694
  description: "Packets the game server sent and received and its network events, oldest first: time, direction, message name, client (peer), size in bytes, server tick, input sequence id and a few facts about the payload (entity count, ack, command). The server keeps the last 2000. Pass the returned latestId as afterId to get only newer ones; network_packet shows a payload. Development only.",
633
- inputSchema: { ...packetFilters, peer: z2.string().optional().describe("Only one client: its player id (list_players, or playerId from list_clients)") },
695
+ inputSchema: { ...packetFilters, peer: z3.string().optional().describe("Only one client: its player id (list_players, or playerId from list_clients)") },
634
696
  annotations: READ_ONLY
635
697
  }, ({ afterId, ...query }) => run(async () => listing(await client.packets({ ...query, after: afterId }))));
636
698
  server.registerTool("network_packet", {
637
699
  title: "One packet on the server",
638
700
  description: "One record from network_packets with its payload, as it was serialized for the wire. Payloads of old records are dropped to bound memory (hasPayload false). Development only.",
639
- inputSchema: { id: z2.number().int().min(1) },
701
+ inputSchema: { id: z3.number().int().min(1) },
640
702
  annotations: READ_ONLY
641
703
  }, ({ id }) => run(async () => {
642
704
  const { record } = await client.packet(id);
@@ -648,8 +710,8 @@ function registerNetworkTools(server, client) {
648
710
  title: "State sync",
649
711
  description: "Who is sent what: the current server tick, the sync distance, each player with the entities in its last state update (tracked), its last acknowledged input and the size of that update; and each synced entity with how many players track it (trackedBy, 0 means no player is in range), whether it changed since it was last synced and the tick it was last sent in. For entities that do not show up or stop updating on a client. Development only.",
650
712
  inputSchema: {
651
- player: z2.string().optional().describe("Only this player, and the entities with `tracked` telling whether it is sent them"),
652
- includeEntities: z2.boolean().default(true)
713
+ player: z3.string().optional().describe("Only this player, and the entities with `tracked` telling whether it is sent them"),
714
+ includeEntities: z3.boolean().default(true)
653
715
  },
654
716
  annotations: READ_ONLY
655
717
  }, ({ player, includeEntities }) => run(async () => {
@@ -676,7 +738,7 @@ function registerNetworkTools(server, client) {
676
738
  server.registerTool("client_packet", {
677
739
  title: "One packet on a client",
678
740
  description: "One record from client_packets with its payload.",
679
- inputSchema: { id: z2.number().int().min(1), clientId: clientId2 },
741
+ inputSchema: { id: z3.number().int().min(1), clientId: clientId2 },
680
742
  annotations: READ_ONLY
681
743
  }, ({ id, clientId: clientId3 }) => run(async () => {
682
744
  const { record } = await client.client("packet", { id }, clientId3);
@@ -689,10 +751,10 @@ function registerNetworkTools(server, client) {
689
751
  description: "What happened between the server and one tab, in order of time: the server's records for that client and the tab's own, merged, each marked with its side. Shows a packet leaving one side and arriving on the other (or not), inputs against the state updates that acknowledge them, and events like sync_enter / sync_leave, dropped and state_gap. Needs the server in development too.",
690
752
  inputSchema: {
691
753
  clientId: clientId2,
692
- sinceMs: z2.number().int().min(100).max(6e5).default(5e3).describe("How far back to look"),
693
- includePings: z2.boolean().default(false).describe("Keep ping / pong, one pair per second"),
694
- eventsOnly: z2.boolean().default(false).describe("Leave the packets out"),
695
- limit: z2.number().int().min(1).max(2e3).default(200).describe("Newest entries kept when more match")
754
+ sinceMs: z3.number().int().min(100).max(6e5).default(5e3).describe("How far back to look"),
755
+ includePings: z3.boolean().default(false).describe("Keep ping / pong, one pair per second"),
756
+ eventsOnly: z3.boolean().default(false).describe("Leave the packets out"),
757
+ limit: z3.number().int().min(1).max(2e3).default(200).describe("Newest entries kept when more match")
696
758
  },
697
759
  annotations: READ_ONLY
698
760
  }, ({ clientId: clientId3, sinceMs, includePings, eventsOnly, limit }) => run(async () => {
@@ -717,7 +779,7 @@ function registerNetworkTools(server, client) {
717
779
  }
718
780
 
719
781
  // src/mcp/pluginTools.ts
720
- import { z as z3 } from "zod";
782
+ import { z as z4 } from "zod";
721
783
  var installCommand = (pkg) => `npx @mavonengine/cli install ${pkg}`;
722
784
  async function installedPlugins(client) {
723
785
  const [{ plugins = [] }, routes] = await Promise.all([
@@ -768,7 +830,7 @@ function registerPluginTools(server, client, list) {
768
830
  server.registerTool("plugin_readme", {
769
831
  title: "Read a plugin's readme",
770
832
  description: "The README of an official MavonEngine plugin as Markdown, by its package name from available_plugins: what it does, its options for mavonengine.json, how a game hooks into it and its limits.",
771
- inputSchema: { package: z3.string().describe("npm package of the plugin, e.g. @mavonengine/chat") },
833
+ inputSchema: { package: z4.string().describe("npm package of the plugin, e.g. @mavonengine/chat") },
772
834
  annotations: { ...READ_ONLY, openWorldHint: true }
773
835
  }, async ({ package: pkg }) => {
774
836
  try {
@@ -794,6 +856,8 @@ network_packets / client_packets list the packets each side sent and received, n
794
856
  client, and network_sync tells which entities each player is sent: use them when something does not arrive or arrives late.
795
857
  client_trace records a few seconds of a tab for frame drops, stutter and slow rendering: the bottleneck, hitches with
796
858
  their causes, hot JS functions, WebGL load, and a trace file for flame charts.
859
+ database_overview lists the tables of the project's database plugin (e.g. @mavonengine/sqlite) and database_rows reads
860
+ one, to check what the game and its plugins stored.
797
861
  list_plugins shows the plugins the project has, available_plugins the official ones it could add and plugin_readme how
798
862
  one is set up and used: look there before building something a plugin already does, like chat.
799
863
  docs_list_pages / docs_get_page read the MavonEngine documentation: check it before guessing how an engine API works.`;
@@ -820,7 +884,7 @@ function createMcpServer(client, docs, pluginList) {
820
884
  server.registerTool("server_metrics", {
821
885
  title: "Full metrics snapshot",
822
886
  description: "The full metrics snapshot. With includeHistory, also the last ~60 samples of CPU, bandwidth and tick timings, to spot spikes.",
823
- inputSchema: { includeHistory: z4.boolean().default(false).describe("Include the per-sample history arrays") },
887
+ inputSchema: { includeHistory: z5.boolean().default(false).describe("Include the per-sample history arrays") },
824
888
  annotations: READ_ONLY
825
889
  }, ({ includeHistory }) => run(async () => {
826
890
  const metrics = await client.metrics();
@@ -840,7 +904,7 @@ function createMcpServer(client, docs, pluginList) {
840
904
  server.registerTool("get_scene", {
841
905
  title: "Active scene",
842
906
  description: "The scene loaded on the server: name, file, whether it hot-reloads, unsaved changes, settings, and its objects with type, transform, props, the plugin that registered the type and whether the server built it (false for client-only types). Development only.",
843
- inputSchema: { includeObjects: z4.boolean().default(true).describe("Include the scene objects, not just the summary") },
907
+ inputSchema: { includeObjects: z5.boolean().default(true).describe("Include the scene objects, not just the summary") },
844
908
  annotations: READ_ONLY
845
909
  }, ({ includeObjects }) => run(async () => {
846
910
  const { scene } = await client.scene();
@@ -855,18 +919,18 @@ function createMcpServer(client, docs, pluginList) {
855
919
  title: "Entities in the world",
856
920
  description: "Entities in the server world: id, type, position, rotation, scale, whether networked or a player, and the scene object it was built from. Filter by type and/or distance to a point (results are then nearest first). Returns the total match count. Development only.",
857
921
  inputSchema: {
858
- type: z4.string().optional().describe("Entity class / networked type name, or scene object type, case-insensitive"),
922
+ type: z5.string().optional().describe("Entity class / networked type name, or scene object type, case-insensitive"),
859
923
  near: vec3.optional().describe("Only entities around this point, nearest first"),
860
- radius: z4.number().nonnegative().optional().describe("Max distance from `near`"),
861
- limit: z4.number().int().min(1).max(500).default(50),
862
- offset: z4.number().int().min(0).default(0)
924
+ radius: z5.number().nonnegative().optional().describe("Max distance from `near`"),
925
+ limit: z5.number().int().min(1).max(500).default(50),
926
+ offset: z5.number().int().min(0).default(0)
863
927
  },
864
928
  annotations: READ_ONLY
865
929
  }, (query) => run(() => client.entities(query)));
866
930
  server.registerTool("get_entity", {
867
931
  title: "One entity",
868
932
  description: "One entity by id, with the state it sends to clients (its serialize() output). Development only.",
869
- inputSchema: { id: z4.string().min(1) },
933
+ inputSchema: { id: z5.string().min(1) },
870
934
  annotations: READ_ONLY
871
935
  }, ({ id }) => run(async () => {
872
936
  const { entity } = await client.entity(id);
@@ -878,10 +942,10 @@ function createMcpServer(client, docs, pluginList) {
878
942
  title: "Server logs",
879
943
  description: "Recent game server log lines, oldest first. The server keeps the last 500 by default. Pass the returned latestId as afterId later to get only newer lines.",
880
944
  inputSchema: {
881
- level: z4.enum(LOG_LEVELS).optional().describe("Only this level and more severe ones, e.g. warn includes error"),
882
- contains: z4.string().optional().describe("Only lines containing this text, case-insensitive"),
883
- afterId: z4.number().int().min(0).default(0),
884
- limit: z4.number().int().min(1).max(500).default(100).describe("Newest lines kept when more match")
945
+ level: z5.enum(LOG_LEVELS).optional().describe("Only this level and more severe ones, e.g. warn includes error"),
946
+ contains: z5.string().optional().describe("Only lines containing this text, case-insensitive"),
947
+ afterId: z5.number().int().min(0).default(0),
948
+ limit: z5.number().int().min(1).max(500).default(100).describe("Newest lines kept when more match")
885
949
  },
886
950
  annotations: READ_ONLY
887
951
  }, ({ level, contains, afterId, limit }) => run(async () => {
@@ -902,10 +966,10 @@ function createMcpServer(client, docs, pluginList) {
902
966
  title: "HTTP requests",
903
967
  description: "Recent HTTP requests the game server answered: method, path, status, duration, bytes, address. Pass the returned latestId as afterId later to get only newer ones.",
904
968
  inputSchema: {
905
- pathContains: z4.string().optional(),
906
- minStatus: z4.number().int().optional().describe("e.g. 400 for errors only"),
907
- afterId: z4.number().int().min(0).default(0),
908
- limit: z4.number().int().min(1).max(500).default(50).describe("Newest requests kept when more match")
969
+ pathContains: z5.string().optional(),
970
+ minStatus: z5.number().int().optional().describe("e.g. 400 for errors only"),
971
+ afterId: z5.number().int().min(0).default(0),
972
+ limit: z5.number().int().min(1).max(500).default(50).describe("Newest requests kept when more match")
909
973
  },
910
974
  annotations: READ_ONLY
911
975
  }, ({ pathContains, minStatus, afterId, limit }) => run(async () => {
@@ -916,6 +980,7 @@ function createMcpServer(client, docs, pluginList) {
916
980
  registerClientTools(server, client);
917
981
  registerNetworkTools(server, client);
918
982
  registerPluginTools(server, client, pluginList);
983
+ registerDatabaseTools(server, client);
919
984
  if (docs)
920
985
  registerDocsTools(server, docs);
921
986
  return server;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mavonengine/cli",
3
3
  "type": "module",
4
- "version": "0.0.4",
4
+ "version": "0.0.5",
5
5
  "description": "MavonEngine command line tools",
6
6
  "license": "MIT",
7
7
  "keywords": [