@mavonengine/cli 0.0.7 → 0.0.8

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.
@@ -2,17 +2,20 @@
2
2
  import {
3
3
  fetchPluginReadme,
4
4
  fetchPluginRegistry
5
- } from "./chunk-ZEMFSSJP.js";
5
+ } from "./chunk-GOPDTCJD.js";
6
+ import {
7
+ registerDocsTools
8
+ } from "./chunk-HRMANFDB.js";
9
+ import {
10
+ version
11
+ } from "./chunk-33OMMYNV.js";
6
12
  import {
7
13
  LOG_LEVELS,
8
14
  READ_ONLY,
9
- registerDocsTools,
10
15
  run,
11
16
  vec3
12
- } from "./chunk-5YUDR7ZR.js";
13
- import {
14
- version
15
- } from "./chunk-3VVGSO5T.js";
17
+ } from "./chunk-WMXVMJDM.js";
18
+ import "./chunk-K3NQKI34.js";
16
19
 
17
20
  // src/mcp/server.ts
18
21
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -25,7 +28,20 @@ import { dirname, join, resolve } from "path";
25
28
  import { z } from "zod";
26
29
 
27
30
  // src/mcp/trace.ts
28
- var REFRESH_RATES = [30, 50, 60, 75, 90, 100, 120, 144, 165, 180, 240, 360];
31
+ var REFRESH_RATES = [
32
+ 30,
33
+ 50,
34
+ 60,
35
+ 75,
36
+ 90,
37
+ 100,
38
+ 120,
39
+ 144,
40
+ 165,
41
+ 180,
42
+ 240,
43
+ 360
44
+ ];
29
45
  var GC_DROP_BYTES = 1024 * 1024;
30
46
  var MB = 1024 * 1024;
31
47
  var VITE_DEPS_RE = /^\/node_modules\/\.vite\/deps\//;
@@ -41,7 +57,13 @@ function stats(values) {
41
57
  if (!values.length)
42
58
  return null;
43
59
  const sum2 = values.reduce((a, b) => a + b, 0);
44
- return { avg: round(sum2 / values.length), p50: round(percentile(values, 50)), p95: round(percentile(values, 95)), p99: round(percentile(values, 99)), max: round(Math.max(...values)) };
60
+ return {
61
+ avg: round(sum2 / values.length),
62
+ p50: round(percentile(values, 50)),
63
+ p95: round(percentile(values, 95)),
64
+ p99: round(percentile(values, 99)),
65
+ max: round(Math.max(...values))
66
+ };
45
67
  }
46
68
  function refreshRate(intervals) {
47
69
  if (intervals.length < 5)
@@ -86,7 +108,10 @@ function weightedSamples(profile) {
86
108
  return profile.samples.map((sample, i) => {
87
109
  const next = profile.samples[i + 1];
88
110
  const weight = next ? Math.min(next.timestamp - sample.timestamp, profile.sampleIntervalMs * 4) : profile.sampleIntervalMs;
89
- return { ...sample, weight: Math.max(0, weight) };
111
+ return {
112
+ ...sample,
113
+ weight: Math.max(0, weight)
114
+ };
90
115
  });
91
116
  }
92
117
  function hotFunctions(profile, limit = 15, from = -Infinity, to = Infinity) {
@@ -105,19 +130,38 @@ function hotFunctions(profile, limit = 15, from = -Infinity, to = Infinity) {
105
130
  const keys = frames.map((frameId) => {
106
131
  const label = frameLabel(profile, frameId);
107
132
  const key = `${label.name}@${label.location}`;
108
- if (!byKey.has(key))
109
- byKey.set(key, { ...label, selfMs: 0, totalMs: 0, selfPercent: 0 });
133
+ if (!byKey.has(key)) {
134
+ byKey.set(key, {
135
+ ...label,
136
+ selfMs: 0,
137
+ totalMs: 0,
138
+ selfPercent: 0
139
+ });
140
+ }
110
141
  return key;
111
142
  });
112
143
  for (const key of new Set(keys))
113
144
  byKey.get(key).totalMs += sample.weight;
114
145
  byKey.get(keys.at(-1)).selfMs += sample.weight;
115
146
  }
116
- const functions = [...byKey.values()].sort((a, b) => b.selfMs - a.selfMs).slice(0, limit).map((fn) => ({ ...fn, selfMs: round(fn.selfMs, 1), totalMs: round(fn.totalMs, 1), selfPercent: busyMs ? round(fn.selfMs / busyMs * 100, 1) : 0 }));
117
- return { busyMs: round(busyMs, 1), idleMs: round(idleMs, 1), functions };
147
+ const functions = [
148
+ ...byKey.values()
149
+ ].sort((a, b) => b.selfMs - a.selfMs).slice(0, limit).map((fn) => ({
150
+ ...fn,
151
+ selfMs: round(fn.selfMs, 1),
152
+ totalMs: round(fn.totalMs, 1),
153
+ selfPercent: busyMs ? round(fn.selfMs / busyMs * 100, 1) : 0
154
+ }));
155
+ return {
156
+ busyMs: round(busyMs, 1),
157
+ idleMs: round(idleMs, 1),
158
+ functions
159
+ };
118
160
  }
119
161
  var sum = (values) => values.reduce((a, b) => a + b, 0);
120
- var mean = (values) => values.length ? sum(values) / values.length : 0;
162
+ function mean(values) {
163
+ return values.length ? sum(values) / values.length : 0;
164
+ }
121
165
  function overlaps(span, from, to) {
122
166
  return span.start < to && span.start + span.duration > from;
123
167
  }
@@ -130,8 +174,9 @@ function hitchCauses(capture, index, budgetMs) {
130
174
  const gl = [previous?.gl, frame.gl].filter(Boolean);
131
175
  const compileMs = sum(gl.map((g) => g.shaderCompileMs));
132
176
  const compiles = sum(gl.map((g) => g.shaderCompiles));
133
- if (compileMs >= 1)
177
+ if (compileMs >= 1) {
134
178
  causes.push(`Shader compilation: ${round(compileMs, 1)}ms${compiles ? ` linking ${compiles} program${compiles === 1 ? "" : "s"}` : ""} (a material or light setup rendered for the first time)`);
179
+ }
135
180
  const uploadMs = sum(gl.map((g) => g.textureUploadMs));
136
181
  if (uploadMs >= 1)
137
182
  causes.push(`Texture uploads: ${round(uploadMs, 1)}ms for ${sum(gl.map((g) => g.textureUploads))} upload(s)`);
@@ -164,8 +209,9 @@ function hitchCauses(capture, index, budgetMs) {
164
209
  if (capture.profile) {
165
210
  const { functions } = hotFunctions(capture.profile, 3, from, to);
166
211
  const hot = functions.filter((fn) => fn.selfMs >= capture.profile.sampleIntervalMs);
167
- if (hot.length)
212
+ if (hot.length) {
168
213
  causes.push(`Hot JS in this frame: ${hot.map((fn) => `${fn.name} ${fn.selfMs}ms${fn.location ? ` (${fn.location})` : ""}`).join(", ")}`);
214
+ }
169
215
  }
170
216
  if (!causes.length)
171
217
  causes.push("No cause recorded in the tab: the browser or OS held the frame back (another tab, compositor, GPU process, power saving), or work outside the game loop");
@@ -190,8 +236,9 @@ function analyzeTrace(capture, { maxHitches = 10 } = {}) {
190
236
  notes.push("Fewer than two frames rendered while tracing: the tab is hidden, frozen or stuck before its first frame");
191
237
  if (capped)
192
238
  notes.push(`Rendering is capped at renderer.maxFps = ${maxFps}: frame times are measured against ${round(1e3 / maxFps, 1)}ms. Set it to 0 to see how fast the game can render`);
193
- if (!capture.gpuTiming.enabled || capture.gpuTiming.note)
239
+ if (!capture.gpuTiming.enabled || capture.gpuTiming.note) {
194
240
  notes.push(`GPU timing: ${capture.gpuTiming.enabled ? "on" : "off"}${capture.gpuTiming.note ? `, ${capture.gpuTiming.note}` : ""}`);
241
+ }
195
242
  if (!capture.jsProfile.enabled)
196
243
  notes.push(`JS sampling: off, ${capture.jsProfile.note ?? "not available"}`);
197
244
  const ticks = capture.ticks;
@@ -203,7 +250,11 @@ function analyzeTrace(capture, { maxHitches = 10 } = {}) {
203
250
  } : null;
204
251
  const passes = capture.passes.map((name, i) => {
205
252
  const times = frames.map((f) => f.passes[i]?.[1]).filter((n) => n !== void 0);
206
- return { name, avgMs: round(mean(times)), maxMs: round(times.length ? Math.max(...times) : 0) };
253
+ return {
254
+ name,
255
+ avgMs: round(mean(times)),
256
+ maxMs: round(times.length ? Math.max(...times) : 0)
257
+ };
207
258
  });
208
259
  const steady = frames.length > 1 ? frames.slice(1) : frames;
209
260
  const avg = (pick) => round(mean(steady.map(pick)), 1);
@@ -283,17 +334,27 @@ function analyzeTrace(capture, { maxHitches = 10 } = {}) {
283
334
  if (heavyPasses.length)
284
335
  findings.push(`Post-processing passes cost GPU fill rate on every pixel: ${heavyPasses.map((p) => p.name).join(", ")}`);
285
336
  }
286
- if (tickStats && budgetMs && tickStats.p95 > budgetMs / 2)
337
+ if (tickStats && budgetMs && tickStats.p95 > budgetMs / 2) {
287
338
  findings.push(`Game ticks are slow (p95 ${tickStats.p95}ms${tickStats.physics ? `, physics p95 ${tickStats.physics.p95}ms` : ""}${tickStats.world ? `, world.update p95 ${tickStats.world.p95}ms` : ""}) and block rendering when they run`);
339
+ }
288
340
  const gcHitches = worst.filter((h) => h.causes.some((c) => c.startsWith("Garbage collection"))).length;
289
341
  if (gcHitches >= 2)
290
342
  findings.push(`${gcHitches} hitches line up with garbage collection: reuse Vector3 / Matrix4 / arrays in update loops instead of allocating each frame`);
291
343
  if (late.length && budgetMs)
292
344
  findings.push(`${late.length} of ${frames.length} frames came late (over ${thresholdMs}ms), ${round(late.length / frames.length * 100, 1)}%`);
293
345
  const measureMap = /* @__PURE__ */ new Map();
294
- for (const span of capture.spans.filter((s) => s.category === "measure"))
295
- measureMap.set(span.name, [...measureMap.get(span.name) ?? [], span.duration]);
296
- const measures = Array.from(measureMap, ([name, durations]) => ({ name, count: durations.length, avgMs: round(mean(durations)), maxMs: round(Math.max(...durations)) })).sort((a, b) => b.avgMs * b.count - a.avgMs * a.count).slice(0, 20);
346
+ for (const span of capture.spans.filter((s) => s.category === "measure")) {
347
+ measureMap.set(span.name, [
348
+ ...measureMap.get(span.name) ?? [],
349
+ span.duration
350
+ ]);
351
+ }
352
+ const measures = Array.from(measureMap, ([name, durations]) => ({
353
+ name,
354
+ count: durations.length,
355
+ avgMs: round(mean(durations)),
356
+ maxMs: round(Math.max(...durations))
357
+ })).sort((a, b) => b.avgMs * b.count - a.avgMs * a.count).slice(0, 20);
297
358
  return {
298
359
  durationMs: capture.durationMs,
299
360
  frames: frames.length,
@@ -318,7 +379,15 @@ function analyzeTrace(capture, { maxHitches = 10 } = {}) {
318
379
  };
319
380
  }
320
381
  var PID = 1;
321
- var TRACKS = { frames: 1, passes: 2, gpu: 3, ticks: 4, js: 5, gl: 6, browser: 7 };
382
+ var TRACKS = {
383
+ frames: 1,
384
+ passes: 2,
385
+ gpu: 3,
386
+ ticks: 4,
387
+ js: 5,
388
+ gl: 6,
389
+ browser: 7
390
+ };
322
391
  var TRACK_NAMES = {
323
392
  [TRACKS.frames]: "Frames (render CPU)",
324
393
  [TRACKS.passes]: "Composer passes",
@@ -336,7 +405,16 @@ function profileEvents(profile) {
336
405
  while (open.length > depth) {
337
406
  const { frameId, start } = open.pop();
338
407
  const label = frameLabel(profile, frameId);
339
- events.push({ name: label.name, cat: "js", ph: "X", ts: us(start), dur: Math.max(1, us(at - start)), pid: PID, tid: TRACKS.js, args: label.location ? { location: label.location } : void 0 });
408
+ events.push({
409
+ name: label.name,
410
+ cat: "js",
411
+ ph: "X",
412
+ ts: us(start),
413
+ dur: Math.max(1, us(at - start)),
414
+ pid: PID,
415
+ tid: TRACKS.js,
416
+ args: label.location ? { location: label.location } : void 0
417
+ });
340
418
  }
341
419
  };
342
420
  const samples = weightedSamples(profile);
@@ -367,10 +445,33 @@ function spanEvent(span) {
367
445
  }
368
446
  function toTraceEvents(capture, label = "MavonEngine game tab") {
369
447
  const events = [
370
- { name: "process_name", ph: "M", ts: 0, pid: PID, tid: 0, args: { name: label } },
448
+ {
449
+ name: "process_name",
450
+ ph: "M",
451
+ ts: 0,
452
+ pid: PID,
453
+ tid: 0,
454
+ args: { name: label }
455
+ },
371
456
  ...Object.entries(TRACK_NAMES).flatMap(([tid, name]) => [
372
- { name: "thread_name", ph: "M", ts: 0, pid: PID, tid: Number(tid), args: { name } },
373
- { name: "thread_sort_index", ph: "M", ts: 0, pid: PID, tid: Number(tid), args: { sort_index: Number(tid) } }
457
+ {
458
+ name: "thread_name",
459
+ ph: "M",
460
+ ts: 0,
461
+ pid: PID,
462
+ tid: Number(tid),
463
+ args: { name }
464
+ },
465
+ {
466
+ name: "thread_sort_index",
467
+ ph: "M",
468
+ ts: 0,
469
+ pid: PID,
470
+ tid: Number(tid),
471
+ args: {
472
+ sort_index: Number(tid)
473
+ }
474
+ }
374
475
  ])
375
476
  ];
376
477
  capture.frames.forEach((frame, index) => {
@@ -382,24 +483,75 @@ function toTraceEvents(capture, label = "MavonEngine game tab") {
382
483
  dur: Math.max(1, us(frame.cpu)),
383
484
  pid: PID,
384
485
  tid: TRACKS.frames,
385
- args: { intervalMs: frame.interval, cpuMs: frame.cpu, gpuMs: frame.gpu, drawCalls: frame.calls, triangles: frame.triangles, gl: frame.gl }
486
+ args: {
487
+ intervalMs: frame.interval,
488
+ cpuMs: frame.cpu,
489
+ gpuMs: frame.gpu,
490
+ drawCalls: frame.calls,
491
+ triangles: frame.triangles,
492
+ gl: frame.gl
493
+ }
386
494
  });
387
495
  frame.passes.forEach((pass, i) => {
388
496
  const [start, duration] = pass ?? [];
389
- if (start !== void 0 && duration !== void 0)
390
- events.push({ name: capture.passes[i] ?? `Pass ${i}`, cat: "pass", ph: "X", ts: us(start), dur: Math.max(1, us(duration)), pid: PID, tid: TRACKS.passes });
497
+ if (start !== void 0 && duration !== void 0) {
498
+ events.push({
499
+ name: capture.passes[i] ?? `Pass ${i}`,
500
+ cat: "pass",
501
+ ph: "X",
502
+ ts: us(start),
503
+ dur: Math.max(1, us(duration)),
504
+ pid: PID,
505
+ tid: TRACKS.passes
506
+ });
507
+ }
391
508
  });
392
- if (frame.gpu !== null)
393
- events.push({ name: `GPU frame ${index}`, cat: "gpu", ph: "X", ts: us(frame.start), dur: Math.max(1, us(frame.gpu)), pid: PID, tid: TRACKS.gpu });
509
+ if (frame.gpu !== null) {
510
+ events.push({
511
+ name: `GPU frame ${index}`,
512
+ cat: "gpu",
513
+ ph: "X",
514
+ ts: us(frame.start),
515
+ dur: Math.max(1, us(frame.gpu)),
516
+ pid: PID,
517
+ tid: TRACKS.gpu
518
+ });
519
+ }
394
520
  const counters = { drawCalls: frame.calls, glDraws: frame.gl.draws };
395
521
  if (frame.interval)
396
522
  counters.fps = round(1e3 / frame.interval, 1);
397
- events.push({ name: "Frame", ph: "C", ts: us(frame.start), pid: PID, tid: 0, args: counters });
398
- if (frame.heap !== null)
399
- events.push({ name: "JS heap (MB)", ph: "C", ts: us(frame.start), pid: PID, tid: 0, args: { used: round(frame.heap / MB) } });
523
+ events.push({
524
+ name: "Frame",
525
+ ph: "C",
526
+ ts: us(frame.start),
527
+ pid: PID,
528
+ tid: 0,
529
+ args: counters
530
+ });
531
+ if (frame.heap !== null) {
532
+ events.push({
533
+ name: "JS heap (MB)",
534
+ ph: "C",
535
+ ts: us(frame.start),
536
+ pid: PID,
537
+ tid: 0,
538
+ args: {
539
+ used: round(frame.heap / MB)
540
+ }
541
+ });
542
+ }
400
543
  });
401
544
  for (const tick of capture.ticks) {
402
- events.push({ name: "tick", cat: "tick", ph: "X", ts: us(tick.start), dur: Math.max(1, us(tick.duration)), pid: PID, tid: TRACKS.ticks, args: { physicsMs: tick.physics, worldMs: tick.world } });
545
+ events.push({
546
+ name: "tick",
547
+ cat: "tick",
548
+ ph: "X",
549
+ ts: us(tick.start),
550
+ dur: Math.max(1, us(tick.duration)),
551
+ pid: PID,
552
+ tid: TRACKS.ticks,
553
+ args: { physicsMs: tick.physics, worldMs: tick.world }
554
+ });
403
555
  }
404
556
  events.push(...capture.spans.map(spanEvent));
405
557
  if (capture.profile)
@@ -419,12 +571,27 @@ function toTraceEvents(capture, label = "MavonEngine game tab") {
419
571
  }
420
572
 
421
573
  // src/mcp/clientTools.ts
422
- var CLIENT_LOG_LEVELS = ["error", "warn", "info", "log", "debug"];
423
- var SEVERITY = { error: 0, warn: 1, info: 2, log: 2, debug: 3 };
574
+ var CLIENT_LOG_LEVELS = [
575
+ "error",
576
+ "warn",
577
+ "info",
578
+ "log",
579
+ "debug"
580
+ ];
581
+ var SEVERITY = {
582
+ error: 0,
583
+ warn: 1,
584
+ info: 2,
585
+ log: 2,
586
+ debug: 3
587
+ };
424
588
  var clientId = z.string().optional().describe("Tab id from list_clients. Default: the only open tab, or the only one not running the editor");
425
589
  function delta(a, b) {
426
590
  const d = { x: b.x - a.x, y: b.y - a.y, z: b.z - a.z };
427
- return { ...d, length: Math.hypot(d.x, d.y, d.z) };
591
+ return {
592
+ ...d,
593
+ length: Math.hypot(d.x, d.y, d.z)
594
+ };
428
595
  }
429
596
  function compareEntities(id, server, client) {
430
597
  if (!server || !client) {
@@ -437,7 +604,12 @@ function compareEntities(id, server, client) {
437
604
  }
438
605
  const serverFields = server.serialized ?? {};
439
606
  const clientFields = client.serialized ?? {};
440
- const differentFields = [.../* @__PURE__ */ new Set([...Object.keys(serverFields), ...Object.keys(clientFields)])].filter((field) => !["id", "position", "rotation", "scale"].includes(field)).filter((field) => JSON.stringify(serverFields[field]) !== JSON.stringify(clientFields[field])).map((field) => ({ field, server: serverFields[field], client: clientFields[field] }));
607
+ const differentFields = [
608
+ .../* @__PURE__ */ new Set([
609
+ ...Object.keys(serverFields),
610
+ ...Object.keys(clientFields)
611
+ ])
612
+ ].filter((field) => !["id", "position", "rotation", "scale"].includes(field)).filter((field) => JSON.stringify(serverFields[field]) !== JSON.stringify(clientFields[field])).map((field) => ({ field, server: serverFields[field], client: clientFields[field] }));
441
613
  const { serialized: _s, ...serverSummary } = server;
442
614
  const { serialized: _c, ...clientSummary } = client;
443
615
  return {
@@ -463,7 +635,11 @@ function registerClientTools(server, client) {
463
635
  annotations: READ_ONLY
464
636
  }, () => run(async () => {
465
637
  const { clients } = await client.clients();
466
- return { devServer: client.clientUrl, clients, ...clients.length ? {} : { note: "No game tab is open. Open the game in a browser" } };
638
+ return {
639
+ devServer: client.clientUrl,
640
+ clients,
641
+ ...clients.length ? {} : { note: "No game tab is open. Open the game in a browser" }
642
+ };
467
643
  }));
468
644
  server.registerTool("client_status", {
469
645
  title: "Client status",
@@ -487,7 +663,10 @@ function registerClientTools(server, client) {
487
663
  server.registerTool("client_entity", {
488
664
  title: "One entity on a client",
489
665
  description: "One entity in a tab's world with its serialized state. The server id of the tab's own player finds its local player.",
490
- inputSchema: { id: z.string().min(1), clientId },
666
+ inputSchema: {
667
+ id: z.string().min(1),
668
+ clientId
669
+ },
491
670
  annotations: READ_ONLY
492
671
  }, ({ id, clientId: clientId3 }) => run(async () => {
493
672
  const { entity } = await client.client("entity", { id }, clientId3);
@@ -498,7 +677,10 @@ function registerClientTools(server, client) {
498
677
  server.registerTool("client_scene", {
499
678
  title: "Scene on a client",
500
679
  description: "The scene loaded in a tab, in the same shape as get_scene: objects with `built` telling whether the client built them.",
501
- inputSchema: { clientId, includeObjects: z.boolean().default(true) },
680
+ inputSchema: {
681
+ clientId,
682
+ includeObjects: z.boolean().default(true)
683
+ },
502
684
  annotations: READ_ONLY
503
685
  }, ({ clientId: clientId3, includeObjects }) => run(async () => {
504
686
  const { scene } = await client.client("scene", {}, clientId3);
@@ -534,7 +716,10 @@ function registerClientTools(server, client) {
534
716
  return {
535
717
  latestId,
536
718
  matched: matches.length,
537
- entries: matches.slice(-limit).map(({ timestamp, ...entry }) => ({ ...entry, time: new Date(timestamp).toISOString() }))
719
+ entries: matches.slice(-limit).map(({ timestamp, ...entry }) => ({
720
+ ...entry,
721
+ time: new Date(timestamp).toISOString()
722
+ }))
538
723
  };
539
724
  }));
540
725
  server.registerTool("client_screenshot", {
@@ -556,7 +741,12 @@ function registerClientTools(server, client) {
556
741
  ]
557
742
  };
558
743
  } catch (err) {
559
- return { isError: true, content: [{ type: "text", text: err.message }] };
744
+ return {
745
+ isError: true,
746
+ content: [
747
+ { type: "text", text: err.message }
748
+ ]
749
+ };
560
750
  }
561
751
  });
562
752
  server.registerTool("client_trace", {
@@ -574,7 +764,12 @@ function registerClientTools(server, client) {
574
764
  },
575
765
  annotations: { ...READ_ONLY, idempotentHint: false }
576
766
  }, ({ clientId: clientId3, durationMs, jsProfile, sampleIntervalMs, gpu, maxHitches, savePath, save }) => run(async () => {
577
- const capture = await client.client("trace", { durationMs, jsProfile: String(jsProfile), sampleIntervalMs, gpu: String(gpu) }, clientId3);
767
+ const capture = await client.client("trace", {
768
+ durationMs,
769
+ jsProfile: String(jsProfile),
770
+ sampleIntervalMs,
771
+ gpu: String(gpu)
772
+ }, clientId3);
578
773
  const analysis = analyzeTrace(capture, { maxHitches });
579
774
  let traceFile;
580
775
  if (save) {
@@ -591,10 +786,16 @@ function registerClientTools(server, client) {
591
786
  server.registerTool("compare_entity", {
592
787
  title: "Compare an entity on server and client",
593
788
  description: "One entity as the server has it next to a tab's copy: position / rotation / scale deltas and the serialized fields that differ. For the tab's own player pass its server id (playerId from list_clients). Needs the server in development too.",
594
- inputSchema: { id: z.string().min(1).describe("Entity id on the server"), clientId },
789
+ inputSchema: {
790
+ id: z.string().min(1).describe("Entity id on the server"),
791
+ clientId
792
+ },
595
793
  annotations: READ_ONLY
596
794
  }, ({ id, clientId: clientId3 }) => run(async () => {
597
- const [onServer, onClient] = await Promise.all([client.entity(id), client.client("entity", { id }, clientId3)]);
795
+ const [onServer, onClient] = await Promise.all([
796
+ client.entity(id),
797
+ client.client("entity", { id }, clientId3)
798
+ ]);
598
799
  return compareEntities(id, onServer.entity, onClient.entity);
599
800
  }));
600
801
  }
@@ -613,7 +814,10 @@ function redactRows(columns, rows) {
613
814
  }
614
815
  return {
615
816
  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])))
817
+ rows: secret.size === 0 ? rows : rows.map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [
818
+ key,
819
+ secret.has(key) && value !== null ? "[redacted]" : value
820
+ ])))
617
821
  };
618
822
  }
619
823
  function registerDatabaseTools(server, client) {
@@ -672,7 +876,10 @@ var packetFilters = {
672
876
  limit: z3.number().int().min(1).max(2e3).default(50).describe("Newest records kept when more match")
673
877
  };
674
878
  function withTime({ timestamp, ...record }) {
675
- return { ...record, time: new Date(timestamp).toISOString() };
879
+ return {
880
+ ...record,
881
+ time: new Date(timestamp).toISOString()
882
+ };
676
883
  }
677
884
  function listing(list) {
678
885
  return {
@@ -692,13 +899,18 @@ function registerNetworkTools(server, client) {
692
899
  server.registerTool("network_packets", {
693
900
  title: "Packets on the server",
694
901
  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.",
695
- inputSchema: { ...packetFilters, peer: z3.string().optional().describe("Only one client: its player id (list_players, or playerId from list_clients)") },
902
+ inputSchema: {
903
+ ...packetFilters,
904
+ peer: z3.string().optional().describe("Only one client: its player id (list_players, or playerId from list_clients)")
905
+ },
696
906
  annotations: READ_ONLY
697
907
  }, ({ afterId, ...query }) => run(async () => listing(await client.packets({ ...query, after: afterId }))));
698
908
  server.registerTool("network_packet", {
699
909
  title: "One packet on the server",
700
910
  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.",
701
- inputSchema: { id: z3.number().int().min(1) },
911
+ inputSchema: {
912
+ id: z3.number().int().min(1)
913
+ },
702
914
  annotations: READ_ONLY
703
915
  }, ({ id }) => run(async () => {
704
916
  const { record } = await client.packet(id);
@@ -717,8 +929,9 @@ function registerNetworkTools(server, client) {
717
929
  }, ({ player, includeEntities }) => run(async () => {
718
930
  const sync = await client.sync();
719
931
  const { entities = [], players = [], ...rest } = sync;
720
- if (!player)
932
+ if (!player) {
721
933
  return includeEntities ? sync : { ...rest, players, entityCount: entities.length };
934
+ }
722
935
  const one = players.find((p) => p.id === player);
723
936
  if (!one)
724
937
  throw new Error(`No player "${player}". Players: ${players.map((p) => p.id).join(", ") || "none"}`);
@@ -726,7 +939,12 @@ function registerNetworkTools(server, client) {
726
939
  return {
727
940
  ...rest,
728
941
  player: one,
729
- ...includeEntities ? { entities: entities.map((entity) => ({ ...entity, tracked: tracked.has(entity.id) })) } : { entityCount: entities.length }
942
+ ...includeEntities ? {
943
+ entities: entities.map((entity) => ({
944
+ ...entity,
945
+ tracked: tracked.has(entity.id)
946
+ }))
947
+ } : { entityCount: entities.length }
730
948
  };
731
949
  }));
732
950
  server.registerTool("client_packets", {
@@ -738,7 +956,10 @@ function registerNetworkTools(server, client) {
738
956
  server.registerTool("client_packet", {
739
957
  title: "One packet on a client",
740
958
  description: "One record from client_packets with its payload.",
741
- inputSchema: { id: z3.number().int().min(1), clientId: clientId2 },
959
+ inputSchema: {
960
+ id: z3.number().int().min(1),
961
+ clientId: clientId2
962
+ },
742
963
  annotations: READ_ONLY
743
964
  }, ({ id, clientId: clientId3 }) => run(async () => {
744
965
  const { record } = await client.client("packet", { id }, clientId3);
@@ -830,7 +1051,9 @@ function registerPluginTools(server, client, list) {
830
1051
  server.registerTool("plugin_readme", {
831
1052
  title: "Read a plugin's readme",
832
1053
  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.",
833
- inputSchema: { package: z4.string().describe("npm package of the plugin, e.g. @mavonengine/chat") },
1054
+ inputSchema: {
1055
+ package: z4.string().describe("npm package of the plugin, e.g. @mavonengine/chat")
1056
+ },
834
1057
  annotations: { ...READ_ONLY, openWorldHint: true }
835
1058
  }, async ({ package: pkg }) => {
836
1059
  try {
@@ -838,9 +1061,18 @@ function registerPluginTools(server, client, list) {
838
1061
  const plugin = plugins.find((candidate) => candidate.package === pkg);
839
1062
  if (!plugin)
840
1063
  throw new Error(`${pkg} is not on the list of plugins. It has: ${plugins.map((candidate) => candidate.package).join(", ") || "nothing"}`);
841
- return { content: [{ type: "text", text: await fetchPluginReadme(plugin, { fetch: list.fetch }) }] };
1064
+ return {
1065
+ content: [
1066
+ { type: "text", text: await fetchPluginReadme(plugin, { fetch: list.fetch }) }
1067
+ ]
1068
+ };
842
1069
  } catch (err) {
843
- return { isError: true, content: [{ type: "text", text: err.message }] };
1070
+ return {
1071
+ isError: true,
1072
+ content: [
1073
+ { type: "text", text: err.message }
1074
+ ]
1075
+ };
844
1076
  }
845
1077
  });
846
1078
  }
@@ -848,7 +1080,9 @@ function registerPluginTools(server, client, list) {
848
1080
  // src/mcp/server.ts
849
1081
  var INSTRUCTIONS = `Reads the live state of a running MavonEngine game: the game server (health, performance, players, scene,
850
1082
  entities, logs, HTTP requests) and, in development, the game tabs open in a browser (renderer stats, the client's world,
851
- network state, console logs, screenshots). Every tool is read-only.
1083
+ network state, console logs, screenshots). These tools are read-only.
1084
+ Tools named <plugin>_<tool> come from the project's plugins, through the client's dev server: what they do is in their
1085
+ descriptions, and their annotations say whether they change the project (files, mavonengine.json).
852
1086
  Server scene / entity tools need the server in development (NODE_ENV is not "production"); client tools need the client
853
1087
  served by Vite in dev. Start with server_status and list_clients. Use type / near filters rather than paging through a world.
854
1088
  compare_entity shows one entity on both sides, for prediction, interpolation and sync bugs.
@@ -866,7 +1100,12 @@ function summarize(metrics) {
866
1100
  return {
867
1101
  ...rest,
868
1102
  players: Array.isArray(players) ? players.length : 0,
869
- cpu: cpu && { current: cpu.current, avg1s: cpu.avg1s, avg10s: cpu.avg10s, avg60s: cpu.avg60s },
1103
+ cpu: cpu && {
1104
+ current: cpu.current,
1105
+ avg1s: cpu.avg1s,
1106
+ avg10s: cpu.avg10s,
1107
+ avg60s: cpu.avg60s
1108
+ },
870
1109
  bandwidth: bandwidth && { sentPerSecond: bandwidth.sentPerSecond, receivedPerSecond: bandwidth.receivedPerSecond },
871
1110
  tick: tick && { budgetMs: tick.budgetMs, latest: tick.latest }
872
1111
  };
@@ -880,11 +1119,16 @@ function createMcpServer(client, docs, pluginList) {
880
1119
  title: "Game server status",
881
1120
  description: "Health and current performance of the game server: uptime, tick rate and tick time against its budget, CPU, bandwidth, memory, player and entity counts, physics bodies, latency simulation. History is left out, see server_metrics.",
882
1121
  annotations: READ_ONLY
883
- }, () => run(async () => ({ server: client.url, ...summarize(await client.metrics()) })));
1122
+ }, () => run(async () => ({
1123
+ server: client.url,
1124
+ ...summarize(await client.metrics())
1125
+ })));
884
1126
  server.registerTool("server_metrics", {
885
1127
  title: "Full metrics snapshot",
886
1128
  description: "The full metrics snapshot. With includeHistory, also the last ~60 samples of CPU, bandwidth and tick timings, to spot spikes.",
887
- inputSchema: { includeHistory: z5.boolean().default(false).describe("Include the per-sample history arrays") },
1129
+ inputSchema: {
1130
+ includeHistory: z5.boolean().default(false).describe("Include the per-sample history arrays")
1131
+ },
888
1132
  annotations: READ_ONLY
889
1133
  }, ({ includeHistory }) => run(async () => {
890
1134
  const metrics = await client.metrics();
@@ -894,7 +1138,12 @@ function createMcpServer(client, docs, pluginList) {
894
1138
  const { history: _cpu, ...cpuNow } = cpu ?? {};
895
1139
  const { history: _bandwidth, ...bandwidthNow } = bandwidth ?? {};
896
1140
  const { history: _tick, ...tickNow } = tick ?? {};
897
- return { ...metrics, cpu: cpuNow, bandwidth: bandwidthNow, tick: tickNow };
1141
+ return {
1142
+ ...metrics,
1143
+ cpu: cpuNow,
1144
+ bandwidth: bandwidthNow,
1145
+ tick: tickNow
1146
+ };
898
1147
  }));
899
1148
  server.registerTool("list_players", {
900
1149
  title: "Connected players",
@@ -904,7 +1153,9 @@ function createMcpServer(client, docs, pluginList) {
904
1153
  server.registerTool("get_scene", {
905
1154
  title: "Active scene",
906
1155
  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.",
907
- inputSchema: { includeObjects: z5.boolean().default(true).describe("Include the scene objects, not just the summary") },
1156
+ inputSchema: {
1157
+ includeObjects: z5.boolean().default(true).describe("Include the scene objects, not just the summary")
1158
+ },
908
1159
  annotations: READ_ONLY
909
1160
  }, ({ includeObjects }) => run(async () => {
910
1161
  const { scene } = await client.scene();
@@ -930,7 +1181,9 @@ function createMcpServer(client, docs, pluginList) {
930
1181
  server.registerTool("get_entity", {
931
1182
  title: "One entity",
932
1183
  description: "One entity by id, with the state it sends to clients (its serialize() output). Development only.",
933
- inputSchema: { id: z5.string().min(1) },
1184
+ inputSchema: {
1185
+ id: z5.string().min(1)
1186
+ },
934
1187
  annotations: READ_ONLY
935
1188
  }, ({ id }) => run(async () => {
936
1189
  const { entity } = await client.entity(id);
@@ -959,7 +1212,10 @@ function createMcpServer(client, docs, pluginList) {
959
1212
  return {
960
1213
  latestId,
961
1214
  matched: matches.length,
962
- entries: matches.slice(-limit).map(({ timestamp, ...entry }) => ({ ...entry, time: new Date(timestamp).toISOString() }))
1215
+ entries: matches.slice(-limit).map(({ timestamp, ...entry }) => ({
1216
+ ...entry,
1217
+ time: new Date(timestamp).toISOString()
1218
+ }))
963
1219
  };
964
1220
  }));
965
1221
  server.registerTool("recent_requests", {
@@ -975,7 +1231,11 @@ function createMcpServer(client, docs, pluginList) {
975
1231
  }, ({ pathContains, minStatus, afterId, limit }) => run(async () => {
976
1232
  const { entries = [], latestId = 0 } = await client.requests(afterId);
977
1233
  const matches = entries.filter((entry) => (!pathContains || entry.path.includes(pathContains)) && (minStatus === void 0 || (entry.status ?? 0) >= minStatus));
978
- return { latestId, matched: matches.length, entries: matches.slice(-limit) };
1234
+ return {
1235
+ latestId,
1236
+ matched: matches.length,
1237
+ entries: matches.slice(-limit)
1238
+ };
979
1239
  }));
980
1240
  registerClientTools(server, client);
981
1241
  registerNetworkTools(server, client);