Skip to content
Merged
Show file tree
Hide file tree
Changes from 31 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
6255d94
feat: add scene content stats to the Current Scene debug widget
dalkia Jul 21, 2026
5d6dd64
Merge branch 'dev' into feat/current-scene-content-stats-debug
dalkia Jul 24, 2026
275428b
Merge branch 'dev' into feat/current-scene-content-stats-debug
dalkia Aug 3, 2026
4f30841
feat: remove content size stat from Current Scene widget
dalkia Aug 3, 2026
22e8c4b
feat: align content stat caps with documented scene limitations
dalkia Aug 3, 2026
61d307f
feat: add scene metrics panel to the scene debug menu
dalkia Aug 3, 2026
124d412
feat: expose scene content stats through an MCP tool
dalkia Aug 3, 2026
b4483cc
feat: add per-model content breakdown MCP tool (demo)
dalkia Aug 3, 2026
92a8c1f
feat: add materials and draw-call estimate to the content breakdown
dalkia Aug 3, 2026
de98d33
feat: split content stats into their own Scene content debug widget
dalkia Aug 4, 2026
fdb47df
feat: per-POV visibility columns in the content breakdown
dalkia Aug 4, 2026
1746336
feat: add get_performance_stats MCP tool
dalkia Aug 4, 2026
448efed
fix: qualify UnityEngine.Time in GetPerformanceStatsTool
dalkia Aug 4, 2026
2cd854a
Merge remote-tracking branch 'origin/dev' into feat/current-scene-con…
dalkia Aug 4, 2026
8190dcb
feat: redesign Scene Stats creator panel
dalkia Aug 4, 2026
051f251
feat: use a 2x2 grid glyph for the Scene Stats sidebar button
dalkia Aug 4, 2026
c711381
feat: use info.png as the Scene Stats sidebar button icon
dalkia Aug 4, 2026
c896ac6
feat: count shader variants in scene content stats
dalkia Aug 4, 2026
9f53073
feat: use dedicated stats-chart icon for the Scene Stats sidebar button
dalkia Aug 4, 2026
19e4831
Merge branch 'dev' into feat/current-scene-content-stats-debug
dalkia Aug 5, 2026
e230057
feat: restyle Scene Stats panel with banded rows and warning percentages
dalkia Aug 5, 2026
f876e62
feat: remove the Scene Stats panel close button
dalkia Aug 5, 2026
a74caf0
feat: make the Scene Stats panel background near-opaque for readability
dalkia Aug 5, 2026
2232d38
chore: soften Scene Stats panel background to 90% opacity
dalkia Aug 5, 2026
da3e2f9
chore: rename External content widget row to Videos
dalkia Aug 5, 2026
5ce04ae
feat: count video/media players instead of external content + NFTs
dalkia Aug 5, 2026
5810e65
chore: label the media-player row External Videos/Audios
dalkia Aug 5, 2026
59b4458
chore: drop the materials cap, show it as an informative count
dalkia Aug 5, 2026
f710d92
Merge branch 'dev' into feat/current-scene-content-stats-debug
dalkia Aug 5, 2026
d5b4aee
feat: per-metric hover tooltips in the Scene Stats panel
dalkia Aug 5, 2026
534a6c1
chore: group capped stat rows above the uncapped ones
dalkia Aug 5, 2026
cf96039
fix: unsubscribe metrics button click handler in OnDisable
dalkia Aug 5, 2026
cb040fe
feat: use InfoIcn sprite for scene stats info marker
dalkia Aug 5, 2026
637014f
chore: move SceneStats icon into the UI sprite atlas
dalkia Aug 5, 2026
b127293
chore: assign sprite id to icon-scene-stats on reimport
dalkia Aug 5, 2026
13dfeb1
refactor: address MCP content-stats tool review feedback
dalkia Aug 5, 2026
bdda35d
fix: divide scene-tick average by contributing samples only
dalkia Aug 7, 2026
ae29b7f
fix: align MCP scene-tick stats with the render sampling window
dalkia Aug 7, 2026
9272863
fix: use the client-wide hiccup definition in get_performance_stats
dalkia Aug 7, 2026
c6ae84e
fix: measure content-stats poll timeout against the wall clock
dalkia Aug 7, 2026
f6fe7a7
fix: refcount MCP content-stats demand so overlapping calls don't can…
dalkia Aug 7, 2026
4dbe4ce
test: cover MCP performance and content-stats tools via injectable waits
dalkia Aug 7, 2026
5f42d52
chore: resolve low-risk lint findings in branch-touched files
dalkia Aug 7, 2026
c6e1800
fix: declare an OutputSchema for get_scene_content_breakdown
dalkia Aug 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,8 @@ await MapRendererContainer
bootstrapContainer.DiagnosticsContainer,
staticContainer.InputBlock,
assetsProvisioner,
debugBuilder
debugBuilder,
staticContainer.ScenesCache
));

if (!localSceneDevelopment)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ public UniTask InitializeAsync(StaticSettings settings, CancellationToken ct)
new AssetsCollidersPlugin(sharedDependencies),
new AvatarShapePlugin(globalWorld, componentsContainer.ComponentPoolsRegistry, launchMode, useRemoteAssetBundles),
new PrimitivesRenderingPlugin(sharedDependencies),
new SceneContentStatsPlugin(),
new VisibilityPlugin(),
new AudioSourcesPlugin(sharedDependencies, container.WebRequestsContainer.WebRequestController, container.CacheCleaner, container.assetsProvisioner),
new AudioAnalysisPlugin(sharedDependencies),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public SceneInstanceDependencies(
/* Pass dependencies here if they are needed by the systems */
ecsWorldSharedDependencies = new ECSWorldInstanceSharedDependencies(sceneData, partitionProvider, ecsToCRDTWriter, entitiesMap,
ExceptionsHandler, EntityCollidersCache, SceneStateProvider, entityEventsBuilder, ecsMultiThreadSync,
systemGroupThrottler, systemsUpdateGate);
systemGroupThrottler, systemsUpdateGate, RuntimeMetrics);

ECSWorldFacade = ecsWorldFactory.CreateWorld(new ECSWorldFactoryArgs(ecsWorldSharedDependencies, systemGroupThrottler, sceneData));
CRDTWorldSynchronizer = new CRDTWorldSynchronizer(ECSWorldFacade.EcsWorld, sdkComponentsRegistry, entityFactory, entitiesMap);
Expand Down
3 changes: 3 additions & 0 deletions Explorer/Assets/DCL/McpServer/Systems/McpServerPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ public void InjectToWorld(ref ArchSystemsWorldBuilder<Arch.Core.World> builder,
.Add(screenshotTool)
.Add(new GetPlayerStateTool(globalWorld, arguments.PlayerEntity, exposedCameraData, currentSceneInfo))
.Add(new GetSceneStateTool(scenesCache, currentSceneInfo, loadingStatus, localSceneDevelopment))
.Add(new GetSceneContentStatsTool(scenesCache))
.Add(new GetSceneContentBreakdownTool(scenesCache))
.Add(new GetPerformanceStatsTool(scenesCache))
.Add(new GetSceneLogsTool(logBuffer))
.Add(new TeleportTool(chatMessagesBus, scenesCache, loadingStatus))
.Add(new MoveToTool(globalWorldActions, globalWorld, arguments.PlayerEntity))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
using DCL.McpServer.Core;
using DCL.McpServer.Tools;
using DCL.Profiling;
using DCL.Utilities;
using ECS.SceneLifeCycle;
using Newtonsoft.Json.Linq;
using NSubstitute;
using NUnit.Framework;
using SceneRunner.Scene;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

namespace DCL.McpServer.Tests
{
public class GetSceneContentStatsToolShould
{
private IScenesCache scenesCache = null!;
private ISceneFacade scene = null!;
private SceneRuntimeMetrics runtimeMetrics = null!;

[SetUp]
public void Setup()
{
runtimeMetrics = new SceneRuntimeMetrics();

ISceneData sceneData = Substitute.For<ISceneData>();
sceneData.Parcels.Returns(new List<Vector2Int> { new (0, 0), new (0, 1) });

scene = Substitute.For<ISceneFacade>();
scene.SceneData.Returns(sceneData);
scene.RuntimeMetrics.Returns(runtimeMetrics);

scenesCache = Substitute.For<IScenesCache>();
scenesCache.CurrentScene.Returns(new ReactiveProperty<ISceneFacade?>(scene));
}

[Test]
public void ErrorWhenNoSceneIsLoaded()
{
// Arrange
scenesCache.CurrentScene.Returns(new ReactiveProperty<ISceneFacade?>(null));
var tool = new GetSceneContentStatsTool(scenesCache, collectionTimeoutMs: 0);

// Act
McpToolResult result = Execute(tool);

// Assert
Assert.That(result.Payload["isError"]!.Value<bool>(), Is.True);
}

[Test]
public void ErrorWhenTheSceneNeverProducedStats()
{
// Arrange — HasData stays false and the zero timeout skips waiting for a pass
var tool = new GetSceneContentStatsTool(scenesCache, collectionTimeoutMs: 0);

// Act
McpToolResult result = Execute(tool);

// Assert
Assert.That(result.Payload["isError"]!.Value<bool>(), Is.True);
Assert.That(runtimeMetrics.ContentStats.RequestedByMcp, Is.False);
}

[Test]
public void ReportStatsWithCapsMatchingTheOutputSchema()
{
// Arrange
SceneContentStats stats = runtimeMetrics.ContentStats;
stats.HasData = true;
stats.Entities = 10;
stats.Triangles = 5200;
stats.Bodies = 12;
stats.Geometries = 7;
stats.Materials = 5;
stats.Textures = 3;
Comment thread
dalkia marked this conversation as resolved.
stats.ShaderVariants = 2;
stats.Colliders = 2;
stats.Videos = 1;

var tool = new GetSceneContentStatsTool(scenesCache, collectionTimeoutMs: 0);

// Act
var structured = (JObject)Execute(tool).Payload["structuredContent"]!;

// Assert
McpSchemaAssert.KeysMatch(tool.OutputSchema, structured);
Assert.That(structured["parcelCount"]!.Value<int>(), Is.EqualTo(2));
Assert.That(structured["fresh"]!.Value<bool>(), Is.False);
Assert.That(structured["entities"]!.Value<int>(), Is.EqualTo(10));
Assert.That(structured["entitiesCap"]!.Value<int>(), Is.EqualTo(400));
Assert.That(structured["triangles"]!.Value<long>(), Is.EqualTo(5200));
Assert.That(structured["trianglesCap"]!.Value<long>(), Is.EqualTo(20000));
Assert.That(structured["geometries"]!.Value<int>(), Is.EqualTo(7));
Assert.That(structured["shaderVariants"]!.Value<int>(), Is.EqualTo(2));
Assert.That(structured["videos"]!.Value<int>(), Is.EqualTo(1));
}

[Test]
public void ClearTheDemandFlagAfterReporting()
{
// Arrange
runtimeMetrics.ContentStats.HasData = true;
var tool = new GetSceneContentStatsTool(scenesCache, collectionTimeoutMs: 0);

// Act
Execute(tool);

// Assert
Assert.That(runtimeMetrics.ContentStats.RequestedByMcp, Is.False);
}

private static McpToolResult Execute(GetSceneContentStatsTool tool) =>
tool.ExecuteAsync(new JObject(), CancellationToken.None).GetAwaiter().GetResult();
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

161 changes: 161 additions & 0 deletions Explorer/Assets/DCL/McpServer/Tools/GetPerformanceStatsTool.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
using Cysharp.Threading.Tasks;
using DCL.McpServer.Core;
using DCL.McpServer.Utils;
using DCL.Profiling;
using ECS.SceneLifeCycle;
using Newtonsoft.Json.Linq;
using SceneRunner.Scene;
using System.Globalization;
using System.Text;
using System.Threading;
using UnityEngine;

namespace DCL.McpServer.Tools
{
/// <summary>
/// Samples the client's real frame rate over its own short window (no shared profiler state
/// is touched) and reports it together with the current scene's tick FPS, so an agent can
/// correlate a viewpoint's content cost with the frame rate it actually produces.
/// </summary>
public class GetPerformanceStatsTool : McpTool
{
private const float DEFAULT_SAMPLE_SECONDS = 2f;
private const float MIN_SAMPLE_SECONDS = 0.5f;
private const float MAX_SAMPLE_SECONDS = 10f;
private const float HICCUP_THRESHOLD_MS = 50f;

private readonly IScenesCache scenesCache;
private readonly long[] tickScratch = new long[SampledCounter.BUFFER_CAPACITY];

public override string Name => "get_performance_stats";

public override string Description =>
"Sample the client's real frame rate over a short window and report render FPS (average, min, max, hiccup frames > 50 ms) plus "
+ "the current scene's tick FPS vs its target. The call holds for sampleSeconds while it measures. Use together with "
+ "get_scene_content_breakdown (sortBy=visibleTriangles) to correlate a viewpoint's content cost with the frame rate it actually "
+ "produces — position the camera first, then sample.";

public override JObject OutputSchema =>
McpJsonSchema.Object()
.Number("sampleSeconds")
.Integer("framesSampled")
.Number("averageFps")
.Number("minFps", "Lowest instantaneous FPS in the window (longest frame).")
.Number("maxFps")
.Number("averageFrameMs")
.Number("maxFrameMs")
.Integer("hiccupFrames", "Frames longer than 50 ms in the window.")
.Object("sceneTick", McpJsonSchema.Object()
.Number("averageFps")
.Number("minFps")
.Number("maxFps")
.Integer("targetFps"),
"The current scene's JS tick rate, or null when no scene is loaded or it has not ticked yet.", nullable: true)
.Build();

public override McpToolAnnotations Annotations => McpToolAnnotations.ReadOnly();

public GetPerformanceStatsTool(IScenesCache scenesCache)
{
this.scenesCache = scenesCache;
}

public override async UniTask<McpToolResult> ExecuteAsync(JObject arguments, CancellationToken ct)
{
float sampleSeconds = Mathf.Clamp(arguments.GetFloat("sampleSeconds", DEFAULT_SAMPLE_SECONDS), MIN_SAMPLE_SECONDS, MAX_SAMPLE_SECONDS);
Comment thread
dalkia marked this conversation as resolved.

var framesSampled = 0;
float totalMs = 0f;
float minFrameMs = float.MaxValue;
float maxFrameMs = 0f;
var hiccupFrames = 0;

float start = UnityEngine.Time.realtimeSinceStartup;

while (UnityEngine.Time.realtimeSinceStartup - start < sampleSeconds)
{
await UniTask.NextFrame(ct);

float frameMs = UnityEngine.Time.unscaledDeltaTime * 1000f;
framesSampled++;
totalMs += frameMs;
if (frameMs < minFrameMs) minFrameMs = frameMs;
if (frameMs > maxFrameMs) maxFrameMs = frameMs;
if (frameMs > HICCUP_THRESHOLD_MS) hiccupFrames++;
}

if (framesSampled == 0)
return McpToolResult.Error("No frames rendered during the sampling window.");

float averageFrameMs = totalMs / framesSampled;
float averageFps = 1000f / averageFrameMs;
float minFps = 1000f / maxFrameMs;
float maxFps = 1000f / minFrameMs;

JObject? sceneTick = null;
ISceneFacade? scene = scenesCache.CurrentScene.Value;

if (scene != null)
{
SceneRuntimeMetrics metrics = scene.RuntimeMetrics;
int tickSamples = metrics.TickTimesNs.CopySnapshot(tickScratch);

if (tickSamples > 0)
{
long totalNs = 0;
long minNs = long.MaxValue;
long maxNs = long.MinValue;

for (var i = 0; i < tickSamples; i++)
{
long ns = tickScratch[i];
if (ns <= 0) continue;
totalNs += ns;
if (ns < minNs) minNs = ns;
if (ns > maxNs) maxNs = ns;
}

if (totalNs > 0)
sceneTick = new JObject
{
["averageFps"] = Round1(1e9f / ((float)totalNs / tickSamples)),
["minFps"] = Round1(1e9f / maxNs),
["maxFps"] = Round1(1e9f / minNs),
["targetFps"] = metrics.TargetFps,
};
}
}

var structured = new JObject
{
["sampleSeconds"] = Round1(sampleSeconds),
["framesSampled"] = framesSampled,
["averageFps"] = Round1(averageFps),
["minFps"] = Round1(minFps),
["maxFps"] = Round1(maxFps),
["averageFrameMs"] = Round1(averageFrameMs),
["maxFrameMs"] = Round1(maxFrameMs),
["hiccupFrames"] = hiccupFrames,
["sceneTick"] = sceneTick ?? (JToken)JValue.CreateNull(),
};

var text = new StringBuilder();
text.Append("Render: ").Append(averageFps.ToString("F1", CultureInfo.InvariantCulture)).Append(" fps avg (min ")
.Append(minFps.ToString("F1", CultureInfo.InvariantCulture)).Append(", max ")
.Append(maxFps.ToString("F1", CultureInfo.InvariantCulture)).Append(") over ")
.Append(framesSampled).Append(" frames / ").Append(sampleSeconds.ToString("F1", CultureInfo.InvariantCulture)).Append("s; ")
.Append(hiccupFrames).AppendLine(" hiccup frames (>50 ms).");

if (sceneTick != null)
text.Append("Scene tick: ").Append(sceneTick["averageFps"]!.Value<float>().ToString("F1", CultureInfo.InvariantCulture))
.Append(" fps avg (target ").Append(sceneTick["targetFps"]!.Value<int>()).Append(").");
else
text.Append("Scene tick: no data (no scene loaded or it has not ticked yet).");

return McpToolResult.TextWithStructured(text.ToString(), structured);
}

private static float Round1(float value) =>
Mathf.Round(value * 10f) / 10f;
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading