Skip to content

Framework API reference

Every class, signal, constant, property and method of the shared addons/godotgo framework, generated from the ## doc comments in framework/addons/godotgo/.

Why each piece exists and how the pieces fit together is in the framework guide. Paths below are relative to framework/addons/godotgo/; members whose names start with an underscore are private or engine callbacks and are not listed.

Class or script File Summary
SaveSystem core/save_system.gd JSON save slots under user://saves/, stamped with a schema version so old files can be detected instead of crashing a load.
Session core/session.gd The round lifecycle shared by every GodotGo game: a small state machine with a score, an objective counter and an optional countdown.
GodotGoMcpBridge mcp/mcp_bridge.gd Publishes GodotGo's own tools to an MCP agent through the Godot AI addon.
mcp/mcp_handlers.gd mcp/mcp_handlers.gd Implements the tools GodotGoMcpBridge publishes to an MCP agent.
plugin.gd plugin.gd Adds GodotGo's node types to the editor's "Create New Node" dialog.
GodotGoTest testing/test_case.gd Base class for headless unit tests, shared by every project in the workspace.
testing/test_runner.gd testing/test_runner.gd Zero-dependency headless test runner.
tools/check_scripts.gd tools/check_scripts.gd Loads scripts, scenes and resources to validate them, then exits 1 if any failed.
tools/new_uid.gd tools/new_uid.gd Prints a fresh Godot resource UID for use in hand-written .tscn/.tres files.
DebugOverlay ui/debug_overlay.gd A drop-in diagnostics panel: frames per second, the running Session's state and the current scene.
MaterialMakerLoader util/material_maker_loader.gd Loads a Material Maker Godot export (StandardMaterial3D .tres) or builds one from PBR maps sitting next to the material.
ObjectPool util/object_pool.gd Reuses instances of a PackedScene instead of allocating one per spawn.
Rng util/rng.gd Deterministic random numbers.
StateMachine util/state_machine.gd A small finite state machine for entity behaviour, built from callables so it needs no node hierarchy and can be unit-tested on its own.
TextGrid util/text_grid.gd An ASCII level map parsed into single-character cells.

SaveSystem

core/save_system.gd · extends RefCounted

JSON save slots under user://saves/, stamped with a schema version so old files can be detected instead of crashing a load.

SaveSystem.store("progress", {"level": 3, "best": 1200})
var data := SaveSystem.fetch("progress", {"level": 1, "best": 0})

Constants

  • const DIR := "user://saves"
  • const VERSION := 1 — Bumped when the envelope format changes. Slots written by a newer version are refused rather than misread.

Methods

  • static func path_for(slot: String) -> String — Absolute user:// path of a slot's file.
  • static func sanitize(slot: String) -> String — Lower-cases a slot name and strips anything that is not a safe filename character.
  • static func store(slot: String, data: Dictionary) -> Error — Writes data to a slot. Returns OK or the file error.
  • static func fetch(slot: String, fallback: Dictionary = {}) -> Dictionary — Reads a slot. Returns fallback when the slot is missing, unreadable, malformed, or written by a newer VERSION.
  • static func has_slot(slot: String) -> bool
  • static func erase(slot: String) -> Error — Deletes a slot. Returns OK when the slot is gone afterwards.
  • static func slots() -> PackedStringArray — Slot names currently on disk, sorted.

Session

core/session.gd · extends Node

The round lifecycle shared by every GodotGo game: a small state machine with a score, an objective counter and an optional countdown.

A game adds a subclass as an autoload named Game:

# scripts/game.gd, registered in project.godot as Game="*res://scripts/game.gd"
extends Session

Scenes call start(), advance(), add_score(), win() and lose(), and react to the signals. No rule here needs a node reference, so every rule stays unit-testable headlessly.

Signals

  • signal state_changed(state: State) — Emitted when state changes. Never emitted for a same-state assignment.
  • signal score_changed(score: int) — Emitted after start() and every successful add_score().
  • signal progress_changed(progress: int, goal: int) — Emitted after start() and every successful advance().
  • signal time_changed(time_left: float) — Emitted after start() and whenever the countdown's tenths digit changes.
  • signal objective_reached — Emitted exactly once per round, the moment progress reaches goal.
  • signal won(result: Dictionary) — Emitted by win() with the round summary from summary().
  • signal lost(reason: String) — Emitted by lose() with one of the REASON constants or a game-specific string.

Enums

  • enum State { READY, PLAYING, PAUSED, WON, LOST }

Constants

  • const REASON_TIME := "time" — The countdown reached zero.
  • const REASON_DEATH := "death" — The player died.
  • const REASON_QUIT := "quit" — The player gave up or left the round.
  • const LOG_PREFIX := "[godotgo]" — Prefix for the framework's stdout lines; tools/smoke.sh looks for it.

Properties

  • var state: State = State.READY
  • var score := 0
  • var progress := 0 — Objective units completed so far (orbs collected, boxes placed, waves survived).
  • var goal := 0 — Objective units needed to finish. 0 means the round has no counted objective.
  • var time_limit := 0.0 — Seconds allowed for the round. 0 disables the countdown.
  • var time_left := 0.0
  • var elapsed := 0.0 — Seconds spent in State.PLAYING this round.

Methods

  • func start(goal_value: int = 0, limit: float = 0.0) -> void — Begins a round. goal_value of 0 means no counted objective; limit of 0 means no countdown.
  • func add_score(points: int) -> bool — Adds points. Returns false (and changes nothing) unless a round is running.
  • func advance(amount: int = 1) -> bool — Advances the objective counter, emitting objective_reached the first time progress reaches goal. Returns false unless playing.
  • func objective_complete() -> bool — True once progress has reached a non-zero goal.
  • func is_playing() -> bool
  • func is_over() -> bool
  • func tick(delta: float) -> void — Advances the clock. Called every frame by _process(); call it directly in tests to step time deterministically.
  • func pause() -> bool — Suspends the clock without ending the round.
  • func resume() -> bool
  • func win() -> bool — Ends the round as a win. Ignored unless playing.
  • func lose(reason: String = REASON_QUIT) -> bool — Ends the round as a loss. Ignored unless playing.
  • func summary() -> Dictionary — A snapshot of the round, used by won and by save files.
  • func reset() -> void — Returns to State.READY with every counter cleared.

GodotGoMcpBridge

mcp/mcp_bridge.gd · extends RefCounted · @tool

Publishes GodotGo's own tools to an MCP agent through the Godot AI addon.

Godot AI (github.com/hi-godot/godot-ai) gives an agent about 120 tools for driving a live editor: nodes, scenes, scripts, animation, materials. What it cannot know is this workspace — that a round lives in a Session subclass, that a project is verified by tools/verify.sh, that an empty test suite is a failure rather than a pass. This registers that knowledge as additional tools, so one agent can both build a scene and prove it still works.

Godot AI is an optional dependency. Nothing here references its classes by name: the scripts are loaded by path and duck-typed, so the framework parses and runs identically on a machine that has never installed it. That is why the handler signatures below leave ctx untyped — naming McpCallContext would make this file fail to parse without it.

var bridge := GodotGoMcpBridge.new()
bridge.register_tools()   # 0 when Godot AI is absent, never an error

Constants

  • const REGISTRY_SCRIPT := "res://addons/godot_ai/custom_tools/mcp_tool_registry.gd" — Where the vendored addon puts the pieces we duck-type against.
  • const SPEC_SCRIPT := "res://addons/godot_ai/custom_tools/mcp_custom_tool_spec.gd"
  • const SOURCE_PATH := "res://addons/godotgo/plugin.cfg" — Identifies these tools as ours in Godot AI's dock and collision policy.
  • const SOURCE_NAME := "godotgo"
  • const HANDLERS_SCRIPT := "res://addons/godotgo/mcp/mcp_handlers.gd" — The handlers live in a separate script because the registry materialises them lazily by path, so a hot reload cannot free an instance mid-call.
  • const MAX_TIMEOUT_MS := 120000 — Ceiling Godot AI enforces on a deferred tool. A whole-workspace verify runs longer than this, which is why every tool that shells out takes one project.

Methods

  • static func is_available() -> bool — True when the Godot AI addon is installed and its registry is live. Both halves matter: the scripts can be present while the plugin is disabled.
  • func register_tools() -> int — Registers every GodotGo tool, replacing any previous registration of the same names. Returns how many were accepted; 0 means Godot AI is not available, which is a normal state and not an error.
  • func unregister_tools() -> void — Removes the tools again, for when the framework plugin is disabled while Godot AI stays up.
  • static func build_specs(spec_script: Resource) -> Array — Turns the definitions into Godot AI spec objects. Separate from registration so the framework's tests can hand them to Godot AI's own validator, which is a far better check of the budgets than a copy of its constants.

mcp/mcp_handlers.gd

extends RefCounted · @tool

Implements the tools GodotGoMcpBridge publishes to an MCP agent.

Every method here has the signature Godot AI's dispatcher calls, (params: Dictionary, ctx) -> Dictionary, and returns either {"data": ...} or {"status": "error", "error": ...}. ctx is deliberately untyped: naming Godot AI's class would stop this file parsing on a machine that has not installed it, and the framework must load the same everywhere. See GodotGoMcpBridge for the whole rationale.

The shell-outs run on a worker thread and answer through ctx.send_deferred(), because a synchronous OS.execute() would freeze the editor for the minute a verify takes.

Constants

  • const DEFERRED := {"_deferred": true} — Godot AI's marker for "the answer is coming later".

Methods

  • func verify(params: Dictionary, ctx) -> Dictionary
  • func check(params: Dictionary, ctx) -> Dictionary
  • func test(params: Dictionary, ctx) -> Dictionary
  • func projects(_params: Dictionary, _ctx) -> Dictionary
  • func framework_api(params: Dictionary, _ctx) -> Dictionary

plugin.gd

extends EditorPlugin · @tool

Adds GodotGo's node types to the editor's "Create New Node" dialog.

The framework works whether or not this plugin is enabled: every class is a global class_name and can be attached or instantiated from code. Enabling it only makes the nodes discoverable in the editor.

Constants

  • const CUSTOM_TYPES := {…}

GodotGoTest

testing/test_case.gd · extends RefCounted

Base class for headless unit tests, shared by every project in the workspace. Subclass in a project's tests/unit/test_*.gd and add methods prefixed with test_. Methods may use await (e.g. on tree.physics_frame) and the runner will wait for them.

Properties

  • var tree: SceneTree — The running SceneTree, for tests that need to add nodes or await frames.

Methods

  • func before_each() -> void — Called before every test_ method.
  • func after_each() -> void — Called after every test_ method, even when it failed.
  • func fail(message: String) -> void
  • func skip(reason: String) -> void — Marks the current test as skipped. Remaining assertions still run but the runner reports the test as skipped rather than passed or failed.
  • func is_headless() -> bool — True when running without a real display (CI, tools/test.sh).
  • func assert_true(condition: bool, message: String = "") -> void
  • func assert_false(condition: bool, message: String = "") -> void
  • func assert_eq(actual: Variant, expected: Variant, message: String = "") -> void
  • func assert_ne(actual: Variant, unexpected: Variant, message: String = "") -> void
  • func assert_almost_eq(actual: float, expected: float, tolerance: float = 0.0001, message: String = "") -> void
  • func assert_null(value: Variant, message: String = "") -> void
  • func assert_not_null(value: Variant, message: String = "") -> void
  • func assert_is(value: Variant, type: Variant, message: String = "") -> void
  • func add_scene(scene: PackedScene) -> Node — Instantiates a PackedScene, adds it to the tree root, and returns it. Free it with free_node() in after_each().
  • func add_node(node: Node) -> Node — Adds an existing node to the tree root.
  • func free_node(node: Variant) -> void — Queues a node for deletion and waits until it is gone. Accepts an already freed reference (e.g. a node that freed itself) without complaint.
  • func physics_frames(count: int) -> void — Waits for count physics frames. Resumes inside the physics frame, before nodes process, so Input.action_press calls made right after are seen as "just pressed" by _physics_process in that same frame.
  • func record(sig: Signal) -> Array — Records every emission of sig until the test ends. Each entry is the emitted arguments padded with nulls to three items; use size() for counts.
  • func add_floor_3d() -> StaticBody3D — Adds a 40 x 1 x 40 static 3D floor on physics layer 1 whose top surface is y = 0.
  • func add_floor_2d() -> StaticBody2D — Adds a 2000 x 40 static 2D floor on physics layer 1 whose top edge is y = 0.

testing/test_runner.gd

extends SceneTree

Zero-dependency headless test runner.

Usage:

tools/godot.sh --headless --path . --script res://tests/test_runner.gd
tools/godot.sh --headless --path . --script res://tests/test_runner.gd -- --filter=player

Discovers tests/unit/**/test_*.gd, instantiates each (must extend GodotGoTest), runs every test_* method, prints a summary, and exits 1 on any failure.

Constants

  • const TEST_ROOT := "res://tests/unit"

tools/check_scripts.gd

extends SceneTree

Loads scripts, scenes and resources to validate them, then exits 1 if any failed. Unlike godot --check-only this runs inside a live SceneTree, so autoload singletons resolve, class_name lookups work and .tscn/.tres files are validated as well. It is also the only form that reports failure on macOS, where --check-only always exits 0.

Usage:

godot --headless --path <project> --script res://addons/godotgo/tools/check_scripts.gd
godot --headless --path <project> --script res://addons/godotgo/tools/check_scripts.gd \
    -- scripts/level.gd scenes/main.tscn

With no file arguments it scans the whole project, skipping SKIPPED_DIRS. Callers that want the shared addon checked (the framework project does) pass files explicitly; tools/check.sh always does.

Constants

  • const SKIPPED_DIRS: Array[String] = [".godot", ".git", "addons"]
  • const CHECKED_EXTENSIONS: Array[String] = ["gd", "tscn", "tres"]

tools/new_uid.gd

extends SceneTree

Prints a fresh Godot resource UID for use in hand-written .tscn/.tres files. Usage: tools/godot.sh --headless --path . --script res://scripts/tools/new_uid.gd

DebugOverlay

ui/debug_overlay.gd · extends CanvasLayer

A drop-in diagnostics panel: frames per second, the running Session's state and the current scene. Press F3 to toggle it.

It builds its own label, so adding the node to a scene is the whole setup and no extra input action is required.

Constants

  • const SESSION_PATH := ^"/root/Game" — Autoload path of the game's Session subclass.

Properties

  • @export var visible_at_start := false
  • @export var toggle_key: Key = KEY_F3

Methods

  • func lines() -> PackedStringArray — The lines the overlay draws, exposed so tests can assert on them without a display.

MaterialMakerLoader

util/material_maker_loader.gd · extends RefCounted

Loads a Material Maker Godot export (StandardMaterial3D .tres) or builds one from PBR maps sitting next to the material.

Usage:

var mat := MaterialMakerLoader.load_material("res://materials/rust", "rust")
$MeshInstance3D.material_override = mat

Constants

  • const MAP_CANDIDATES: Dictionary[String, Array] = {…} — StandardMaterial3D texture property -> candidate file names, tried in order. "%s" is replaced with the material stem (the .tres name without extension).
  • const ORM_CANDIDATES: Array = ["%s_orm.png", "orm.png"] — Packed occlusion/roughness/metallic map as written by Material Maker's "Godot 4 Standard" export. Used when the separate maps are absent.
  • const ORM_CHANNELS: Dictionary[String, BaseMaterial3D.TextureChannel] = {…} — ORM channel layout (glTF convention): R = ambient occlusion, G = roughness, B = metallic.
  • const FEATURE_FLAGS: Dictionary[String, String] = {…} — Texture properties whose feature toggle must be switched on for the map to render.

Methods

  • static func load_material(material_dir: String, material_name: String = "") -> StandardMaterial3D — Returns the exported .tres at material_dir/material_name.tres when it exists, otherwise a StandardMaterial3D assembled from whichever PBR maps are present. material_name defaults to the directory name.
  • static func find_maps(material_dir: String, stem: String) -> Dictionary[String, String] — Lists which maps load_material() would pick up for a material, keyed by StandardMaterial3D property. A packed ORM map is reported under the key "orm". Useful for tooling and tests.

ObjectPool

util/object_pool.gd · extends Node

Reuses instances of a PackedScene instead of allocating one per spawn.

Spare instances are held outside the scene tree; acquire() hands one back for the caller to add wherever it likes, and release() takes it out of the tree and returns it to the pool.

var bullet := pool.acquire()
if bullet:
    add_child(bullet)
    bullet.global_position = muzzle.global_position
# later
pool.release(bullet)

A pooled scene may implement pool_acquired() and pool_released() to reset its own state; the pool calls them when they exist.

Signals

  • signal acquired(node: Node)
  • signal released(node: Node)

Properties

  • @export var scene: PackedScene — The scene instantiated for every pooled object.
  • @export_range(0, 512, 1) var initial_size := 0 — Instances created up front in _ready().
  • @export_range(0, 4096, 1) var max_size := 0 — Refuse to create more than this many live instances. 0 means no ceiling.

Methods

  • func prewarm(count: int) -> void — Creates instances ahead of time so the first spawns do not allocate.
  • func acquire() -> Node — Returns a ready instance that is not in the tree, or null when scene is unset or max_size is reached.
  • func release(node: Node) -> void — Removes node from the tree and returns it to the pool. Releasing a node twice, or one from another pool, is reported and ignored.
  • func release_all() -> void — Releases everything currently handed out.
  • func in_use() -> int — Instances currently handed out.
  • func available() -> int — Spare instances ready to hand out.
  • func created() -> int — Instances this pool has ever created.

Rng

util/rng.gd · extends RefCounted

Deterministic random numbers. The same seed always produces the same sequence, which is what makes spawn patterns and shuffles testable.

var rng := Rng.new(1234)
var wave := rng.pick(["bat", "slime", "ghost"])

Properties

  • var seed_value: int = 0 — The seed this generator was created or reseeded with.

Methods

  • Rng.new(initial_seed: int = 0)
  • func reseed(new_seed: int) -> void — Restarts the sequence from new_seed.
  • func get_state() -> int — Opaque generator position. Save it and assign it back to resume a sequence.
  • func set_state(value: int) -> void
  • func randi() -> int
  • func randi_range(from: int, to: int) -> int — Inclusive on both ends.
  • func randf() -> float
  • func randf_range(from: float, to: float) -> float
  • func chance(probability: float) -> bool — True with probability probability (0.0 never, 1.0 always).
  • func pick(items: Array) -> Variant — A uniformly chosen element, or null for an empty array.
  • func shuffled(items: Array) -> Array — A new array with the elements shuffled; the input is left alone.
  • func weighted_pick(items: Array, weights: Array) -> Variant — Picks an element whose chance is proportional to its weight. Non-positive weights are ignored; returns null when nothing is selectable.
  • func point_in_rect(rect: Rect2) -> Vector2 — A random point inside the given rectangle.
  • func direction() -> Vector2 — A unit vector with a uniformly random direction.

StateMachine

util/state_machine.gd · extends RefCounted

A small finite state machine for entity behaviour, built from callables so it needs no node hierarchy and can be unit-tested on its own.

var fsm := StateMachine.new()
fsm.add_state(&"idle", _idle_update)
fsm.add_state(&"chase", _chase_update, _on_chase_enter)
fsm.start(&"idle")
# in _physics_process:
fsm.update(delta)

Signals

  • signal transitioned(from: StringName, to: StringName) — Emitted on every accepted transition, including the initial start().

Properties

  • var current: StringName = &""
  • var previous: StringName = &""
  • var time_in_state := 0.0 — Seconds spent in current, reset on every transition.

Methods

  • func add_state(state_name: StringName, on_update := Callable(), on_enter := Callable(), on_exit := Callable()) -> void — Registers a state. Every callback is optional; on_update receives the frame delta, the others take no arguments.
  • func has_state(state_name: StringName) -> bool
  • func states() -> Array[StringName] — Registered state names, in alphabetical order.
  • func start(state_name: StringName) -> bool — Enters the first state without running an exit callback. Returns false when the state is unknown.
  • func transition_to(state_name: StringName) -> bool — Leaves the current state and enters state_name. Returns false when the state is unknown or already current.
  • func update(delta: float) -> void — Runs the current state's update callback and advances time_in_state.

TextGrid

util/text_grid.gd · extends RefCounted

An ASCII level map parsed into single-character cells.

Levels are plain text files, which makes them diffable, hand-editable and trivial to assert on in tests. Rows are padded with spaces to a common width.

var grid := TextGrid.parse("###\n#@#\n###")
grid.find_first("@")  # -> Vector2i(1, 1)

Constants

  • const EMPTY := " "

Properties

  • var width := 0
  • var height := 0

Methods

  • static func parse(text: String) -> TextGrid — Parses text into a grid. Blank leading and trailing lines are dropped.
  • static func from_file(path: String) -> TextGrid — Parses a res:// or user:// text file. Returns an empty grid when the file cannot be read.
  • func in_bounds(pos: Vector2i) -> bool
  • func at(pos: Vector2i) -> String — The character at pos, or EMPTY when out of bounds.
  • func cell(x: int, y: int) -> String
  • func set_at(pos: Vector2i, symbol: String) -> void — Overwrites one cell. Out-of-bounds writes are ignored.
  • func find_all(symbol: String) -> Array[Vector2i] — Every position holding symbol, in reading order.
  • func find_first(symbol: String) -> Vector2i — The first position holding symbol, or (-1, -1) when absent.
  • func find_any(symbols: String) -> Array[Vector2i] — Every position whose character appears in symbols.
  • func count(symbol: String) -> int
  • func clone() -> TextGrid — An independent copy, safe to mutate.
  • func to_text() -> String