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,43 @@
# Agent Note: MCP object spawning, destruction and component editing

Status: implemented

## Problem

With [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md) in place, coding agents running a game under `nsgo dev -automation` can read scenes, layers, live entities, and components, but cannot mutate runtime world state—they cannot spawn prefabs to reproduce bugs, destroy entities, or tweak component values to test gameplay hypotheses on the next simulation step.

## Decision

Extend `packages/game/mcp` with a dedicated mutation tool group in `edit.go` (`game_prefabs_list`, `game_entity_spawn`, `game_entity_destroy`, `game_component_set`, `game_component_remove`) hooked into `Bridge.Tools()`, backed by prefab registration APIs (`Config.Prefabs`, `Bridge.RegisterPrefab`, `Bridge.RegisterEntityPrefab`, `Bridge.RegisterScenePrefab`), typed component editor APIs (`RegisterMutableComponent`, `RegisterComponentEditor`), and strict codec mutation helpers (`World.DecodeComponent`, `World.PatchComponent`, `World.RemoveComponent`) in `packages/game/entities`.

## Architecture and mutation contract

- **Minimal hookup in `mcp.go`**: All mutation types, schemas, registration APIs, and handlers live in `packages/game/mcp/edit.go`; `mcp.go` adds only `Config.Prefabs`, `write`/`remove` hooks on `componentEntry`, prefab storage fields on `Bridge`, and `b.editTools()` in `Bridge.Tools()`. This isolates parallel MCP PRs (#462–#469) from merge conflicts.
- **Prefab sources**: `Bridge` supports three prefab kinds (`"custom"`, `"entity_prefab"`, `"scene"`): custom `PrefabSpawner` callbacks with optional `overrides`, `*entities.Prefab` templates via `RegisterEntityPrefab`, and validated self-contained `*sceneformat.SceneDoc` templates via `RegisterScenePrefab` (instantiated through `sceneformat.SpawnEntities`). `game_prefabs_list` enumerates all registered prefabs in deterministic sorted order.
- **Atomic spawning and rollback**: `game_entity_spawn` validates `x`/`y` finite float32 bounds, parent ref liveness, and prefab existence before spawning. If applying `parent` or any entry in `components` fails after spawn, every newly created entity (including scene-prefab children) is destroyed before returning the error so failed calls never leak half-initialized entities.
- **Patch-by-default strict component edits**: `game_component_set` defaults to patching existing component fields (`replace: false`) so editing a single field (such as `transform2d.x` or `health.hp`) preserves omitted fields like `scaleX`/`scaleY` or `max`, while `replace: true` decodes into a fresh zero value. Both codec helpers (`World.PatchComponent` / `World.DecodeComponent`) and bridge editors decode JSON with `DisallowUnknownFields()`, reject trailing tokens, reject `null` for non-nullable types, and reject non-finite floats (`NaN`, `±Inf`). Patching (`internal/jsonedit.Patch`) decodes onto a clone whose exported pointers, maps, slices and interfaces are freshly allocated, so a partial decode error or a rejecting editor never reaches the live entity, and then takes from the clone only the fields the patch changed, so unexported fields, `json:"-"` fields (callbacks, handles, caches) and the identity of untouched pointers survive. A JSON round-trip copy was the first approach; it was replaced because it zeroed exactly those runtime fields on `RegisterMutableComponent` types, and its shallow-copy fallback for values that cannot be marshalled shared live maps with the decoder. Codec edits are also refused when the decoded value cannot be encoded back, so a custom `UnmarshalJSON` that yields `NaN` cannot break later snapshots.
- **Hierarchy invariants**: Built-in `"transform2d"` writes go through `entities.Set`, which delegates to `Hierarchy2D.SetLocal` whenever a hierarchy is attached so `WorldTransform2D` dirty flags propagate to descendants automatically. Built-in `"world_transform2d"` is explicitly read-only because it is a derived cache overwritten on `Hierarchy2D.Sync()`. `game_entity_destroy` accepts `"cascade"`, `"orphan"`, `"keep_world"`, and `"reparent"` policies without lazily instantiating `Hierarchy2D` when an entity has no children; `"reparent"` keeps the children's world transforms, and an omitted policy reports the hierarchy's actual default (or `"none"` for a childless entity). Scene prefabs must have exactly one top-level object so the spawn result names every spawned entity through the root's subtree.
- **Read-only vs mutable bridge components**: `RegisterComponent[T]` and `RegisterComponentFunc` remain read-only so inspection-only registrations (such as components carrying callbacks) do not silently become writable. Callers opt in with `RegisterMutableComponent[T]` or upgrade an existing registration with `RegisterComponentEditor[T]` to enforce domain invariants before writing.

## Alternatives considered

### Making `RegisterComponent[T]` automatically writable

Allowing `game_component_set` to write to every `RegisterComponent[T]` registration would save one registration call for transient structs. It was rejected because games intentionally use `RegisterComponent` for read-only debug views or structs with runtime callbacks/handles (`OnTick func()`, pointers), where unconstrained JSON writes could corrupt invariants or zero unexported fields; explicit `RegisterMutableComponent` and `RegisterComponentEditor` keep the safety boundary clear while `entities.RegisterCodec` components remain automatically editable.

### Replace-only `game_component_set` (no default patch mode)

Decoding every `game_component_set` payload into a zero-valued struct would be simpler to implement. It was rejected because Go's zero value for `entities.Transform2D` has `ScaleX: 0, ScaleY: 0` (collapsed scale), so an agent sending `{"x": 100, "y": 50}` would silently make the object invisible, and tweaking one field on a gameplay struct (like `health.hp`) would wipe unrelated fields (`health.max`). Patching by default with an explicit `"replace": true` flag supports both workflows safely.

### Handling codec decoding purely inside `packages/game/mcp` via `World.Snapshot` / `Restore`

Avoiding changes to `packages/game/entities` by snapshotting, editing JSON, and calling `World.Restore` would keep `entities` untouched. It was rejected because `Snapshot`/`Restore` is O(world size), resets un-serialized transient component stores, and does not support strict `DisallowUnknownFields` decoding for a single entity's component. Adding `DecodeComponent`, `PatchComponent`, and `RemoveComponent` methods to `entities.World` keeps single-entity edits O(1) and preserves transient components.

## Consequences

- **Benefits**: Coding agents can discover prefabs, spawn entities (with hierarchy and initial components), edit codec/built-in/custom components with immediate effect on the next simulation step, remove components, and destroy subtrees with explicit hierarchy policies—all with strict validation and atomic rollback on error.
- **Costs**: `packages/game/entities` gains three public codec mutation methods (`DecodeComponent`, `PatchComponent`, `RemoveComponent`) to maintain alongside `EncodeComponent`. Patch mode clones the existing component value with reflection and compares fields to merge the result, which is negligible for interactive MCP edits but not intended for per-frame inner loops.

## 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 ./entities`, `go tool nsgo test -run TestStabilityTable .`, `go run ./tools/changelog check`, and `bun run verify-notes`.
4 changes: 4 additions & 0 deletions changelog.d/mcp-spawn-destroy-edit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Added

- `game/mcp`: add `game_prefabs_list`, `game_entity_spawn`, `game_entity_destroy`, `game_component_set`, and `game_component_remove` tools along with prefab registration (`Config.Prefabs`, `Bridge.RegisterPrefab`, `Bridge.RegisterEntityPrefab`, `Bridge.RegisterScenePrefab`) and typed component editing (`RegisterMutableComponent`, `RegisterComponentEditor`) (#464).
- `game/entities`: add `World.DecodeComponent`, `World.PatchComponent`, and `World.RemoveComponent` strict JSON codec mutation helpers (#464).
44 changes: 39 additions & 5 deletions docs/en/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,49 @@ if err != nil {
- When a `scene.Manager` controller draws via a custom `Controller.Draw` without setting `Controller.Scene`, `SceneFunc` / `Scene` provides the current scene's layers automatically.
- When `EntityName` or `EntityLayer` is omitted (or returns `""`), `game/mcp` falls back to [`sceneformat.ObjectRef`](editor.md) if the entity carries one.

## Inspecting components
## Inspecting and editing components

Components registered on an [`entities.World`](entities.md) with `entities.RegisterCodec` are readable automatically. In addition:
Components registered on an [`entities.World`](entities.md) with `entities.RegisterCodec` are readable and editable automatically. In addition:

- Built-in `entities.Transform2D`, `entities.WorldTransform2D` and `sceneformat.ObjectRef` components are surfaced automatically as `"transform2d"`, `"world_transform2d"` and `"object_ref"` unless that type or name is already registered.
- Transient or non-saved runtime components can be exposed with `mcp.RegisterComponent[T](bridge, name)` or a custom reader via `mcp.RegisterComponentFunc(bridge, name, read)`.
- Built-in `entities.Transform2D`, `entities.WorldTransform2D` and `sceneformat.ObjectRef` components are surfaced automatically as `"transform2d"`, `"world_transform2d"` and `"object_ref"` unless that type or name is already registered. `"transform2d"` and `"object_ref"` are editable directly (with `"transform2d"` propagating `Hierarchy2D` dirty flags automatically); `"world_transform2d"` is derived from the hierarchy and read-only.
- Transient or non-saved runtime components can be exposed read-only with `mcp.RegisterComponent[T](bridge, name)` or `mcp.RegisterComponentFunc(bridge, name, read)`, or exposed for both reading and editing with `mcp.RegisterMutableComponent[T](bridge, name)` or `mcp.RegisterComponentEditor[T](bridge, name, apply)`. `RegisterComponentEditor` can add editing to an earlier `RegisterComponent[T]` registration of the same type, but not to a `RegisterComponentFunc` reader, whose value need not be stored as `T`.
- `game_component_set` decodes values strictly with `DisallowUnknownFields`, rejects non-finite floats (`NaN`, `±Inf`) and invalid nulls, and patches existing fields by default (preserving omitted fields unless `"replace": true` is passed) without leaving partially mutated state on error. A patch keeps every field it does not change exactly as it was, including unexported fields, fields tagged `json:"-"` such as callbacks and handles, and the identity of pointers, maps and slices; a field it changes gets a freshly allocated value, so an error or an editor that rejects the value leaves the live component untouched. A codec component whose decoded value cannot be encoded back, such as a `NaN` produced by a custom `UnmarshalJSON`, is refused before it is stored.
- Component values are serialized with `encoding/json`; if a runtime value contains non-finite floats (`NaN`, `+Inf`, `-Inf`), callback fields, channels or cyclic pointers, `game/mcp` falls back to a safe sanitizer (`"NaN"`, `"+Inf"`, `"-Inf"`, `"<func>"`, `"<chan>"`, `"<cycle>"`) so an agent can still diagnose broken runtime state.

```go
if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil {
if err := mcp.RegisterMutableComponent[AIState](bridge, "ai"); err != nil {
return err
}
if err := mcp.RegisterComponentEditor[Health](bridge, "health", func(w *entities.World, e entities.Entity, h Health) error {
if h.HP < 0 {
return errors.New("hp cannot be negative")
}
entities.Set(w, e, h)
return nil
}); err != nil {
return err
}
```

## Registering prefabs

Prefabs can be registered on `mcp.Config.Prefabs` or on the `*mcp.Bridge` so agents can discover them with `game_prefabs_list` and spawn them with `game_entity_spawn`:

- `bridge.RegisterPrefab(name, spawn)` (or `Config.Prefabs`) registers a custom `mcp.PrefabSpawner` (`func(w *entities.World, overrides map[string]any) (entities.Entity, error)`).
- `bridge.RegisterEntityPrefab(p)` registers an [`*entities.Prefab`](entities.md) under `p.Name()`.
- `bridge.RegisterScenePrefab(name, doc)` registers a validated, self-contained [`*sceneformat.SceneDoc`](editor.md) template spawned via `sceneformat.SpawnEntities`. The document must hold exactly one top-level object, the spawned root; nest the rest under it. Every spawn attaches the document's `sceneformat.ObjectRef` IDs unchanged, so repeated spawns produce entities with the same object IDs, which `game_entities_list` also shows as their names unless `EntityName` says otherwise.

```go
if err := bridge.RegisterEntityPrefab(coinPrefab); err != nil {
return err
}
if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil {
return err
}
```

If `game_entity_spawn` fails while applying `parent` or `components`, or while reading the new entity's components back, the newly spawned entity (and any scene-prefab children) are rolled back automatically. `x` and `y` are validated before anything is spawned.

## Registered tools

| Tool | Arguments | What it returns |
Expand All @@ -77,6 +106,11 @@ if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil {
| `game_tunable_set` | `name` (required), `value` (required), `clamp` (optional, default `false`) | Updates a registered tunable (`float`, `int`, `bool` or `string`) with strict type checking and range validation (or clamping when `clamp: true`), returning `old_value`, applied `value`, metadata and `clamped`. |
| `game_console_commands_list` | `include_builtin` (optional, default `true`) | Built-in and custom `debug.Console` commands sorted by name with `help` text and `builtin` flag. |
| `game_console_exec` | `command` (required) | Runs one command line through `debug.Console`, returning `command`, `ok`, `output`, `lines`, and `error` (when the console command fails). |
| `game_prefabs_list` | `{}` | Sorted list of registered prefabs (`name` and `kind`: `"custom"`, `"entity_prefab"`, or `"scene"`). |
| `game_entity_spawn` | `prefab`, `overrides`, `parent`, `x`, `y`, `components` (all optional) | Newly spawned live entity's stable `ref`, `index`, `generation`, `prefab`, metadata, `parent`, `children`, and initial `components` snapshot. |
| `game_entity_destroy` | `ref` (required), `policy` (optional: `"cascade"`, `"orphan"`, `"keep_world"`, or `"reparent"`) | Confirmation of destruction with `ref`, the `policy` applied to children (the hierarchy's default, usually `"orphan"`, when omitted; `"none"` when omitted and the entity had no children), and count of `destroyed` entities. `"reparent"` keeps the children's world transforms. |
| `game_component_set` | `ref` (required), `component` (required), `value` (required), `replace` (optional, default `false`) | Updated component `value` read back from the live entity; edits take effect on the next simulation step. If the write succeeded but the read-back failed, `value` is `null` and `read_error` says why; the edit still stands. |
| `game_component_remove` | `ref` (required), `component` (required) | Whether the component was present and `removed` from the live entity. |

All tools reject unknown argument fields.

Expand Down
Loading
Loading