@playcanvas/inspector 0.4.0 → 0.6.0

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.
@@ -0,0 +1,1149 @@
1
+ import { Material, RenderTarget, Texture, revision, version } from 'playcanvas';
2
+
3
+ import { assetRows } from './asset-view.js';
4
+ import { cameraRows } from './camera-view.js';
5
+ import { layerRows } from './layer-view.js';
6
+ import { copyListRow, copySubject } from './copy-json.js';
7
+ import { passRows } from './frame-graph-view.js';
8
+ import { matchesFilter } from './hierarchy-view.js';
9
+ import { LEVELS } from './log-capture.js';
10
+ import { materialListRows, surveyMaterials } from './material-view.js';
11
+ import { bufferOwners, memoryRows, videoMemory } from './memory-view.js';
12
+ import { meshListRows, surveyMeshes } from './mesh-view.js';
13
+ import { SERIES, frameJson, header, loadJson, passesOf, seriesRows, toCsv } from './perf-copy.js';
14
+ import { captureNorms, isHitch, rangeStats } from './perf-view.js';
15
+ import { renderTargetRows } from './render-target-view.js';
16
+ import { scriptListRows, surveyScripts } from './script-view.js';
17
+ import { shaderRows } from './shader-view.js';
18
+ import { kindOf } from './ref-registry.js';
19
+ import { textureRows } from './texture-view.js';
20
+
21
+ /** @import { AppBase, GraphNode } from 'playcanvas' */
22
+ /** @import { CopyOptions } from './copy-json.js' */
23
+ /** @import { FrameSnapshot } from './frame-graph-view.js' */
24
+ /** @import { ListRow } from './list-view.js' */
25
+ /** @import { PerfCapture } from './perf-capture.js' */
26
+ /** @import { PropertyRow, PropertySection } from './model.js' */
27
+ /** @import { RefRegistry } from './ref-registry.js' */
28
+ /** @import { LogCapture } from './log-capture.js' */
29
+ /** @import { ImageCapture } from './image-capture.js' */
30
+
31
+ /**
32
+ * What the tools read the app through, provided by the inspector.
33
+ *
34
+ * @typedef {object} McpHost
35
+ * @ignore
36
+ * @property {AppBase} app - The app.
37
+ * @property {RefRegistry} refs - The ids of the objects the tools return.
38
+ * @property {(obj: object, subject: boolean) => PropertySection[]|PropertyRow[]|null} modelFor -
39
+ * The model of an object as its tab shows it; for the subject of a request, with the lists of what
40
+ * uses it.
41
+ * @property {(obj: object) => boolean} opaque - Whether an object is never followed, see
42
+ * {@link CopyOptions#opaque}.
43
+ * @property {(obj: object) => boolean} exclude - Whether a node belongs to the inspector rather
44
+ * than the app.
45
+ * @property {() => FrameSnapshot} frame - The frame graph of the frame rendered last.
46
+ * @property {McpPerfHost} perf - The capture of the Performance tab, and its controls.
47
+ * @property {LogCapture} logs - The messages the page logged since the tools were turned on.
48
+ * @property {() => ImageCapture} images - Captures textures and the canvas into images.
49
+ * @property {McpTimeHost} time - Pausing and stepping the app, as the Pause and Step buttons do.
50
+ */
51
+
52
+ /**
53
+ * The Pause and Step buttons, as the time tools drive them.
54
+ *
55
+ * @typedef {object} McpTimeHost
56
+ * @ignore
57
+ * @property {() => boolean} paused - Whether the app is paused.
58
+ * @property {(paused: boolean) => void} setPaused - Pauses or resumes the app.
59
+ * @property {(frames: number, timeout: number) => Promise<number>} step - Pauses the app if it is
60
+ * not, then runs that many frames with time moving, and resolves with how many ran before the
61
+ * timeout, in milliseconds.
62
+ * @property {() => number} frame - The number of the app frame now.
63
+ */
64
+
65
+ /**
66
+ * The Performance tab as the perf tools drive it: its capture, and the switches the panel shows,
67
+ * set through the panel so its controls follow.
68
+ *
69
+ * @typedef {object} McpPerfHost
70
+ * @ignore
71
+ * @property {PerfCapture} capture - The capture.
72
+ * @property {(on: boolean) => void} setRecording - Starts or stops recording, as the Record button.
73
+ * @property {(on: boolean) => void} setGpuTimings - Turns the GPU timings on or off.
74
+ * @property {(on: boolean) => void} setScriptTiming - Turns the timing of scripts on or off.
75
+ * @property {() => void} clear - Forgets every frame, as the Clear button.
76
+ * @property {() => boolean} gpuSupported - Whether the device can time the GPU.
77
+ * @property {() => boolean} gpuTimings - Whether the GPU is being timed.
78
+ * @property {() => boolean} paused - Whether the inspector has paused the app.
79
+ * @property {() => object} device - What to say about the device in a capture.
80
+ * @property {boolean} byAgent - Whether the frames kept were recorded by the tools, rather than by
81
+ * the user, whose capture the tools do not clear unasked. Starting to record from the panel or
82
+ * from code clears it.
83
+ * @property {PerfSession|null} session - The recording the tools are stopping after a number of
84
+ * frames, if any.
85
+ */
86
+
87
+ /**
88
+ * A recording the perf tools stop after a number of frames.
89
+ *
90
+ * @typedef {object} PerfSession
91
+ * @ignore
92
+ * @property {number} from - The first frame it records.
93
+ * @property {number} target - The frame it stops before.
94
+ * @property {boolean} hidden - Whether the page was hidden while it recorded.
95
+ * @property {() => void} onFrame - Stops it once the frames are recorded.
96
+ * @property {() => void} onVisibility - Notes the page being hidden.
97
+ * @property {ReturnType<typeof setTimeout>} timer - Stops it when it takes too long.
98
+ * @property {((reason: string) => void)|null} done - Hands the reason it ended to a caller waiting.
99
+ */
100
+
101
+ /**
102
+ * A tool, described the way WebMCP and MCP describe one.
103
+ *
104
+ * @typedef {object} McpTool
105
+ * @property {string} name - The name the tool is called by.
106
+ * @property {string} description - What the tool does, for the agent choosing it.
107
+ * @property {object} inputSchema - The JSON schema of its arguments.
108
+ * @property {{ readOnlyHint: boolean, destructiveHint?: boolean }} annotations - Hints about its
109
+ * effects: most tools only read; the perf tools change the inspector's capture, never the app.
110
+ */
111
+
112
+ /**
113
+ * @typedef {McpTool & { execute: (host: McpHost, args: any) => any }} McpToolImpl
114
+ * @ignore
115
+ */
116
+
117
+ // the most entries a list or search returns at once, and how many links a get follows at most
118
+ const MAX_LIMIT = 500;
119
+ const MAX_DEPTH = 4;
120
+
121
+ // the lists an index holds, and the most entries of each, so even a huge app gives a bounded index
122
+ const INDEX_LISTS = ['cameras', 'layers', 'materials', 'textures', 'shaders', 'meshes', 'renderTargets', 'scripts', 'assets', 'passes'];
123
+ const MAX_INDEX_ENTRIES = 2000;
124
+
125
+ // how many objects a get copies in full, so a deep get of a big scene stays a sensible size
126
+ const MAX_GET_OBJECTS = 2000;
127
+
128
+ /**
129
+ * The lists of the inspector's tabs, by the kind a list tool names them.
130
+ *
131
+ * @type {Record<string, (host: McpHost) => ListRow[]>}
132
+ */
133
+ const LISTS = {
134
+ textures: ({ app }) => textureRows(app.graphicsDevice),
135
+ shaders: ({ app }) => shaderRows(app.graphicsDevice),
136
+ materials: ({ app }) => materialListRows(surveyMaterials(app)),
137
+ meshes: ({ app }) => meshListRows(surveyMeshes(app)),
138
+ scripts: ({ app }) => scriptListRows(surveyScripts(app)),
139
+ cameras: ({ app }) => cameraRows(app, null),
140
+ layers: ({ app }) => layerRows(app),
141
+ assets: ({ app }) => assetRows(app.assets, 'type'),
142
+ renderTargets: host => renderTargetRows(host.app.graphicsDevice, host.frame()),
143
+ passes: host => passRows(host.frame(), host.app.graphicsDevice),
144
+ memory: ({ app }) => memoryRows(app.graphicsDevice, bufferOwners(app))
145
+ };
146
+
147
+ // the lists whose objects the app may rebuild every frame, which get ids by row key instead
148
+ const KEYED_LISTS = new Set(['passes', 'renderTargets']);
149
+
150
+ // the properties of a material that describe its class rather than itself
151
+ const MATERIAL_TABLES = new Set(['propertyDescriptors', 'textureDescriptors', 'textureIdentifiers']);
152
+
153
+ /**
154
+ * Leaves out of a material what says nothing about it: the settings of each texture slot left
155
+ * empty (its tiling, offset, rotation, uv set and channel), the channel of a vertex color not
156
+ * used, and the tables its class keeps. A material otherwise lists some 300 properties.
157
+ *
158
+ * @param {PropertySection[]|PropertyRow[]|null} model - The model of a material.
159
+ * @returns {PropertySection[]|PropertyRow[]|null} The model, trimmed.
160
+ */
161
+ function trimMaterial(model) {
162
+ if (!model) return model;
163
+ const trimRows = (rows) => {
164
+ const raw = new Map(rows.map(row => [row.label, 'raw' in row.value ? row.value.raw : row.value.target]));
165
+ return rows.filter((row) => {
166
+ if (MATERIAL_TABLES.has(row.label)) return false;
167
+ const slot = /^(.+Map)(?:Tiling|Offset|Rotation|Uv|Channel)$/.exec(row.label);
168
+ if (slot && raw.has(slot[1]) && !raw.get(slot[1])) return false;
169
+ const vertex = /^(.+VertexColor)Channel$/.exec(row.label);
170
+ if (vertex && raw.has(vertex[1]) && !raw.get(vertex[1])) return false;
171
+ return true;
172
+ });
173
+ };
174
+ if (model.length && Array.isArray(/** @type {any} */ (model[0]).rows)) {
175
+ return /** @type {PropertySection[]} */ (model).map(section => ({ ...section, rows: trimRows(section.rows) }));
176
+ }
177
+ return trimRows(/** @type {PropertyRow[]} */ (model));
178
+ }
179
+
180
+ /**
181
+ * @param {McpHost} host - The host.
182
+ * @param {object} obj - An object.
183
+ * @param {boolean} subject - Whether it is the object asked for.
184
+ * @returns {PropertySection[]|PropertyRow[]|null} Its model, as the tools show it.
185
+ */
186
+ function modelOf(host, obj, subject) {
187
+ const model = host.modelFor(obj, subject);
188
+ return obj instanceof Material ? trimMaterial(model) : model;
189
+ }
190
+
191
+ /**
192
+ * Checks arguments against a tool's input schema: required properties, and the type, range and
193
+ * allowed values of each property given. The browser passes arguments on as they are.
194
+ *
195
+ * @param {McpTool} tool - The tool.
196
+ * @param {any} args - The arguments.
197
+ */
198
+ function validate(tool, args) {
199
+ if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new Error('The arguments must be an object');
200
+ const schema = /** @type {any} */ (tool.inputSchema);
201
+ for (const name of schema.required ?? []) {
202
+ if (args[name] === undefined) throw new Error(`"${name}" is required`);
203
+ }
204
+ for (const [name, value] of Object.entries(args)) {
205
+ const prop = schema.properties?.[name];
206
+ if (!prop) throw new Error(`Unknown argument "${name}". Arguments: ${Object.keys(schema.properties ?? {}).join(', ') || 'none'}`);
207
+ const ok = prop.type === 'integer' ? Number.isInteger(value) : typeof value === prop.type;
208
+ if (!ok) throw new Error(`"${name}" must be ${prop.type === 'integer' ? 'an integer' : `a ${prop.type}`}`);
209
+ if (prop.enum && !prop.enum.includes(value)) throw new Error(`"${name}" must be one of: ${prop.enum.join(', ')}`);
210
+ if (prop.pattern && !new RegExp(prop.pattern).test(value)) throw new Error(`"${name}" must match ${prop.pattern}`);
211
+ if (prop.minimum !== undefined && value < prop.minimum) throw new Error(`"${name}" must be at least ${prop.minimum}`);
212
+ if (prop.maximum !== undefined && value > prop.maximum) throw new Error(`"${name}" must be at most ${prop.maximum}`);
213
+ }
214
+ }
215
+
216
+ /**
217
+ * @param {*} value - A number argument.
218
+ * @param {number} fallback - Its default.
219
+ * @param {number} max - Its largest value.
220
+ * @returns {number} The number, a whole one between 0 and max.
221
+ */
222
+ function clampInt(value, fallback, max) {
223
+ const n = Number.isFinite(value) ? Math.floor(value) : fallback;
224
+ return Math.max(0, Math.min(max, n));
225
+ }
226
+
227
+ /**
228
+ * @param {GraphNode} node - A node.
229
+ * @returns {string[]} The types of its components.
230
+ */
231
+ function componentsOf(node) {
232
+ const c = /** @type {any} */ (node).c;
233
+ return c ? Object.keys(c) : [];
234
+ }
235
+
236
+ /**
237
+ * @param {McpHost} host - The host.
238
+ * @returns {object} What the app is, and how it runs.
239
+ */
240
+ function appSummary(host) {
241
+ const app = /** @type {any} */ (host.app);
242
+ const device = app.graphicsDevice;
243
+
244
+ let entities = 0;
245
+ const count = (node) => {
246
+ if (host.exclude(node)) return;
247
+ entities++;
248
+ for (const child of node.children) count(child);
249
+ };
250
+ count(app.root);
251
+
252
+ const frame = app.stats?.frame ?? {};
253
+ const stats = {};
254
+ for (const key of ['fps', 'ms', 'triangles', 'shaders', 'materials', 'cullTime', 'renderTime', 'updateTime']) {
255
+ if (typeof frame[key] === 'number') stats[key] = frame[key];
256
+ }
257
+ if (typeof app.stats?.drawCalls?.total === 'number') stats.drawCalls = app.stats.drawCalls.total;
258
+
259
+ return {
260
+ engine: { version, revision },
261
+ device: {
262
+ type: device.deviceType,
263
+ width: device.width,
264
+ height: device.height,
265
+ maxPixelRatio: device.maxPixelRatio,
266
+ videoMemoryBytes: videoMemory(device)
267
+ },
268
+ root: host.refs.idOf(app.root),
269
+ entities,
270
+ assets: app.assets?.list().length ?? 0,
271
+ timeScale: app.timeScale,
272
+ stats,
273
+ lists: Object.keys(LISTS)
274
+ };
275
+ }
276
+
277
+ /**
278
+ * @param {McpHost} host - The host.
279
+ * @param {any} args - The search.
280
+ * @returns {object} The entities found.
281
+ */
282
+ function findEntities(host, args) {
283
+ const name = typeof args?.name === 'string' ? args.name.toLowerCase() : '';
284
+ const component = typeof args?.component === 'string' ? args.component.toLowerCase() : '';
285
+ const script = typeof args?.script === 'string' ? args.script.toLowerCase() : '';
286
+ const tag = typeof args?.tag === 'string' ? args.tag : '';
287
+ const limit = clampInt(args?.limit, 50, MAX_LIMIT);
288
+
289
+ const found = [];
290
+ let total = 0;
291
+ const visit = (node) => {
292
+ if (host.exclude(node)) return;
293
+ const match = (!name || matchesFilter(node, name, 'name')) &&
294
+ (!component || matchesFilter(node, component, 'component')) &&
295
+ (!script || matchesFilter(node, script, 'script')) &&
296
+ (!tag || node.tags.has(tag));
297
+ if (match) {
298
+ total++;
299
+ if (found.length < limit) {
300
+ found.push({
301
+ $id: host.refs.idOf(node),
302
+ name: node.name,
303
+ path: node.path,
304
+ enabled: node.enabled,
305
+ components: componentsOf(node)
306
+ });
307
+ }
308
+ }
309
+ for (const child of node.children) visit(child);
310
+ };
311
+ visit(host.app.root);
312
+ return { total, entities: found, truncated: total > found.length };
313
+ }
314
+
315
+ /**
316
+ * @param {McpHost} host - The host.
317
+ * @param {string} kind - Which list, one of {@link LISTS}.
318
+ * @param {string} filter - The lower-cased text names must contain, or empty for every entry.
319
+ * @param {number} offset - How many matching entries to skip.
320
+ * @param {number} limit - The most entries to return.
321
+ * @returns {{ total: number, entries: object[] }} The entries, and how many match in all.
322
+ */
323
+ function listEntries(host, kind, filter, offset, limit) {
324
+ const make = LISTS[kind];
325
+ const keyed = KEYED_LISTS.has(kind);
326
+ const entries = [];
327
+ let total = 0;
328
+ let group = null;
329
+ for (const row of make(host)) {
330
+ if (row.header) {
331
+ group = row.name;
332
+ continue;
333
+ }
334
+ if (filter && !(row.matches ? row.matches(filter) : row.name.toLowerCase().includes(filter))) continue;
335
+ if (total++ < offset || entries.length >= limit) continue;
336
+
337
+ const entry = {};
338
+ const item = row.item;
339
+ if ((typeof item === 'object' && item !== null) || typeof item === 'function') {
340
+ // a pass rebuilt every frame keeps its id, which finds the pass at its place in the frame
341
+ entry.$id = keyed ? host.refs.keyedId(kindOf(item), row.key, () => make(host).find(r => r.key === row.key)?.item ?? null) : host.refs.idOf(item);
342
+ entry.$type = typeof item === 'function' ? 'Script' : item.constructor?.name ?? 'Object';
343
+ }
344
+ if (group) entry.group = group;
345
+ const figures = copyListRow(row).json;
346
+ // a row naming no object of its own, such as a step of a pass, is named by what it belongs to
347
+ if (!figures.name && row.name) entry.name = row.name;
348
+ for (const [key, value] of Object.entries(figures)) {
349
+ // the separators the panel puts between cells mean nothing here
350
+ const text = typeof value === 'string' ? value.replace(/^·\s*/, '') : value;
351
+ // a row's tags, such as 'skinned' and 'morph', make one list
352
+ if (/^tag(?: \(\d+\))?$/.test(key)) (entry.tags ??= []).push(text);
353
+ else entry[key] = text;
354
+ }
355
+ entries.push(entry);
356
+ }
357
+ return { total, entries };
358
+ }
359
+
360
+ /**
361
+ * @param {McpHost} host - The host.
362
+ * @param {any} args - Which list, and which part of it.
363
+ * @returns {object} The entries.
364
+ */
365
+ function list(host, args) {
366
+ if (!LISTS[args?.kind]) throw new Error(`Unknown list "${args?.kind}". One of: ${Object.keys(LISTS).join(', ')}`);
367
+ const filter = typeof args?.filter === 'string' ? args.filter.toLowerCase() : '';
368
+ const offset = clampInt(args?.offset, 0, Number.MAX_SAFE_INTEGER);
369
+ const limit = clampInt(args?.limit, 100, MAX_LIMIT);
370
+ const { total, entries } = listEntries(host, args.kind, filter, offset, limit);
371
+ return { kind: args.kind, total, offset, entries, truncated: offset + entries.length < total };
372
+ }
373
+
374
+ /**
375
+ * @param {McpHost} host - The host.
376
+ * @returns {object} Everything the app holds, an entry each with its id: the summary, every
377
+ * entity with its path and components, and the entries of every list but memory.
378
+ */
379
+ function index(host) {
380
+ const entities = [];
381
+ let total = 0;
382
+ const visit = (node) => {
383
+ if (host.exclude(node)) return;
384
+ // the root is the summary's, and has no path
385
+ if (node !== host.app.root && total++ < MAX_INDEX_ENTRIES) {
386
+ const entry = { $id: host.refs.idOf(node), path: node.path, components: componentsOf(node) };
387
+ if (!node.enabled) entry.enabled = false;
388
+ entities.push(entry);
389
+ }
390
+ for (const child of node.children) visit(child);
391
+ };
392
+ visit(host.app.root);
393
+
394
+ const out = { summary: appSummary(host), entities: { total, entries: entities, truncated: total > entities.length } };
395
+ for (const kind of INDEX_LISTS) {
396
+ const result = listEntries(host, kind, '', 0, MAX_INDEX_ENTRIES);
397
+ out[kind] = { total: result.total, entries: result.entries, truncated: result.total > result.entries.length };
398
+ }
399
+ return out;
400
+ }
401
+
402
+ /**
403
+ * @param {McpHost} host - The host.
404
+ * @param {any} args - The id, and how far to follow links.
405
+ * @returns {object} The object, as its tab shows it.
406
+ */
407
+ function get(host, args) {
408
+ const id = typeof args?.id === 'string' ? args.id : '';
409
+ const obj = host.refs.get(id);
410
+ if (!obj) throw new Error(`No object with id "${id}": it is unknown, or the app has let go of it`);
411
+ const depth = clampInt(args?.depth, 0, MAX_DEPTH);
412
+ const result = copySubject(obj, /** @type {any} */ (modelOf(host, obj, true)), {
413
+ depth,
414
+ maxObjects: MAX_GET_OBJECTS,
415
+ backlinks: true,
416
+ code: args?.sources === true,
417
+ idOf: o => host.refs.idOf(o),
418
+ modelFor: o => modelOf(host, o, false),
419
+ opaque: host.opaque,
420
+ exclude: host.exclude
421
+ });
422
+ // an object found by a stable key is named by the id it was asked for
423
+ const json = { ...result.json, $id: id };
424
+ if (result.truncated) json.$truncated = true;
425
+ return json;
426
+ }
427
+
428
+ // the series playcanvas_perf_series returns, and the most rows of one at once
429
+ const PERF_SERIES = [...Object.keys(SERIES), 'scripts', 'counters', 'loading', 'events'];
430
+ const MAX_SERIES_ROWS = 300;
431
+
432
+ // how many of each kind of entry a summary lists, so it stays a few KB
433
+ const SUMMARY_PASSES = 15;
434
+ const SUMMARY_SCRIPTS = 10;
435
+ const SUMMARY_HITCHES = 10;
436
+ const SUMMARY_LOADS = 10;
437
+
438
+ // how long a recording of a number of frames may take by default, and at most, in seconds
439
+ const PERF_TIMEOUT = 30;
440
+ const MAX_PERF_TIMEOUT = 300;
441
+
442
+ /**
443
+ * @param {number} v - A figure.
444
+ * @returns {number} It to three decimals, which is a microsecond for a time in milliseconds.
445
+ */
446
+ function round(v) {
447
+ return Math.round(v * 1000) / 1000;
448
+ }
449
+
450
+ /**
451
+ * @returns {string} Whether the page is visible, hidden or else, as the browser says; frames stop
452
+ * while it is hidden.
453
+ */
454
+ function visibility() {
455
+ return typeof document !== 'undefined' ? document.visibilityState : 'unknown';
456
+ }
457
+
458
+ /**
459
+ * @param {PerfCapture} capture - The capture.
460
+ * @param {number} frame - A frame number, as the frames are numbered in what the tools return.
461
+ * @returns {number} Its sequence number.
462
+ */
463
+ function seqOf(capture, frame) {
464
+ return capture.startedAtStartup ? frame : frame - 1;
465
+ }
466
+
467
+ /**
468
+ * @param {PerfCapture} capture - The capture.
469
+ * @param {any} args - The first and last frame numbers asked for, both optional.
470
+ * @returns {{ from: number, to: number }} The frames, as sequence numbers, within those kept.
471
+ */
472
+ function rangeOf(capture, args) {
473
+ if (!capture.count) throw new Error('Nothing is recorded: start a capture with playcanvas_perf_record');
474
+ const first = capture.first;
475
+ const last = capture.end - 1;
476
+ const from = args?.from === undefined ? first : Math.max(first, seqOf(capture, args.from));
477
+ const to = args?.to === undefined ? last : Math.min(last, seqOf(capture, args.to));
478
+ if (from > to) throw new Error(`No frames kept in that range. Frames kept: ${capture.frameNumber(first)} to ${capture.frameNumber(last)}`);
479
+ return { from, to };
480
+ }
481
+
482
+ /**
483
+ * @param {PerfCapture} capture - The capture.
484
+ * @param {string|Float64Array} key - The channel, or a ring of values like one.
485
+ * @param {number} from - The first frame.
486
+ * @param {number} to - The last frame, inclusive.
487
+ * @returns {object|null} The smallest, mean, 95th percentile and largest of the figure over the
488
+ * frames, with how many frames had it where some did not, or null where none did.
489
+ */
490
+ function figureStats(capture, key, from, to) {
491
+ const { count, avg, p95, max } = rangeStats(capture, key, from, to);
492
+ if (!count) return null;
493
+ const data = typeof key === 'string' ? capture.data[key] : key;
494
+ let min = Infinity;
495
+ for (let seq = from; seq <= to; seq++) {
496
+ const v = data[capture.slot(seq)];
497
+ if (v < min) min = v;
498
+ }
499
+ /** @type {any} */
500
+ const out = { min: round(min), avg: round(avg), p95: round(p95), max: round(max) };
501
+ if (count < to - from + 1) out.frames = count;
502
+ return out;
503
+ }
504
+
505
+ /**
506
+ * @param {PerfCapture} capture - The capture.
507
+ * @param {number} from - The first frame.
508
+ * @param {number} to - The last frame, inclusive.
509
+ * @param {(seq: number) => number} value - The figure of a frame.
510
+ * @returns {Float64Array} A ring of the figure, like the channels of the capture, for
511
+ * {@link figureStats}.
512
+ */
513
+ function ringOf(capture, from, to, value) {
514
+ const ring = new Float64Array(capture.slots).fill(NaN);
515
+ for (let seq = from; seq <= to; seq++) ring[capture.slot(seq)] = value(seq);
516
+ return ring;
517
+ }
518
+
519
+ /**
520
+ * @param {Record<string, object|null>} figures - Figures by name.
521
+ * @returns {Record<string, object>} Those that some frame had.
522
+ */
523
+ function present(figures) {
524
+ return Object.fromEntries(Object.entries(figures).filter(([, v]) => v));
525
+ }
526
+
527
+ /**
528
+ * The capture, or a span of it, in a few KB: for each series the smallest, mean, 95th percentile
529
+ * and largest figure, the GPU passes and script types that took longest, the hitches, what loaded
530
+ * and the shader compiles. Durations are in milliseconds, memory in bytes.
531
+ *
532
+ * @param {McpHost} host - The host.
533
+ * @param {number} from - The first frame.
534
+ * @param {number} to - The last frame, inclusive.
535
+ * @param {boolean} [withInspector] - Whether to count the inspector's own time in the CPU figures.
536
+ * @returns {object} The summary.
537
+ */
538
+ function perfSummary(host, from, to, withInspector = false) {
539
+ const perf = host.perf;
540
+ const capture = perf.capture;
541
+ const d = capture.data;
542
+ const stats = key => figureStats(capture, key, from, to);
543
+
544
+ const head = header(capture, from, to);
545
+ const interval = rangeStats(capture, 'interval', from, to);
546
+ /** @type {any} */
547
+ const out = {
548
+ ...head,
549
+ medianFrame: round(head.medianFrame),
550
+ displayInterval: round(head.displayInterval),
551
+ fps: interval.count ? round(1000 / interval.avg) : null,
552
+ device: perf.device(),
553
+ recording: capture.recording,
554
+ options: { gpuTimings: perf.gpuTimings(), scriptTiming: capture.timeScripts },
555
+ visibility: visibility()
556
+ };
557
+ if (perf.session?.hidden) out.hiddenWhileRecording = true;
558
+ if (perf.paused()) out.paused = true;
559
+
560
+ const inspector = rangeStats(capture, 'inspector', from, to);
561
+ out.inspectorTime = withInspector ?
562
+ 'included in the CPU figures' :
563
+ `left out of the CPU figures: ${round(inspector.count ? inspector.avg : 0)} ms a frame on average; pass includeInspector to count it`;
564
+
565
+ const update = withInspector ? 'update' : ringOf(capture, from, to, seq => d.update[capture.slot(seq)] - d.inspector[capture.slot(seq)]);
566
+ out.frameTime = stats('interval');
567
+ out.cpu = present({
568
+ total: stats(withInspector ? 'cpu' : 'cpuApp'),
569
+ update: stats(update),
570
+ render: stats('render'),
571
+ scripts: stats('scripts'),
572
+ physics: stats('physics'),
573
+ animation: stats('anim'),
574
+ ...(withInspector ? { inspector: stats('inspector') } : {})
575
+ });
576
+
577
+ // the GPU passes by name, those that took longest on average first
578
+ const gpu = stats('gpu');
579
+ if (gpu) {
580
+ const names = new Set();
581
+ for (let seq = from; seq <= to; seq++) {
582
+ for (const pass of capture.passesInOrder(seq)) names.add(pass.name);
583
+ }
584
+ const passes = [...names].map((name) => {
585
+ const ring = ringOf(capture, from, to, seq => (Number.isFinite(d.gpu[capture.slot(seq)]) ? passesOf(capture, seq)[name] ?? 0 : NaN));
586
+ return { name, ...figureStats(capture, ring, from, to) };
587
+ }).sort((a, b) => b.avg - a.avg);
588
+ out.gpu = { frame: gpu, passes: passes.slice(0, SUMMARY_PASSES) };
589
+ if (passes.length > SUMMARY_PASSES) out.gpu.morePasses = passes.length - SUMMARY_PASSES;
590
+ }
591
+
592
+ // the script types that took longest on average, over the frames scripts were timed in
593
+ const scripts = stats('scriptsTotal');
594
+ if (scripts) {
595
+ const types = capture.scriptNames.map((name, id) => ({ name, ...figureStats(capture, ringOf(capture, from, to, seq => capture.scriptTime(seq, id)), from, to) }))
596
+ .filter(type => type.avg > 0)
597
+ .sort((a, b) => b.avg - a.avg);
598
+ out.scripts = { total: scripts, calls: stats('scriptCalls'), timingCost: stats('scriptCost'), top: types.slice(0, SUMMARY_SCRIPTS) };
599
+ if (types.length > SUMMARY_SCRIPTS) out.scripts.moreTypes = types.length - SUMMARY_SCRIPTS;
600
+ }
601
+
602
+ out.draws = present({
603
+ total: stats('draws'),
604
+ forward: stats('drawsForward'),
605
+ shadow: stats('drawsShadow'),
606
+ primitives: stats('primitives'),
607
+ computeDispatches: stats('dispatches')
608
+ });
609
+ out.memory = present({ jsHeap: stats('heap'), video: stats('vram'), textures: stats('vramTex') });
610
+
611
+ // the frames that took far longer than the median one, the longest first
612
+ const { median } = captureNorms(capture);
613
+ const hitches = [];
614
+ let compiles = 0;
615
+ let compileTime = 0;
616
+ const loads = [];
617
+ for (let seq = from; seq <= to; seq++) {
618
+ const s = capture.slot(seq);
619
+ if (isHitch(capture, seq, median)) {
620
+ /** @type {any} */
621
+ const hitch = { frame: capture.frameNumber(seq), interval: round(d.interval[s]), cpu: round(d[withInspector ? 'cpu' : 'cpuApp'][s]) };
622
+ if (Number.isFinite(d.gpu[s])) hitch.gpu = round(d.gpu[s]);
623
+ if (d.compiles[s] > 0) hitch.shaderCompiles = d.compiles[s];
624
+ if (capture.loads(seq).length) hitch.loads = capture.loads(seq).length;
625
+ hitches.push(hitch);
626
+ }
627
+ if (d.compiles[s] > 0) {
628
+ compiles += d.compiles[s];
629
+ compileTime += d.compileTime[s];
630
+ }
631
+ for (const load of capture.loads(seq)) loads.push({ frame: capture.frameNumber(seq), ...loadJson(load, d.tick[s]) });
632
+ }
633
+ hitches.sort((a, b) => b.interval - a.interval);
634
+ out.hitches = { count: hitches.length, longest: hitches.slice(0, SUMMARY_HITCHES) };
635
+ if (compiles) out.shaderCompiles = { count: compiles, time: round(compileTime) };
636
+ if (loads.length) {
637
+ const timed = loads.filter(load => load.kind !== 'milestone').sort((a, b) => (b.duration ?? 0) - (a.duration ?? 0));
638
+ const bytes = timed.reduce((sum, load) => sum + (load.bytes ?? 0), 0);
639
+ out.loads = {
640
+ count: timed.length,
641
+ bytes,
642
+ failed: timed.filter(load => load.failed).length,
643
+ longest: timed.slice(0, SUMMARY_LOADS).map(({ frame, kind, name, type, duration, bytes, failed }) => ({
644
+ frame, kind, name, ...(type ? { type } : {}), ...(Number.isFinite(duration) ? { duration: round(duration) } : {}), ...(bytes ? { bytes } : {}), ...(failed ? { failed } : {})
645
+ }))
646
+ };
647
+ }
648
+ return out;
649
+ }
650
+
651
+ /**
652
+ * @param {McpHost} host - The host.
653
+ * @returns {object} Whether the inspector is recording, what it keeps, its options and whether the
654
+ * page is visible.
655
+ */
656
+ function perfStatus(host) {
657
+ const perf = host.perf;
658
+ const capture = perf.capture;
659
+ /** @type {any} */
660
+ const out = {
661
+ recording: capture.recording,
662
+ frames: capture.count,
663
+ capacity: capture.capacity,
664
+ recordedBy: capture.count || capture.recording ? (perf.byAgent ? 'agent' : 'user') : null
665
+ };
666
+ if (capture.count) out.range = { from: capture.frameNumber(capture.first), to: capture.frameNumber(capture.end - 1) };
667
+ const session = perf.session;
668
+ if (session) out.framesLeft = Math.max(0, session.target - capture.end);
669
+ out.options = {
670
+ gpuTimings: perf.gpuTimings(),
671
+ gpuTimingsSupported: perf.gpuSupported(),
672
+ scriptTiming: capture.timeScripts,
673
+ scriptTimingSupported: capture.supports.scripts,
674
+ engineBuild: capture.detailed ? 'profiler or debug' : 'release'
675
+ };
676
+ out.visibility = visibility();
677
+ if (session?.hidden) out.hiddenWhileRecording = true;
678
+ if (perf.paused()) out.paused = true;
679
+ return out;
680
+ }
681
+
682
+ /**
683
+ * Ends the recording the tools stop after a number of frames, telling a caller waiting for it why.
684
+ * Stops recording too, unless only letting go of it.
685
+ *
686
+ * @param {McpHost} host - The host.
687
+ * @param {string} reason - Why it ended.
688
+ * @param {boolean} [stop] - Whether to stop recording.
689
+ */
690
+ function endPerfSession(host, reason, stop = true) {
691
+ const perf = host.perf;
692
+ const session = perf.session;
693
+ if (!session) return;
694
+ perf.session = null;
695
+ host.app.off('frameupdate', session.onFrame);
696
+ clearTimeout(session.timer);
697
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', session.onVisibility);
698
+ if (stop && perf.capture.recording) perf.setRecording(false);
699
+ session.done?.(reason);
700
+ }
701
+
702
+ /**
703
+ * @param {McpHost} host - The host.
704
+ * @param {any} args - How many frames to record, the options, whether to clear what is kept, and
705
+ * whether to wait.
706
+ * @returns {Promise<object>|object} Once the frames are recorded, how recording ended and the
707
+ * summary of the frames recorded; or, without waiting, the status.
708
+ */
709
+ function perfRecord(host, args) {
710
+ const perf = host.perf;
711
+ const capture = perf.capture;
712
+ const userFrames = !perf.byAgent && (capture.count > 0 || capture.recording);
713
+ if (userFrames && args.clear === undefined) {
714
+ throw new Error(`The user ${capture.recording ? 'is recording' : `recorded the ${capture.count} frames kept`}. ` +
715
+ 'Pass clear: true to discard them and record afresh, or clear: false to add to them');
716
+ }
717
+ if (args.gpuTimings && !perf.gpuSupported()) throw new Error('This device cannot time the GPU');
718
+ if (args.scriptTiming && !capture.supports.scripts) throw new Error('This app has no script system to time');
719
+
720
+ endPerfSession(host, 'restarted', false);
721
+ if (args.clear ?? true) {
722
+ if (capture.recording) perf.setRecording(false);
723
+ perf.clear();
724
+ }
725
+ if (args.gpuTimings !== undefined) perf.setGpuTimings(args.gpuTimings);
726
+ if (args.scriptTiming !== undefined) perf.setScriptTiming(args.scriptTiming);
727
+ if (!capture.recording) perf.setRecording(true);
728
+ perf.byAgent = true;
729
+
730
+ if (!args.frames) return { ...perfStatus(host), note: 'Recording until playcanvas_perf_stop, keeping the last frames up to the capacity' };
731
+
732
+ const from = capture.end;
733
+ /** @type {PerfSession} */
734
+ const session = {
735
+ from,
736
+ target: from + args.frames,
737
+ hidden: visibility() === 'hidden',
738
+ onFrame: () => {
739
+ // the capture completes a frame as the next begins, so it has it by now
740
+ if (!capture.recording) endPerfSession(host, 'stopped from the panel', false);
741
+ else if (capture.end >= session.target) endPerfSession(host, 'recorded');
742
+ },
743
+ onVisibility: () => {
744
+ if (visibility() === 'hidden') session.hidden = true;
745
+ },
746
+ timer: setTimeout(() => endPerfSession(host, 'timed out'), (args.timeout ?? PERF_TIMEOUT) * 1000),
747
+ done: null
748
+ };
749
+ perf.session = session;
750
+ host.app.on('frameupdate', session.onFrame);
751
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', session.onVisibility);
752
+
753
+ if (args.wait === false) return { ...perfStatus(host), note: `Recording ${args.frames} frames, then stopping` };
754
+ return new Promise((resolve) => {
755
+ session.done = (reason) => {
756
+ const recorded = capture.end - Math.max(from, capture.first);
757
+ /** @type {any} */
758
+ const out = { ended: reason, frames: recorded };
759
+ if (reason === 'timed out') {
760
+ out.note = `Only ${recorded} of ${args.frames} frames were recorded in ${args.timeout ?? PERF_TIMEOUT} s: ` +
761
+ 'frames stop while the page is hidden, and slow down while the app is paused or busy';
762
+ }
763
+ if (recorded > 0) out.summary = perfSummary(host, Math.max(from, capture.first), capture.end - 1);
764
+ else out.status = perfStatus(host);
765
+ resolve(out);
766
+ };
767
+ });
768
+ }
769
+
770
+ /**
771
+ * @param {McpHost} host - The host.
772
+ * @returns {object} The summary of every frame kept, once recording is stopped.
773
+ */
774
+ function perfStop(host) {
775
+ const perf = host.perf;
776
+ endPerfSession(host, 'stopped');
777
+ if (perf.capture.recording) perf.setRecording(false);
778
+ if (!perf.capture.count) return perfStatus(host);
779
+ return perfSummary(host, perf.capture.first, perf.capture.end - 1);
780
+ }
781
+
782
+ /**
783
+ * @param {McpHost} host - The host.
784
+ * @param {any} args - The frames, and whether to count the inspector's time.
785
+ * @returns {object} The summary.
786
+ */
787
+ function perfSummaryTool(host, args) {
788
+ const { from, to } = rangeOf(host.perf.capture, args);
789
+ return perfSummary(host, from, to, args.includeInspector === true);
790
+ }
791
+
792
+ /**
793
+ * @param {McpHost} host - The host.
794
+ * @param {any} args - The frame number.
795
+ * @returns {object} Everything recorded for the frame.
796
+ */
797
+ function perfFrame(host, args) {
798
+ const capture = host.perf.capture;
799
+ const seq = seqOf(capture, args.frame);
800
+ if (!capture.has(seq)) {
801
+ throw new Error(capture.count ?
802
+ `Frame ${args.frame} is not kept. Frames kept: ${capture.frameNumber(capture.first)} to ${capture.frameNumber(capture.end - 1)}` :
803
+ 'Nothing is recorded: start a capture with playcanvas_perf_record');
804
+ }
805
+ return frameJson(capture, seq);
806
+ }
807
+
808
+ /**
809
+ * @param {McpHost} host - The host.
810
+ * @param {any} args - The series, the frames and the format.
811
+ * @returns {object|string} The rows of the series, as JSON or CSV.
812
+ */
813
+ function perfSeries(host, args) {
814
+ const capture = host.perf.capture;
815
+ const range = rangeOf(capture, args);
816
+ // a series with a row per frame stops after the most rows; the others, which skip frames, are
817
+ // bounded by the frames kept
818
+ const to = PERF_SERIES.indexOf(args.key) < Object.keys(SERIES).length ? Math.min(range.to, range.from + MAX_SERIES_ROWS - 1) : range.to;
819
+ const rows = seriesRows(capture, args.key, range.from, to);
820
+ /** @type {any} */
821
+ const out = { series: args.key, range: { from: capture.frameNumber(range.from), to: capture.frameNumber(to) } };
822
+ if (to < range.to) out.next = capture.frameNumber(to + 1);
823
+ if (args.format === 'csv') out.csv = toCsv(rows);
824
+ else out.rows = rows;
825
+ return out;
826
+ }
827
+
828
+ /**
829
+ * The tools of the inspector. None of them changes the app: most only read it, and the perf tools
830
+ * drive the inspector's own capture.
831
+ *
832
+ * @type {McpToolImpl[]}
833
+ */
834
+ /**
835
+ * @param {McpHost} host - The host.
836
+ * @param {any} args - Which messages.
837
+ * @returns {object} The messages logged since the tools were turned on, newest last.
838
+ */
839
+ function logs(host, args) {
840
+ const capture = host.logs;
841
+ const level = args.level ?? 'log';
842
+ const allowed = new Set(LEVELS.slice(0, LEVELS.indexOf(level) + 1));
843
+ const filter = typeof args.filter === 'string' ? args.filter.toLowerCase() : '';
844
+ const since = args.since ?? 0;
845
+ const limit = clampInt(args.limit, 100, MAX_LIMIT);
846
+ const counts = Object.fromEntries(LEVELS.map(l => [l, 0]));
847
+ const matching = [];
848
+ for (const entry of capture.entries) {
849
+ // the counts cover the same messages as the entries, every level of them
850
+ if (entry.seq <= since) continue;
851
+ counts[entry.level] += entry.count;
852
+ if (!allowed.has(entry.level)) continue;
853
+ if (filter && !entry.text.toLowerCase().includes(filter)) continue;
854
+ matching.push(entry);
855
+ }
856
+ const oldest = capture.entries[0]?.seq ?? capture.seq + 1;
857
+ const out = {
858
+ capturing: capture.capturing,
859
+ // the newest of what matches, when there is more than the limit
860
+ entries: matching.slice(-limit),
861
+ total: matching.length,
862
+ truncated: matching.length > limit,
863
+ next: capture.seq,
864
+ counts
865
+ };
866
+ if (since && since < oldest - 1) out.dropped = `Messages after ${since} up to ${oldest - 1} were dropped: only the last 1000 are kept`;
867
+ return out;
868
+ }
869
+
870
+ /**
871
+ * @param {McpHost} host - The host.
872
+ * @param {any} args - What to capture.
873
+ * @returns {Promise<object>} The image, under $image, with what it shows.
874
+ */
875
+ async function screenshot(host, args) {
876
+ const maxSize = args.maxSize ?? (args.id ? 512 : 1024);
877
+ if (!args.id) {
878
+ const image = await host.images().canvas({ maxSize });
879
+ const device = host.app.graphicsDevice;
880
+ return { $image: { mimeType: 'image/png', data: image.png }, width: image.width, height: image.height, source: { kind: 'canvas', width: device.width, height: device.height } };
881
+ }
882
+
883
+ const obj = host.refs.get(args.id);
884
+ if (!obj) throw new Error(`No object with id "${args.id}": it is unknown, or the app has let go of it`);
885
+ let texture = null;
886
+ let attachment;
887
+ if (obj instanceof Texture) {
888
+ texture = obj;
889
+ } else if (obj instanceof RenderTarget) {
890
+ attachment = args.attachment ?? (obj.colorBuffer ? 'color0' : 'depth');
891
+ texture = attachment === 'depth' ? obj.depthBuffer : obj.getColorBuffer(Number(attachment.slice(5)));
892
+ if (!texture) throw new Error(`The render target has no ${attachment} attachment${obj.depth && !obj.depthBuffer ? ' it can be read from: its depth is a renderbuffer, not a texture' : ''}`);
893
+ } else {
894
+ throw new Error(`A screenshot takes the id of a texture or a render target, or no id for the canvas, not a ${obj.constructor?.name ?? 'value'}`);
895
+ }
896
+
897
+ const channels = args.channels ?? 'rgb';
898
+ const image = await host.images().texture(texture, { maxSize, channels });
899
+ const source = { $id: args.id, $type: obj.constructor?.name, name: obj.name, width: texture.width, height: texture.height, format: texture.format };
900
+ if (attachment) source.attachment = attachment;
901
+ if (channels !== 'rgb') source.channels = channels;
902
+ return { $image: { mimeType: 'image/png', data: image.png }, width: image.width, height: image.height, source };
903
+ }
904
+
905
+ /**
906
+ * @param {McpHost} host - The host.
907
+ * @param {any} args - Whether to pause.
908
+ * @returns {object} Whether the app is paused, and its frame.
909
+ */
910
+ function pause(host, args) {
911
+ host.time.setPaused(args.paused);
912
+ return { paused: host.time.paused(), frame: host.time.frame() };
913
+ }
914
+
915
+ /**
916
+ * @param {McpHost} host - The host.
917
+ * @param {any} args - How many frames.
918
+ * @returns {Promise<object>} How many frames ran, and the frame the app is paused on.
919
+ */
920
+ async function step(host, args) {
921
+ const frames = args.frames ?? 1;
922
+ const from = host.time.frame();
923
+ const ran = await host.time.step(frames, (args.timeout ?? 10) * 1000);
924
+ const out = { paused: true, stepped: ran, frame: host.time.frame(), from };
925
+ if (ran < frames) out.note = `Only ${ran} of ${frames} frames ran before the timeout: frames stop while the page is hidden`;
926
+ return out;
927
+ }
928
+
929
+ const TOOLS = [{
930
+ name: 'playcanvas_app_summary',
931
+ description: 'Summarize the running PlayCanvas app: engine version, graphics device and its video memory, ' +
932
+ 'entity and asset counts, frame stats, the id of the scene root, and the lists playcanvas_list can return.',
933
+ inputSchema: { type: 'object', properties: {} },
934
+ annotations: { readOnlyHint: true },
935
+ execute: appSummary
936
+ }, {
937
+ name: 'playcanvas_index',
938
+ description: 'Index everything the app holds in one call, to start from: the summary, every entity with its ' +
939
+ 'id, path and components, and every camera, material, texture, shader, mesh, render target, script class, ' +
940
+ 'asset and frame-graph pass with its id and the figures its list shows, such as size and format. Pass ' +
941
+ 'the ids to playcanvas_get for the details. Each list holds up to 2000 entries.',
942
+ inputSchema: { type: 'object', properties: {} },
943
+ annotations: { readOnlyHint: true },
944
+ execute: index
945
+ }, {
946
+ name: 'playcanvas_find_entities',
947
+ description: 'Find entities in the scene hierarchy by name, component type, script name and tag, all ' +
948
+ 'optional and combined. Matching is by case-insensitive substring except the tag, which is exact. ' +
949
+ 'Returns each entity with its id, to pass to playcanvas_get.',
950
+ inputSchema: {
951
+ type: 'object',
952
+ properties: {
953
+ name: { type: 'string', description: 'Part of the entity name.' },
954
+ component: { type: 'string', description: 'Part of a component type, such as "render" or "camera".' },
955
+ script: { type: 'string', description: 'Part of the name of a script on the entity.' },
956
+ tag: { type: 'string', description: 'A tag the entity has.' },
957
+ limit: { type: 'integer', minimum: 1, maximum: MAX_LIMIT, default: 50 }
958
+ }
959
+ },
960
+ annotations: { readOnlyHint: true },
961
+ execute: findEntities
962
+ }, {
963
+ name: 'playcanvas_list',
964
+ description: 'List what one tab of the inspector lists: textures, shaders, materials, meshes, scripts, ' +
965
+ 'cameras, layers (the layer composition in render order), assets, renderTargets, passes (the frame graph ' +
966
+ 'of the last frame) or memory (GPU buffers ' +
967
+ 'and textures by kind). Each entry has an id to pass to playcanvas_get, and the figures the list shows.',
968
+ inputSchema: {
969
+ type: 'object',
970
+ properties: {
971
+ kind: { type: 'string', enum: Object.keys(LISTS) },
972
+ filter: { type: 'string', description: 'Only entries whose name contains this, case-insensitive.' },
973
+ offset: { type: 'integer', minimum: 0, default: 0 },
974
+ limit: { type: 'integer', minimum: 1, maximum: MAX_LIMIT, default: 100 }
975
+ },
976
+ required: ['kind']
977
+ },
978
+ annotations: { readOnlyHint: true },
979
+ execute: list
980
+ }, {
981
+ name: 'playcanvas_get',
982
+ description: 'Get an object by id, as the inspector shows it: an entity with its components, a mesh ' +
983
+ 'instance, material, shader, texture, mesh, render target, pass, layer, asset, script or buffer. Every object ' +
984
+ 'it links to carries an $id to get next, so links can be followed, such as entity -> render component ' +
985
+ '-> mesh instance -> material -> shader. Lists of what uses the object, and a node\'s parent, are ' +
986
+ 'included as references. depth follows links in place, up to 4 away: 0 returns the object alone. ' +
987
+ 'Source code, such as a shader\'s, is summarized unless sources is true.',
988
+ inputSchema: {
989
+ type: 'object',
990
+ properties: {
991
+ id: { type: 'string', description: 'An $id returned by any of the tools, such as "material:12".' },
992
+ depth: { type: 'integer', minimum: 0, maximum: MAX_DEPTH, default: 0 },
993
+ sources: { type: 'boolean', default: false, description: 'Include source code, such as the sources of a shader.' }
994
+ },
995
+ required: ['id']
996
+ },
997
+ annotations: { readOnlyHint: true },
998
+ execute: get
999
+ }, {
1000
+ name: 'playcanvas_perf_record',
1001
+ description: 'Start recording frames on the inspector\'s Performance tab: CPU update and render times, GPU time ' +
1002
+ 'per pass, script times, draw calls, memory, hitches and loads, a frame each, keeping the last 1000. ' +
1003
+ 'With frames, it stops by itself after that many and, unless wait is false, returns the summary of ' +
1004
+ 'those frames; it gives up after timeout seconds, as frames stop while the page is hidden. Without ' +
1005
+ 'frames, it records until playcanvas_perf_stop. gpuTimings and scriptTiming turn those timings on or ' +
1006
+ 'off; script timing costs about half a microsecond a script call, counted as the inspector\'s time. A ' +
1007
+ 'capture the user recorded is not discarded unless clear is true; clear: false adds to what is kept. ' +
1008
+ 'Changes the inspector\'s capture and switches, never the app.',
1009
+ inputSchema: {
1010
+ type: 'object',
1011
+ properties: {
1012
+ frames: { type: 'integer', minimum: 1, maximum: 1000, description: 'Stop after this many frames.' },
1013
+ gpuTimings: { type: 'boolean', description: 'Time the GPU passes, where the device can.' },
1014
+ scriptTiming: { type: 'boolean', description: 'Time each script type.' },
1015
+ clear: { type: 'boolean', description: 'Discard the frames kept first. Defaults to true, but a capture the user recorded is only discarded when this is given.' },
1016
+ wait: { type: 'boolean', default: true, description: 'With frames, wait for them and return their summary.' },
1017
+ timeout: { type: 'integer', minimum: 1, maximum: MAX_PERF_TIMEOUT, default: PERF_TIMEOUT, description: 'With frames, the seconds to wait for them before stopping.' }
1018
+ }
1019
+ },
1020
+ annotations: { readOnlyHint: false, destructiveHint: false },
1021
+ execute: perfRecord
1022
+ }, {
1023
+ name: 'playcanvas_perf_stop',
1024
+ description: 'Stop recording frames on the Performance tab, keeping them, and return the summary of every ' +
1025
+ 'frame kept, as playcanvas_perf_summary does.',
1026
+ inputSchema: { type: 'object', properties: {} },
1027
+ annotations: { readOnlyHint: false, destructiveHint: false },
1028
+ execute: perfStop
1029
+ }, {
1030
+ name: 'playcanvas_perf_status',
1031
+ description: 'Whether the Performance tab is recording, how many frames it keeps and which, who recorded ' +
1032
+ 'them, how many frames a recording of playcanvas_perf_record has left, the timings on, and whether ' +
1033
+ 'the page is visible, as frames stop while it is hidden.',
1034
+ inputSchema: { type: 'object', properties: {} },
1035
+ annotations: { readOnlyHint: true },
1036
+ execute: perfStatus
1037
+ }, {
1038
+ name: 'playcanvas_perf_summary',
1039
+ description: 'Summarize the frames recorded, in a few KB: for frame time, CPU update and render, scripts, ' +
1040
+ 'GPU time, draw calls and memory the min, average, 95th percentile and max, the GPU passes and script ' +
1041
+ 'types that took longest, the hitches (frames over twice the median), what loaded and the shader ' +
1042
+ 'compiles. Times are in ms, memory in bytes. The CPU figures leave out the inspector\'s own time ' +
1043
+ 'unless includeInspector is true. from and to pick frames by number; then use playcanvas_perf_frame ' +
1044
+ 'for one frame in full and playcanvas_perf_series for a figure frame by frame.',
1045
+ inputSchema: {
1046
+ type: 'object',
1047
+ properties: {
1048
+ from: { type: 'integer', minimum: 0, description: 'The first frame, by number. Defaults to the first kept.' },
1049
+ to: { type: 'integer', minimum: 0, description: 'The last frame, by number. Defaults to the last kept.' },
1050
+ includeInspector: { type: 'boolean', default: false, description: 'Count the inspector\'s own time in the CPU figures.' }
1051
+ }
1052
+ },
1053
+ annotations: { readOnlyHint: true },
1054
+ execute: perfSummaryTool
1055
+ }, {
1056
+ name: 'playcanvas_perf_frame',
1057
+ description: 'Everything recorded for one frame, by number: CPU phases, GPU passes in the order they ran ' +
1058
+ 'with the effect running each, script types, draw calls, memory, resources, shader compiles, events, ' +
1059
+ 'counters and loads. Times are in ms, memory in bytes.',
1060
+ inputSchema: {
1061
+ type: 'object',
1062
+ properties: {
1063
+ frame: { type: 'integer', minimum: 0, description: 'The frame number, as the summary and series name frames.' }
1064
+ },
1065
+ required: ['frame']
1066
+ },
1067
+ annotations: { readOnlyHint: true },
1068
+ execute: perfFrame
1069
+ }, {
1070
+ name: 'playcanvas_perf_series',
1071
+ description: 'One figure frame by frame, a row per frame: frame (the frame interval), cpu (its phases), gpu ' +
1072
+ '(a column per pass), draws, memory or resources; or scripts (a column per script type, frames timed ' +
1073
+ 'only), counters (app.stats.user), loading (a row per load) or events (frames with any). A series with ' +
1074
+ `a row per frame returns up to ${MAX_SERIES_ROWS} rows; next is the frame to continue from. format csv ` +
1075
+ 'returns the rows as CSV text, which is smaller.',
1076
+ inputSchema: {
1077
+ type: 'object',
1078
+ properties: {
1079
+ key: { type: 'string', enum: PERF_SERIES },
1080
+ from: { type: 'integer', minimum: 0, description: 'The first frame, by number. Defaults to the first kept.' },
1081
+ to: { type: 'integer', minimum: 0, description: 'The last frame, by number. Defaults to the last kept.' },
1082
+ format: { type: 'string', enum: ['json', 'csv'], default: 'json' }
1083
+ },
1084
+ required: ['key']
1085
+ },
1086
+ annotations: { readOnlyHint: true },
1087
+ execute: perfSeries
1088
+ }, {
1089
+ name: 'playcanvas_logs',
1090
+ description: 'The messages the page logged to the console since the MCP tools were turned on, and the errors ' +
1091
+ 'nothing caught: the engine\'s warnings and errors (in a debug build), shader compile errors, failed loads and ' +
1092
+ 'the app\'s own messages. Newest last; a message repeated in a row is counted, not repeated. level is the least ' +
1093
+ 'severe level returned (error, warn, info, log, debug). Pass the next number returned as since to get only ' +
1094
+ 'what was logged after, such as around a step to reproduce; counts then cover only those messages too.',
1095
+ inputSchema: {
1096
+ type: 'object',
1097
+ properties: {
1098
+ level: { type: 'string', enum: LEVELS, default: 'log', description: 'The least severe level returned.' },
1099
+ filter: { type: 'string', description: 'Only messages containing this, case-insensitive.' },
1100
+ since: { type: 'integer', minimum: 0, description: 'Only messages numbered after this.' },
1101
+ limit: { type: 'integer', minimum: 1, maximum: MAX_LIMIT, default: 100 }
1102
+ }
1103
+ },
1104
+ annotations: { readOnlyHint: true },
1105
+ execute: logs
1106
+ }, {
1107
+ name: 'playcanvas_screenshot',
1108
+ description: 'Capture an image. Without id, what the canvas shows. With the id of a texture or a render target ' +
1109
+ '(from playcanvas_list or playcanvas_get), that texture, or an attachment of the target, as the inspector ' +
1110
+ 'previews it: encoded and HDR textures decoded, depth as grayscale, a single channel as grayscale. channels ' +
1111
+ 'shows stored channels instead, such as "aaa" for alpha. Returns a PNG image.',
1112
+ inputSchema: {
1113
+ type: 'object',
1114
+ properties: {
1115
+ id: { type: 'string', description: 'A texture or render target id. Omit for the canvas.' },
1116
+ attachment: { type: 'string', enum: ['color0', 'color1', 'color2', 'color3', 'color4', 'color5', 'color6', 'color7', 'depth'], description: 'The attachment of a render target. Defaults to color0, or depth for a depth-only target.' },
1117
+ channels: { type: 'string', pattern: '^[rgba]{3}$', default: 'rgb', description: 'Three of r, g, b and a: stored channels to show. rgb decodes the texture.' },
1118
+ maxSize: { type: 'integer', minimum: 16, maximum: 2048, description: 'The longest side of the image, at most. Defaults to 512 for a texture and 1024 for the canvas.' }
1119
+ }
1120
+ },
1121
+ annotations: { readOnlyHint: true },
1122
+ execute: screenshot
1123
+ }, {
1124
+ name: 'playcanvas_pause',
1125
+ description: 'Pause or resume the app, as the inspector\'s Pause button does: time stands still while it keeps ' +
1126
+ 'rendering, so what is on screen and in the lists holds still. Use playcanvas_step to move on frame by frame.',
1127
+ inputSchema: {
1128
+ type: 'object',
1129
+ properties: { paused: { type: 'boolean' } },
1130
+ required: ['paused']
1131
+ },
1132
+ annotations: { readOnlyHint: false, destructiveHint: false },
1133
+ execute: pause
1134
+ }, {
1135
+ name: 'playcanvas_step',
1136
+ description: 'Run frames with time moving, then hold the app paused: pauses it first if it is not. Returns once ' +
1137
+ 'the frames have run, or after timeout seconds, as frames stop while the page is hidden.',
1138
+ inputSchema: {
1139
+ type: 'object',
1140
+ properties: {
1141
+ frames: { type: 'integer', minimum: 1, maximum: 600, default: 1 },
1142
+ timeout: { type: 'integer', minimum: 1, maximum: 120, default: 10 }
1143
+ }
1144
+ },
1145
+ annotations: { readOnlyHint: false, destructiveHint: false },
1146
+ execute: step
1147
+ }];
1148
+
1149
+ export { TOOLS, endPerfSession, validate };