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,47 @@
# Agent Note: MCP input recording and deterministic replay

Status: implemented

## Problem

`game/replay` provides fixed-step input recording (`replay.Recorder`) and deterministic playback (`replay.Player`) over versioned YAML files, and [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md) lets coding agents inspect a running game via `nsgo mcp`. However, agents have no MCP tools to start or stop an input recording of a running session or replay a stored or inline YAML recording back through the live simulation to reproduce exact state.

## Decision

Add `ReplayController` (configured via `ReplayConfig` on `mcp.Config.Replay`) and six `game_replay_*` automation tools in `packages/game/mcp/replay.go`, appended to `Bridge.Tools()` alongside the inspection tools. `ReplayController` itself implements `replay.ActionSource`, switching transparently between live `Source`, an active `replay.Recorder`, and an active `replay.Player` so a game wires MCP record and replay into one unchanged update loop.

## Architecture and tool contract

- **Single `ActionSource` facade (`ReplayController`)**: Games construct `ctrl := mcp.NewReplayController(cfg)`, pass `ctrl` to their simulation as its `replay.ActionSource`, and supply `Replay: ctrl` in `mcp.Config`. During live play `ctrl` forwards to `cfg.Source`; during recording it delegates to a `replay.Recorder` wrapping `cfg.Source`; during playback it delegates to a `replay.Player` created from the target `replay.Recording` and still steps `cfg.Source`, so the live previous-step snapshot is current when playback ends. `cfg.Source` is required: an earlier pre-built `Recorder` fallback was dropped because with no `Source` live play had no input at all.
- **Final-step playback lifecycle**: In `replay.Player.Step()`, advancing the last recorded frame (`TotalSteps - 1`) sets `Done() == true` before the simulation reads `Pressed`/`JustPressed`/`Axis` for that tick. `ReplayController` therefore keeps `player` attached through that final step, runs one trailing `player.Step()` on the next `Step()` so actions held at the end fire `JustReleased` once, and clears it on the `Step()` after that (resuming live input), on `game_replay_stop`, or before starting a new record/play session. Synchronous `run_to_end`/`steps` leave a completed player attached for the trailing step. Meanwhile `game_replay_status` reports `replaying: false` and `replay_done: true` as soon as `player.Done()` becomes true so polling agents observe completion without needing an extra live step.
- **Six tools with strict JSON decoding**:
- `game_replay_status`: returns recording/playback flags, frame counters, active names/metadata, and sorted `saved_recordings`.
- `game_replay_record_start`: starts recording with optional `name` (auto-allocated sequentially when omitted), `seed` (falls back to `SeedFunc` or `0`), `actions`/`axes` overrides, string `metadata`, and `reset` (default `true` when `ResetFunc` or a seed target is configured, the same default as `game_replay_play`, so a recording started mid-game replays to the same state). The rate is not an argument: it is the game's fixed rate, the Bridge loop's `StepRate()` or else `ReplayConfig.StepRate` or `60`. Refuses starting while already recording or actively replaying.
- `game_replay_record_stop`: validates optional `save_path` before mutating state so an invalid path never discards an active recording, encodes canonical `replay` v2 YAML via `Recording.Encode()`, stores a clone in memory under its name, optionally writes inside `ReplayConfig.SaveDir` through `os.Root` (rejecting absolute paths, `..` and symbolic links that leave it, and refusing an existing file or stored name unless `overwrite: true`), and returns summary fields plus the YAML text.
- `game_replay_play`: accepts either a stored `name` or inline `yaml` (decoded and validated via `replay.Decode`), refuses a recording whose `rate` differs from the game's fixed rate, resets by default (re-seeding `Config.Random`, `Config.RandomStreams` and `Config.SetSeed` as `game_loop_seed` does, then `ResetFunc(rec.Seed)`, rolling back if it fails), and supports frame-by-frame playback, synchronous stepping (`steps: 1..3600`), or full synchronous playback (`run_to_end: true`, recordings up to `MaxLoopSteps`) using `StepFunc` or else the Bridge loop's `StepNow`, so `game_loop_status` stays in sync.
- `game_replay_stop`: stops an active playback early and fires `OnReplayStop`.
- `game_replay_list`: returns sorted summaries (`name`, `frames`, `seed`, `step_rate`, `events`, `actions`, `axes`, `metadata`) of stored recordings.
- **Pure `game/replay` v2 YAML preservation**: Optional MCP `metadata` is stored alongside the `replay.Recording` in `ReplayController`'s in-memory map rather than added to the YAML schema, keeping exported YAML 100% compatible with `replay.Decode`'s `KnownFields(true)` check and `go tool game replay`.

## Alternatives considered

### Putting `Recorder`/`Player` wiring callbacks on `mcp.Config` without implementing `replay.ActionSource`

`mcp.Config` could expose `OnStartRecord` / `OnStartReplay` hooks and require every game to manually swap its own `ActionSource` variable across live, record, and playback modes. This was rejected because every game would reimplement the same three-mode multiplexer and easily hit the final-step `Player.Done()` subtlety (dropping inputs on the last recorded step or getting stuck after playback ends). Making `ReplayController` itself a `replay.ActionSource` encapsulates those invariants once while still offering lifecycle hooks (`OnRecordStart`, `OnRecordStop`, `OnReplayStart`, `OnReplayStop`).

### Persisting MCP `metadata` inside the `.replay.yaml` file

Adding a `metadata` field to `replay.Recording` would persist agent labels on disk with the recording. This was rejected because `packages/game/replay` is a Stable package with a strict version-2 YAML contract checked by conformance tests and `go tool game replay`; keeping recordings in canonical v2 YAML ensures recordings created through MCP can be dropped straight into `testdata/` for CI regression tests with no format divergence.

### Allowing arbitrary filesystem paths in `game_replay_record_stop`

Letting an agent pass any file path to `save_path` would simplify one-off exports without setting `SaveDir`. This was rejected because MCP tools may be invoked by autonomous coding agents; confining disk writes to an explicit opt-in `ReplayConfig.SaveDir` (and returning the full YAML inline by default with in-memory storage) keeps playback self-contained on every target including WebAssembly while preventing unintended writes outside the project directory.

## Consequences

- **Benefits**: Agents can record live input sequences over MCP, inspect their deterministic v2 YAML, store or export them safely, and replay them (by name, from inline YAML, synchronously, or frame-by-frame) to reproduce bit-identical simulation and ECS component state. Games wire the capability in a handful of lines by passing `ReplayController` as their `replay.ActionSource`, and parallel MCP tool groups remain isolated in separate files.
- **Costs**: Games that want `run_to_end` or `steps` synchronous playback must expose a deterministic `StepFunc` (or a loop on `mcp.Config`) and `ResetFunc`, and must configure watched `Actions`/`Axes` names (matching `replay.NewRecorder`) because `input.Actions` does not enumerate all dynamic action names by itself. In-memory recordings live for the lifetime of the `ReplayController` unless deleted or replaced by name.

## Verification

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

- `game/mcp`: add `ReplayController` and MCP record/replay tools (`game_replay_status`, `game_replay_record_start`, `game_replay_record_stop`, `game_replay_play`, `game_replay_stop`, `game_replay_list`) for starting/stopping input recordings and replaying them deterministically (#467).
41 changes: 41 additions & 0 deletions docs/en/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r
| `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. |
| `game_replay_status` | `{}` | Current recording and playback state (`recording`, `replaying`, `replay_done`, `frames_recorded`, `replay_frame`, `replay_total_frames`), active names/metadata, and sorted `saved_recordings`. |
| `game_replay_record_start` | `name`, `seed`, `actions`, `axes`, `metadata`, `reset` (all optional; `reset` defaults to `true` when `ResetFunc` or a seed target is configured) | Resets to `seed` (see below) and starts recording per-step inputs via `replay.Recorder` at the game's fixed step rate, returning the resolved recording name, seed, step rate, watched names and metadata. |
| `game_replay_record_stop` | `name` (optional), `save_path` (optional, relative to `ReplayConfig.SaveDir`), `overwrite` (default `false`) | Stops the active recording, stores it in memory (and optionally writes it under `SaveDir`), and returns its summary plus deterministic version-2 YAML text (`yaml`). An existing stored name or file is refused unless `overwrite: true`, and the recording continues. |
| `game_replay_play` | `name` or `yaml` (mutually exclusive), `run_to_end` (default `false`), `steps` (`1..3600`), `reset` (default `true` when `ResetFunc` or a seed target is configured) | Resets to the recording's seed and starts deterministic playback via `replay.Player`, optionally advancing all (`run_to_end`, recordings up to `3600` steps) or `steps` frames synchronously via `StepFunc` or the game loop's `StepNow`. A recording whose `rate` differs from the game's fixed step rate is refused. |
| `game_replay_stop` | `{}` | Stops an active replay playback cleanly and reports how many frames were played. |
| `game_replay_list` | `{}` | Lists stored recordings in sorted name order with `frames`, `seed`, `step_rate`, `events`, `actions`, `axes` and `metadata`. |

All tools reject unknown argument fields.

Expand Down Expand Up @@ -146,6 +152,41 @@ console.RegisterCommand("spawn", "spawn <kind> [count]", g.handleSpawn)
- `game_tunables_list` and `game_tunable_get` read live values directly without adding entries to the console's interactive command history or output log.
- `game_tunable_set` enforces each tunable's registered type (`float`, `int`, `bool` or `string`) and numeric `[min, max]` bounds by default without mutating the variable on error. Passing `"clamp": true` clamps out-of-range numeric values into `[min, max]` and sets `"clamped": true` in the response.
- `game_console_exec` executes built-in commands (`help`, `list`, `get`, `set`, `clear`) and game-registered commands through `debug.Console.Exec`, returning `{command, ok, output, lines, error}`. Invalid MCP arguments or a missing `Console` return a tool error, while command execution failures (such as an unknown command name or invalid command arguments) return `ok: false` with the command's `error` message.
## Recording and replaying inputs

Create a `*mcp.ReplayController` with `mcp.NewReplayController`, pass it to your simulation as its [`replay.ActionSource`](replay.md), and attach it on `mcp.Config.Replay`:

```go
var ctrl *mcp.ReplayController
ctrl = mcp.NewReplayController(mcp.ReplayConfig{
Source: g.actions,
Actions: []string{"left", "right", "jump", "dash"},
Axes: []string{"move_x"},
StepRate: 60,
SeedFunc: func() uint64 { return g.seed },
ResetFunc: func(seed uint64) error {
g.actions.Reset()
g.Reset(seed)
return nil
},
StepFunc: func(dt time.Duration) {
g.Step(ctrl, dt)
},
})

bridge, err := mcp.Attach(cx, mcp.Config{
WorldFunc: func() *entities.World { return g.world },
Replay: ctrl,
})
```

- Because `ReplayController` implements `replay.ActionSource`, your game loop reads input from `ctrl` identically during live play (forwarded to `Source`), recording (`replay.Recorder`) and playback (`replay.Player`). `Source` is required. It is still stepped during playback, so its previous-step snapshot is current when live input resumes.
- Recording and playback share one reset: the Bridge's seed targets (`Config.Random`, `Config.RandomStreams`, `Config.SetSeed`, the same ones `game_loop_seed` uses) are re-seeded with the seed, then `ResetFunc(seed)` runs. `reset` defaults to `true` on both tools whenever there is something to reset, so a recording started mid-game with default arguments replays to the same state. Passing `reset: false` to `game_replay_record_start` records from the current state, and that recording only reproduces from the same state.
- The recording's `rate` is the game's fixed step rate: the Bridge's loop (`Config.Loop` / `Config.LoopFunc`) `StepRate()` when there is one, otherwise `ReplayConfig.StepRate` (default `60`). `game_replay_play` refuses a recording made at another rate, because each step would get a different `dt`.
- Recordings stopped via `game_replay_record_stop` are stored in memory under their name and returned as canonical deterministic [`game/replay`](replay.md) v2 YAML text. Set `ReplayConfig.SaveDir` if you also want agents to write recordings to relative paths on disk via `save_path`; the write goes through `os.Root`, so absolute paths, `..` and symbolic links cannot leave `SaveDir`. `metadata` stays only in the in-memory store: it is not part of the YAML, so a saved file or an inline `yaml` replay does not carry it.
- `game_replay_play` accepts either a stored `name` or inline `yaml` text and replays either synchronously (`run_to_end: true` or `steps: N`) or frame by frame as the game loop advances. Without `StepFunc`, synchronous playback advances the Bridge's loop with `Loop.StepNow`, so `game_loop_status` counts the replayed steps and game time. Like `game_loop_step`, a single call advances at most `MaxLoopSteps` (`3600`) steps.
- After the final recorded step, the next `ctrl.Step()` is a trailing playback step that releases actions still held at the end of the recording (firing `JustReleased` once); the step after it returns to live input and calls `OnReplayStop`.

## 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