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 tunables and debug console commands

Status: implemented

## Problem

Coding agents connected to a running game via `game/mcp` (introduced in [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md)) can inspect scenes, layers, entities and components, but cannot read or adjust live tuning variables (`debug.Console` tunables) or invoke registered debug console commands without driving the interactive console UI view. Meanwhile, `debug.Console` only exposed text-formatted `list`/`help` output through `Exec`, which mutates command history and output entries and hides structured type/range/default metadata.

## Decision

Add structured inspection and typed mutation methods to `packages/game/debug.Console` (`RegisterString`, `Tunables`, `Tunable`, `SetTunable`, `Commands`, backed by `TunableInfo`, `TunableChange` and `CommandInfo` in `debug/types.go` with release-build stubs in `debug/console_release.go`) and expose five new MCP tools in `packages/game/mcp/console.go`: `game_tunables_list`, `game_tunable_get`, `game_tunable_set`, `game_console_commands_list` and `game_console_exec`, wired into `Bridge` via `Config.Console`, `Config.ConsoleFunc`, `Bridge.SetConsole` and `Bridge.Tools()`.

## Tool contract and design

- **Minimal `mcp.go` hookup**: All tool constants, schemas, handlers and result structs live in `packages/game/mcp/console.go` so parallel MCP tool PRs (#462–#469) touch only `Config`, setter methods and `Bridge.Tools()` in `mcp.go`.
- **Side-effect-free structured queries**: `game_tunables_list`, `game_tunable_get` and `game_console_commands_list` query `debug.Console.Tunables()`, `Tunable(name)` and `Commands()` directly under `Console.mu` without appending to `Console.History()` or `Console.Entries()`. Results are sorted deterministically by name, and numeric bounds include `0` explicitly (using non-nil `any` values so `omitempty` only omits absent bounds on `bool`/`string` tunables). Registration captures each tunable's initial `*ptr` value as `Default`.
- **Strict typing and range handling in `game_tunable_set`**: Arguments use `DisallowUnknownFields()` and decode `value` strictly against the tunable's registered type (`float`, `int`, `bool` or `string`), explicitly rejecting `null`, non-finite floats, fractional numbers for `int`, and mismatched JSON kinds. Out-of-range numeric values fail by default without mutating the bound pointer; passing `"clamp": true` clamps into `[min, max]`, including an integer beyond `int`'s range, and reports `"clamped": true`. `game/mcp` only decodes the JSON value into the tunable's Go type; `Console.SetTunable(name, value, clamp)` checks the type and range, clamps, writes and snapshots the result under one lock, so a tunable re-registered between the tool's lookup and its write is never clamped with stale bounds. Responses always return both `old_value` and applied `value`.
- **Structured console execution in `game_console_exec`**: Tool-level errors (unconfigured `Console`, unknown JSON fields, missing/empty `command`) return MCP handler errors. Command execution delegates to `debug.Console.Exec` and returns `{command, ok, output, lines, error}` so agents receive both normalized output lines and structured command failure diagnostics (`ok: false`, `error: "..."`) without crashing or conflating command syntax errors with transport/schema errors.
- **Release build compatibility**: `TunableInfo`, `TunableChange` and `CommandInfo` live in untagged `debug/types.go`, and `debug/console_release.go` provides matching zero-cost stubs (`SetTunable` returns an error there, since nothing is registered and a nil error would claim a write that never happened) so `-tags release` builds of both `game/debug` and `game/mcp` compile cleanly.

## Alternatives considered

### Parsing `Console.Exec("list")` and `Console.Exec("help")` inside `game/mcp`

Building the MCP tools solely on `debug.Console.Exec` would avoid adding methods to `packages/game/debug`. It was rejected because `Exec("list")` and `Exec("help")` mutate interactive console history and output logs on every read, conflate built-in and custom commands in formatted text, omit registration defaults, and couple `game/mcp` to human-readable string formatting.

### Returning MCP handler errors when `Console.Exec` returns an error

Propagating command errors from `game_console_exec` directly as Go `error` values would match `game_tunable_set`. It was rejected because console commands are interactive shell-like operations whose result payload explicitly carries `{ok, output, lines, error}` so agents can distinguish valid console execution failures (unknown command, bad command arguments) from MCP call errors (missing console, invalid tool schema) while still inspecting any captured output.

### Silently clamping out-of-range values in `game_tunable_set` by default

Always clamping numeric writes to `[min, max]` would prevent range errors during automated tuning sweeps. It was rejected because `debug.Console.Exec("set ...")` and `Console.LoadTunables` strictly refuse out-of-range values without mutating variables; preserving strict validation by default and offering opt-in `"clamp": true` with `"clamped": true` in the response keeps behavior consistent while still supporting clamping when desired.

## Consequences

- **Benefits**: Agents can discover registered tunables and commands, change live physics/gameplay parameters with immediate observable effects, and run custom debug commands with structured output and clear errors. `debug.Console` also gains string tunables and structured inspection APIs usable outside MCP.
- **Costs**: `packages/game/debug` adds five exported methods (`RegisterString`, `Tunables`, `Tunable`, `SetTunable`, `Commands`) and three structs (`TunableInfo`, `TunableChange`, `CommandInfo`) that must stay synchronized between `console.go` and `console_release.go`.

## 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 ./debug`, `go tool nsgo test -tags release ./debug`, `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-tunables-console-466.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Added

- `game/mcp`: add tunables and debug console MCP tools (`game_tunables_list`, `game_tunable_get`, `game_tunable_set`, `game_console_commands_list`, `game_console_exec`) configured via `Config.Console`, `Config.ConsoleFunc` and `Bridge.SetConsole` (#466).
- `game/debug`: add `Console.RegisterString`, `Console.Tunables`, `Console.Tunable`, `Console.SetTunable` and `Console.Commands` with `TunableInfo`, `TunableChange` and `CommandInfo`; `SaveTunables` and `LoadTunables` persist string tunables (#466).
4 changes: 2 additions & 2 deletions docs/en/formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -1263,10 +1263,10 @@ These formats are JSON: a program writes most of them for itself, and the rest a
| A key in `core.Storage`, `debug.console.tunables` by default | none | `debug.Console.SaveTunables`, `debug.Console.LoadTunables` | An object of each tunable's name and value |

```json
{"cheat.god":false,"player.lives":3,"player.speed":1.5}
{"cheat.god":false,"level.name":"cave_1","player.lives":3,"player.speed":1.5}
```

The names are those the game registered with `RegisterFloat`, `RegisterInt` and `RegisterBool`; `LoadTunables` skips a name nothing registered and refuses a value outside its range.
The names are those the game registered with `RegisterFloat`, `RegisterInt`, `RegisterBool` and `RegisterString`; `LoadTunables` skips a name nothing registered, refuses a value outside its range or of the wrong JSON type, and applies none of the values when it refuses one.

<!-- format: tooling/devstate -->
### Dev session snapshot
Expand Down
27 changes: 25 additions & 2 deletions 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 and fixed-step loop controls 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 and debug console 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 All @@ -27,13 +27,14 @@ bridge, err := mcp.Attach(cx, mcp.Config{
Actions: g.actions,
Viewport: &g.viewport,
ViewSizeFunc: g.currentViewSize,
Console: g.console,
})
if err != nil {
return err
}
```

- When a game replaces its `*scene.Scene`, `*entities.World` or `*game.Loop` across level restarts, supply `SceneFunc` / `WorldFunc` / `LoopFunc` (or call `bridge.SetScene` / `bridge.SetWorld` / `bridge.SetLoop`).
- When a game replaces its `*scene.Scene`, `*entities.World`, `*game.Loop` or `*debug.Console` across level restarts, supply `SceneFunc` / `WorldFunc` / `LoopFunc` / `ConsoleFunc` (or call `bridge.SetScene` / `bridge.SetWorld` / `bridge.SetLoop` / `bridge.SetConsole`).
- To support `game_loop_seed`, configure `Random` (`*random.Stream`), `RandomStreams` (`*random.Streams`) and/or a custom `SetSeed` callback; if none is set, `game_loop_seed` returns an actionable error.
- 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.
Expand Down Expand Up @@ -71,6 +72,11 @@ if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil {
| `game_input_axis` | `name` + `value`, `axes` map (`{name: value}`), and/or `clear` (`bool`) | Sets or clears 1D or multi-axis analog values in `[-1, 1]` on `input.Actions`. |
| `game_input_pointer` | `x`, `y` (required), `action` (`"press"`, `"release"`, `"move"`, `"click"`, default `"click"`), `space` (`"game"` or `"world"`, default `"game"`), `button` (`"left"`, `"right"`, `"middle"`) | Maps coordinates through the active scene's `Camera` (when `space="world"`) and `screen.Viewport` into view space, forwards to `input.Actions`, runs `Scene.HitTest` / `Scene.DispatchPress`, invokes `Config.OnPointer`, and returns both game/view coordinates, `in_viewport`, and hit metadata (`hit`, `hit_layer`, `hit_kind`, `hit_frame`, `hit_batch_index`, `hit_sprite_index`, `hit_drawable_index`, `dispatched`). |
| `game_input_actions_list` | `{}` | Lists configured action and axis names on `input.Actions` with their current step state (`pressed`, `just_pressed`, `just_released`, `binding_count`, `value`, `negative`, `positive`). |
| `game_tunables_list` | `prefix` (optional) | Registered `debug.Console` tunables sorted by name with `type`, current `value`, registration `default`, and numeric `min`/`max` bounds. |
| `game_tunable_get` | `name` (required) | One registered tunable's `name`, `type`, current `value`, registration `default`, and numeric `min`/`max` bounds. |
| `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). |

All tools reject unknown argument fields.

Expand All @@ -89,6 +95,23 @@ When `Actions`, `Viewport` / `ViewportFunc`, `ViewSizeFunc`, or `OnPointer` are
- **Actions and axes**: `game_input_action` drives `Actions.Press`, `Actions.Release`, `Actions.Trigger` and `Actions.SetAxis`; `game_input_axis` sets or clears one or more analog axes in `[-1, 1]`. All injected inputs follow `Actions.Step()` snapshot semantics just like physical inputs, and `Actions.Reset()` clears them cleanly.
- **Pointer coordinate pipeline**: `game_input_pointer` takes `(x, y)` in `"game"` space (virtual canvas points) or `"world"` space (converted to game space through the active scene's `Camera.WorldToView`), then maps game coordinates through `screen.Viewport.GameToView` using `ViewSizeFunc` (falling back to the attached scope's `Env().Window()` and then the viewport's virtual size).
- **Delivery**: Mapped view coordinates are forwarded to `input.Actions` (so `Actions.MapPoint = viewport.ViewToGame` recovers the exact game position for `MouseRegion` bindings). When `in_viewport` is true, `Scene.HitTest` and primary `Scene.DispatchPress` run in game coordinates so pressing at a sprite's position hits that sprite and triggers its `OnPress` callback. `Config.OnPointer` receives every injected `PointerEvent` (a `"click"` emits `PointerPress` followed by `PointerRelease`).

## Tunables and debug console

Pass a [`*debug.Console`](debug.md) via `Config.Console`, `Config.ConsoleFunc`, or `bridge.SetConsole` so agents can inspect and adjust live game variables and run custom debug commands:

```go
console := debug.NewConsole()
console.RegisterFloat("physics.gravity", 0, 2000, &g.gravity)
console.RegisterInt("player.max_jumps", 1, 5, &g.maxJumps)
console.RegisterBool("player.god_mode", &g.godMode)
console.RegisterString("level.name", &g.levelName)
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.
## 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
4 changes: 2 additions & 2 deletions docs/zh/formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -1263,10 +1263,10 @@ entities:
| `core.Storage` 中的一个键,默认为 `debug.console.tunables` | 无 | `debug.Console.SaveTunables`、`debug.Console.LoadTunables` | 以各参数名为键、参数值为值的对象 |

```json
{"cheat.god":false,"player.lives":3,"player.speed":1.5}
{"cheat.god":false,"level.name":"cave_1","player.lives":3,"player.speed":1.5}
```

参数名是游戏用 `RegisterFloat`、`RegisterInt` 和 `RegisterBool` 注册的名称;`LoadTunables` 跳过没有注册的名称,并拒绝超出范围的值。
参数名是游戏用 `RegisterFloat`、`RegisterInt`、`RegisterBool` 和 `RegisterString` 注册的名称;`LoadTunables` 跳过没有注册的名称,拒绝超出范围或 JSON 类型不符的值,且只要拒绝其中一个值,就一个值也不应用。

<!-- format: tooling/devstate -->
### 开发会话快照
Expand Down
Loading
Loading