From f8f615f0a1ea44911e8074c5c66dd7d2b8e02557 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Tue, 24 Nov 2026 18:36:17 +0900 Subject: [PATCH 1/4] feat(mcp): add tunables and debug console tools (#466) --- .../2026-11-24-mcp-tunables-and-console.md | 42 ++ changelog.d/mcp-tunables-console-466.md | 4 + docs/en/mcp.md | 27 +- docs/zh/mcp.md | 27 +- packages/game/debug/console.go | 319 +++++++++- packages/game/debug/console_release.go | 15 + packages/game/debug/console_test.go | 102 +++- packages/game/debug/debug_release_test.go | 11 + packages/game/debug/types.go | 26 + packages/game/mcp/console.go | 543 ++++++++++++++++++ packages/game/mcp/console_test.go | 507 ++++++++++++++++ packages/game/mcp/doc.go | 5 + packages/game/mcp/example_test.go | 5 + packages/game/mcp/mcp.go | 16 + 14 files changed, 1618 insertions(+), 31 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-24-mcp-tunables-and-console.md create mode 100644 changelog.d/mcp-tunables-console-466.md create mode 100644 packages/game/mcp/console.go create mode 100644 packages/game/mcp/console_test.go diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-tunables-and-console.md b/.agents/notes/implemented/feature/2026-11-24-mcp-tunables-and-console.md new file mode 100644 index 00000000..3ebfd1f5 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-tunables-and-console.md @@ -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` and `CommandInfo` in `debug/types.go` with release-build no-op 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]` and reports `"clamped": true`. 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` and `CommandInfo` live in untagged `debug/types.go`, and `debug/console_release.go` provides matching zero-cost no-op stubs 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 two structs (`TunableInfo`, `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`. diff --git a/changelog.d/mcp-tunables-console-466.md b/changelog.d/mcp-tunables-console-466.md new file mode 100644 index 00000000..af582ffc --- /dev/null +++ b/changelog.d/mcp-tunables-console-466.md @@ -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` and `CommandInfo` (#466). diff --git a/docs/en/mcp.md b/docs/en/mcp.md index 93c28fda..c8b9fa85 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -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. @@ -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. @@ -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. @@ -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 [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::"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`: diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 9bce6886..5a12ad2c 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -1,6 +1,6 @@ # mcp -`game/mcp` 通过 NSGo 的 `github.com/nsgo-dev/nsgo/automation` 包,把运行中游戏的场景、图层、实体、组件以及固定步长主循环控制暴露给 MCP 智能体。 +`game/mcp` 通过 NSGo 的 `github.com/nsgo-dev/nsgo/automation` 包,把运行中游戏的场景、图层、实体、组件、固定步长主循环控制、游戏坐标输入注入、可调参数与调试控制台暴露给 MCP 智能体。 NSGo 内置的 `nsgo mcp` 服务器只能看到原生视图,而游戏通常绘制在单个 `Canvas` 或 GPU 视图中。把 `mcp.Bridge` 挂载到 `core.Scope` 上后,它会通过 `automation.Register` 在引擎响应式图上注册游戏专用工具;当应用在 `go tool nsgo dev -automation` 或 `go tool nsgo test` 下运行时,`nsgo mcp` 会自动将这些工具与内置工具一并提供。在普通构建与发布构建中,`automation.Register` 为空操作,不会引入运行时协议开销。 @@ -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 } ``` -- 如果游戏在重开关卡时会替换 `*scene.Scene`、`*entities.World` 或 `*game.Loop`,可以提供 `SceneFunc` / `WorldFunc` / `LoopFunc`(或调用 `bridge.SetScene` / `bridge.SetWorld` / `bridge.SetLoop`)。 +- 如果游戏在重开关卡时会替换 `*scene.Scene`、`*entities.World`、`*game.Loop` 或 `*debug.Console`,可以提供 `SceneFunc` / `WorldFunc` / `LoopFunc` / `ConsoleFunc`(或调用 `bridge.SetScene` / `bridge.SetWorld` / `bridge.SetLoop` / `bridge.SetConsole`)。 - 若要启用 `game_loop_seed`,可配置 `Random`(`*random.Stream`)、`RandomStreams`(`*random.Streams`)和/或自定义 `SetSeed` 回调;若都未配置,调用 `game_loop_seed` 会返回明确的可操作错误。 - 如果 `scene.Manager` 的控制器通过自定义 `Controller.Draw` 绘制而没有设置 `Controller.Scene`,`SceneFunc` / `Scene` 会自动作为当前场景的图层来源。 - 未提供 `EntityName` 或 `EntityLayer`(或其返回 `""`)时,若实体带有 [`sceneformat.ObjectRef`](editor.md),`game/mcp` 会自动回退到其中的 `ID` 和 `Layer`。 @@ -71,6 +72,11 @@ if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil { | `game_input_axis` | `name` + `value`、`axes` 映射(`{name: value}`)和/或 `clear`(`bool`) | 在 `input.Actions` 上设置或清除单个或多个 `[-1, 1]` 模拟量轴值。 | | `game_input_pointer` | `x`、`y`(必填)、`action`(`"press"`、`"release"`、`"move"`、`"click"`,默认 `"click"`)、`space`(`"game"` 或 `"world"`,默认 `"game"`)、`button`(`"left"`、`"right"`、`"middle"`) | 将坐标经当前场景 `Camera`(当 `space="world"`)和 `screen.Viewport` 映射到视图坐标,转发到 `input.Actions`,执行 `Scene.HitTest` / `Scene.DispatchPress`,调用 `Config.OnPointer`,并返回游戏/视图坐标、`in_viewport` 与命中信息(`hit`、`hit_layer`、`hit_kind`、`hit_frame`、`hit_batch_index`、`hit_sprite_index`、`hit_drawable_index`、`dispatched`)。 | | `game_input_actions_list` | `{}` | 列出 `input.Actions` 上已配置的动作和轴名称及其当前步状态(`pressed`、`just_pressed`、`just_released`、`binding_count`、`value`、`negative`、`positive`)。 | +| `game_tunables_list` | `prefix`(可选) | 按名称排序的已注册 `debug.Console` 可调参数列表,包含 `type`、当前 `value`、注册时的 `default` 以及数值型的 `min`/`max` 范围。 | +| `game_tunable_get` | `name`(必填) | 单个已注册可调参数的 `name`、`type`、当前 `value`、注册时的 `default` 以及数值型的 `min`/`max` 范围。 | +| `game_tunable_set` | `name`(必填)、`value`(必填)、`clamp`(可选,默认 `false`) | 按严格类型检查与范围校验(或 `clamp: true` 时钳位)更新已注册的可调参数(`float`、`int`、`bool` 或 `string`),返回 `old_value`、生效后的 `value`、元数据与 `clamped` 标记。 | +| `game_console_commands_list` | `include_builtin`(可选,默认 `true`) | 按名称排序的 `debug.Console` 内置命令与自定义命令列表,包含 `help` 说明与 `builtin` 标记。 | +| `game_console_exec` | `command`(必填) | 通过 `debug.Console` 执行一条命令行,返回 `command`、`ok`、`output`、`lines` 以及命令失败时的 `error`。 | 所有工具都会拒绝未知的参数字段。 @@ -89,6 +95,23 @@ if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil { - **动作与轴注入**:`game_input_action` 驱动 `Actions.Press`、`Actions.Release`、`Actions.Trigger` 和 `Actions.SetAxis`;`game_input_axis` 一次设置或清除一个或多个 `[-1, 1]` 模拟量轴。所有注入输入与物理输入一样遵循 `Actions.Step()` 步快照语义,并会在 `Actions.Reset()` 时一并清除。 - **指针坐标管线**:`game_input_pointer` 接收 `"game"` 空间(虚拟画布坐标)或 `"world"` 空间(经当前场景 `Camera.WorldToView` 转换到游戏空间)的 `(x, y)`,随后结合 `ViewSizeFunc`(回退到挂载作用域的 `Env().Window()`,再回退到视口虚拟尺寸)通过 `screen.Viewport.GameToView` 映射到视图坐标。 - **事件派发**:映射后的视图坐标会转发到 `input.Actions`(因此 `Actions.MapPoint = viewport.ViewToGame` 会准确还原游戏坐标并触发 `MouseRegion` 绑定)。当 `in_viewport` 为真时,会在游戏坐标下执行 `Scene.HitTest` 与主按钮 `Scene.DispatchPress`,确保在精灵游戏位置按下即可命中该精灵并触发其 `OnPress` 回调;`Config.OnPointer` 会收到每次注入的 `PointerEvent`(`"click"` 依次派发 `PointerPress` 和 `PointerRelease`)。 + +## 可调参数与调试控制台 + +通过 `Config.Console`、`Config.ConsoleFunc` 或 `bridge.SetConsole` 传入 [`*debug.Console`](debug.md),即可让智能体检查和调整运行中的游戏参数并执行自定义调试命令: + +```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 [count]", g.handleSpawn) +``` + +- `game_tunables_list` 与 `game_tunable_get` 直接读取实时值,不会向控制台交互历史或输出日志中写入多余记录。 +- `game_tunable_set` 默认严格校验参数注册类型(`float`、`int`、`bool` 或 `string`)及数值 `[min, max]` 范围,校验失败时不修改变量。传入 `"clamp": true` 时会将越界数值钳位到 `[min, max]` 并在响应中标记 `"clamped": true`。 +- `game_console_exec` 通过 `debug.Console.Exec` 运行内置命令(`help`、`list`、`get`、`set`、`clear`)与游戏自定义命令,返回 `{command, ok, output, lines, error}`。无效的 MCP 参数或未配置 `Console` 会返回工具级错误;命令本身的执行失败(例如未知命令名或参数无效)则返回 `ok: false` 与对应的 `error` 信息。 ## 稳定的实体引用 每个存活实体都会获得一个格式为 `"entity::"`(例如 `"entity:0:1"`)的代数引用,由 `FormatEntityRef` 格式化并由 `ParseEntityRef` 解析: diff --git a/packages/game/debug/console.go b/packages/game/debug/console.go index 7cb029cc..6ed57713 100644 --- a/packages/game/debug/console.go +++ b/packages/game/debug/console.go @@ -3,6 +3,8 @@ package debug import ( + "bytes" + "cmp" "encoding/json" "errors" "fmt" @@ -34,18 +36,63 @@ const ( tunableFloat tunableKind = iota tunableInt tunableBool + tunableString ) type consoleTunable struct { - name string - kind tunableKind - minFloat float64 - maxFloat float64 - floatPtr *float64 - minInt int - maxInt int - intPtr *int - boolPtr *bool + name string + kind tunableKind + minFloat float64 + maxFloat float64 + defaultFloat float64 + floatPtr *float64 + minInt int + maxInt int + defaultInt int + intPtr *int + defaultBool bool + boolPtr *bool + defaultString string + stringPtr *string +} + +func (t *consoleTunable) info() TunableInfo { + switch t.kind { + case tunableFloat: + return TunableInfo{ + Name: t.name, + Type: "float", + Value: *t.floatPtr, + Default: t.defaultFloat, + Min: t.minFloat, + Max: t.maxFloat, + } + case tunableInt: + return TunableInfo{ + Name: t.name, + Type: "int", + Value: *t.intPtr, + Default: t.defaultInt, + Min: t.minInt, + Max: t.maxInt, + } + case tunableBool: + return TunableInfo{ + Name: t.name, + Type: "bool", + Value: *t.boolPtr, + Default: t.defaultBool, + } + case tunableString: + return TunableInfo{ + Name: t.name, + Type: "string", + Value: *t.stringPtr, + Default: t.defaultString, + } + default: + return TunableInfo{Name: t.name} + } } func (t *consoleTunable) formatValue() string { @@ -56,6 +103,8 @@ func (t *consoleTunable) formatValue() string { return strconv.Itoa(*t.intPtr) case tunableBool: return strconv.FormatBool(*t.boolPtr) + case tunableString: + return *t.stringPtr default: return "" } @@ -69,6 +118,8 @@ func (t *consoleTunable) formatRange() string { return fmt.Sprintf("[%d, %d]", t.minInt, t.maxInt) case tunableBool: return "[true|false]" + case tunableString: + return "[string]" default: return "" } @@ -103,11 +154,120 @@ func (t *consoleTunable) setString(raw string) error { } *t.boolPtr = v return nil + case tunableString: + *t.stringPtr = raw + return nil default: return fmt.Errorf("unsupported tunable %q", t.name) } } +func (t *consoleTunable) setValue(value any) (oldVal, newVal any, err error) { + switch t.kind { + case tunableFloat: + var v float64 + switch x := value.(type) { + case float64: + v = x + case float32: + v = float64(x) + case int: + v = float64(x) + case int8: + v = float64(x) + case int16: + v = float64(x) + case int32: + v = float64(x) + case int64: + v = float64(x) + case uint: + v = float64(x) + case uint8: + v = float64(x) + case uint16: + v = float64(x) + case uint32: + v = float64(x) + case uint64: + v = float64(x) + default: + return nil, nil, fmt.Errorf("invalid float value %T for %q", value, t.name) + } + if math.IsNaN(v) || math.IsInf(v, 0) { + return nil, nil, fmt.Errorf("invalid float %v for %q", v, t.name) + } + if v < t.minFloat || v > t.maxFloat { + return nil, nil, fmt.Errorf("%q value %g out of range [%g, %g]", t.name, v, t.minFloat, t.maxFloat) + } + old := *t.floatPtr + *t.floatPtr = v + return old, v, nil + case tunableInt: + var v int + switch x := value.(type) { + case int: + v = x + case int8: + v = int(x) + case int16: + v = int(x) + case int32: + v = int(x) + case int64: + if x < math.MinInt || x > math.MaxInt { + return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, x, t.minInt, t.maxInt) + } + v = int(x) + case uint: + if uint64(x) > math.MaxInt { + return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, x, t.minInt, t.maxInt) + } + v = int(x) + case uint8: + v = int(x) + case uint16: + v = int(x) + case uint32: + if uint64(x) > math.MaxInt { + return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, x, t.minInt, t.maxInt) + } + v = int(x) + case uint64: + if x > math.MaxInt { + return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, x, t.minInt, t.maxInt) + } + v = int(x) + default: + return nil, nil, fmt.Errorf("invalid int value %T for %q", value, t.name) + } + if v < t.minInt || v > t.maxInt { + return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, v, t.minInt, t.maxInt) + } + old := *t.intPtr + *t.intPtr = v + return old, v, nil + case tunableBool: + v, ok := value.(bool) + if !ok { + return nil, nil, fmt.Errorf("invalid bool value %T for %q", value, t.name) + } + old := *t.boolPtr + *t.boolPtr = v + return old, v, nil + case tunableString: + v, ok := value.(string) + if !ok { + return nil, nil, fmt.Errorf("invalid string value %T for %q", value, t.name) + } + old := *t.stringPtr + *t.stringPtr = v + return old, v, nil + default: + return nil, nil, fmt.Errorf("unsupported tunable %q", t.name) + } +} + func parseConsoleBool(s string) (bool, error) { switch strings.ToLower(strings.TrimSpace(s)) { case "1", "t", "true", "on", "yes": @@ -181,11 +341,12 @@ func (c *Console) RegisterFloat(name string, minVal, maxVal float64, ptr *float6 } c.mu.Lock() c.tunables[name] = &consoleTunable{ - name: name, - kind: tunableFloat, - minFloat: minVal, - maxFloat: maxVal, - floatPtr: ptr, + name: name, + kind: tunableFloat, + minFloat: minVal, + maxFloat: maxVal, + defaultFloat: *ptr, + floatPtr: ptr, } c.mu.Unlock() } @@ -204,11 +365,12 @@ func (c *Console) RegisterInt(name string, minVal, maxVal int, ptr *int) { } c.mu.Lock() c.tunables[name] = &consoleTunable{ - name: name, - kind: tunableInt, - minInt: minVal, - maxInt: maxVal, - intPtr: ptr, + name: name, + kind: tunableInt, + minInt: minVal, + maxInt: maxVal, + defaultInt: *ptr, + intPtr: ptr, } c.mu.Unlock() } @@ -224,13 +386,115 @@ func (c *Console) RegisterBool(name string, ptr *bool) { } c.mu.Lock() c.tunables[name] = &consoleTunable{ - name: name, - kind: tunableBool, - boolPtr: ptr, + name: name, + kind: tunableBool, + defaultBool: *ptr, + boolPtr: ptr, } c.mu.Unlock() } +// RegisterString registers a string tunable bound to ptr. +func (c *Console) RegisterString(name string, ptr *string) { + if c == nil || ptr == nil { + return + } + name = strings.TrimSpace(name) + if name == "" { + return + } + c.mu.Lock() + c.tunables[name] = &consoleTunable{ + name: name, + kind: tunableString, + defaultString: *ptr, + stringPtr: ptr, + } + c.mu.Unlock() +} + +// Tunables returns a snapshot of all registered tunables sorted by name. +func (c *Console) Tunables() []TunableInfo { + if c == nil { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + if len(c.tunables) == 0 { + return nil + } + out := make([]TunableInfo, 0, len(c.tunables)) + for _, t := range c.tunables { + out = append(out, t.info()) + } + slices.SortFunc(out, func(a, b TunableInfo) int { + return cmp.Compare(a.Name, b.Name) + }) + return out +} + +// Tunable returns a snapshot of the named tunable and reports whether it is registered. +func (c *Console) Tunable(name string) (TunableInfo, bool) { + if c == nil { + return TunableInfo{}, false + } + c.mu.Lock() + defer c.mu.Unlock() + t, ok := c.tunables[name] + if !ok { + return TunableInfo{}, false + } + return t.info(), true +} + +// SetTunable updates the named tunable to value after checking its type and numeric range. +// On success it returns the previous and new values; on failure the tunable is left unchanged. +func (c *Console) SetTunable(name string, value any) (oldVal, newVal any, err error) { + if c == nil { + return nil, nil, errors.New("debug: nil console") + } + c.mu.Lock() + defer c.mu.Unlock() + t, ok := c.tunables[name] + if !ok { + return nil, nil, fmt.Errorf("unknown tunable %q", name) + } + return t.setValue(value) +} + +// Commands returns all built-in and registered console commands sorted by name. +func (c *Console) Commands() []CommandInfo { + if c == nil { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + seen := make(map[string]struct{}, len(builtinHelp)+len(c.commands)) + out := make([]CommandInfo, 0, len(builtinHelp)+len(c.commands)) + for _, b := range builtinHelp { + seen[b.name] = struct{}{} + out = append(out, CommandInfo{ + Name: b.name, + Help: b.help, + Builtin: true, + }) + } + for _, cmd := range c.commands { + if _, dup := seen[cmd.name]; dup { + continue + } + out = append(out, CommandInfo{ + Name: cmd.name, + Help: cmd.help, + Builtin: false, + }) + } + slices.SortFunc(out, func(a, b CommandInfo) int { + return cmp.Compare(a.Name, b.Name) + }) + return out +} + // Exec parses and executes one command line, updating history and output entries. func (c *Console) Exec(line string) (string, error) { if c == nil { @@ -529,6 +793,8 @@ func (c *Console) SaveTunables(st core.Storage, key string) error { payload[name] = *t.intPtr case tunableBool: payload[name] = *t.boolPtr + case tunableString: + payload[name] = *t.stringPtr } } c.mu.Unlock() @@ -573,6 +839,7 @@ func (c *Console) LoadTunables(st core.Storage, key string) error { f float64 i int b bool + s string } names := make([]string, 0, len(parsed)) for name := range parsed { @@ -612,6 +879,12 @@ func (c *Console) LoadTunables(st core.Storage, key string) error { return bad(name, "store true or false", "invalid stored bool for %q", name) } updates = append(updates, pendingUpdate{t: t, b: v}) + case tunableString: + var v string + if bytes.Equal(bytes.TrimSpace(rawVal), []byte("null")) || json.Unmarshal(rawVal, &v) != nil { + return bad(name, "store a string", "invalid stored string for %q", name) + } + updates = append(updates, pendingUpdate{t: t, s: v}) } } @@ -623,6 +896,8 @@ func (c *Console) LoadTunables(st core.Storage, key string) error { *u.t.intPtr = u.i case tunableBool: *u.t.boolPtr = u.b + case tunableString: + *u.t.stringPtr = u.s } } return nil diff --git a/packages/game/debug/console_release.go b/packages/game/debug/console_release.go index 6b3daf26..d877931c 100644 --- a/packages/game/debug/console_release.go +++ b/packages/game/debug/console_release.go @@ -24,6 +24,21 @@ func (*Console) RegisterInt(string, int, int, *int) {} // RegisterBool is a no-op in release builds. func (*Console) RegisterBool(string, *bool) {} +// RegisterString is a no-op in release builds. +func (*Console) RegisterString(string, *string) {} + +// Tunables always returns nil in release builds. +func (*Console) Tunables() []TunableInfo { return nil } + +// Tunable always reports not found in release builds. +func (*Console) Tunable(string) (TunableInfo, bool) { return TunableInfo{}, false } + +// SetTunable is a no-op in release builds. +func (*Console) SetTunable(string, any) (any, any, error) { return nil, nil, nil } + +// Commands always returns nil in release builds. +func (*Console) Commands() []CommandInfo { return nil } + // Exec is a no-op in release builds. func (*Console) Exec(string) (string, error) { return "", nil } diff --git a/packages/game/debug/console_test.go b/packages/game/debug/console_test.go index 453f77c8..37a4c828 100644 --- a/packages/game/debug/console_test.go +++ b/packages/game/debug/console_test.go @@ -209,13 +209,16 @@ func TestConsoleStoragePersistence(t *testing.T) { g1 := 9.8 n1 := 5 b1 := false + s1 := "start" c1.RegisterFloat("gravity", 0, 100, &g1) c1.RegisterInt("lives", 1, 99, &n1) c1.RegisterBool("debug_ai", &b1) + c1.RegisterString("level", &s1) _, _ = c1.Exec("set gravity 33.25") _, _ = c1.Exec("set lives 12") _, _ = c1.Exec("set debug_ai true") + _, _ = c1.Exec(`set level "boss room"`) if err := c1.SaveTunables(st, "dev.tunables"); err != nil { t.Fatalf("SaveTunables error = %v", err) @@ -226,15 +229,17 @@ func TestConsoleStoragePersistence(t *testing.T) { g2 := 1.0 n2 := 1 b2 := false + s2 := "initial" c2.RegisterFloat("gravity", 0, 100, &g2) c2.RegisterInt("lives", 1, 99, &n2) c2.RegisterBool("debug_ai", &b2) + c2.RegisterString("level", &s2) if err := c2.LoadTunables(st, "dev.tunables"); err != nil { t.Fatalf("LoadTunables error = %v", err) } - if g2 != 33.25 || n2 != 12 || !b2 { - t.Fatalf("restored tunables = (%v, %d, %v), want (33.25, 12, true)", g2, n2, b2) + if g2 != 33.25 || n2 != 12 || !b2 || s2 != "boss room" { + t.Fatalf("restored tunables = (%v, %d, %v, %q), want (33.25, 12, true, %q)", g2, n2, b2, s2, "boss room") } // Missing key is a clean no-op. @@ -242,15 +247,21 @@ func TestConsoleStoragePersistence(t *testing.T) { t.Fatalf("LoadTunables(missing) error = %v", err) } - // Out-of-range persisted value fails without mutating current values. + // Out-of-range or null persisted values fail without mutating current values. if err := st.SetItem("dev.bad", `{"gravity": 999}`); err != nil { t.Fatalf("SetItem error = %v", err) } if err := c2.LoadTunables(st, "dev.bad"); err == nil { t.Fatal("LoadTunables(out-of-range) succeeded, want error") } - if g2 != 33.25 { - t.Fatalf("gravity mutated to %v after rejected LoadTunables", g2) + if err := st.SetItem("dev.badstr", `{"level": null}`); err != nil { + t.Fatalf("SetItem error = %v", err) + } + if err := c2.LoadTunables(st, "dev.badstr"); err == nil { + t.Fatal("LoadTunables(null string) succeeded, want error") + } + if g2 != 33.25 || s2 != "boss room" { + t.Fatalf("tunables mutated after rejected LoadTunables: gravity=%v level=%q", g2, s2) } } @@ -312,3 +323,84 @@ func TestConsoleViewInteractionAndOverlayComposition(t *testing.T) { t.Fatalf("console output %v missing unknown command error", app.Texts()) } } + +func TestConsoleStructuredInspectionAndStringTunable(t *testing.T) { + c := debug.NewConsole() + gravity := 9.8 + lives := 3 + god := false + level := "cave_1" + + c.RegisterFloat("gravity", 0, 50, &gravity) + c.RegisterInt("lives", 1, 99, &lives) + c.RegisterBool("god", &god) + c.RegisterString("level", &level) + c.RegisterCommand("spawn", "spawn [count]", func(args []string) (string, error) { + return "spawned", nil + }) + // Custom command with the same name as a built-in must not shadow built-in in Commands(). + c.RegisterCommand("help", "shadowed", func(args []string) (string, error) { + return "nope", nil + }) + + tunables := c.Tunables() + if len(tunables) != 4 { + t.Fatalf("len(Tunables) = %d, want 4", len(tunables)) + } + wantNames := []string{"god", "gravity", "level", "lives"} + for i, want := range wantNames { + if tunables[i].Name != want { + t.Fatalf("tunables[%d].Name = %q, want %q", i, tunables[i].Name, want) + } + } + + oldV, newV, err := c.SetTunable("gravity", 20.5) + if err != nil || oldV != 9.8 || newV != 20.5 || gravity != 20.5 { + t.Fatalf("SetTunable(gravity) = (%v, %v, %v), gravity=%v", oldV, newV, err, gravity) + } + if info, ok := c.Tunable("gravity"); !ok || info.Value != 20.5 || info.Default != 9.8 || info.Min != 0.0 || info.Max != 50.0 { + t.Fatalf("Tunable(gravity) = (%+v, %v)", info, ok) + } + oldS, newS, err := c.SetTunable("level", "cave_2") + if err != nil || oldS != "cave_1" || newS != "cave_2" || level != "cave_2" { + t.Fatalf("SetTunable(level) = (%v, %v, %v), level=%q", oldS, newS, err, level) + } + if out, err := c.Exec(`set level "boss room"`); err != nil || out != "level = boss room" || level != "boss room" { + t.Fatalf("Exec(set level) = (%q, %v), level=%q", out, err, level) + } + + // Range and type rejections leave variables untouched. + if _, _, err := c.SetTunable("gravity", 99.0); err == nil || gravity != 20.5 { + t.Fatalf("out-of-range SetTunable(gravity) = %v, gravity=%v", err, gravity) + } + if _, _, err := c.SetTunable("lives", "10"); err == nil || lives != 3 { + t.Fatalf("wrong-type SetTunable(lives) = %v, lives=%d", err, lives) + } + if _, _, err := c.SetTunable("god", 1); err == nil || god != false { + t.Fatalf("wrong-type SetTunable(god) = %v, god=%v", err, god) + } + if _, _, err := c.SetTunable("level", 42); err == nil || level != "boss room" { + t.Fatalf("wrong-type SetTunable(level) = %v, level=%q", err, level) + } + if _, _, err := c.SetTunable("missing", 1); err == nil { + t.Fatal("SetTunable(missing) succeeded, want error") + } + + // Commands() returns sorted built-ins + custom commands without duplicates. + cmds := c.Commands() + wantCmds := []string{"clear", "get", "help", "list", "set", "spawn"} + if len(cmds) != len(wantCmds) { + t.Fatalf("len(Commands) = %d (%+v), want %d", len(cmds), cmds, len(wantCmds)) + } + for i, want := range wantCmds { + if cmds[i].Name != want { + t.Fatalf("cmds[%d] = %+v, want %q", i, cmds[i], want) + } + if want == "spawn" && cmds[i].Builtin { + t.Fatalf("spawn marked builtin: %+v", cmds[i]) + } + if want != "spawn" && !cmds[i].Builtin { + t.Fatalf("%q not marked builtin: %+v", want, cmds[i]) + } + } +} diff --git a/packages/game/debug/debug_release_test.go b/packages/game/debug/debug_release_test.go index c255b921..ff7ca0ad 100644 --- a/packages/game/debug/debug_release_test.go +++ b/packages/game/debug/debug_release_test.go @@ -135,6 +135,7 @@ func TestReleaseBuildIsDisabledZeroCostStub(t *testing.T) { vFloat := 1.5 vInt := 3 vBool := true + vStr := "hello" c.RegisterCommand("cmd", "help", func([]string) (string, error) { t.Error("console command invoked in release build") return "bad", nil @@ -142,9 +143,19 @@ func TestReleaseBuildIsDisabledZeroCostStub(t *testing.T) { c.RegisterFloat("f", 0, 10, &vFloat) c.RegisterInt("i", 0, 10, &vInt) c.RegisterBool("b", &vBool) + c.RegisterString("s", &vStr) if out, err := c.Exec("set f 9"); out != "" || err != nil || vFloat != 1.5 { t.Fatalf("Console.Exec in release = (%q, %v), vFloat=%v", out, err, vFloat) } + if len(c.Tunables()) != 0 || len(c.Commands()) != 0 { + t.Fatal("Console Tunables/Commands returned data in release build") + } + if _, ok := c.Tunable("f"); ok { + t.Fatal("Console.Tunable returned true in release build") + } + if oldV, newV, err := c.SetTunable("f", 2.0); oldV != nil || newV != nil || err != nil || vFloat != 1.5 { + t.Fatalf("Console.SetTunable in release = (%v, %v, %v), vFloat=%v", oldV, newV, err, vFloat) + } if len(c.History()) != 0 || c.HistoryPrev() != "" || c.HistoryNext() != "" || len(c.Entries()) != 0 || len(c.Complete("s")) != 0 { t.Fatal("Console history/entries/complete returned data in release build") } diff --git a/packages/game/debug/types.go b/packages/game/debug/types.go index 920fb3b3..03136050 100644 --- a/packages/game/debug/types.go +++ b/packages/game/debug/types.go @@ -69,6 +69,32 @@ type ConsoleEntry struct { IsError bool } +// TunableInfo describes one registered tunable variable on a Console. +type TunableInfo struct { + // Name is the tunable's registered name. + Name string + // Type is "float", "int", "bool" or "string". + Type string + // Value is the tunable's current value (float64, int, bool or string). + Value any + // Default is the value captured when the tunable was registered. + Default any + // Min is the inclusive lower bound for numeric tunables ("float" or "int"), or nil for other types. + Min any + // Max is the inclusive upper bound for numeric tunables ("float" or "int"), or nil for other types. + Max any +} + +// CommandInfo describes one command available on a Console. +type CommandInfo struct { + // Name is the command name as typed on the console. + Name string + // Help is the command's usage or description text. + Help string + // Builtin reports whether the command is built into Console. + Builtin bool +} + // ScopeSummary summarizes a named timing scope's cost for overlay display. type ScopeSummary struct { // Name is the scope identifier passed to Begin or Scope. diff --git a/packages/game/mcp/console.go b/packages/game/mcp/console.go new file mode 100644 index 00000000..51097f8c --- /dev/null +++ b/packages/game/mcp/console.go @@ -0,0 +1,543 @@ +package mcp + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "math" + "math/big" + "strings" + + "github.com/nsgo-dev/game/packages/game/debug" + "github.com/nsgo-dev/nsgo/automation" +) + +// Tool names for debug console and tunable tools registered by Bridge. +const ( + // ToolTunablesList lists registered tunables on the debug console with values, defaults and bounds. + ToolTunablesList = "game_tunables_list" + // ToolTunableGet reads one registered tunable's current value and metadata by name. + ToolTunableGet = "game_tunable_get" + // ToolTunableSet updates one registered tunable's value with type and range checking. + ToolTunableSet = "game_tunable_set" + // ToolConsoleCommandsList lists built-in and custom commands registered on the debug console. + ToolConsoleCommandsList = "game_console_commands_list" + // ToolConsoleExec runs a command string through the debug console and returns its output. + ToolConsoleExec = "game_console_exec" +) + +// TunableInfo describes one registered tunable variable returned by game_tunables_list and game_tunable_get. +type TunableInfo struct { + Name string `json:"name"` + Type string `json:"type"` + Value any `json:"value"` + Default any `json:"default"` + Min any `json:"min,omitempty"` + Max any `json:"max,omitempty"` +} + +// TunablesListResult is the JSON result of game_tunables_list. +type TunablesListResult struct { + Total int `json:"total"` + Tunables []TunableInfo `json:"tunables"` +} + +// TunableSetResult is the JSON result of game_tunable_set. +type TunableSetResult struct { + Name string `json:"name"` + Type string `json:"type"` + OldValue any `json:"old_value"` + Value any `json:"value"` + Default any `json:"default"` + Min any `json:"min,omitempty"` + Max any `json:"max,omitempty"` + Clamped bool `json:"clamped,omitempty"` +} + +// ConsoleCommandInfo describes one debug console command returned by game_console_commands_list. +type ConsoleCommandInfo struct { + Name string `json:"name"` + Help string `json:"help,omitempty"` + Builtin bool `json:"builtin"` +} + +// ConsoleCommandsListResult is the JSON result of game_console_commands_list. +type ConsoleCommandsListResult struct { + Total int `json:"total"` + Commands []ConsoleCommandInfo `json:"commands"` +} + +// ConsoleExecResult is the JSON result of game_console_exec. +type ConsoleExecResult struct { + Command string `json:"command"` + OK bool `json:"ok"` + Output string `json:"output"` + Lines []string `json:"lines"` + Error string `json:"error,omitempty"` +} + +var ( + schemaTunablesList = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "prefix": { + "type": "string", + "description": "Filter tunables to those whose name starts with this prefix." + } + } + }`) + + schemaTunableGet = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "name": { + "type": "string", + "description": "Registered tunable name returned by game_tunables_list." + } + } + }`) + + schemaTunableSet = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "required": ["name", "value"], + "properties": { + "name": { + "type": "string", + "description": "Registered tunable name returned by game_tunables_list." + }, + "value": { + "description": "New value matching the tunable's type (number for float/int, boolean for bool, string for string)." + }, + "clamp": { + "type": "boolean", + "description": "Clamp out-of-range numeric values to [min, max] instead of returning an error (default false)." + } + } + }`) + + schemaConsoleCommandsList = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "include_builtin": { + "type": "boolean", + "description": "Include built-in console commands (clear, get, help, list, set) alongside game-registered commands (default true)." + } + } + }`) + + schemaConsoleExec = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "required": ["command"], + "properties": { + "command": { + "type": "string", + "description": "Console command line to run (for example \"set gravity 1200\" or \"spawn enemy 3\")." + } + } + }`) +) + +func (b *Bridge) consoleTools() []automation.Tool { + return []automation.Tool{ + { + Name: ToolTunablesList, + Description: "List registered debug console tunables sorted by name, including type, current value, registration default and numeric bounds.", + InputSchema: schemaTunablesList, + Handler: b.handleTunablesList, + }, + { + Name: ToolTunableGet, + Description: "Read one registered debug console tunable's current value, type, default and numeric bounds by name.", + InputSchema: schemaTunableGet, + Handler: b.handleTunableGet, + }, + { + Name: ToolTunableSet, + Description: "Set one registered debug console tunable's value with strict type checking and range validation (or optional clamping), returning both old and new values.", + InputSchema: schemaTunableSet, + Handler: b.handleTunableSet, + }, + { + Name: ToolConsoleCommandsList, + Description: "List built-in and custom commands registered on the debug console with their usage descriptions.", + InputSchema: schemaConsoleCommandsList, + Handler: b.handleConsoleCommandsList, + }, + { + Name: ToolConsoleExec, + Description: "Execute a command line on the debug console and return structured execution status, output text, output lines and any command error.", + InputSchema: schemaConsoleExec, + Handler: b.handleConsoleExec, + }, + } +} + +func (b *Bridge) activeConsole() *debug.Console { + if b == nil { + return nil + } + if b.cfg.ConsoleFunc != nil { + if c := b.cfg.ConsoleFunc(); c != nil { + return c + } + } + return b.cfg.Console +} + +func (b *Bridge) requireConsole() (*debug.Console, error) { + c := b.activeConsole() + if c == nil { + return nil, errors.New("mcp: no debug console configured") + } + return c, nil +} + +func sanitizeJSONNumber(v any) any { + switch f := v.(type) { + case float64: + switch { + case math.IsNaN(f): + return "NaN" + case math.IsInf(f, 1): + return "+Inf" + case math.IsInf(f, -1): + return "-Inf" + } + case float32: + f64 := float64(f) + switch { + case math.IsNaN(f64): + return "NaN" + case math.IsInf(f64, 1): + return "+Inf" + case math.IsInf(f64, -1): + return "-Inf" + } + } + return v +} + +func tunableInfoFrom(t debug.TunableInfo) TunableInfo { + return TunableInfo{ + Name: t.Name, + Type: t.Type, + Value: sanitizeJSONNumber(t.Value), + Default: sanitizeJSONNumber(t.Default), + Min: sanitizeJSONNumber(t.Min), + Max: sanitizeJSONNumber(t.Max), + } +} + +func missingTunableError(c *debug.Console, name string) error { + all := c.Tunables() + if len(all) == 0 { + return fmt.Errorf("mcp: tunable %q not found (no tunables registered)", name) + } + avail := make([]string, len(all)) + for i, t := range all { + avail[i] = t.Name + } + return fmt.Errorf("mcp: tunable %q not found (available: %s)", name, strings.Join(avail, ", ")) +} + +type tunablesListArgs struct { + Prefix string `json:"prefix"` +} + +func (b *Bridge) handleTunablesList(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[tunablesListArgs](raw) + if err != nil { + return nil, err + } + c, err := b.requireConsole() + if err != nil { + return nil, err + } + all := c.Tunables() + out := make([]TunableInfo, 0, len(all)) + for _, t := range all { + if args.Prefix != "" && !strings.HasPrefix(t.Name, args.Prefix) { + continue + } + out = append(out, tunableInfoFrom(t)) + } + return TunablesListResult{ + Total: len(out), + Tunables: out, + }, nil +} + +type tunableGetArgs struct { + Name string `json:"name"` +} + +func (b *Bridge) handleTunableGet(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[tunableGetArgs](raw) + if err != nil { + return nil, err + } + if strings.TrimSpace(args.Name) == "" { + return nil, errors.New("mcp: name is required") + } + c, err := b.requireConsole() + if err != nil { + return nil, err + } + info, ok := c.Tunable(args.Name) + if !ok { + return nil, missingTunableError(c, args.Name) + } + return tunableInfoFrom(info), nil +} + +type tunableSetArgs struct { + Name string `json:"name"` + Value json.RawMessage `json:"value"` + Clamp bool `json:"clamp"` +} + +func (b *Bridge) handleTunableSet(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[tunableSetArgs](raw) + if err != nil { + return nil, err + } + if strings.TrimSpace(args.Name) == "" { + return nil, errors.New("mcp: name is required") + } + rawVal := bytes.TrimSpace(args.Value) + if len(rawVal) == 0 { + return nil, errors.New("mcp: value is required") + } + c, err := b.requireConsole() + if err != nil { + return nil, err + } + info, ok := c.Tunable(args.Name) + if !ok { + return nil, missingTunableError(c, args.Name) + } + if bytes.Equal(rawVal, []byte("null")) { + return nil, fmt.Errorf("mcp: tunable %q expects %s, got null", info.Name, info.Type) + } + + var ( + typedVal any + clamped bool + ) + switch info.Type { + case "float": + var v float64 + if err := json.Unmarshal(rawVal, &v); err != nil { + if kind := jsonValueKind(rawVal); kind == "number" { + return nil, fmt.Errorf("mcp: tunable %q requires a finite float, got %s", info.Name, string(rawVal)) + } + return nil, fmt.Errorf("mcp: tunable %q expects float, got %s", info.Name, jsonValueKind(rawVal)) + } + if math.IsNaN(v) || math.IsInf(v, 0) { + return nil, fmt.Errorf("mcp: tunable %q requires a finite float", info.Name) + } + if args.Clamp { + if minF, ok := info.Min.(float64); ok && !math.IsNaN(minF) && !math.IsInf(minF, 0) && v < minF { + v = minF + clamped = true + } + if maxF, ok := info.Max.(float64); ok && !math.IsNaN(maxF) && !math.IsInf(maxF, 0) && v > maxF { + v = maxF + clamped = true + } + } + typedVal = v + case "int": + v, err := decodeStrictInt(info.Name, rawVal) + if err != nil { + return nil, err + } + if args.Clamp { + if minI, ok := info.Min.(int); ok && v < minI { + v = minI + clamped = true + } + if maxI, ok := info.Max.(int); ok && v > maxI { + v = maxI + clamped = true + } + } + typedVal = v + case "bool": + var v bool + if err := json.Unmarshal(rawVal, &v); err != nil { + return nil, fmt.Errorf("mcp: tunable %q expects bool, got %s", info.Name, jsonValueKind(rawVal)) + } + typedVal = v + case "string": + var v string + if err := json.Unmarshal(rawVal, &v); err != nil { + return nil, fmt.Errorf("mcp: tunable %q expects string, got %s", info.Name, jsonValueKind(rawVal)) + } + typedVal = v + default: + return nil, fmt.Errorf("mcp: unsupported tunable type %q for %q", info.Type, info.Name) + } + + oldVal, newVal, err := c.SetTunable(args.Name, typedVal) + if err != nil { + return nil, fmt.Errorf("mcp: %w", err) + } + return TunableSetResult{ + Name: info.Name, + Type: info.Type, + OldValue: sanitizeJSONNumber(oldVal), + Value: sanitizeJSONNumber(newVal), + Default: sanitizeJSONNumber(info.Default), + Min: sanitizeJSONNumber(info.Min), + Max: sanitizeJSONNumber(info.Max), + Clamped: clamped, + }, nil +} + +func decodeStrictInt(name string, raw []byte) (int, error) { + if kind := jsonValueKind(raw); kind != "number" { + return 0, fmt.Errorf("mcp: tunable %q expects int, got %s", name, kind) + } + var i int + if err := json.Unmarshal(raw, &i); err == nil { + return i, nil + } + var f float64 + if err := json.Unmarshal(raw, &f); err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, fmt.Errorf("mcp: tunable %q expects int, got invalid number %s", name, string(raw)) + } + if f < float64(math.MinInt) || f > float64(math.MaxInt) { + return 0, fmt.Errorf("mcp: tunable %q integer %s overflows int", name, string(raw)) + } + r, ok := new(big.Rat).SetString(string(raw)) + if !ok { + return 0, fmt.Errorf("mcp: tunable %q expects int, got invalid number %s", name, string(raw)) + } + if !r.IsInt() { + return 0, fmt.Errorf("mcp: tunable %q expects int, got non-integer number %s", name, string(raw)) + } + num := r.Num() + if !num.IsInt64() { + return 0, fmt.Errorf("mcp: tunable %q integer %s overflows int", name, string(raw)) + } + v64 := num.Int64() + if v64 < math.MinInt || v64 > math.MaxInt { + return 0, fmt.Errorf("mcp: tunable %q integer %s overflows int", name, string(raw)) + } + return int(v64), nil +} + +func jsonValueKind(raw []byte) string { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return "empty" + } + switch trimmed[0] { + case '"': + return "string" + case '{': + return "object" + case '[': + return "array" + case 't', 'f': + return "bool" + case 'n': + return "null" + default: + if trimmed[0] == '-' || (trimmed[0] >= '0' && trimmed[0] <= '9') { + return "number" + } + return "invalid" + } +} + +type consoleCommandsListArgs struct { + IncludeBuiltin *bool `json:"include_builtin"` +} + +func (b *Bridge) handleConsoleCommandsList(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[consoleCommandsListArgs](raw) + if err != nil { + return nil, err + } + includeBuiltin := true + if args.IncludeBuiltin != nil { + includeBuiltin = *args.IncludeBuiltin + } + c, err := b.requireConsole() + if err != nil { + return nil, err + } + all := c.Commands() + out := make([]ConsoleCommandInfo, 0, len(all)) + for _, cmd := range all { + if !includeBuiltin && cmd.Builtin { + continue + } + out = append(out, ConsoleCommandInfo{ + Name: cmd.Name, + Help: cmd.Help, + Builtin: cmd.Builtin, + }) + } + return ConsoleCommandsListResult{ + Total: len(out), + Commands: out, + }, nil +} + +type consoleExecArgs struct { + Command string `json:"command"` +} + +func (b *Bridge) handleConsoleExec(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[consoleExecArgs](raw) + if err != nil { + return nil, err + } + cmd := strings.TrimSpace(args.Command) + if cmd == "" { + return nil, errors.New("mcp: command is required") + } + c, err := b.requireConsole() + if err != nil { + return nil, err + } + out, execErr := c.Exec(cmd) + if execErr != nil { + return ConsoleExecResult{ + Command: cmd, + OK: false, + Output: out, + Lines: splitOutputLines(out), + Error: execErr.Error(), + }, nil + } + return ConsoleExecResult{ + Command: cmd, + OK: true, + Output: out, + Lines: splitOutputLines(out), + }, nil +} + +func splitOutputLines(out string) []string { + if out == "" { + return []string{} + } + normalized := strings.ReplaceAll(out, "\r\n", "\n") + normalized = strings.TrimSuffix(normalized, "\n") + if normalized == "" { + return []string{} + } + return strings.Split(normalized, "\n") +} diff --git a/packages/game/mcp/console_test.go b/packages/game/mcp/console_test.go new file mode 100644 index 00000000..a889547d --- /dev/null +++ b/packages/game/mcp/console_test.go @@ -0,0 +1,507 @@ +package mcp_test + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "strconv" + "strings" + "testing" + + "github.com/nsgo-dev/game/packages/game/debug" + "github.com/nsgo-dev/game/packages/game/entities" + "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// TestTunablesChangeAffectsLiveSimulation verifies the end-to-end acceptance +// flow: an agent lists tunables, reads physics parameters, raises jump_speed +// and lowers gravity via game_tunable_set, steps the live simulation, and sees +// the player reach a measurably higher apex via game_component_get. +func TestTunablesChangeAffectsLiveSimulation(t *testing.T) { + gravity := 800.0 + jumpSpeed := 300.0 + maxJumps := 1 + godMode := false + levelName := "cave_1" + + console := debug.NewConsole() + console.RegisterFloat("player.jump_speed", 100, 1200, &jumpSpeed) + console.RegisterFloat("physics.gravity", 0, 2000, &gravity) + console.RegisterInt("player.max_jumps", 1, 5, &maxJumps) + console.RegisterBool("player.god_mode", &godMode) + console.RegisterString("level.name", &levelName) + + world := entities.NewWorld() + if err := entities.RegisterCodec[posComp](world, "position"); err != nil { + t.Fatal(err) + } + player := world.Spawn() + entities.Set(world, player, posComp{X: 0, Y: 0}) + + // Simulate a single jump from Y=0 using the live tunable pointers and record the peak height. + simulateJumpApex := func() float64 { + y := 0.0 + vy := jumpSpeed + peak := 0.0 + const dt = 1.0 / 60.0 + for range 240 { + vy -= gravity * dt + y += vy * dt + if y > peak { + peak = y + } + if y <= 0 && vy < 0 { + break + } + } + entities.Set(world, player, posComp{X: 0, Y: float32(peak)}) + return peak + } + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + world.Attach(cx) + if _, err := mcp.Attach(cx, mcp.Config{ + World: world, + Console: console, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // 1. List all tunables and verify deterministic sorted order and metadata (including min=0). + listRaw, err := callToolRaw(t, app, cx, mcp.ToolTunablesList, nil) + if err != nil { + t.Fatalf("game_tunables_list failed: %v", err) + } + var listRes mcp.TunablesListResult + if err := json.Unmarshal(listRaw, &listRes); err != nil { + t.Fatal(err) + } + wantNames := []string{"level.name", "physics.gravity", "player.god_mode", "player.jump_speed", "player.max_jumps"} + if listRes.Total != len(wantNames) || len(listRes.Tunables) != len(wantNames) { + t.Fatalf("tunables list = %+v, want %d items", listRes, len(wantNames)) + } + for i, want := range wantNames { + if listRes.Tunables[i].Name != want { + t.Fatalf("tunables[%d].Name = %q, want %q", i, listRes.Tunables[i].Name, want) + } + } + // Verify numeric min=0 is serialized in JSON rather than omitted. + if !strings.Contains(string(listRaw), `"min":0`) { + t.Fatalf("expected physics.gravity min:0 in JSON output: %s", listRaw) + } + + // Prefix filter narrows to player.* tunables. + playerOnly := callTool[mcp.TunablesListResult](t, app, cx, mcp.ToolTunablesList, map[string]any{ + "prefix": "player.", + }) + if playerOnly.Total != 3 || playerOnly.Tunables[0].Name != "player.god_mode" || playerOnly.Tunables[2].Name != "player.max_jumps" { + t.Fatalf("prefix-filtered tunables = %+v", playerOnly) + } + + // 2. Read a single tunable before changing it. + gotJump := callTool[mcp.TunableInfo](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "player.jump_speed"}) + if gotJump.Type != "float" || gotJump.Value != 300.0 || gotJump.Default != 300.0 || gotJump.Min != 100.0 || gotJump.Max != 1200.0 { + t.Fatalf("tunable get(player.jump_speed) = %+v", gotJump) + } + + // Baseline jump height with default tunables. + var baselinePeak float64 + app.Post(func() { baselinePeak = simulateJumpApex() }) + app.Settle() + + baseComp := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ + "ref": mcp.FormatEntityRef(player), + "component": "position", + }) + var basePos posComp + if err := json.Unmarshal(baseComp.Value, &basePos); err != nil { + t.Fatal(err) + } + + // 3. Agent changes float, int, bool and string tunables via game_tunable_set. + setJump := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, map[string]any{ + "name": "player.jump_speed", + "value": 600, + }) + if setJump.OldValue != 300.0 || setJump.Value != 600.0 || setJump.Default != 300.0 || setJump.Clamped || jumpSpeed != 600.0 { + t.Fatalf("set player.jump_speed = %+v, var=%v", setJump, jumpSpeed) + } + + setGrav := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, map[string]any{ + "name": "physics.gravity", + "value": 400.0, + }) + if setGrav.OldValue != 800.0 || setGrav.Value != 400.0 || gravity != 400.0 { + t.Fatalf("set physics.gravity = %+v, var=%v", setGrav, gravity) + } + + setJumps := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, map[string]any{ + "name": "player.max_jumps", + "value": 3, + }) + if setJumps.OldValue != 1.0 || setJumps.Value != 3.0 || maxJumps != 3 { + t.Fatalf("set player.max_jumps = %+v, var=%d", setJumps, maxJumps) + } + + setGod := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, map[string]any{ + "name": "player.god_mode", + "value": true, + }) + if setGod.OldValue != false || setGod.Value != true || !godMode { + t.Fatalf("set player.god_mode = %+v, var=%v", setGod, godMode) + } + + setLevel := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, map[string]any{ + "name": "level.name", + "value": "boss_lair", + }) + if setLevel.OldValue != "cave_1" || setLevel.Value != "boss_lair" || levelName != "boss_lair" { + t.Fatalf("set level.name = %+v, var=%q", setLevel, levelName) + } + + // 4. Re-run jump simulation and verify the agent sees the dramatic height increase! + var boostedPeak float64 + app.Post(func() { boostedPeak = simulateJumpApex() }) + app.Settle() + + boostedComp := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ + "ref": mcp.FormatEntityRef(player), + "component": "position", + }) + var boostedPos posComp + if err := json.Unmarshal(boostedComp.Value, &boostedPos); err != nil { + t.Fatal(err) + } + if boostedPeak <= baselinePeak*4 || float64(boostedPos.Y) <= float64(basePos.Y)*4 { + t.Fatalf("expected tunable change to increase jump apex >4x: baseline=%v (%v) boosted=%v (%v)", + baselinePeak, basePos.Y, boostedPeak, boostedPos.Y) + } + + // 5. Optional clamp clamps out-of-range numeric values cleanly and reports clamped=true. + clampedFloat := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, map[string]any{ + "name": "player.jump_speed", + "value": 9999, + "clamp": true, + }) + if clampedFloat.OldValue != 600.0 || clampedFloat.Value != 1200.0 || !clampedFloat.Clamped || jumpSpeed != 1200.0 { + t.Fatalf("clamped float = %+v, var=%v", clampedFloat, jumpSpeed) + } + clampedInt := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, map[string]any{ + "name": "player.max_jumps", + "value": 0, + "clamp": true, + }) + if clampedInt.OldValue != 3.0 || clampedInt.Value != 1.0 || !clampedInt.Clamped || maxJumps != 1 { + t.Fatalf("clamped int = %+v, var=%d", clampedInt, maxJumps) + } + // Whole float JSON number (e.g. 4.0) is accepted for int tunables. + wholeFloatInt := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, `{"name":"player.max_jumps","value":4.0}`) + if wholeFloatInt.Value != 4.0 || maxJumps != 4 { + t.Fatalf("whole float int = %+v, var=%d", wholeFloatInt, maxJumps) + } + // Reading back reflects current value while preserving original registration default. + afterJump := callTool[mcp.TunableInfo](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "player.jump_speed"}) + if math.Abs(afterJump.Value.(float64)-1200) > 1e-9 || math.Abs(afterJump.Default.(float64)-300) > 1e-9 { + t.Fatalf("after get = %+v", afterJump) + } +} + +func TestConsoleCommandsListAndExec(t *testing.T) { + gravity := 980.0 + spawned := make([]string, 0) + + console := debug.NewConsole() + console.RegisterFloat("gravity", 0, 5000, &gravity) + console.RegisterCommand("spawn", "spawn [count] - spawn enemies into the room", func(args []string) (string, error) { + if len(args) < 1 || len(args) > 2 { + return "", errors.New("usage: spawn [count]") + } + count := 1 + if len(args) == 2 { + n, err := strconv.Atoi(args[1]) + if err != nil || n < 1 { + return "", fmt.Errorf("invalid count %q", args[1]) + } + count = n + } + lines := make([]string, 0, count) + for i := range count { + id := fmt.Sprintf("%s_%d", args[0], i+1) + spawned = append(spawned, id) + lines = append(lines, "spawned "+id) + } + return strings.Join(lines, "\n"), nil + }) + console.RegisterCommand("echo", "echo - echo message", func(args []string) (string, error) { + return strings.Join(args, " | "), nil + }) + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{Console: console}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // 1. List all commands (built-ins + custom), sorted alphabetically. + allCmds := callTool[mcp.ConsoleCommandsListResult](t, app, cx, mcp.ToolConsoleCommandsList, nil) + wantAll := []string{"clear", "echo", "get", "help", "list", "set", "spawn"} + if allCmds.Total != len(wantAll) || len(allCmds.Commands) != len(wantAll) { + t.Fatalf("commands list = %+v, want %v", allCmds, wantAll) + } + for i, want := range wantAll { + if allCmds.Commands[i].Name != want { + t.Fatalf("commands[%d] = %+v, want %q", i, allCmds.Commands[i], want) + } + } + if allCmds.Commands[6].Builtin || !strings.Contains(allCmds.Commands[6].Help, "spawn enemies") { + t.Fatalf("spawn command metadata = %+v", allCmds.Commands[6]) + } + + // Filter to custom commands only. + customCmds := callTool[mcp.ConsoleCommandsListResult](t, app, cx, mcp.ToolConsoleCommandsList, map[string]any{ + "include_builtin": false, + }) + if customCmds.Total != 2 || customCmds.Commands[0].Name != "echo" || customCmds.Commands[1].Name != "spawn" { + t.Fatalf("custom commands = %+v", customCmds) + } + + // 2. Execute built-in set command and verify variable updated. + setRes := callTool[mcp.ConsoleExecResult](t, app, cx, mcp.ToolConsoleExec, map[string]any{ + "command": "set gravity 1200", + }) + if !setRes.OK || setRes.Error != "" || setRes.Output != "gravity = 1200" || len(setRes.Lines) != 1 || setRes.Lines[0] != "gravity = 1200" || gravity != 1200 { + t.Fatalf("exec set gravity = %+v, gravity=%v", setRes, gravity) + } + + // 3. Execute custom multi-line command and verify all output lines are captured cleanly. + spawnRes := callTool[mcp.ConsoleExecResult](t, app, cx, mcp.ToolConsoleExec, map[string]any{ + "command": "spawn enemy 3", + }) + if !spawnRes.OK || spawnRes.Error != "" || len(spawned) != 3 { + t.Fatalf("exec spawn = %+v, spawned=%v", spawnRes, spawned) + } + wantLines := []string{"spawned enemy_1", "spawned enemy_2", "spawned enemy_3"} + if len(spawnRes.Lines) != 3 || spawnRes.Lines[0] != wantLines[0] || spawnRes.Lines[2] != wantLines[2] { + t.Fatalf("spawn lines = %#v, want %#v", spawnRes.Lines, wantLines) + } + + // Quoted arguments pass through splitConsoleArgs properly. + echoRes := callTool[mcp.ConsoleExecResult](t, app, cx, mcp.ToolConsoleExec, map[string]any{ + "command": `echo "hello world" second`, + }) + if !echoRes.OK || echoRes.Output != "hello world | second" { + t.Fatalf("exec echo = %+v", echoRes) + } + + // 4. Unknown command and failing custom command return {ok: false, error: ...} without panicking. + unknownRes := callTool[mcp.ConsoleExecResult](t, app, cx, mcp.ToolConsoleExec, map[string]any{ + "command": "does_not_exist arg1", + }) + if unknownRes.OK || !strings.Contains(unknownRes.Error, "unknown command") || len(unknownRes.Lines) != 0 { + t.Fatalf("exec unknown = %+v, want ok=false with unknown command error", unknownRes) + } + + badArgRes := callTool[mcp.ConsoleExecResult](t, app, cx, mcp.ToolConsoleExec, map[string]any{ + "command": "spawn enemy nope", + }) + if badArgRes.OK || !strings.Contains(badArgRes.Error, "invalid count") { + t.Fatalf("exec bad arg = %+v, want ok=false with invalid count", badArgRes) + } + + badQuoteRes := callTool[mcp.ConsoleExecResult](t, app, cx, mcp.ToolConsoleExec, map[string]any{ + "command": `echo "unterminated`, + }) + if badQuoteRes.OK || !strings.Contains(badQuoteRes.Error, "unterminated") { + t.Fatalf("exec bad quote = %+v", badQuoteRes) + } + + // Built-in clear succeeds with empty output and empty lines slice. + clearRes := callTool[mcp.ConsoleExecResult](t, app, cx, mcp.ToolConsoleExec, map[string]any{ + "command": "clear", + }) + if !clearRes.OK || clearRes.Error != "" || clearRes.Output != "" || len(clearRes.Lines) != 0 { + t.Fatalf("exec clear = %+v", clearRes) + } +} + +func TestConsoleDynamicResolutionAndErrors(t *testing.T) { + var ( + cx *core.Scope + bridge *mcp.Bridge + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + var err error + bridge, err = mcp.Attach(cx, mcp.Config{}) + if err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // 1. Nil Console returns clean errors on every console/tunable tool without panicking. + for _, tc := range []struct { + tool string + args any + }{ + {mcp.ToolTunablesList, nil}, + {mcp.ToolTunableGet, map[string]any{"name": "gravity"}}, + {mcp.ToolTunableSet, map[string]any{"name": "gravity", "value": 10}}, + {mcp.ToolConsoleCommandsList, nil}, + {mcp.ToolConsoleExec, map[string]any{"command": "help"}}, + } { + if _, err := callToolRaw(t, app, cx, tc.tool, tc.args); err == nil || !strings.Contains(err.Error(), "no debug console") { + t.Fatalf("%s with nil console = %v, want no debug console error", tc.tool, err) + } + } + + // 2. Attach a console via SetConsole and test validation & error handling. + c1 := debug.NewConsole() + speed := 10.0 + lives := 3 + debugDraw := false + title := "intro" + c1.RegisterFloat("speed", 0, 100, &speed) + c1.RegisterInt("lives", 1, 10, &lives) + c1.RegisterBool("debug_draw", &debugDraw) + c1.RegisterString("title", &title) + + app.Post(func() { bridge.SetConsole(c1) }) + app.Settle() + + // Unknown JSON fields rejected on every tool. + for _, tool := range []string{ + mcp.ToolTunablesList, + mcp.ToolTunableGet, + mcp.ToolTunableSet, + mcp.ToolConsoleCommandsList, + mcp.ToolConsoleExec, + } { + if _, err := callToolRaw(t, app, cx, tool, `{"bogus":1}`); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("%s with unknown field = %v, want unknown field error", tool, err) + } + } + + // Missing required arguments rejected. + if _, err := callToolRaw(t, app, cx, mcp.ToolTunableGet, `{}`); err == nil || !strings.Contains(err.Error(), "name is required") { + t.Fatalf("tunable_get missing name = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolTunableSet, `{"name":"speed"}`); err == nil || !strings.Contains(err.Error(), "value is required") { + t.Fatalf("tunable_set missing value = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolTunableSet, `{"value":5}`); err == nil || !strings.Contains(err.Error(), "name is required") { + t.Fatalf("tunable_set missing name = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolConsoleExec, `{"command":" "}`); err == nil || !strings.Contains(err.Error(), "command is required") { + t.Fatalf("console_exec empty command = %v", err) + } + + // Unknown tunable reports available names. + if _, err := callToolRaw(t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "nope"}); err == nil || !strings.Contains(err.Error(), "not found") || !strings.Contains(err.Error(), "speed") { + t.Fatalf("tunable_get unknown = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolTunableSet, map[string]any{"name": "nope", "value": 1}); err == nil || !strings.Contains(err.Error(), "not found") { + t.Fatalf("tunable_set unknown = %v", err) + } + + // Type mismatches, null values and out-of-range values fail without mutating variables. + badSets := []struct { + payload string + want string + }{ + {`{"name":"speed","value":null}`, "expects float, got null"}, + {`{"name":"speed","value":"fast"}`, "expects float, got string"}, + {`{"name":"speed","value":true}`, "expects float, got bool"}, + {`{"name":"speed","value":101}`, "out of range"}, + {`{"name":"speed","value":-1}`, "out of range"}, + {`{"name":"speed","value":1e500}`, "finite float"}, + {`{"name":"lives","value":2.5}`, "non-integer"}, + {`{"name":"lives","value":9007199254740993.5}`, "non-integer"}, + {`{"name":"lives","value":1e30}`, "overflows int"}, + {`{"name":"lives","value":"3"}`, "expects int, got string"}, + {`{"name":"lives","value":0}`, "out of range"}, + {`{"name":"lives","value":11}`, "out of range"}, + {`{"name":"debug_draw","value":"true"}`, "expects bool, got string"}, + {`{"name":"debug_draw","value":1}`, "expects bool, got number"}, + {`{"name":"title","value":123}`, "expects string, got number"}, + {`{"name":"title","value":false}`, "expects string, got bool"}, + } + for _, tc := range badSets { + if _, err := callToolRaw(t, app, cx, mcp.ToolTunableSet, tc.payload); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("tunable_set(%s) = %v, want substring %q", tc.payload, err, tc.want) + } + } + if speed != 10.0 || lives != 3 || debugDraw != false || title != "intro" { + t.Fatalf("variables mutated after rejected calls: speed=%v lives=%d debugDraw=%v title=%q", speed, lives, debugDraw, title) + } + + // Scientific-notation integer values are accepted for int tunables. + sciInt := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, `{"name":"lives","value":5e0}`) + if sciInt.Value != 5.0 || lives != 5 { + t.Fatalf("scientific int = %+v, lives=%d", sciInt, lives) + } + + // Non-finite runtime floats serialize safely as "NaN"/"+Inf" rather than failing JSON encoding, + // and can be inspected and recovered via game_tunable_set. + speed = math.NaN() + nanList := callTool[mcp.TunablesListResult](t, app, cx, mcp.ToolTunablesList, map[string]any{"prefix": "speed"}) + if nanList.Total != 1 || nanList.Tunables[0].Value != "NaN" { + t.Fatalf("nan list = %+v, want Value=\"NaN\"", nanList) + } + nanGet := callTool[mcp.TunableInfo](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "speed"}) + if nanGet.Value != "NaN" { + t.Fatalf("nan get = %+v, want Value=\"NaN\"", nanGet) + } + recoverRes := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, map[string]any{"name": "speed", "value": 25.0}) + if recoverRes.OldValue != "NaN" || recoverRes.Value != 25.0 || speed != 25.0 { + t.Fatalf("recover from NaN = %+v, speed=%v", recoverRes, speed) + } + + // Structured tunable/command queries do not pollute interactive console history or output entries. + _ = callTool[mcp.ConsoleCommandsListResult](t, app, cx, mcp.ToolConsoleCommandsList, nil) + if len(c1.History()) != 0 || len(c1.Entries()) != 0 { + t.Fatalf("structured queries polluted console state: history=%v entries=%v", c1.History(), c1.Entries()) + } + + // 3. ConsoleFunc dynamically switches active console on each call. + c2 := debug.NewConsole() + volume := 0.5 + c2.RegisterFloat("volume", 0, 1, &volume) + + active := c1 + app.Post(func() { + bridge.Detach() + var err error + bridge, err = mcp.Attach(cx, mcp.Config{ + ConsoleFunc: func() *debug.Console { return active }, + }) + if err != nil { + t.Fatal(err) + } + }) + app.Settle() + + res1 := callTool[mcp.TunablesListResult](t, app, cx, mcp.ToolTunablesList, nil) + if res1.Total != 4 { + t.Fatalf("c1 tunables = %+v, want 4", res1) + } + active = c2 + res2 := callTool[mcp.TunablesListResult](t, app, cx, mcp.ToolTunablesList, nil) + if res2.Total != 1 || res2.Tunables[0].Name != "volume" { + t.Fatalf("c2 tunables = %+v, want [volume]", res2) + } + + // Nil bridge SetConsole is a safe no-op. + var nilBridge *mcp.Bridge + nilBridge.SetConsole(c1) +} diff --git a/packages/game/mcp/doc.go b/packages/game/mcp/doc.go index cb96e529..6ffa8aa8 100644 --- a/packages/game/mcp/doc.go +++ b/packages/game/mcp/doc.go @@ -17,6 +17,11 @@ // - game_input_axis: inject or clear 1D or multi-axis analog values in [-1, 1] on [input.Actions]. // - game_input_pointer: inject a pointer press, release, move, or click in game (or camera world) coordinates, mapped through [screen.Viewport] and hit-tested/dispatched on the active [scene.Scene]. // - game_input_actions_list: list configured action and axis names with their current step state. +// - game_tunables_list: list registered debug console tunables with their type, current value, default and numeric bounds. +// - game_tunable_get: read one registered tunable's current value and metadata by name. +// - game_tunable_set: update one registered tunable's value with type checking and range validation or optional clamping. +// - game_console_commands_list: list built-in and registered debug console commands with their usage descriptions. +// - game_console_exec: execute a debug console command line and return its structured status, output text, output lines and error. // // Components registered on an [entities.World] with [entities.RegisterCodec] are readable automatically. Transient or non-saved components can also be exposed with [RegisterComponent] or [RegisterComponentFunc], and built-in [entities.Transform2D], [entities.WorldTransform2D] and [sceneformat.ObjectRef] components are surfaced automatically when present and not already registered under another name. // diff --git a/packages/game/mcp/example_test.go b/packages/game/mcp/example_test.go index 500603a4..93f7f756 100644 --- a/packages/game/mcp/example_test.go +++ b/packages/game/mcp/example_test.go @@ -50,4 +50,9 @@ func ExampleNew() { // game_input_axis // game_input_pointer // game_input_actions_list + // game_tunables_list + // game_tunable_get + // game_tunable_set + // game_console_commands_list + // game_console_exec } diff --git a/packages/game/mcp/mcp.go b/packages/game/mcp/mcp.go index 204991c4..037a6876 100644 --- a/packages/game/mcp/mcp.go +++ b/packages/game/mcp/mcp.go @@ -14,6 +14,7 @@ import ( "strings" "github.com/nsgo-dev/game/packages/game" + "github.com/nsgo-dev/game/packages/game/debug" "github.com/nsgo-dev/game/packages/game/entities" "github.com/nsgo-dev/game/packages/game/input" "github.com/nsgo-dev/game/packages/game/random" @@ -113,6 +114,12 @@ type Config struct { // OnPointer is called whenever game_input_pointer injects a pointer press, release or move, after viewport mapping and scene hit testing. OnPointer func(PointerEvent) + + // Console is the game's debug console for tunable inspection/mutation and command execution tools. + Console *debug.Console + + // ConsoleFunc dynamically resolves the active debug console on each tool call. When non-nil and returning a non-nil console, it overrides Console. + ConsoleFunc func() *debug.Console } type compTypeKey any @@ -258,6 +265,14 @@ func (b *Bridge) SetViewport(vp *screen.Viewport) { b.cfg.Viewport = vp } +// SetConsole replaces the static debug Console configured on b. +// If Config.ConsoleFunc is set and returns a non-nil console, ConsoleFunc continues to take precedence. +func (b *Bridge) SetConsole(c *debug.Console) { + if b == nil { + return + } + b.cfg.Console = c +} // Tools returns the full set of automation.Tool definitions owned by b, assembled from each tool group. func (b *Bridge) Tools() []automation.Tool { if b == nil { @@ -267,6 +282,7 @@ func (b *Bridge) Tools() []automation.Tool { out = append(out, b.inspectTools()...) out = append(out, b.loopTools()...) out = append(out, b.inputTools()...) + out = append(out, b.consoleTools()...) return out } From 74e8e6722651a2a6f4fbcf741086496b3f329116 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:02:49 +0900 Subject: [PATCH 2/4] style(mcp): gofmt mcp.go after the rebase and keep the SetConsole comment on one line --- packages/game/mcp/mcp.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/game/mcp/mcp.go b/packages/game/mcp/mcp.go index 037a6876..057e0abb 100644 --- a/packages/game/mcp/mcp.go +++ b/packages/game/mcp/mcp.go @@ -265,14 +265,14 @@ func (b *Bridge) SetViewport(vp *screen.Viewport) { b.cfg.Viewport = vp } -// SetConsole replaces the static debug Console configured on b. -// If Config.ConsoleFunc is set and returns a non-nil console, ConsoleFunc continues to take precedence. +// SetConsole replaces the static debug Console configured on b. If Config.ConsoleFunc is set and returns a non-nil console, ConsoleFunc continues to take precedence. func (b *Bridge) SetConsole(c *debug.Console) { if b == nil { return } b.cfg.Console = c } + // Tools returns the full set of automation.Tool definitions owned by b, assembled from each tool group. func (b *Bridge) Tools() []automation.Tool { if b == nil { From a6bfb034578f4c18c4562c4cc5cf084352404616 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:02:49 +0900 Subject: [PATCH 3/4] docs(formats): document string tunables in the console tunables format RegisterString adds a persisted value kind, so the format section names it, its example carries a string tunable, and readTunables registers it so the example stays checked. --- docs/en/formats.md | 4 ++-- docs/zh/formats.md | 4 ++-- packages/game/formats_test.go | 4 +++- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/en/formats.md b/docs/en/formats.md index 83c7f587..28e58f6e 100644 --- a/docs/en/formats.md +++ b/docs/en/formats.md @@ -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. ### Dev session snapshot diff --git a/docs/zh/formats.md b/docs/zh/formats.md index 239ffc0f..1cd0a661 100644 --- a/docs/zh/formats.md +++ b/docs/zh/formats.md @@ -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 类型不符的值,且只要拒绝其中一个值,就一个值也不应用。 ### 开发会话快照 diff --git a/packages/game/formats_test.go b/packages/game/formats_test.go index cc24e3d4..ffd6b153 100644 --- a/packages/game/formats_test.go +++ b/packages/game/formats_test.go @@ -262,7 +262,7 @@ func readInputBindings(t *testing.T, data []byte) error { } // exampleTunables are the tunables the debug example sets, registered as a game registers its own, since LoadTunables skips a name nothing registered. -var exampleTunables = []string{"cheat.god", "player.lives", "player.speed"} +var exampleTunables = []string{"cheat.god", "level.name", "player.lives", "player.speed"} func readTunables(t *testing.T, data []byte) error { var names map[string]json.RawMessage @@ -282,9 +282,11 @@ func readTunables(t *testing.T, data []byte) error { var speed float64 var lives int var god bool + var level string c.RegisterFloat("player.speed", 0, 10, &speed) c.RegisterInt("player.lives", 1, 9, &lives) c.RegisterBool("cheat.god", &god) + c.RegisterString("level.name", &level) return c.LoadTunables(st, "") } From 94cdd364907a21a1c2897fa155edd6750163e36b Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:02:49 +0900 Subject: [PATCH 4/4] fix(debug,mcp): clamp and write tunables under one console lock Console.SetTunable now takes a clamp flag and returns a TunableChange with the previous value and a snapshot taken under the same lock as the write, so game_tunable_set never clamps with bounds read before a tunable was re-registered. With clamp, an integer beyond int's range (such as 1e30) is clamped to the tunable's bound instead of failing with "overflows int". In release builds SetTunable returns an error rather than a nil error for a write that never happened. mcp.TunableInfo is renamed TunableResult so it no longer shares a name with debug.TunableInfo. The acceptance test now attaches a game.Loop whose Update integrates the jump from the tunable pointers, starts the jump with game_console_exec and steps it with game_loop_step. New tests cover string tunables in SaveTunables/LoadTunables, a number refused for a string tunable with no other value applied, and clamping at int's limits. --- .../2026-11-24-mcp-tunables-and-console.md | 8 +- changelog.d/mcp-tunables-console-466.md | 2 +- packages/game/debug/console.go | 96 ++++++++----- packages/game/debug/console_release.go | 12 +- packages/game/debug/console_test.go | 53 +++++-- packages/game/debug/debug_release_test.go | 4 +- packages/game/debug/types.go | 10 ++ packages/game/mcp/console.go | 111 +++++++-------- packages/game/mcp/console_test.go | 132 +++++++++++------- 9 files changed, 259 insertions(+), 169 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-tunables-and-console.md b/.agents/notes/implemented/feature/2026-11-24-mcp-tunables-and-console.md index 3ebfd1f5..691e12b4 100644 --- a/.agents/notes/implemented/feature/2026-11-24-mcp-tunables-and-console.md +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-tunables-and-console.md @@ -8,15 +8,15 @@ Coding agents connected to a running game via `game/mcp` (introduced in [MCP sce ## Decision -Add structured inspection and typed mutation methods to `packages/game/debug.Console` (`RegisterString`, `Tunables`, `Tunable`, `SetTunable`, `Commands`, backed by `TunableInfo` and `CommandInfo` in `debug/types.go` with release-build no-op 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()`. +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]` and reports `"clamped": true`. Responses always return both `old_value` and applied `value`. +- **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` and `CommandInfo` live in untagged `debug/types.go`, and `debug/console_release.go` provides matching zero-cost no-op stubs so `-tags release` builds of both `game/debug` and `game/mcp` compile cleanly. +- **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 @@ -35,7 +35,7 @@ Always clamping numeric writes to `[min, max]` would prevent range errors during ## 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 two structs (`TunableInfo`, `CommandInfo`) that must stay synchronized between `console.go` and `console_release.go`. +- **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 diff --git a/changelog.d/mcp-tunables-console-466.md b/changelog.d/mcp-tunables-console-466.md index af582ffc..ed40653e 100644 --- a/changelog.d/mcp-tunables-console-466.md +++ b/changelog.d/mcp-tunables-console-466.md @@ -1,4 +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` and `CommandInfo` (#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). diff --git a/packages/game/debug/console.go b/packages/game/debug/console.go index 6ed57713..40379eaa 100644 --- a/packages/game/debug/console.go +++ b/packages/game/debug/console.go @@ -162,7 +162,8 @@ func (t *consoleTunable) setString(raw string) error { } } -func (t *consoleTunable) setValue(value any) (oldVal, newVal any, err error) { +// setValue stores value after checking its type and range. With clamp, a number outside the range, including an integer beyond int's range, is stored as the nearest bound and clamped reports it; without clamp it is refused. On error the tunable is unchanged. +func (t *consoleTunable) setValue(value any, clamp bool) (old any, clamped bool, err error) { switch t.kind { case tunableFloat: var v float64 @@ -192,19 +193,29 @@ func (t *consoleTunable) setValue(value any) (oldVal, newVal any, err error) { case uint64: v = float64(x) default: - return nil, nil, fmt.Errorf("invalid float value %T for %q", value, t.name) + return nil, false, fmt.Errorf("invalid float value %T for %q", value, t.name) } if math.IsNaN(v) || math.IsInf(v, 0) { - return nil, nil, fmt.Errorf("invalid float %v for %q", v, t.name) + return nil, false, fmt.Errorf("invalid float %v for %q", v, t.name) } if v < t.minFloat || v > t.maxFloat { - return nil, nil, fmt.Errorf("%q value %g out of range [%g, %g]", t.name, v, t.minFloat, t.maxFloat) + if !clamp { + return nil, false, fmt.Errorf("%q value %g out of range [%g, %g]", t.name, v, t.minFloat, t.maxFloat) + } + if v < t.minFloat { + v = t.minFloat + } else { + v = t.maxFloat + } + clamped = true } - old := *t.floatPtr + old = *t.floatPtr *t.floatPtr = v - return old, v, nil + return old, clamped, nil case tunableInt: var v int + // beyond is -1 or +1 when value lies below or above int's range. + beyond := 0 switch x := value.(type) { case int: v = x @@ -215,56 +226,72 @@ func (t *consoleTunable) setValue(value any) (oldVal, newVal any, err error) { case int32: v = int(x) case int64: - if x < math.MinInt || x > math.MaxInt { - return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, x, t.minInt, t.maxInt) + switch { + case x < math.MinInt: + beyond = -1 + case x > math.MaxInt: + beyond = 1 + default: + v = int(x) } - v = int(x) case uint: if uint64(x) > math.MaxInt { - return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, x, t.minInt, t.maxInt) + beyond = 1 + } else { + v = int(x) } - v = int(x) case uint8: v = int(x) case uint16: v = int(x) case uint32: if uint64(x) > math.MaxInt { - return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, x, t.minInt, t.maxInt) + beyond = 1 + } else { + v = int(x) } - v = int(x) case uint64: if x > math.MaxInt { - return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, x, t.minInt, t.maxInt) + beyond = 1 + } else { + v = int(x) } - v = int(x) default: - return nil, nil, fmt.Errorf("invalid int value %T for %q", value, t.name) + return nil, false, fmt.Errorf("invalid int value %T for %q", value, t.name) } - if v < t.minInt || v > t.maxInt { - return nil, nil, fmt.Errorf("%q value %d out of range [%d, %d]", t.name, v, t.minInt, t.maxInt) + if beyond != 0 || v < t.minInt || v > t.maxInt { + if !clamp { + return nil, false, fmt.Errorf("%q value %v out of range [%d, %d]", t.name, value, t.minInt, t.maxInt) + } + switch { + case beyond < 0 || (beyond == 0 && v < t.minInt): + v = t.minInt + default: + v = t.maxInt + } + clamped = true } - old := *t.intPtr + old = *t.intPtr *t.intPtr = v - return old, v, nil + return old, clamped, nil case tunableBool: v, ok := value.(bool) if !ok { - return nil, nil, fmt.Errorf("invalid bool value %T for %q", value, t.name) + return nil, false, fmt.Errorf("invalid bool value %T for %q", value, t.name) } - old := *t.boolPtr + old = *t.boolPtr *t.boolPtr = v - return old, v, nil + return old, false, nil case tunableString: v, ok := value.(string) if !ok { - return nil, nil, fmt.Errorf("invalid string value %T for %q", value, t.name) + return nil, false, fmt.Errorf("invalid string value %T for %q", value, t.name) } - old := *t.stringPtr + old = *t.stringPtr *t.stringPtr = v - return old, v, nil + return old, false, nil default: - return nil, nil, fmt.Errorf("unsupported tunable %q", t.name) + return nil, false, fmt.Errorf("unsupported tunable %q", t.name) } } @@ -447,19 +474,22 @@ func (c *Console) Tunable(name string) (TunableInfo, bool) { return t.info(), true } -// SetTunable updates the named tunable to value after checking its type and numeric range. -// On success it returns the previous and new values; on failure the tunable is left unchanged. -func (c *Console) SetTunable(name string, value any) (oldVal, newVal any, err error) { +// SetTunable updates the named tunable to value after checking its type and numeric range, and returns the previous value with a snapshot of the tunable after the change, both taken under the same lock as the write. A float tunable takes any Go integer or float; an int tunable takes any Go integer. With clamp, a number outside the tunable's range, including an integer beyond int's range, is stored as the nearest bound and TunableChange.Clamped is set; without clamp it is refused. On error the tunable is left unchanged. +func (c *Console) SetTunable(name string, value any, clamp bool) (TunableChange, error) { if c == nil { - return nil, nil, errors.New("debug: nil console") + return TunableChange{}, errors.New("debug: nil console") } c.mu.Lock() defer c.mu.Unlock() t, ok := c.tunables[name] if !ok { - return nil, nil, fmt.Errorf("unknown tunable %q", name) + return TunableChange{}, fmt.Errorf("unknown tunable %q", name) + } + old, clamped, err := t.setValue(value, clamp) + if err != nil { + return TunableChange{}, err } - return t.setValue(value) + return TunableChange{Old: old, Tunable: t.info(), Clamped: clamped}, nil } // Commands returns all built-in and registered console commands sorted by name. diff --git a/packages/game/debug/console_release.go b/packages/game/debug/console_release.go index d877931c..61f7794f 100644 --- a/packages/game/debug/console_release.go +++ b/packages/game/debug/console_release.go @@ -2,7 +2,11 @@ package debug -import "github.com/nsgo-dev/nsgo/core" +import ( + "errors" + + "github.com/nsgo-dev/nsgo/core" +) var releaseConsole Console @@ -33,8 +37,10 @@ func (*Console) Tunables() []TunableInfo { return nil } // Tunable always reports not found in release builds. func (*Console) Tunable(string) (TunableInfo, bool) { return TunableInfo{}, false } -// SetTunable is a no-op in release builds. -func (*Console) SetTunable(string, any) (any, any, error) { return nil, nil, nil } +// SetTunable changes nothing and returns an error in release builds, where no tunable is registered. +func (*Console) SetTunable(string, any, bool) (TunableChange, error) { + return TunableChange{}, errors.New("debug: console disabled in release builds") +} // Commands always returns nil in release builds. func (*Console) Commands() []CommandInfo { return nil } diff --git a/packages/game/debug/console_test.go b/packages/game/debug/console_test.go index 37a4c828..782432b9 100644 --- a/packages/game/debug/console_test.go +++ b/packages/game/debug/console_test.go @@ -260,8 +260,15 @@ func TestConsoleStoragePersistence(t *testing.T) { if err := c2.LoadTunables(st, "dev.badstr"); err == nil { t.Fatal("LoadTunables(null string) succeeded, want error") } - if g2 != 33.25 || s2 != "boss room" { - t.Fatalf("tunables mutated after rejected LoadTunables: gravity=%v level=%q", g2, s2) + // A number for a string tunable is refused, and a refused load applies none of its other values either. + if err := st.SetItem("dev.mixed", `{"gravity": 50, "lives": 7, "level": 42}`); err != nil { + t.Fatalf("SetItem error = %v", err) + } + if err := c2.LoadTunables(st, "dev.mixed"); err == nil { + t.Fatal("LoadTunables(number for string) succeeded, want error") + } + if g2 != 33.25 || n2 != 12 || s2 != "boss room" { + t.Fatalf("tunables mutated after rejected LoadTunables: gravity=%v lives=%d level=%q", g2, n2, s2) } } @@ -354,38 +361,58 @@ func TestConsoleStructuredInspectionAndStringTunable(t *testing.T) { } } - oldV, newV, err := c.SetTunable("gravity", 20.5) - if err != nil || oldV != 9.8 || newV != 20.5 || gravity != 20.5 { - t.Fatalf("SetTunable(gravity) = (%v, %v, %v), gravity=%v", oldV, newV, err, gravity) + ch, err := c.SetTunable("gravity", 20.5, false) + if err != nil || ch.Old != 9.8 || ch.Tunable.Value != 20.5 || ch.Tunable.Max != 50.0 || ch.Clamped || gravity != 20.5 { + t.Fatalf("SetTunable(gravity) = (%+v, %v), gravity=%v", ch, err, gravity) } if info, ok := c.Tunable("gravity"); !ok || info.Value != 20.5 || info.Default != 9.8 || info.Min != 0.0 || info.Max != 50.0 { t.Fatalf("Tunable(gravity) = (%+v, %v)", info, ok) } - oldS, newS, err := c.SetTunable("level", "cave_2") - if err != nil || oldS != "cave_1" || newS != "cave_2" || level != "cave_2" { - t.Fatalf("SetTunable(level) = (%v, %v, %v), level=%q", oldS, newS, err, level) + ch, err = c.SetTunable("level", "cave_2", false) + if err != nil || ch.Old != "cave_1" || ch.Tunable.Value != "cave_2" || level != "cave_2" { + t.Fatalf("SetTunable(level) = (%+v, %v), level=%q", ch, err, level) } if out, err := c.Exec(`set level "boss room"`); err != nil || out != "level = boss room" || level != "boss room" { t.Fatalf("Exec(set level) = (%q, %v), level=%q", out, err, level) } // Range and type rejections leave variables untouched. - if _, _, err := c.SetTunable("gravity", 99.0); err == nil || gravity != 20.5 { + if _, err := c.SetTunable("gravity", 99.0, false); err == nil || gravity != 20.5 { t.Fatalf("out-of-range SetTunable(gravity) = %v, gravity=%v", err, gravity) } - if _, _, err := c.SetTunable("lives", "10"); err == nil || lives != 3 { + if _, err := c.SetTunable("lives", "10", false); err == nil || lives != 3 { t.Fatalf("wrong-type SetTunable(lives) = %v, lives=%d", err, lives) } - if _, _, err := c.SetTunable("god", 1); err == nil || god != false { + if _, err := c.SetTunable("lives", uint64(math.MaxUint64), false); err == nil || lives != 3 { + t.Fatalf("beyond-int SetTunable(lives) = %v, lives=%d", err, lives) + } + if _, err := c.SetTunable("gravity", math.NaN(), true); err == nil || gravity != 20.5 { + t.Fatalf("NaN SetTunable(gravity, clamp) = %v, gravity=%v", err, gravity) + } + if _, err := c.SetTunable("god", 1, false); err == nil || god != false { t.Fatalf("wrong-type SetTunable(god) = %v, god=%v", err, god) } - if _, _, err := c.SetTunable("level", 42); err == nil || level != "boss room" { + if _, err := c.SetTunable("level", 42, false); err == nil || level != "boss room" { t.Fatalf("wrong-type SetTunable(level) = %v, level=%q", err, level) } - if _, _, err := c.SetTunable("missing", 1); err == nil { + if _, err := c.SetTunable("missing", 1, false); err == nil { t.Fatal("SetTunable(missing) succeeded, want error") } + // Clamping stores the nearest bound, including for integers beyond int's range. + if ch, err := c.SetTunable("gravity", 99.0, true); err != nil || !ch.Clamped || ch.Old != 20.5 || ch.Tunable.Value != 50.0 || gravity != 50 { + t.Fatalf("clamped SetTunable(gravity) = (%+v, %v), gravity=%v", ch, err, gravity) + } + if ch, err := c.SetTunable("lives", uint64(math.MaxUint64), true); err != nil || !ch.Clamped || ch.Tunable.Value != 99 || lives != 99 { + t.Fatalf("clamped beyond-int SetTunable(lives) = (%+v, %v), lives=%d", ch, err, lives) + } + if ch, err := c.SetTunable("lives", -5, true); err != nil || !ch.Clamped || ch.Old != 99 || lives != 1 { + t.Fatalf("clamped SetTunable(lives, -5) = (%+v, %v), lives=%d", ch, err, lives) + } + if ch, err := c.SetTunable("lives", 3, true); err != nil || ch.Clamped || lives != 3 { + t.Fatalf("in-range SetTunable(lives, clamp) = (%+v, %v), lives=%d", ch, err, lives) + } + // Commands() returns sorted built-ins + custom commands without duplicates. cmds := c.Commands() wantCmds := []string{"clear", "get", "help", "list", "set", "spawn"} diff --git a/packages/game/debug/debug_release_test.go b/packages/game/debug/debug_release_test.go index ff7ca0ad..8e60700c 100644 --- a/packages/game/debug/debug_release_test.go +++ b/packages/game/debug/debug_release_test.go @@ -153,8 +153,8 @@ func TestReleaseBuildIsDisabledZeroCostStub(t *testing.T) { if _, ok := c.Tunable("f"); ok { t.Fatal("Console.Tunable returned true in release build") } - if oldV, newV, err := c.SetTunable("f", 2.0); oldV != nil || newV != nil || err != nil || vFloat != 1.5 { - t.Fatalf("Console.SetTunable in release = (%v, %v, %v), vFloat=%v", oldV, newV, err, vFloat) + if ch, err := c.SetTunable("f", 2.0, false); ch != (debug.TunableChange{}) || err == nil || vFloat != 1.5 { + t.Fatalf("Console.SetTunable in release = (%+v, %v), vFloat=%v; want an error and no change", ch, err, vFloat) } if len(c.History()) != 0 || c.HistoryPrev() != "" || c.HistoryNext() != "" || len(c.Entries()) != 0 || len(c.Complete("s")) != 0 { t.Fatal("Console history/entries/complete returned data in release build") diff --git a/packages/game/debug/types.go b/packages/game/debug/types.go index 03136050..f7967448 100644 --- a/packages/game/debug/types.go +++ b/packages/game/debug/types.go @@ -85,6 +85,16 @@ type TunableInfo struct { Max any } +// TunableChange is the result of Console.SetTunable. +type TunableChange struct { + // Old is the tunable's value before the change. + Old any + // Tunable describes the tunable after the change; its Value is the value stored. + Tunable TunableInfo + // Clamped reports whether the requested value lay outside the tunable's range and was stored as the nearest bound. + Clamped bool +} + // CommandInfo describes one command available on a Console. type CommandInfo struct { // Name is the command name as typed on the console. diff --git a/packages/game/mcp/console.go b/packages/game/mcp/console.go index 51097f8c..79490f6b 100644 --- a/packages/game/mcp/console.go +++ b/packages/game/mcp/console.go @@ -28,8 +28,8 @@ const ( ToolConsoleExec = "game_console_exec" ) -// TunableInfo describes one registered tunable variable returned by game_tunables_list and game_tunable_get. -type TunableInfo struct { +// TunableResult describes one registered tunable variable, as game_tunables_list and game_tunable_get return it. It is debug.TunableInfo in JSON form, with a non-finite float bound written as "NaN", "+Inf" or "-Inf". +type TunableResult struct { Name string `json:"name"` Type string `json:"type"` Value any `json:"value"` @@ -40,8 +40,8 @@ type TunableInfo struct { // TunablesListResult is the JSON result of game_tunables_list. type TunablesListResult struct { - Total int `json:"total"` - Tunables []TunableInfo `json:"tunables"` + Total int `json:"total"` + Tunables []TunableResult `json:"tunables"` } // TunableSetResult is the JSON result of game_tunable_set. @@ -225,8 +225,8 @@ func sanitizeJSONNumber(v any) any { return v } -func tunableInfoFrom(t debug.TunableInfo) TunableInfo { - return TunableInfo{ +func tunableResultFrom(t debug.TunableInfo) TunableResult { + return TunableResult{ Name: t.Name, Type: t.Type, Value: sanitizeJSONNumber(t.Value), @@ -262,12 +262,12 @@ func (b *Bridge) handleTunablesList(_ context.Context, raw json.RawMessage) (any return nil, err } all := c.Tunables() - out := make([]TunableInfo, 0, len(all)) + out := make([]TunableResult, 0, len(all)) for _, t := range all { if args.Prefix != "" && !strings.HasPrefix(t.Name, args.Prefix) { continue } - out = append(out, tunableInfoFrom(t)) + out = append(out, tunableResultFrom(t)) } return TunablesListResult{ Total: len(out), @@ -295,7 +295,7 @@ func (b *Bridge) handleTunableGet(_ context.Context, raw json.RawMessage) (any, if !ok { return nil, missingTunableError(c, args.Name) } - return tunableInfoFrom(info), nil + return tunableResultFrom(info), nil } type tunableSetArgs struct { @@ -328,9 +328,10 @@ func (b *Bridge) handleTunableSet(_ context.Context, raw json.RawMessage) (any, return nil, fmt.Errorf("mcp: tunable %q expects %s, got null", info.Name, info.Type) } + // Decode the JSON value into the tunable's Go type; SetTunable then checks the type again, clamps and writes under one lock, so a tunable re-registered in between is never written with stale bounds. var ( - typedVal any - clamped bool + typedVal any + saturated bool ) switch info.Type { case "float": @@ -341,36 +342,13 @@ func (b *Bridge) handleTunableSet(_ context.Context, raw json.RawMessage) (any, } return nil, fmt.Errorf("mcp: tunable %q expects float, got %s", info.Name, jsonValueKind(rawVal)) } - if math.IsNaN(v) || math.IsInf(v, 0) { - return nil, fmt.Errorf("mcp: tunable %q requires a finite float", info.Name) - } - if args.Clamp { - if minF, ok := info.Min.(float64); ok && !math.IsNaN(minF) && !math.IsInf(minF, 0) && v < minF { - v = minF - clamped = true - } - if maxF, ok := info.Max.(float64); ok && !math.IsNaN(maxF) && !math.IsInf(maxF, 0) && v > maxF { - v = maxF - clamped = true - } - } typedVal = v case "int": - v, err := decodeStrictInt(info.Name, rawVal) + v, sat, err := decodeStrictInt(info.Name, rawVal, args.Clamp) if err != nil { return nil, err } - if args.Clamp { - if minI, ok := info.Min.(int); ok && v < minI { - v = minI - clamped = true - } - if maxI, ok := info.Max.(int); ok && v > maxI { - v = maxI - clamped = true - } - } - typedVal = v + typedVal, saturated = v, sat case "bool": var v bool if err := json.Unmarshal(rawVal, &v); err != nil { @@ -387,53 +365,68 @@ func (b *Bridge) handleTunableSet(_ context.Context, raw json.RawMessage) (any, return nil, fmt.Errorf("mcp: unsupported tunable type %q for %q", info.Type, info.Name) } - oldVal, newVal, err := c.SetTunable(args.Name, typedVal) + ch, err := c.SetTunable(args.Name, typedVal, args.Clamp) if err != nil { return nil, fmt.Errorf("mcp: %w", err) } + after := tunableResultFrom(ch.Tunable) return TunableSetResult{ - Name: info.Name, - Type: info.Type, - OldValue: sanitizeJSONNumber(oldVal), - Value: sanitizeJSONNumber(newVal), - Default: sanitizeJSONNumber(info.Default), - Min: sanitizeJSONNumber(info.Min), - Max: sanitizeJSONNumber(info.Max), - Clamped: clamped, + Name: after.Name, + Type: after.Type, + OldValue: sanitizeJSONNumber(ch.Old), + Value: after.Value, + Default: after.Default, + Min: after.Min, + Max: after.Max, + Clamped: ch.Clamped || saturated, }, nil } -func decodeStrictInt(name string, raw []byte) (int, error) { +// decodeStrictInt decodes an integral JSON number for the int tunable name. A number beyond int's range is refused, or with clamp returned as math.MinInt or math.MaxInt with saturated set, so SetTunable clamps it to the tunable's bound. +func decodeStrictInt(name string, raw []byte, clamp bool) (v int, saturated bool, err error) { if kind := jsonValueKind(raw); kind != "number" { - return 0, fmt.Errorf("mcp: tunable %q expects int, got %s", name, kind) + return 0, false, fmt.Errorf("mcp: tunable %q expects int, got %s", name, kind) } var i int if err := json.Unmarshal(raw, &i); err == nil { - return i, nil + return i, false, nil } var f float64 if err := json.Unmarshal(raw, &f); err != nil || math.IsNaN(f) || math.IsInf(f, 0) { - return 0, fmt.Errorf("mcp: tunable %q expects int, got invalid number %s", name, string(raw)) + return 0, false, fmt.Errorf("mcp: tunable %q expects int, got invalid number %s", name, string(raw)) } + // Checked before big.Rat so a huge exponent is never expanded. if f < float64(math.MinInt) || f > float64(math.MaxInt) { - return 0, fmt.Errorf("mcp: tunable %q integer %s overflows int", name, string(raw)) + if f != math.Trunc(f) { + return 0, false, fmt.Errorf("mcp: tunable %q expects int, got non-integer number %s", name, string(raw)) + } + if !clamp { + return 0, false, fmt.Errorf("mcp: tunable %q integer %s overflows int", name, string(raw)) + } + if f < 0 { + return math.MinInt, true, nil + } + return math.MaxInt, true, nil } r, ok := new(big.Rat).SetString(string(raw)) if !ok { - return 0, fmt.Errorf("mcp: tunable %q expects int, got invalid number %s", name, string(raw)) + return 0, false, fmt.Errorf("mcp: tunable %q expects int, got invalid number %s", name, string(raw)) } if !r.IsInt() { - return 0, fmt.Errorf("mcp: tunable %q expects int, got non-integer number %s", name, string(raw)) + return 0, false, fmt.Errorf("mcp: tunable %q expects int, got non-integer number %s", name, string(raw)) } num := r.Num() - if !num.IsInt64() { - return 0, fmt.Errorf("mcp: tunable %q integer %s overflows int", name, string(raw)) - } - v64 := num.Int64() - if v64 < math.MinInt || v64 > math.MaxInt { - return 0, fmt.Errorf("mcp: tunable %q integer %s overflows int", name, string(raw)) + if !num.IsInt64() || num.Int64() < math.MinInt || num.Int64() > math.MaxInt { + // f rounded into int's range although the exact number lies just past it. + if !clamp { + return 0, false, fmt.Errorf("mcp: tunable %q integer %s overflows int", name, string(raw)) + } + if num.Sign() < 0 { + return math.MinInt, true, nil + } + return math.MaxInt, true, nil } - return int(v64), nil + return int(num.Int64()), false, nil } func jsonValueKind(raw []byte) string { diff --git a/packages/game/mcp/console_test.go b/packages/game/mcp/console_test.go index a889547d..ab2ff189 100644 --- a/packages/game/mcp/console_test.go +++ b/packages/game/mcp/console_test.go @@ -8,7 +8,9 @@ import ( "strconv" "strings" "testing" + "time" + "github.com/nsgo-dev/game/packages/game" "github.com/nsgo-dev/game/packages/game/debug" "github.com/nsgo-dev/game/packages/game/entities" "github.com/nsgo-dev/game/packages/game/mcp" @@ -16,10 +18,12 @@ import ( "github.com/nsgo-dev/nsgo/nsgotest" ) -// TestTunablesChangeAffectsLiveSimulation verifies the end-to-end acceptance -// flow: an agent lists tunables, reads physics parameters, raises jump_speed -// and lowers gravity via game_tunable_set, steps the live simulation, and sees -// the player reach a measurably higher apex via game_component_get. +// jumpComp records the highest point of the player's current jump. +type jumpComp struct { + Apex float32 `json:"apex"` +} + +// TestTunablesChangeAffectsLiveSimulation is the acceptance flow of #466: an agent lists tunables, starts a jump with game_console_exec, steps the running game.Loop with game_loop_step and reads the apex with game_component_get, then raises jump_speed and lowers gravity with game_tunable_set and sees the next jump reach a far higher apex. func TestTunablesChangeAffectsLiveSimulation(t *testing.T) { gravity := 800.0 jumpSpeed := 300.0 @@ -41,32 +45,41 @@ func TestTunablesChangeAffectsLiveSimulation(t *testing.T) { player := world.Spawn() entities.Set(world, player, posComp{X: 0, Y: 0}) - // Simulate a single jump from Y=0 using the live tunable pointers and record the peak height. - simulateJumpApex := func() float64 { - y := 0.0 - vy := jumpSpeed - peak := 0.0 - const dt = 1.0 / 60.0 - for range 240 { - vy -= gravity * dt - y += vy * dt - if y > peak { - peak = y - } - if y <= 0 && vy < 0 { - break + if err := entities.RegisterCodec[jumpComp](world, "jump"); err != nil { + t.Fatal(err) + } + entities.Set(world, player, jumpComp{}) + + // The game's own fixed-step physics reads the tunables through their pointers on every update. + var y, vy, apex float64 + console.RegisterCommand("jump", "jump - launch the player at player.jump_speed", func([]string) (string, error) { + y, vy, apex = 0, jumpSpeed, 0 + return "jump", nil + }) + loop := &game.Loop{ + Rate: 60, + Paused: true, + Update: func(dt time.Duration) { + s := dt.Seconds() + vy -= gravity * s + y += vy * s + if y <= 0 { + y, vy = 0, 0 } - } - entities.Set(world, player, posComp{X: 0, Y: float32(peak)}) - return peak + apex = max(apex, y) + entities.Set(world, player, posComp{X: 0, Y: float32(y)}) + entities.Set(world, player, jumpComp{Apex: float32(apex)}) + }, } var cx *core.Scope app := nsgotest.Start(t, func(scope *core.Scope) core.Node { cx = scope world.Attach(cx) + loop.Run(cx) if _, err := mcp.Attach(cx, mcp.Config{ World: world, + Loop: loop, Console: console, }); err != nil { t.Fatal(err) @@ -74,6 +87,28 @@ func TestTunablesChangeAffectsLiveSimulation(t *testing.T) { return core.View{} }) + // jumpApex jumps through the console, steps the loop for four seconds of game time, and reads the apex back. + jumpApex := func() float64 { + t.Helper() + exec := callTool[mcp.ConsoleExecResult](t, app, cx, mcp.ToolConsoleExec, map[string]any{"command": "jump"}) + if !exec.OK { + t.Fatalf("game_console_exec(jump) = %+v", exec) + } + step := callTool[mcp.LoopStepResult](t, app, cx, mcp.ToolLoopStep, map[string]any{"count": 240}) + if step.StepsAdvanced != 240 { + t.Fatalf("game_loop_step = %+v, want 240 steps", step) + } + comp := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ + "ref": mcp.FormatEntityRef(player), + "component": "jump", + }) + var j jumpComp + if err := json.Unmarshal(comp.Value, &j); err != nil { + t.Fatal(err) + } + return float64(j.Apex) + } + // 1. List all tunables and verify deterministic sorted order and metadata (including min=0). listRaw, err := callToolRaw(t, app, cx, mcp.ToolTunablesList, nil) if err != nil { @@ -106,23 +141,15 @@ func TestTunablesChangeAffectsLiveSimulation(t *testing.T) { } // 2. Read a single tunable before changing it. - gotJump := callTool[mcp.TunableInfo](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "player.jump_speed"}) + gotJump := callTool[mcp.TunableResult](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "player.jump_speed"}) if gotJump.Type != "float" || gotJump.Value != 300.0 || gotJump.Default != 300.0 || gotJump.Min != 100.0 || gotJump.Max != 1200.0 { t.Fatalf("tunable get(player.jump_speed) = %+v", gotJump) } - // Baseline jump height with default tunables. - var baselinePeak float64 - app.Post(func() { baselinePeak = simulateJumpApex() }) - app.Settle() - - baseComp := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ - "ref": mcp.FormatEntityRef(player), - "component": "position", - }) - var basePos posComp - if err := json.Unmarshal(baseComp.Value, &basePos); err != nil { - t.Fatal(err) + // Baseline jump with the registered values: about 300²/(2·800) = 56 units. + baselineApex := jumpApex() + if baselineApex < 50 || baselineApex > 60 { + t.Fatalf("baseline apex = %v, want about 56", baselineApex) } // 3. Agent changes float, int, bool and string tunables via game_tunable_set. @@ -166,22 +193,10 @@ func TestTunablesChangeAffectsLiveSimulation(t *testing.T) { t.Fatalf("set level.name = %+v, var=%q", setLevel, levelName) } - // 4. Re-run jump simulation and verify the agent sees the dramatic height increase! - var boostedPeak float64 - app.Post(func() { boostedPeak = simulateJumpApex() }) - app.Settle() - - boostedComp := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ - "ref": mcp.FormatEntityRef(player), - "component": "position", - }) - var boostedPos posComp - if err := json.Unmarshal(boostedComp.Value, &boostedPos); err != nil { - t.Fatal(err) - } - if boostedPeak <= baselinePeak*4 || float64(boostedPos.Y) <= float64(basePos.Y)*4 { - t.Fatalf("expected tunable change to increase jump apex >4x: baseline=%v (%v) boosted=%v (%v)", - baselinePeak, basePos.Y, boostedPeak, boostedPos.Y) + // 4. The next jump in the running loop uses the new values: about 600²/(2·400) = 450 units. + boostedApex := jumpApex() + if boostedApex <= baselineApex*4 { + t.Fatalf("apex after game_tunable_set = %v, want more than 4x the baseline %v", boostedApex, baselineApex) } // 5. Optional clamp clamps out-of-range numeric values cleanly and reports clamped=true. @@ -207,7 +222,7 @@ func TestTunablesChangeAffectsLiveSimulation(t *testing.T) { t.Fatalf("whole float int = %+v, var=%d", wholeFloatInt, maxJumps) } // Reading back reflects current value while preserving original registration default. - afterJump := callTool[mcp.TunableInfo](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "player.jump_speed"}) + afterJump := callTool[mcp.TunableResult](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "player.jump_speed"}) if math.Abs(afterJump.Value.(float64)-1200) > 1e-9 || math.Abs(afterJump.Default.(float64)-300) > 1e-9 { t.Fatalf("after get = %+v", afterJump) } @@ -451,14 +466,23 @@ func TestConsoleDynamicResolutionAndErrors(t *testing.T) { t.Fatalf("scientific int = %+v, lives=%d", sciInt, lives) } - // Non-finite runtime floats serialize safely as "NaN"/"+Inf" rather than failing JSON encoding, - // and can be inspected and recovered via game_tunable_set. + // With clamp, an integer beyond int's range is clamped to the tunable's bound like any other out-of-range value. + overMax := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, `{"name":"lives","value":1e30,"clamp":true}`) + if overMax.Value != 10.0 || !overMax.Clamped || lives != 10 { + t.Fatalf("clamped 1e30 = %+v, lives=%d", overMax, lives) + } + underMin := callTool[mcp.TunableSetResult](t, app, cx, mcp.ToolTunableSet, `{"name":"lives","value":-1e30,"clamp":true}`) + if underMin.Value != 1.0 || !underMin.Clamped || lives != 1 { + t.Fatalf("clamped -1e30 = %+v, lives=%d", underMin, lives) + } + + // Non-finite runtime floats serialize safely as "NaN"/"+Inf" rather than failing JSON encoding, and can be inspected and recovered via game_tunable_set. speed = math.NaN() nanList := callTool[mcp.TunablesListResult](t, app, cx, mcp.ToolTunablesList, map[string]any{"prefix": "speed"}) if nanList.Total != 1 || nanList.Tunables[0].Value != "NaN" { t.Fatalf("nan list = %+v, want Value=\"NaN\"", nanList) } - nanGet := callTool[mcp.TunableInfo](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "speed"}) + nanGet := callTool[mcp.TunableResult](t, app, cx, mcp.ToolTunableGet, map[string]any{"name": "speed"}) if nanGet.Value != "NaN" { t.Fatalf("nan get = %+v, want Value=\"NaN\"", nanGet) }