GitHub시작하기

API 레퍼런스는 소스 코드의 Go 문서 주석에서 추출되며 영어로 작성되어 있습니다.

package mcp

import "github.com/nsgo-dev/game/pkg/mcp"

개요

Package mcp exposes a running NSGo game's state to coding agents over MCP through github.com/nsgo-dev/nsgo/automation.

NSGo's built-in `nsgo mcp` server inspects native views, whereas a game draws into a single Canvas or GPU view. Attaching a Bridge to a core.Scope registers game-specific tools via automation.Register so `nsgo mcp` serves them automatically alongside the built-in tools:

  • game_scenes_list: list active scenes on the scene stack and any registered named scenes, including the current scene and transition progress.
  • game_layers_list: list layers of a scene in draw order with visibility, z-order, coordinate space, parallax, depth sort and item counts.
  • game_entities_list: list live entities with stable generational references ("entity:<index>:<generation>") across steps, hierarchy links and component names.
  • game_entity_inspect: inspect a single live entity by its stable reference, returning metadata, hierarchy links and all readable component values.
  • game_component_get: read one component's value on a live entity by reference and component name.
  • game_loop_status: report the game loop's paused state, effective time scale, fixed step rate, total steps, simulated game time and whether random seeding is configured.
  • game_loop_pause: pause the game loop without accumulating a catch-up backlog.
  • game_loop_resume: resume a paused game loop.
  • game_loop_step: synchronously advance the game loop by N fixed updates (1..3600, default 1), advancing exact simulated game time.
  • game_loop_time_scale: set the game loop's simulation time scale (finite, >= 0; 0 resets to the default 1x speed).
  • game_loop_seed: set the deterministic random seed via Config.Random, Config.RandomStreams and/or Config.SetSeed.
  • game_input_action: inject a press, release, tap, or analog axis value for a named action on input.Actions.
  • 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.
  • game_prefabs_list: list registered prefabs available to game_entity_spawn.
  • game_entity_spawn: spawn a registered prefab or empty entity with optional parent, position and component overrides.
  • game_entity_destroy: destroy a live entity by stable reference with an optional hierarchy child policy.
  • game_component_set: set or patch a component's value on a live entity so the change takes effect on the next simulation step.
  • game_component_remove: remove a component from a live entity.
  • game_replay_status: report input recording and playback status, frame progress and saved recordings.
  • game_replay_record_start: start recording per-step inputs into a named recording.
  • game_replay_record_stop: stop the active recording, store it and return its deterministic YAML text and summary.
  • game_replay_play: replay a stored or inline YAML recording deterministically, optionally resetting and running to completion.
  • game_replay_stop: stop an active replay playback cleanly.
  • game_replay_list: list stored recordings with frame counts, seeds, step rates and metadata.
  • game_perf_readout: read live frame timing (FPS, frame/update/draw costs and percentiles), draw statistics, allocations per frame, heap/GC counters, asset memory, and optional frame history or profiler zones matching the debug overlay.
  • game_perf_zones: list named profiler timing zones sorted by recent per-frame cost.
  • game_perf_reset: reset accumulated debug overlay frame timings, pushed draw statistics, profiler zones and GC monitor history.
  • game_assets_list: list loaded asset groups, asset keys/types, load states, and estimated memory usage in bytes.
  • game_asset_reload: reload a named asset, URI, or path (or all loaded assets) in place and report structured reload diagnostics.
  • game_assets_reload_group: reload every loaded asset in a named asset group in place.
  • game_screenshot: capture the game view as PNG, optionally with aligned sprite bounds, physics collision shapes, reference grid, camera frame and labels drawn on top.

Components registered on an entities.World with entities.RegisterCodec are readable and editable automatically. Transient or non-saved components can also be exposed with RegisterComponent, RegisterComponentFunc, RegisterMutableComponent or RegisterComponentEditor, and built-in entities.Transform2D, entities.WorldTransform2D and sceneformat.ObjectRef components are surfaced automatically when present and not already registered under another name. Prefabs can be registered via Config.Prefabs, Bridge.RegisterPrefab, Bridge.RegisterEntityPrefab or Bridge.RegisterScenePrefab.

Like automation.Register, attachment is active in `nsgo dev -automation` and test builds (`nsgo test`) and is a no-op in ordinary and release builds. Call Attach, Bridge.Attach and Bridge.Detach on the engine goroutine.

색인

상수

const (
	// ToolAssetsList lists asset groups, asset keys/types, load states, and estimated memory usage in bytes.
	ToolAssetsList = "game_assets_list"
	// ToolAssetReload reloads a single named asset, URI, or path (or all loaded assets) in place.
	ToolAssetReload = "game_asset_reload"
	// ToolAssetsReloadGroup reloads every loaded asset in a named asset group in place.
	ToolAssetsReloadGroup = "game_assets_reload_group"
)

Asset and hot-reload tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation.

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"
)

Tool names for debug console and tunable tools registered by Bridge.

const (
	// ToolPrefabsList lists registered prefabs available to game_entity_spawn.
	ToolPrefabsList = "game_prefabs_list"
	// ToolEntitySpawn spawns a registered prefab or an empty entity with optional parent, position and component overrides.
	ToolEntitySpawn = "game_entity_spawn"
	// ToolEntityDestroy destroys a live entity by stable reference with an optional hierarchy child policy.
	ToolEntityDestroy = "game_entity_destroy"
	// ToolComponentSet sets or patches one component's value on a live entity.
	ToolComponentSet = "game_component_set"
	// ToolComponentRemove removes one component from a live entity.
	ToolComponentRemove = "game_component_remove"
)

Tool names for object mutation registered by Bridge with github.com/nsgo-dev/nsgo/automation.

const (
	// ToolInputAction injects a press, release, tap, or analog value for a named input action.
	ToolInputAction = "game_input_action"
	// ToolInputAxis injects or clears one or more analog axis values in [-1, 1].
	ToolInputAxis = "game_input_axis"
	// ToolInputPointer injects a pointer press, release, move, or click in game (or world) coordinates mapped through the viewport.
	ToolInputPointer = "game_input_pointer"
	// ToolInputActionsList lists configured actions and axes along with their current step state.
	ToolInputActionsList = "game_input_actions_list"
)

Input injection tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation.

const (
	// ToolLoopStatus reports the game loop's current paused state, time scale, step rate, step count and simulated game time.
	ToolLoopStatus = "game_loop_status"
	// ToolLoopPause pauses the game loop's fixed updates without accumulating a catch-up backlog.
	ToolLoopPause = "game_loop_pause"
	// ToolLoopResume resumes a paused game loop.
	ToolLoopResume = "game_loop_resume"
	// ToolLoopStep synchronously advances the game loop by a requested number of fixed updates.
	ToolLoopStep = "game_loop_step"
	// ToolLoopTimeScale sets the game loop's simulation time scale.
	ToolLoopTimeScale = "game_loop_time_scale"
	// ToolLoopSeed sets the game's deterministic random seed.
	ToolLoopSeed = "game_loop_seed"
)

Loop-control tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation.

const (
	// ToolScenesList lists active scenes on the stack and any registered named scenes.
	ToolScenesList = "game_scenes_list"
	// ToolLayersList lists layers in a scene in draw order.
	ToolLayersList = "game_layers_list"
	// ToolEntitiesList lists live entities with stable generational references.
	ToolEntitiesList = "game_entities_list"
	// ToolEntityInspect reads a single live entity's metadata, hierarchy and component values.
	ToolEntityInspect = "game_entity_inspect"
	// ToolComponentGet reads one component's value on a live entity.
	ToolComponentGet = "game_component_get"
)

Tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation.

const (
	// ToolPerfReadout reads live frame timing, draw statistics, allocation/GC telemetry, and optional frame history or profiler zones.
	ToolPerfReadout = "game_perf_readout"
	// ToolPerfZones lists named profiler timing zones sorted by recent cost.
	ToolPerfZones = "game_perf_zones"
	// ToolPerfReset resets accumulated overlay frame stats, profiler zones, and GC monitor history.
	ToolPerfReset = "game_perf_reset"
)

Performance readout tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation.

const (
	// ToolReplayStatus reports current recording/playback state, frame progress and saved recording names.
	ToolReplayStatus = "game_replay_status"
	// ToolReplayRecordStart starts recording fixed-step inputs into a named recording.
	ToolReplayRecordStart = "game_replay_record_start"
	// ToolReplayRecordStop stops the active recording, stores it and returns its deterministic YAML text and summary.
	ToolReplayRecordStop = "game_replay_record_stop"
	// ToolReplayPlay starts replaying a stored recording by name or an inline YAML recording.
	ToolReplayPlay = "game_replay_play"
	// ToolReplayStop stops an active replay playback.
	ToolReplayStop = "game_replay_stop"
	// ToolReplayList lists stored recordings with their frame counts, seeds, step rates and metadata.
	ToolReplayList = "game_replay_list"
)

Replay tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation.

const MaxLoopSteps = 3600

MaxLoopSteps is the maximum number of fixed updates a single game_loop_step call may advance.

const ToolScreenshot = "game_screenshot"

ToolScreenshot captures the game view as a PNG image, optionally with aligned sprite bounds, physics collision shapes, reference grid, camera frame and label overlays drawn on top.

변수

var (
	// ErrEmptyAssetKey reports registering a custom asset with an empty key.
	ErrEmptyAssetKey = errors.New("mcp: empty asset key")
	// ErrDuplicateAsset reports registering a custom asset key that is already registered on the Bridge.
	ErrDuplicateAsset = errors.New("mcp: duplicate asset registration")
)
var (
	// ErrEmptyPrefabName reports registering a prefab with an empty name.
	ErrEmptyPrefabName = errors.New("mcp: empty prefab name")
	// ErrDuplicatePrefab reports registering a prefab name that is already registered on the Bridge.
	ErrDuplicatePrefab = errors.New("mcp: duplicate prefab registration")
)
var (
	// ErrNilBridge reports an operation attempted on a nil Bridge.
	ErrNilBridge = errors.New("mcp: nil bridge")
	// ErrAlreadyAttached reports calling Bridge.Attach on a Bridge that is already attached to a live scope.
	ErrAlreadyAttached = errors.New("mcp: bridge is already attached")
	// ErrEmptyComponentName reports registering a component inspector with an empty name.
	ErrEmptyComponentName = errors.New("mcp: empty component name")
	// ErrDuplicateComponent reports registering a component name that is already registered on the Bridge.
	ErrDuplicateComponent = errors.New("mcp: duplicate component registration")
)
var (
	// ErrReplayNotConfigured reports a replay tool call on a Bridge without a configured ReplayController.
	ErrReplayNotConfigured = errors.New("mcp: no replay controller configured")
	// ErrAlreadyRecording reports starting a recording while another recording is already active.
	ErrAlreadyRecording = errors.New("mcp: recording is already in progress")
	// ErrNotRecording reports stopping a recording when none is active.
	ErrNotRecording = errors.New("mcp: no recording in progress")
	// ErrAlreadyReplaying reports starting a recording or replay while playback is already in progress.
	ErrAlreadyReplaying = errors.New("mcp: replay is already in progress")
	// ErrNotReplaying reports stopping a replay when none is active.
	ErrNotReplaying = errors.New("mcp: no replay in progress")
)

함수

func FormatEntityRef(e entities.Entity) string

FormatEntityRef formats e as a stable generational reference string ("entity:<index>:<generation>") usable across MCP calls and simulation steps. It returns "" for entities.Zero.

func ParseEntityRef(ref string) (entities.Entity, error)

ParseEntityRef parses a reference returned by FormatEntityRef back into an entities.Entity handle. It refuses malformed strings and zero generations.

func RegisterComponent[T any](b *Bridge, name string) error

RegisterComponent registers a typed component inspector for component type T under name on b.

Use this to expose runtime components that are not registered with entities.RegisterCodec on the World, or to override how a component is named or inspected.

func RegisterComponentEditor[T any](b *Bridge, name string, apply func(w *entities.World, e entities.Entity, v T) error) error

RegisterComponentEditor registers a typed component editor for component type T under name on b.

When name is not yet registered on b, it also registers inspection and removal for T. When name was previously registered read-only with RegisterComponent[T] for the same type T, it attaches the editor to that registration. It refuses a name registered with RegisterComponentFunc, whose reader may expose data that is not stored as T, and a name registered for another type. apply receives the strictly decoded and finite-validated value and may enforce domain invariants or synchronize secondary runtime state before writing.

func RegisterComponentFunc(b *Bridge, name string, read func(w *entities.World, e entities.Entity) (any, bool, error)) error

RegisterComponentFunc registers a custom component reader under name on b. read returns (value, true, nil) when entity e carries the component, (nil, false, nil) when absent, or an error.

func RegisterMutableComponent[T any](b *Bridge, name string) error

RegisterMutableComponent registers component type T under name on b for both inspection (game_entities_list, game_entity_inspect, game_component_get) and mutation (game_component_set, game_component_remove, game_entity_spawn).

Edits are strictly decoded with DisallowUnknownFields, validated against NaN/Inf floats, and written with entities.Set[T].

타입

type AssetEntry struct {
	Key      string `json:"key"`
	Kind     string `json:"kind"`
	URI      string `json:"uri,omitempty"`
	ImageURI string `json:"image_uri,omitempty"`
	Loaded   bool   `json:"loaded"`
	Bytes    int64  `json:"bytes"`
	Frames   int    `json:"frames,omitempty"`
}

AssetEntry describes one asset within an asset group returned by game_assets_list.

type AssetGroupSummary struct {
	Name   string       `json:"name"`
	Source string       `json:"source"`
	State  string       `json:"state"`
	Loaded int          `json:"loaded"`
	Total  int          `json:"total"`
	Bytes  int64        `json:"bytes"`
	Error  string       `json:"error,omitempty"`
	Assets []AssetEntry `json:"assets"`
}

AssetGroupSummary describes one asset group and its estimated memory usage returned by game_assets_list.

type AssetReloadResult struct {
	Reloaded   bool           `json:"reloaded"`
	Key        string         `json:"key,omitempty"`
	Group      string         `json:"group,omitempty"`
	Kind       string         `json:"kind,omitempty"`
	Bytes      int64          `json:"bytes"`
	DurationMS float64        `json:"duration_ms"`
	Revision   int            `json:"revision,omitempty"`
	Items      []ReloadedItem `json:"items,omitempty"`
	Error      string         `json:"error,omitempty"`
}

AssetReloadResult is the JSON result of game_asset_reload.

type AssetsListResult struct {
	Revision   int                 `json:"revision,omitempty"`
	GroupCount int                 `json:"group_count"`
	AssetCount int                 `json:"asset_count"`
	TotalBytes int64               `json:"total_bytes"`
	Groups     []AssetGroupSummary `json:"groups"`
}

AssetsListResult is the JSON result of game_assets_list.

type AssetsReloadGroupResult struct {
	Group      string         `json:"group"`
	Reloaded   bool           `json:"reloaded"`
	Count      int            `json:"count"`
	Failed     int            `json:"failed,omitempty"`
	Skipped    int            `json:"skipped,omitempty"`
	Bytes      int64          `json:"bytes"`
	DurationMS float64        `json:"duration_ms"`
	Revision   int            `json:"revision,omitempty"`
	Items      []ReloadedItem `json:"items"`
	Error      string         `json:"error,omitempty"`
}

AssetsReloadGroupResult is the JSON result of game_assets_reload_group.

type Bridge struct {
	// contains filtered or unexported fields
}

Bridge exposes a running game's subsystems to nsgo mcp via automation.Register.

Create a Bridge with New or Attach, optionally register additional component inspectors, editors or prefabs, and attach it to a core.Scope on the engine goroutine. Disposing the scope or calling Detach unregisters every tool automatically.

func Attach(cx *core.Scope, cfg Config) (*Bridge, error)

Attach constructs a Bridge for cfg and registers its tools on cx until cx is disposed. Call it on the engine goroutine.

func New(cfg Config) *Bridge

New constructs a Bridge for cfg without registering its tools yet. Call Bridge.Attach on the engine goroutine to register its tools on a core.Scope.

func (b *Bridge) Attach(cx *core.Scope) error

Attach registers all of b's tools on a child scope of cx via automation.Register. If any registration fails, all tools registered by this call are cleaned up before returning the error. Call Attach on the engine goroutine.

func (b *Bridge) Attached() bool

Attached reports whether b is currently attached to a live scope.

func (b *Bridge) Detach()

Detach unregisters all tools registered by b on its attached scope. Calling Detach when b is nil or not attached is a no-op.

func (b *Bridge) RegisterAsset(asset CustomAsset) error

RegisterAsset registers a custom game-managed asset on b for game_assets_list and game_asset_reload.

func (b *Bridge) RegisterAtlas(key, group, jsonPath string, atlas *sprite.Atlas, readFile func(ctx context.Context, path string) ([]byte, error)) error

RegisterAtlas registers a standalone live *sprite.Atlas (not owned by an assets.Manager) on b so game_assets_list reports its frame count and estimated memory, and game_asset_reload re-parses jsonPath via readFile and updates *atlas in place without replacing the pointer.

func (b *Bridge) RegisterEntityPrefab(p *entities.Prefab) error

RegisterEntityPrefab registers an *entities.Prefab under its Prefab.Name on b for game_prefabs_list and game_entity_spawn.

func (b *Bridge) RegisterPrefab(name string, spawn PrefabSpawner) error

RegisterPrefab registers a custom prefab spawner under name on b for game_prefabs_list and game_entity_spawn.

func (b *Bridge) RegisterScenePrefab(name string, doc *sceneformat.SceneDoc) error

RegisterScenePrefab registers a self-contained *sceneformat.SceneDoc template under name on b so game_entity_spawn can instantiate it via sceneformat.SpawnEntities.

doc must pass sceneformat.Validate, must not refer to unresolved external scenes, and must hold exactly one top-level object across its layers, which becomes the spawned root entity; nest every other object under it as a child. Each spawn attaches the document's sceneformat.ObjectRef IDs unchanged, so repeated spawns produce entities with the same object IDs and names.

func (b *Bridge) Replay() *ReplayController

Replay returns the ReplayController configured on b, or nil if none is set.

func (b *Bridge) SetActions(a *input.Actions)

SetActions replaces the static Actions configured on b. If Config.ActionsFunc is set and returns a non-nil *input.Actions, ActionsFunc continues to take precedence.

func (b *Bridge) SetAssets(m *assets.Manager)

SetAssets replaces the static Assets manager configured on b. If Config.AssetsFunc is set and returns a non-nil manager, AssetsFunc continues to take precedence.

func (b *Bridge) SetConsole(c *debug.Console)

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) SetLoop(l *game.Loop)

SetLoop replaces the static Loop configured on b. If Config.LoopFunc is set and returns a non-nil loop, LoopFunc continues to take precedence.

func (b *Bridge) SetPhysics(w *physics.World)

SetPhysics replaces the static 2D physics world configured on b. If Config.PhysicsFunc is set and returns a non-nil world, PhysicsFunc continues to take precedence.

func (b *Bridge) SetReplay(ctrl *ReplayController)

SetReplay replaces the ReplayController configured on b.

func (b *Bridge) SetRigidPhysics(w *physics.RigidWorld)

SetRigidPhysics replaces the static 2D rigid-body physics world configured on b. If Config.RigidPhysicsFunc is set and returns a non-nil world, RigidPhysicsFunc continues to take precedence.

func (b *Bridge) SetScene(s *scene.Scene)

SetScene replaces the static standalone Scene configured on b. If Config.Scenes has an active scene or Config.SceneFunc returns a non-nil scene, those take precedence.

func (b *Bridge) SetViewport(vp *screen.Viewport)

SetViewport replaces the static Viewport configured on b. If Config.ViewportFunc is set and returns a viewport with positive dimensions, ViewportFunc continues to take precedence.

func (b *Bridge) SetWorld(w *entities.World)

SetWorld replaces the static World configured on b. If Config.WorldFunc is set and returns a non-nil world, WorldFunc continues to take precedence.

func (b *Bridge) Tools() []automation.Tool

Tools returns the full set of automation.Tool definitions owned by b, assembled from each tool group.

type CameraInfo struct {
	X        float32 `json:"x"`
	Y        float32 `json:"y"`
	Zoom     float32 `json:"zoom"`
	Rotation float32 `json:"rotation,omitempty"`
	Width    float32 `json:"width"`
	Height   float32 `json:"height"`
}

CameraInfo describes a 2D scene's camera state.

type ComponentGetResult struct {
	Ref       string          `json:"ref"`
	Component string          `json:"component"`
	Value     json.RawMessage `json:"value"`
}

ComponentGetResult is the JSON result of game_component_get.

type ComponentRemoveResult struct {
	Ref       string `json:"ref"`
	Component string `json:"component"`
	Removed   bool   `json:"removed"`
}

ComponentRemoveResult is the JSON result of game_component_remove.

type ComponentSetResult struct {
	Ref       string          `json:"ref"`
	Component string          `json:"component"`
	Value     json.RawMessage `json:"value"`
	// ReadError is set when the write succeeded but reading the component back failed; Value is then null.
	ReadError string `json:"read_error,omitempty"`
}

ComponentSetResult is the JSON result of game_component_set.

type Config struct {
	// Scenes is the game's scene stack manager. When set, game_scenes_list reports the active stack and transition state, and game_layers_list defaults to the current scene.
	Scenes *scene.Manager

	// Scene is a standalone active scene for games that do not use a scene.Manager.
	Scene *scene.Scene

	// SceneFunc dynamically resolves the active scene on each tool call (for example, when restarting a level allocates a new *scene.Scene). When non-nil and returning a non-nil scene, it overrides Scene.
	SceneFunc func() *scene.Scene

	// SceneName maps a scene.Controller on Scenes's stack to a human-readable name such as "title", "gameplay" or "pause". When nil or returning "", stack entries receive stable fallback names ("scene:0", "scene:1", ...).
	SceneName func(*scene.Controller) string

	// NamedScenes registers additional named scenes (active or inactive) so game_scenes_list lists them and game_layers_list can inspect them by name.
	NamedScenes map[string]*scene.Scene

	// World is the game's ECS entity world for entity and component inspection tools.
	World *entities.World

	// WorldFunc dynamically resolves the active entity world on each tool call (for example, when switching levels replaces the *entities.World). When non-nil and returning a non-nil world, it overrides World.
	WorldFunc func() *entities.World

	// EntityName returns a human-readable name for a live entity (such as "player" or "slime_1"). When nil or returning "", inspection falls back to sceneformat.ObjectRef.ID if attached.
	EntityName func(entities.Entity) string

	// EntityTags returns labels/tags attached to a live entity (such as ["enemy", "boss"]).
	EntityTags func(entities.Entity) []string

	// EntityLayer returns the scene layer name an entity belongs to. When nil or returning "", inspection falls back to sceneformat.ObjectRef.Layer if attached.
	EntityLayer func(entities.Entity) string
	// Loop is the game's fixed-step loop for pause, resume, synchronous stepping and time-scale tools.
	Loop *game.Loop

	// LoopFunc dynamically resolves the active game loop on each tool call. When non-nil and returning a non-nil loop, it overrides Loop.
	LoopFunc func() *game.Loop

	// Random is a deterministic random stream re-seeded by game_loop_seed.
	Random *random.Stream

	// RandomStreams is a named deterministic random stream manager re-seeded by game_loop_seed.
	RandomStreams *random.Streams

	// SetSeed is a custom callback invoked by game_loop_seed to apply a deterministic random seed.
	SetSeed func(uint64)

	// Actions is the game's input action map driven by game_input_action, game_input_axis, game_input_actions_list and game_input_pointer.
	Actions *input.Actions

	// ActionsFunc dynamically resolves the active input.Actions on each tool call. When non-nil and returning a non-nil *input.Actions, it overrides Actions.
	ActionsFunc func() *input.Actions

	// Viewport maps virtual game coordinates to view coordinates for game_input_pointer, and maps the game's virtual canvas onto the image when game_screenshot renders the game view and aligns overlays.
	Viewport *screen.Viewport

	// ViewportFunc dynamically resolves the active screen.Viewport on each tool call. When non-nil and returning a viewport with positive dimensions, it overrides Viewport.
	ViewportFunc func() screen.Viewport

	// ViewSizeFunc returns the current canvas/view size in points for Viewport.Layout and Viewport.GameToView.
	// When nil or returning a non-positive size, pointer mapping falls back to the attached scope's Env().Window(), and then to the viewport's virtual size.
	ViewSizeFunc func() core.Size

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

	// Prefabs registers named prefab spawners available to game_prefabs_list and game_entity_spawn. Additional prefabs (including *entities.Prefab and *sceneformat.SceneDoc templates) can also be registered on the Bridge via RegisterPrefab, RegisterEntityPrefab and RegisterScenePrefab.
	Prefabs map[string]PrefabSpawner

	// Replay configures input recording and deterministic playback tools.
	Replay *ReplayController

	// Overlay is the game's development debug overlay for frame timing, draw statistics, GC/allocation and asset memory readouts.
	Overlay *debug.Overlay

	// Profiler is a named-scope timing profiler. When nil, performance tools fall back to Overlay.Profiler().
	Profiler *debug.Profiler

	// GC is a per-frame GC and allocation monitor. When nil, performance tools fall back to Overlay.GC().
	GC *debug.GCMonitor

	// Memory is an asset memory tracker. When nil, performance tools fall back to Overlay.Memory().
	Memory *debug.MemoryTracker

	// DrawStatsFunc dynamically supplies per-frame draw statistics (draw calls, sprites, batches, triangles, vertices). When nil, performance tools fall back to Overlay.DrawStats() or RenderStatsFunc.
	DrawStatsFunc func() debug.DrawStats

	// RenderStatsFunc supplies 3D per-frame render statistics (culling, batching, state switches, geometry and GPU memory). A game using game/render3d returns mcp.PerfRender3DStats(stats) for its latest render3d.RenderStats.
	RenderStatsFunc func() PerfRender3DStats

	// Assets is the game's asset manager for listing loaded asset groups/memory and reloading assets or groups.
	Assets *assets.Manager

	// AssetsFunc dynamically resolves the active asset manager on each tool call. When non-nil and returning a non-nil manager, it overrides Assets.
	AssetsFunc func() *assets.Manager

	// Resources is an optional resource.Library whose loaded YAML resources are listed and can be reloaded by path.
	Resources *resource.Library

	// Shaders is an optional hotreload.ShaderReloader whose tracked shaders are listed and can be reloaded by name or path.
	Shaders *hotreload.ShaderReloader

	// Materials is an optional hotreload.MaterialReloader whose tracked materials are listed and can be reloaded by name or path.
	Materials *hotreload.MaterialReloader

	// ReloadAsset is an optional custom reload callback invoked by game_asset_reload when no configured asset manager, reloader or custom asset owns key.
	ReloadAsset func(ctx context.Context, key string) error

	// Physics is the game's 2D physics world used to draw collision shape overlays in game_screenshot.
	Physics *physics.World

	// PhysicsFunc dynamically resolves the active 2D physics world on each screenshot call. When non-nil and returning a non-nil world, it overrides Physics.
	PhysicsFunc func() *physics.World

	// RigidPhysics is an optional 2D rigid-body physics world whose bodies are drawn alongside Physics when collision shape overlays are enabled.
	RigidPhysics *physics.RigidWorld

	// RigidPhysicsFunc dynamically resolves the active 2D rigid-body physics world on each screenshot call. When non-nil and returning a non-nil world, it overrides RigidPhysics.
	RigidPhysicsFunc func() *physics.RigidWorld

	// DrawFrame optionally records the game's current frame into d for a target of width by height pixels. When nil, game_screenshot renders the active scene (from Scenes or Scene/SceneFunc) under Viewport if configured.
	DrawFrame func(d *core.Drawing, width, height int)

	// CaptureFrame optionally returns an already-rendered game frame (for example from a GPU readback or offscreen canvas). Requested overlays are composited on top in the same camera and viewport coordinates.
	CaptureFrame func(ctx context.Context) (*image.RGBA, error)

	// ScreenshotDir confines relative output paths written when game_screenshot is called with a path argument. When empty, writing to disk via path is refused.
	ScreenshotDir string

	// ScreenshotBackground optionally fills the screenshot canvas before drawing the game frame when CaptureFrame is nil. Zero leaves the background transparent.
	ScreenshotBackground core.Color
}

Config names the parts of a running game that MCP tools inspect and drive. Every field is optional; tools whose subsystem is unconfigured still register and return either an empty list or an explanatory error when called.

type ConsoleCommandInfo struct {
	Name    string `json:"name"`
	Help    string `json:"help,omitempty"`
	Builtin bool   `json:"builtin"`
}

ConsoleCommandInfo describes one debug console command returned by game_console_commands_list.

type ConsoleCommandsListResult struct {
	Total    int                  `json:"total"`
	Commands []ConsoleCommandInfo `json:"commands"`
}

ConsoleCommandsListResult is the JSON result of game_console_commands_list.

type ConsoleExecResult struct {
	Command string   `json:"command"`
	OK      bool     `json:"ok"`
	Output  string   `json:"output"`
	Lines   []string `json:"lines"`
	Error   string   `json:"error,omitempty"`
}

ConsoleExecResult is the JSON result of game_console_exec.

type CustomAsset struct {
	// Key is the unique asset identifier (required).
	Key string
	// Group is the asset group name reported by game_assets_list (defaults to "custom" when empty).
	Group string
	// Kind describes the asset type (e.g. "atlas", "image", "scene", "shader", "material", "sound", "bytes", "custom").
	Kind string
	// URI is an optional source path or URI shown in game_assets_list and matched by game_asset_reload.
	URI string
	// Bytes returns the asset's current estimated memory footprint in bytes (optional).
	Bytes func() int64
	// Frames returns the current frame count for atlas-like assets (optional).
	Frames func() int
	// Reload reloads the asset in place (optional).
	Reload func(ctx context.Context) error
}

CustomAsset registers a game-managed asset outside assets.Manager (such as a standalone sprite.Atlas, scene file, or data table) so game_assets_list reports its memory and game_asset_reload / game_assets_reload_group can reload it on demand.

type EntitiesListResult struct {
	Total    int             `json:"total"`
	Returned int             `json:"returned"`
	Entities []EntitySummary `json:"entities"`
}

EntitiesListResult is the JSON result of game_entities_list.

type EntityDestroyResult struct {
	Ref       string `json:"ref"`
	Policy    string `json:"policy"`
	Destroyed int    `json:"destroyed"`
}

EntityDestroyResult is the JSON result of game_entity_destroy.

type EntityInspectResult struct {
	Ref        string                     `json:"ref"`
	Index      uint32                     `json:"index"`
	Generation uint32                     `json:"generation"`
	Name       string                     `json:"name,omitempty"`
	Layer      string                     `json:"layer,omitempty"`
	Tags       []string                   `json:"tags,omitempty"`
	Parent     string                     `json:"parent,omitempty"`
	Children   []string                   `json:"children,omitempty"`
	Components map[string]json.RawMessage `json:"components"`
}

EntityInspectResult is the JSON result of game_entity_inspect.

type EntitySpawnResult struct {
	Ref        string                     `json:"ref"`
	Index      uint32                     `json:"index"`
	Generation uint32                     `json:"generation"`
	Prefab     string                     `json:"prefab,omitempty"`
	Name       string                     `json:"name,omitempty"`
	Layer      string                     `json:"layer,omitempty"`
	Tags       []string                   `json:"tags,omitempty"`
	Parent     string                     `json:"parent,omitempty"`
	Children   []string                   `json:"children,omitempty"`
	Components map[string]json.RawMessage `json:"components"`
}

EntitySpawnResult is the JSON result of game_entity_spawn.

type EntitySummary struct {
	Ref        string                     `json:"ref"`
	Index      uint32                     `json:"index"`
	Generation uint32                     `json:"generation"`
	Name       string                     `json:"name,omitempty"`
	Layer      string                     `json:"layer,omitempty"`
	Tags       []string                   `json:"tags,omitempty"`
	Parent     string                     `json:"parent,omitempty"`
	ChildCount int                        `json:"child_count,omitempty"`
	Components []string                   `json:"components,omitempty"`
	Values     map[string]json.RawMessage `json:"values,omitempty"`
}

EntitySummary describes one live entity returned by game_entities_list.

type InputActionInfo struct {
	Name         string `json:"name"`
	Pressed      bool   `json:"pressed"`
	JustPressed  bool   `json:"just_pressed,omitempty"`
	JustReleased bool   `json:"just_released,omitempty"`
	BindingCount int    `json:"binding_count,omitempty"`
}

InputActionInfo describes one action entry returned by game_input_actions_list.

type InputActionResult struct {
	Name         string   `json:"name"`
	Mode         string   `json:"mode"`
	Value        *float64 `json:"value,omitempty"`
	Pressed      bool     `json:"pressed"`
	JustPressed  bool     `json:"just_pressed,omitempty"`
	JustReleased bool     `json:"just_released,omitempty"`
	Axis         float64  `json:"axis,omitempty"`
}

InputActionResult is the JSON result of game_input_action.

type InputActionsListResult struct {
	Configured bool              `json:"configured"`
	Actions    []InputActionInfo `json:"actions"`
	Axes       []InputAxisInfo   `json:"axes"`
}

InputActionsListResult is the JSON result of game_input_actions_list.

type InputAxisInfo struct {
	Name     string  `json:"name"`
	Value    float64 `json:"value"`
	Negative string  `json:"negative,omitempty"`
	Positive string  `json:"positive,omitempty"`
}

InputAxisInfo describes one axis entry returned by game_input_actions_list.

type InputAxisResult struct {
	Axes    map[string]float64 `json:"axes"`
	Cleared []string           `json:"cleared,omitempty"`
}

InputAxisResult is the JSON result of game_input_axis.

type InputPointerResult struct {
	Action           string   `json:"action"`
	Space            string   `json:"space"`
	Button           string   `json:"button"`
	GameX            float32  `json:"game_x"`
	GameY            float32  `json:"game_y"`
	ViewX            float32  `json:"view_x"`
	ViewY            float32  `json:"view_y"`
	WorldX           *float32 `json:"world_x,omitempty"`
	WorldY           *float32 `json:"world_y,omitempty"`
	InViewport       bool     `json:"in_viewport"`
	Dispatched       bool     `json:"dispatched,omitempty"`
	Hit              bool     `json:"hit"`
	HitLayer         string   `json:"hit_layer,omitempty"`
	HitSpace         string   `json:"hit_space,omitempty"`
	HitKind          string   `json:"hit_kind,omitempty"`
	HitFrame         string   `json:"hit_frame,omitempty"`
	HitBatchIndex    *int     `json:"hit_batch_index,omitempty"`
	HitSpriteIndex   *int     `json:"hit_sprite_index,omitempty"`
	HitDrawableIndex *int     `json:"hit_drawable_index,omitempty"`
	HitX             *float32 `json:"hit_x,omitempty"`
	HitY             *float32 `json:"hit_y,omitempty"`
}

InputPointerResult is the JSON result of game_input_pointer.

type LayerInfo struct {
	Index         int     `json:"index"`
	DrawIndex     int     `json:"draw_index"`
	Name          string  `json:"name"`
	Space         string  `json:"space"`
	Visible       bool    `json:"visible"`
	Order         int     `json:"order"`
	ParallaxX     float32 `json:"parallax_x"`
	ParallaxY     float32 `json:"parallax_y"`
	OffsetX       float32 `json:"offset_x,omitempty"`
	OffsetY       float32 `json:"offset_y,omitempty"`
	RepeatX       bool    `json:"repeat_x,omitempty"`
	RepeatY       bool    `json:"repeat_y,omitempty"`
	RepeatWidth   float32 `json:"repeat_width,omitempty"`
	RepeatHeight  float32 `json:"repeat_height,omitempty"`
	DepthSort     string  `json:"depth_sort"`
	ItemCount     int     `json:"item_count"`
	BatchCount    int     `json:"batch_count,omitempty"`
	SpriteCount   int     `json:"sprite_count,omitempty"`
	TilemapCount  int     `json:"tilemap_count,omitempty"`
	DrawableCount int     `json:"drawable_count,omitempty"`
}

LayerInfo describes one scene layer returned by game_layers_list.

type LayersListResult struct {
	Scene  string      `json:"scene"`
	Layers []LayerInfo `json:"layers"`
}

LayersListResult is the JSON result of game_layers_list.

type LoopSeedResult struct {
	Seed uint64 `json:"seed"`
}

LoopSeedResult is the JSON result of game_loop_seed.

type LoopStatusResult struct {
	Paused          bool    `json:"paused"`
	TimeScale       float64 `json:"time_scale"`
	StepSeconds     float64 `json:"step_seconds"`
	StepHz          int     `json:"step_hz"`
	Steps           uint64  `json:"steps"`
	GameTimeSeconds float64 `json:"game_time_seconds"`
	SeedConfigured  bool    `json:"seed_configured"`
}

LoopStatusResult is the JSON result of game_loop_status, game_loop_pause, game_loop_resume and game_loop_time_scale.

type LoopStepResult struct {
	StepsAdvanced   int     `json:"steps_advanced"`
	TotalSteps      uint64  `json:"total_steps"`
	GameTimeSeconds float64 `json:"game_time_seconds"`
	DeltaSeconds    float64 `json:"delta_seconds"`
	Paused          bool    `json:"paused"`
}

LoopStepResult is the JSON result of game_loop_step.

type OverlayStyle struct {
	BoundsColor     core.Color
	BoxColor        core.Color
	CircleColor     core.Color
	TriggerColor    core.Color
	SolidTileColor  core.Color
	OneWayTileColor core.Color
	GridColor       core.Color
	CameraColor     core.Color
	LabelTextColor  core.Color
	LabelBgColor    core.Color
}

OverlayStyle defines the colors drawn by game_screenshot diagnostic overlays.

func DefaultOverlayStyle() OverlayStyle

DefaultOverlayStyle returns the default high-contrast colors for game_screenshot overlays. Collision shape colors match physics.DefaultDebugStyle.

type OverlaysDrawn struct {
	Bounds          bool `json:"bounds,omitempty"`
	CollisionShapes bool `json:"collision_shapes,omitempty"`
	Grid            bool `json:"grid,omitempty"`
	Camera          bool `json:"camera,omitempty"`
	Labels          bool `json:"labels,omitempty"`
	// SpriteBounds counts the sprites outlined: those in scene layers' Item.Batch. Sprites a Drawable item or a tilemap draws get no outline.
	SpriteBounds   int `json:"sprite_bounds,omitempty"`
	PhysicsBoxes   int `json:"physics_boxes,omitempty"`
	PhysicsCircles int `json:"physics_circles,omitempty"`
	// PhysicsPolygons, PhysicsCapsules and PhysicsLines count the polygon, capsule, and segment or chain bodies outlined.
	PhysicsPolygons int `json:"physics_polygons,omitempty"`
	PhysicsCapsules int `json:"physics_capsules,omitempty"`
	PhysicsLines    int `json:"physics_lines,omitempty"`
	PhysicsTriggers int `json:"physics_triggers,omitempty"`
	PhysicsTiles    int `json:"physics_tiles,omitempty"`
}

OverlaysDrawn summarizes which overlays were rendered on a screenshot and how many primitives each drew.

type PerfFrameSample struct {
	FrameMs  float64 `json:"frame_ms"`
	UpdateMs float64 `json:"update_ms"`
	DrawMs   float64 `json:"draw_ms"`
	GCHitch  bool    `json:"gc_hitch,omitempty"`
	Cause    string  `json:"cause,omitempty"`
}

PerfFrameSample is one chronological frame timing entry from the debug overlay's ring buffer.

type PerfMemoryGroup struct {
	Group      string           `json:"group"`
	TotalBytes int64            `json:"total_bytes"`
	Budget     int64            `json:"budget,omitempty"`
	OverBudget bool             `json:"over_budget,omitempty"`
	Count      int              `json:"count"`
	ByKind     map[string]int64 `json:"by_kind,omitempty"`
}

PerfMemoryGroup summarizes tracked asset memory for one debug.MemoryTracker group.

type PerfMemorySummary struct {
	TotalBytes  int64             `json:"total_bytes"`
	TotalBudget int64             `json:"total_budget,omitempty"`
	OverBudget  bool              `json:"over_budget,omitempty"`
	Groups      []PerfMemoryGroup `json:"groups"`
}

PerfMemorySummary summarizes tracked asset memory from a debug.MemoryTracker.

type PerfReadoutResult struct {
	FPS            float64 `json:"fps"`
	FrameMs        float64 `json:"frame_ms"`
	UpdateMs       float64 `json:"update_ms"`
	DrawMs         float64 `json:"draw_ms"`
	SampleCount    int     `json:"sample_count"`
	LatestFrameMs  float64 `json:"latest_frame_ms"`
	LatestUpdateMs float64 `json:"latest_update_ms"`
	LatestDrawMs   float64 `json:"latest_draw_ms"`
	MinFrameMs     float64 `json:"min_frame_ms"`
	MaxFrameMs     float64 `json:"max_frame_ms"`
	P50FrameMs     float64 `json:"p50_frame_ms"`
	P95FrameMs     float64 `json:"p95_frame_ms"`
	P99FrameMs     float64 `json:"p99_frame_ms"`

	DrawCalls int    `json:"draw_calls"`
	Sprites   int    `json:"sprites"`
	Batches   int    `json:"batches"`
	Triangles uint64 `json:"triangles"`
	Vertices  uint64 `json:"vertices"`

	AllocsPerFrame      float64 `json:"allocs_per_frame"`
	AllocBytesPerFrame  float64 `json:"alloc_bytes_per_frame"`
	LastFrameAllocs     uint64  `json:"last_frame_allocs"`
	LastFrameAllocBytes uint64  `json:"last_frame_alloc_bytes"`
	HeapBytes           uint64  `json:"heap_bytes"`
	GCCount             uint64  `json:"gc_count"`
	GCLastPauseMs       float64 `json:"gc_last_pause_ms"`
	GCMaxPauseMs        float64 `json:"gc_max_pause_ms"`
	GCRecentHitches     int     `json:"gc_recent_hitches"`

	Render3D    *PerfRender3DStats `json:"render3d,omitempty"`
	AssetMemory *PerfMemorySummary `json:"asset_memory,omitempty"`
	History     []PerfFrameSample  `json:"history,omitempty"`
	Zones       []PerfZoneInfo     `json:"zones,omitempty"`
	Sources     PerfSources        `json:"sources"`
}

PerfReadoutResult is the JSON result of game_perf_readout.

type PerfRender3DStats struct {
	TotalItems       int    `json:"total_items"`
	CulledItems      int    `json:"culled_items"`
	Occluded         int    `json:"occluded"`
	VisibleItems     int    `json:"visible_items"`
	OpaqueDraws      int    `json:"opaque_draws"`
	TransparentDraws int    `json:"transparent_draws"`
	InstancedBatches int    `json:"instanced_batches"`
	TotalDrawCalls   int    `json:"total_draw_calls"`
	Triangles        uint64 `json:"triangles"`
	Vertices         uint64 `json:"vertices"`
	MaterialSwitches int    `json:"material_switches"`
	PipelineSwitches int    `json:"pipeline_switches"`
	TextureBytes     uint64 `json:"texture_bytes"`
	BufferBytes      uint64 `json:"buffer_bytes"`
}

PerfRender3DStats is a 3D renderer's per-frame statistics in snake_case JSON form. It has the same fields in the same order as render3d.RenderStats, so a game converts one with mcp.PerfRender3DStats(stats) and game/mcp does not link the 3D renderer.

type PerfResetResult struct {
	ResetFrameStats bool `json:"reset_frame_stats"`
	ResetProfiler   bool `json:"reset_profiler"`
	ResetGC         bool `json:"reset_gc"`
	ResetDrawStats  bool `json:"reset_draw_stats"`
}

PerfResetResult is the JSON result of game_perf_reset.

type PerfSources struct {
	Overlay   bool `json:"overlay"`
	Profiler  bool `json:"profiler"`
	GC        bool `json:"gc"`
	Memory    bool `json:"memory"`
	DrawStats bool `json:"draw_stats"`
	Render3D  bool `json:"render3d"`
}

PerfSources reports which telemetry providers contributed to a performance readout.

type PerfZoneInfo struct {
	Name   string  `json:"name"`
	LastMs float64 `json:"last_ms"`
	AvgMs  float64 `json:"avg_ms"`
	MaxMs  float64 `json:"max_ms"`
	Calls  int     `json:"calls"`
}

PerfZoneInfo summarizes one named timing scope from debug.Profiler.

type PerfZonesResult struct {
	Recording      bool           `json:"recording"`
	RecordedFrames int            `json:"recorded_frames"`
	Total          int            `json:"total"`
	Zones          []PerfZoneInfo `json:"zones"`
}

PerfZonesResult is the JSON result of game_perf_zones.

type PointerAction string

PointerAction identifies the kind of pointer event delivered to Config.OnPointer.

const (
	// PointerPress reports a pointer button press.
	PointerPress PointerAction = "press"
	// PointerRelease reports a pointer button release.
	PointerRelease PointerAction = "release"
	// PointerMove reports pointer movement.
	PointerMove PointerAction = "move"
)
type PointerEvent struct {
	// Action is PointerPress, PointerRelease, or PointerMove. A "click" tool call emits PointerPress followed by PointerRelease.
	Action PointerAction
	// Button is the mouse button for the event (MouseButtonLeft, MouseButtonRight, MouseButtonMiddle, or MouseButtonNone when hovering).
	Button core.MouseButton
	// GamePoint is the event position in virtual game canvas coordinates.
	GamePoint core.Point
	// ViewPoint is GamePoint mapped through the configured screen.Viewport into view coordinates (equal to GamePoint when no viewport is configured).
	ViewPoint core.Point
	// WorldPoint is GamePoint converted into world coordinates through the active scene's Camera when present, or the supplied world point when space="world".
	WorldPoint core.Point
	// HasWorldPoint reports whether WorldPoint is populated.
	HasWorldPoint bool
	// InViewport reports whether ViewPoint lies inside the visible viewport area (true when no viewport is configured).
	InViewport bool
	// Hit is the topmost hit returned by the active scene's HitTest(GamePoint) when InViewport is true, or nil if nothing was hit.
	Hit *scene.HitResult
	// Dispatched reports whether Scene.DispatchPress invoked a sprite or drawable OnPress callback for this event.
	Dispatched bool
}

PointerEvent describes a pointer event injected through game_input_pointer after viewport mapping and scene hit testing.

type PrefabInfo struct {
	Name string `json:"name"`
	Kind string `json:"kind"`
}

PrefabInfo describes one registered prefab returned by game_prefabs_list.

type PrefabSpawner func(w *entities.World, overrides map[string]any) (entities.Entity, error)

PrefabSpawner spawns a live entity into w with optional override parameters from game_entity_spawn.

type PrefabsListResult struct {
	Prefabs []PrefabInfo `json:"prefabs"`
}

PrefabsListResult is the JSON result of game_prefabs_list.

type ReloadedItem struct {
	Key    string `json:"key"`
	Group  string `json:"group,omitempty"`
	Kind   string `json:"kind,omitempty"`
	URI    string `json:"uri,omitempty"`
	Bytes  int64  `json:"bytes"`
	Frames int    `json:"frames,omitempty"`
	// Skipped says why the asset was left unchanged without an error, such as a sound or an image with no file behind it.
	Skipped string `json:"skipped,omitempty"`
	Error   string `json:"error,omitempty"`
}

ReloadedItem describes one asset touched during a reload operation.

type RenderedPNG struct {
	// PNG is the encoded image.
	PNG []byte
	// Width and Height are the image's size in pixels.
	Width, Height int
	// SkippedOps counts the drawing operations the rasterizer does not support, such as text, by their core.DrawKind name.
	SkippedOps map[string]int
	// SkippedImages counts the images it could not draw because their source is not in memory (a URI, asset: or offscreen source rather than Pixels or Data).
	SkippedImages int
}

RenderedPNG is a drawing RenderPNG rasterized: the PNG and what the software rasterizer could not draw, so a caller can say the picture is partial.

func RenderPNG(ops []core.DrawOp, width, height int, background core.Color) (RenderedPNG, error)

RenderPNG plays ops, a recorded core.Drawing's operations, into a width by height pixel image over background and encodes it as PNG, with the software rasterizer game_screenshot uses when it draws a frame itself, so tools outside a running game, such as the editor's viewport_image, get the same picture on every platform and headless. Zero background leaves the image transparent. It refuses a size that is not positive, exceeds 8192 pixels on a side or 4096 × 4096 pixels in all.

type ReplayConfig struct {
	// Source is the live replay.ActionSource (such as *input.Actions) forwarded during live play and wrapped by a fresh replay.Recorder on each game_replay_record_start. It is required for recording, and it keeps being stepped during playback so its previous-step snapshot is current when live input resumes.
	Source replay.ActionSource

	// Actions lists the default watched action names recorded by game_replay_record_start when the caller omits actions.
	Actions []string

	// Axes lists the default watched axis names recorded by game_replay_record_start when the caller omits axes.
	Axes []string

	// StepRate is the game's fixed step rate in steps per second when the Bridge has no game loop (Config.Loop or Config.LoopFunc); with a loop, the loop's StepRate is used. It defaults to 60. Recordings are made at this rate, and game_replay_play refuses a recording made at another rate.
	StepRate int

	// StepFunc, when set, advances the simulation by one fixed step of duration dt and is expected to call the controller's Step method once. game_replay_play uses it for run_to_end and steps; without it, those advance the Bridge's game loop with Loop.StepNow.
	StepFunc func(dt time.Duration)

	// SeedFunc, when set, supplies the default seed for game_replay_record_start when the caller omits seed.
	SeedFunc func() uint64

	// ResetFunc, when set, resets the simulation deterministically to seed. With reset (the default when ResetFunc or a seed target is configured), game_replay_record_start and game_replay_play first re-seed the Bridge's seed targets (Config.Random, Config.RandomStreams, Config.SetSeed) and then call ResetFunc, so a recording and its replay start from the same state.
	ResetFunc func(seed uint64) error

	// OnRecordStart, when set, is called after a recording starts.
	OnRecordStart func(name string, seed uint64)

	// OnRecordStop, when set, is called after a recording stops with the stored name and a copy of the completed recording.
	OnRecordStop func(name string, rec *replay.Recording)

	// OnReplayStart, when set, is called after ResetFunc succeeds and playback starts.
	OnReplayStart func(rec *replay.Recording)

	// OnReplayStop, when set, is called when playback finishes or is stopped early.
	OnReplayStop func()

	// SaveDir is an optional root directory on disk where game_replay_record_stop may write YAML recordings when save_path is supplied. Writes go through os.Root, so relative paths and symbolic links cannot leave SaveDir; when SaveDir is empty, save_path is refused.
	SaveDir string
}

ReplayConfig configures a ReplayController for MCP input recording and deterministic playback.

Pass the resulting *ReplayController as your game's replay.ActionSource so live play, recording and playback share the exact same update loop.

type ReplayController struct {
	// contains filtered or unexported fields
}

ReplayController coordinates live input forwarding, recording via replay.Recorder, and deterministic playback via replay.Player for MCP tools.

ReplayController implements replay.ActionSource so a game can read inputs from it unconditionally across live play, recording and playback.

func NewReplayController(cfg ReplayConfig) *ReplayController

NewReplayController creates a ReplayController from cfg.

func (c *ReplayController) Axis(name string) float64

Axis returns the value of axis name on the active input source for the current step.

func (c *ReplayController) DeleteRecording(name string) bool

DeleteRecording removes the stored recording named name and reports whether it existed.

func (c *ReplayController) GetRecording(name string) (*replay.Recording, bool)

GetRecording returns a deep copy of the stored recording named name.

func (c *ReplayController) JustPressed(name string) bool

JustPressed reports whether name became pressed on the active input source on the current step.

func (c *ReplayController) JustReleased(name string) bool

JustReleased reports whether name was released on the active input source on the current step.

func (c *ReplayController) Pressed(name string) bool

Pressed reports whether name is pressed on the active input source for the current step.

func (c *ReplayController) Recording() bool

Recording reports whether an input recording is currently in progress.

func (c *ReplayController) RecordingNames() []string

RecordingNames returns the sorted names of all recordings stored in c.

func (c *ReplayController) Replaying() bool

Replaying reports whether replay playback is currently in progress (not yet finished).

func (c *ReplayController) SaveRecording(name string, rec *replay.Recording) error

SaveRecording validates and stores a deep copy of rec under name in c's in-memory store.

func (c *ReplayController) Step()

Step advances the active replay.Player, active replay.Recorder or live Source by one fixed step.

After the final recorded step, one more Step is a trailing playback step that releases actions still held at the end of the recording (firing JustReleased once); the Step after it finishes playback and resumes live input. The live Source is stepped during playback too, so its previous-step snapshot is current when live input resumes.

type ReplayListResult struct {
	Count      int             `json:"count"`
	Recordings []ReplaySummary `json:"recordings"`
}

ReplayListResult is the JSON result of game_replay_list.

type ReplayPlayResult struct {
	Name              string `json:"name,omitempty"`
	Seed              uint64 `json:"seed"`
	StepRate          int    `json:"step_rate"`
	Replaying         bool   `json:"replaying"`
	Completed         bool   `json:"completed"`
	FramesPlayed      int    `json:"frames_played"`
	ReplayTotalFrames int    `json:"replay_total_frames"`
}

ReplayPlayResult is the JSON result of game_replay_play.

type ReplayRecordStartResult struct {
	Recording bool              `json:"recording"`
	Name      string            `json:"name"`
	Seed      uint64            `json:"seed"`
	StepRate  int               `json:"step_rate"`
	Actions   []string          `json:"actions,omitempty"`
	Axes      []string          `json:"axes,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

ReplayRecordStartResult is the JSON result of game_replay_record_start.

type ReplayRecordStopResult struct {
	Name      string            `json:"name"`
	Frames    int               `json:"frames"`
	Seed      uint64            `json:"seed"`
	StepRate  int               `json:"step_rate"`
	Events    int               `json:"events"`
	Actions   []string          `json:"actions,omitempty"`
	Axes      []string          `json:"axes,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	SavedPath string            `json:"saved_path,omitempty"`
	YAML      string            `json:"yaml"`
}

ReplayRecordStopResult is the JSON result of game_replay_record_stop.

type ReplayStatusResult struct {
	Recording         bool              `json:"recording"`
	RecordingName     string            `json:"recording_name,omitempty"`
	RecordingSeed     uint64            `json:"recording_seed,omitempty"`
	RecordingStepRate int               `json:"recording_step_rate,omitempty"`
	RecordingMetadata map[string]string `json:"recording_metadata,omitempty"`
	FramesRecorded    int               `json:"frames_recorded"`
	Replaying         bool              `json:"replaying"`
	ReplayDone        bool              `json:"replay_done,omitempty"`
	ReplayName        string            `json:"replay_name,omitempty"`
	ReplayFrame       int               `json:"replay_frame"`
	ReplayTotalFrames int               `json:"replay_total_frames"`
	SavedRecordings   []string          `json:"saved_recordings"`
}

ReplayStatusResult is the JSON result of game_replay_status.

type ReplayStopResult struct {
	Stopped           bool   `json:"stopped"`
	Name              string `json:"name,omitempty"`
	FramesPlayed      int    `json:"frames_played"`
	ReplayTotalFrames int    `json:"replay_total_frames"`
}

ReplayStopResult is the JSON result of game_replay_stop.

type ReplaySummary struct {
	Name     string            `json:"name"`
	Frames   int               `json:"frames"`
	Seed     uint64            `json:"seed"`
	StepRate int               `json:"step_rate"`
	Events   int               `json:"events"`
	Actions  []string          `json:"actions,omitempty"`
	Axes     []string          `json:"axes,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

ReplaySummary describes one stored recording returned by game_replay_list.

type SceneInfo struct {
	Name        string      `json:"name"`
	Active      bool        `json:"active"`
	Current     bool        `json:"current,omitempty"`
	StackIndex  *int        `json:"stack_index,omitempty"`
	Transparent bool        `json:"transparent,omitempty"`
	LayerCount  int         `json:"layer_count"`
	Camera      *CameraInfo `json:"camera,omitempty"`
}

SceneInfo describes one active or named scene returned by game_scenes_list.

type ScenesListResult struct {
	Current       string      `json:"current,omitempty"`
	StackDepth    int         `json:"stack_depth"`
	Transitioning bool        `json:"transitioning,omitempty"`
	Progress      float64     `json:"progress,omitempty"`
	Scenes        []SceneInfo `json:"scenes"`
}

ScenesListResult is the JSON result of game_scenes_list.

type ScreenshotOverlays struct {
	// Bounds draws crisp bounding rectangles aligned with every visible sprite in the scene.
	Bounds bool `json:"bounds,omitempty"`
	// CollisionShapes draws 2D physics collision shapes (boxes, circles, triggers, rigid bodies and collision tiles).
	CollisionShapes bool `json:"collision_shapes,omitempty"`
	// Physics is an alias for CollisionShapes; setting either enables collision-shape overlays.
	Physics bool `json:"physics,omitempty"`
	// Grid draws a reference grid in world space (or view space when no camera is active).
	Grid bool `json:"grid,omitempty"`
	// GridStep sets the spacing of the reference grid in world points when Grid is true (default 32).
	GridStep float32 `json:"grid_step,omitempty"`
	// Camera draws the active camera's visible frame and center crosshair.
	Camera bool `json:"camera,omitempty"`
	// Labels draws compact text labels next to drawn sprite bounds and physics bodies.
	Labels bool `json:"labels,omitempty"`
}

ScreenshotOverlays configures diagnostic overlays drawn on top of a game_screenshot capture.

type ScreenshotResult struct {
	Width         int           `json:"width"`
	Height        int           `json:"height"`
	Format        string        `json:"format"`
	Scene         string        `json:"scene,omitempty"`
	Path          string        `json:"path,omitempty"`
	Bytes         int           `json:"bytes"`
	PNGBase64     string        `json:"png_base64,omitempty"`
	OverlaysDrawn OverlaysDrawn `json:"overlays_drawn"`
	// SkippedOps counts, by draw operation kind (such as "DrawFillText" or "DrawEllipse"), what the software rasterizer did not draw when the frame was rendered rather than captured. A non-empty map means the image is partial.
	SkippedOps map[string]int `json:"skipped_ops,omitempty"`
	// SkippedImages counts image and atlas draws the software rasterizer left out because their source is not in memory (a URI, an "asset:" file or an Offscreen canvas) or could not be decoded. Use CaptureFrame to see them.
	SkippedImages int `json:"skipped_images,omitempty"`
}

ScreenshotResult is the JSON result of game_screenshot.

type TunableResult 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"`
}

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 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"`
}

TunableSetResult is the JSON result of game_tunable_set.

type TunablesListResult struct {
	Total    int             `json:"total"`
	Tunables []TunableResult `json:"tunables"`
}

TunablesListResult is the JSON result of game_tunables_list.