Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
@@ -0,0 +1,42 @@
# Agent Note: MCP assets inspection and hot reload

Status: implemented

## Problem

Agents debugging or iterating on a running NSGo game over `nsgo mcp` (see [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md)) could inspect scenes, layers, and entities, but had no way to see which asset groups were loaded, how much memory they held, or to reload edited assets such as sprite atlases, shaders, materials, and YAML resources on demand without restarting the game.

## Decision

Extend `packages/game/mcp` with a dedicated `assets.go` tool group (`game_assets_list`, `game_asset_reload`, `game_assets_reload_group`) and minimal additive `Config` hookup in `mcp.go`, backed by read-only stats and synchronous in-place reload helpers in `packages/game/assets`, `packages/game/tooling/hotreload`, and `packages/game/resource`.

## Architecture and tool contract

- **Minimal `mcp.go` surface for parallel work**: All asset tool constants, schemas, result structs, handlers, and `RegisterAsset` / `RegisterAtlas` helpers live in `packages/game/mcp/assets.go`. `mcp.go` only adds optional `Config` fields (`Assets`, `AssetsFunc`, `Resources`, `Shaders`, `Materials`, `ReloadAsset`), one unexported `customAssets` registry pointer on `Bridge`, and `b.assetTools()` in `Bridge.Tools()`.
- **Deterministic group listing and memory accounting**: `packages/game/assets/stats.go` adds side-effect-free `Manager.GroupNames`, `Manager.LookupGroup`, `Manager.GroupStats`, and `Group.Stats` using untracked signal reads so MCP calls never subscribe to reactive signals or lazily create phantom groups. `Group` tracks raw file byte sizes alongside loaded resources (`rawBytes`) and combines them with pixel buffers (`ImageSource.Pixels`), inline byte payloads (`ImageSource.Data`), declared image/atlas dimensions, and decoded PCM duration estimates for sounds. `game_assets_list` merges `assets.Manager` groups, loaded `resource.Library` paths, `ShaderReloader` shaders, `MaterialReloader` materials, and custom registered assets, sorted deterministically by `(name, source)` and per-group `key`.
- **Off-goroutine fetch, engine-goroutine apply**: `automation.Call` executes tool handlers synchronously on the engine goroutine, and a handler cannot wait for work posted back to it. `Manager.ReloadAsset` and `Manager.ReloadGroup` therefore read updated bytes through each group's configured reader (`g.readAssetFunc()`), parse atlases and run custom loaders on a separate goroutine, as `Group.Load` does, wait for it (or for the call's context, after which unapplied custom values are released), and then update loaded assets in place on the engine goroutine (`*cur = *next` for `*sprite.Atlas`) before incrementing `Manager.Revision()` once. Existing `*sprite.Atlas` pointers held by running game code see updated frames immediately and reactive canvases redraw on `Revision()`. Sounds, images without a file and files at a density the screen does not show are reported as skipped: a sound decodes asynchronously on the platform, so its result could not be reported in the same call, and replacing an unshown density would drop the source's other scales, as `Manager.Reload` already avoids.
- **Structured reload diagnostics vs protocol errors**: Argument validation errors (unknown JSON fields via `DisallowUnknownFields()`, missing `key`/`group`, invalid `state`, conflicting `key` + `all`), unconfigured/disposed managers, and unknown asset/group lookups return Go errors to `automation.Call`. Parse, read, schema, or shader compilation errors on a matched asset preserve the previously working asset and return a structured JSON `AssetReloadResult` / `AssetsReloadGroupResult` with `reloaded: false` and the diagnostic message in `error`, keeping the live game running.
- **Unified reload across hot-reload subsystems**: Small additive `ReloadFile` / `ReloadShaderFile` / `ReloadMaterialFile` and path getters in `packages/game/resource` and `packages/game/tooling/hotreload` (building on [Shader and material hot reload](2026-11-24-shader-material-hot-reload.md)) allow `game_asset_reload` and `game_assets_reload_group` to reload atlases, images, bytes, custom assets, shaders, materials, and YAML resources uniformly from their configured file systems.

## Alternatives considered

### Re-using `Group.Release()` followed by `Group.Load()` for MCP reloads

Releasing and asynchronously reloading a group would require no new per-spec reload code in `packages/game/assets`. It was rejected for two reasons: (1) `Group.Release()` + `Group.Load()` allocates new `*sprite.Atlas` pointers, so game systems holding an existing `*sprite.Atlas` pointer would never see the update; and (2) `Group.Load()` completes asynchronously via `core.Scope.Post`, which cannot be waited on synchronously inside an `automation.Call` handler on the engine goroutine without deadlocking.

### Returning reload parse/compile failures as raw tool call errors

Returning parse or shader compile errors as top-level Go errors from `game_asset_reload` would match argument errors. It was rejected because reloading an asset (or a whole group via `game_assets_reload_group` / `all: true`) can partially succeed and benefits from returning timing (`duration_ms`), preserved `bytes`, `group`, per-item status (`items`), and structured `error` details alongside `reloaded: false` so agents can diagnose broken edits cleanly.

### Routing all reloads exclusively through `hotreload.Watcher`

Delegating MCP reloads solely to `hotreload.Watcher` would avoid adding `ReloadAsset` / `ReloadShaderFile` / `ReloadMaterialFile`. It was rejected because `hotreload.Watcher` is a polling loop compiled out under `-tags release` and games using `assets.WithFS` or `nsgotest` often run without an active filesystem polling watcher; direct on-demand reload works deterministically in both `nsgo dev -automation` and `nsgo test`.

## Consequences

- **Benefits**: Coding agents can inspect loaded asset groups, states, asset keys, and memory usage and trigger deterministic in-place reloads of atlases, images, bytes, custom assets, shaders, materials, and YAML resources over `nsgo mcp`, immediately updating the running game while keeping broken edits non-fatal.
- **Costs**: `packages/game/assets` maintains `rawBytes` per loaded asset for memory accounting and an on-demand reload path alongside `Manager.Reload(uri, data)`. Memory figures for URI-only images and decoded sounds without inline pixel/byte buffers are estimates derived from declared dimensions, frame extents, or audio duration.

## Verification

Verified with `gofmt`, `go run ./cmd/gameschema -check`, `go tool nsgo check -target macos,windows,linux,android,web`, `go tool nsgo test ./mcp`, `go tool nsgo test ./assets`, `go tool nsgo test ./resource`, `go tool nsgo test ./tooling/hotreload`, `go tool nsgo test -run TestStabilityTable .`, `go run ./tools/changelog check`, and `bun run verify-notes`.
5 changes: 5 additions & 0 deletions changelog.d/mcp-assets-hotreload.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Added

- `game/mcp`: added `game_assets_list`, `game_asset_reload`, and `game_assets_reload_group` tools plus `RegisterAsset`, `RegisterAtlas`, and `Config` asset/hot-reload hooks to inspect loaded asset groups/memory and hot-reload atlases, images, bytes, custom assets, shaders, materials, and YAML resources in place; sounds, images without a file and unshown densities are reported as skipped (#469).
- `game/assets`: added read-only `Manager.Disposed`, `Manager.GroupNames`, `Manager.LookupGroup`, `Manager.GroupStats`, `Group.Stats`, and on-demand in-place `Manager.ReloadAsset` and `Manager.ReloadGroup` helpers that read and parse off the engine goroutine, plus `EstimateAtlasBytes` (#469).
- `game/tooling/hotreload`, `game/resource`: added `ShaderReloader.ShaderPath`, `ShaderReloader.ReloadShaderFile`, `MaterialReloader.MaterialPath`, `MaterialReloader.ReloadMaterialFile`, and `Library.ReloadFile` helpers for on-demand hot reload (#469).
20 changes: 19 additions & 1 deletion docs/en/mcp.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# mcp

`game/mcp` exposes a running game's scenes, layers, entities, components, fixed-step loop controls, game-coordinate input injection, tunables and debug console to coding agents over MCP through NSGo's `github.com/nsgo-dev/nsgo/automation` package.
`game/mcp` exposes a running game's scenes, layers, entities, components, fixed-step loop controls, game-coordinate input injection, tunables, debug console, loaded asset groups and hot reload controls to coding agents over MCP through NSGo's `github.com/nsgo-dev/nsgo/automation` package.

NSGo's built-in `nsgo mcp` server sees native views only; a game draws into one `Canvas` or GPU view. Attaching an `mcp.Bridge` to a `core.Scope` registers game-specific tools on the engine's reactive graph so `nsgo mcp` serves them alongside the built-in tools whenever the app runs under `go tool nsgo dev -automation` or `go tool nsgo test`. In ordinary and release builds, `automation.Register` is a no-op and adds no runtime protocol.

Expand Down Expand Up @@ -30,6 +30,11 @@ bridge, err := mcp.Attach(cx, mcp.Config{
Console: g.console,
Overlay: g.debugOverlay,
RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(g.lastRenderStats) },
Assets: g.assets,
Resources: g.resources,
Shaders: g.shaderReloader,
Materials: g.materialReloader,
ReloadAsset: g.reloadCustomAsset,
})
if err != nil {
return err
Expand Down Expand Up @@ -122,6 +127,9 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r
| `game_perf_readout` | `include_history` (optional, default `false`), `history_limit` (optional), `include_zones` (optional, default `false`), `zones_limit` (optional) | Live performance readout matching the debug overlay: `fps`, rolling average and latest `frame_ms`/`update_ms`/`draw_ms`, min/max/p50/p95/p99 frame times, draw stats (`draw_calls`, `sprites`, `batches`, `triangles`, `vertices`), per-frame heap allocations (`allocs_per_frame`, `alloc_bytes_per_frame`, `last_frame_allocs`, `last_frame_alloc_bytes`), `heap_bytes`, `gc_count`, GC pause/hitch metrics, optional `render3d` and `asset_memory` breakdowns, and optional chronological `history` and profiler `zones`. |
| `game_perf_zones` | `limit` (optional) | Named timing zones from `debug.Profiler` sorted by recent frame cost (`name`, `last_ms`, `avg_ms`, `max_ms`, `calls`), plus `recording`, `recorded_frames` and `total`. |
| `game_perf_reset` | `{}` | Resets accumulated `debug.Overlay` frame timings and pushed draw stats, `debug.Profiler` zone timings, and `debug.GCMonitor` history. A profiler trace recording started with `StartRecording` keeps running and keeps its events. |
| `game_assets_list` | `group` (optional), `state` (`loaded`/`loading`/`unloaded`/`failed`), `kind` (optional) | Deterministically sorted asset groups (`assets.Manager` groups, `resource.Library`, `hotreload.ShaderReloader`, `hotreload.MaterialReloader`, and custom registered assets) with load states, asset keys/kinds/URIs, frame counts, per-group estimated bytes, and `total_bytes`. |
| `game_asset_reload` | `key` (name, URI or relative path), `group` (optional), `all` (boolean, optional) | Reloads a matching asset in place (or all loaded assets when `all: true`), returning `{reloaded, key, group, kind, bytes, duration_ms, revision, items, error}`; each item carries `skipped` when it was left unchanged without an error. Parse and compile errors are returned in the structured result while keeping the previously loaded working asset intact. `all: true` needs an asset manager, reloader or registered asset; `Config.ReloadAsset` only reloads a single key. |
| `game_assets_reload_group` | `group` (required) | Reloads every loaded asset in the named group in place, reporting per-item results, `count` reloaded, `failed`, `skipped`, memory bytes, duration, and any item errors without crashing the running game. |

All tools reject unknown argument fields.

Expand Down Expand Up @@ -200,6 +208,16 @@ Pass your [`debug.Overlay`](debug.md) via `Config.Overlay` to expose the exact s
- `Config.RenderStatsFunc` attaches detailed 3D culling, batching, state-switch and GPU memory metrics from [`render3d.RenderStats`](render3d.md) under `render3d`, and populates top-level `draw_calls`, `batches`, `triangles` and `vertices` automatically when no 2D draw-stats provider is set. `mcp.PerfRender3DStats` has the same fields as `render3d.RenderStats`, so `mcp.PerfRender3DStats(stats)` converts one; `game/mcp` does not import `game/render3d`, so a 2D game that attaches the bridge does not link the 3D renderer.
- `game_perf_readout` always includes a `sources` object indicating which telemetry providers are active (`overlay`, `profiler`, `gc`, `memory`, `draw_stats`, `render3d`).

## Assets and hot reload

Wire `Config.Assets` (or `Config.AssetsFunc` / `bridge.SetAssets`), `Config.Resources`, `Config.Shaders`, `Config.Materials`, and/or `Config.ReloadAsset` to let agents inspect memory usage and trigger live reloads without restarting the game:

- **In-place atlas updates**: Reloading an atlas in `assets.Manager` (by asset name such as `"hero"`, full URI `"asset:sprites/hero.json"`, relative path `"sprites/hero.json"`, or image path `"sprites/hero.png"`) updates the existing `*sprite.Atlas` pointer in place and increments `assets.Manager.Revision()`, so sprites holding the atlas pointer and canvases reading `Revision()` update immediately.
- **Standalone assets and atlases**: Games that hold a `*sprite.Atlas` or custom resource outside `assets.Manager` can register it with `bridge.RegisterAtlas(...)` or `bridge.RegisterAsset(mcp.CustomAsset{...})`.
- **Safe failure handling**: Syntax, schema, or shader compilation errors leave the previous working atlas, shader, material, or resource active and return `reloaded: false` with the diagnostic message in `error`.
- **Skipped assets**: Sounds are not replaced in place, images with no file behind them (such as generated textures) have nothing to reload, and a file at a density the screen does not show (the 1x file on a 2x screen) would change nothing on screen. These items carry `skipped` with the reason (`assets.SkippedSound`, `assets.SkippedNoFile`, `assets.SkippedDensity`) and count neither as reloaded nor as failed. A group reload also skips an image whose file the group's reader cannot find; reloading that image by key reports the read error.
- **Off the engine goroutine**: `Manager.ReloadAsset` and `Manager.ReloadGroup` read files, parse atlases and run custom loaders on another goroutine, as `Group.Load` does, and apply the results on the engine goroutine once they finish. The tool call waits for them, so a custom reader or loader must not wait on the engine goroutine; when the call's context ends first, nothing is replaced and the tool returns the context's error.

## Stable entity references

Every live entity receives a generational reference formatted as `"entity:<index>:<generation>"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`:
Expand Down
Loading
Loading