Contract Surface — godot-mcp-toolkit ⇄ godot-mcp-server
The as-built wire contract between the two repos: every format, protocol message, and field the server consumes from the toolkit, each with a stability tier.
The toolkit owns this contract. It is the protocol producer/publisher — it owns the ports, the WebSocket framing, the response envelope, the error-code vocabulary, and the registry / token / LSP publishing. The server (godot-mcp-server, the npm MCP bridge) is the consumer; it opens a localhost WebSocket to the toolkit and forwards an AI assistant’s MCP calls over it. This document is the canonical, version-controlled description of that boundary; the architecture doc covers the toolkit’s internals.
Each entry records the toolkit shape (the authoritative wire form, with the file where it is defined) and the server consumer (how the bridge reads or produces it). File references name the file only — line numbers rot and are omitted; grep the named file for the symbol.
Stability tiers
The tiers feed semantic versioning:
- public — semver-protected. Breaking a public contract requires a major version bump.
- semi-public — deprecate first, then change across a minor release.
- internal — no compatibility guarantee; may change at any time.
The full per-tool name + parameter-schema catalogue (C8) and the tool-group catalogue (C12) are not duplicated here — they live in the generated tool-reference doc. This document describes the framing of tools and groups (naming convention, registration, activation), not the per-tool list.
Maintaining this document
Each detail section below carries a provenance comment immediately above it:
<!-- data-depicts="<toolkit source files> server:<server source files>" data-verified="<toolkit short-sha>" data-verified-server="<server short-sha>" -->
data-depicts lists the toolkit (publisher-side) files the section is drawn from, as space-separated, repo-root-relative paths, followed by a server:<path> entry for each server file the section describes (server:src/registry.ts, relative to the server repo’s root). data-verified is the toolkit commit the section was last checked-correct against, and data-verified-server the server commit its server half was last checked against. Bumping either stamp is an attestation that a human or agent re-read that half of the section against the code at that SHA — it is never auto-generated. This repo’s freshness check skips server: entries (such a path names no file in this repo, so it never flags one), so server drift is caught by re-reading the section against a server checkout (a sibling clone of the server repo), not by that check.
When the contract changes: edit the affected section, then bump the stamp of each half you re-read. Find what to re-check by grepping data-depicts for a file you changed (a server file as its server: entry); the advisory freshness check (scripts/check_arch_freshness.sh docs/dev/contract.md) lists sections whose depicted files moved since their data-verified SHA. It over-flags by design — a false re-check costs a glance; a missed drift ships a lying contract. The script never fails a build, but whoever moves a depicted file must follow that change with a commit that re-attests the affected section; the release rule is in the release runbook.
This document carries only the current as-built state; how the contract reached it is in the git history and the CHANGELOG.
Summary index
| # | Contract | Where defined (toolkit) | Tier |
|---|---|---|---|
| C1 | WebSocket transport & framing (JSON-RPC 2.0/WS, ports, bind, buffer) | transport/mcp_server.gd, runtime/mcp_runtime_server.gd, transport/ws_transport.gd | public |
| C2 | Auth handshake (first-frame token exchange; version + headless fields) | security/auth.gd + both servers + transport/ws_transport.gd + versioning/mcp_version_utils.gd | public |
| C3 | Response envelope (success + error shape) | contract/mcp_toolkit_success.gd, contract/mcp_toolkit_error.gd | public |
| C4 | Error-code vocabulary (CODES) | contract/mcp_toolkit_error.gd | public |
| C5 | Dispatch + concurrency notifications (JSON-RPC codes; _queued/_executing/_cancel/echo; id coercion) | transport/dispatch/{server_request_router,dispatch_lane,mutation_watchdog}.gd + transport/mcp_server.gd | public |
| C6 | Idempotency (status + if_exists) | create commands + commands/editor_helpers.gd | public |
| C7 | Type-tag coercion vocabulary (18 tags, bidirectional) | contract/coerce.gd | public |
| C8 | Tool names & param schemas (domain.verb) | commands/*.gd + transport/mcp_toolkit_command_registry.gd | public |
| C9 | Read-only model (GODOT_MCP_READ_ONLY; server-authoritative; published annotations) | transport/mcp_toolkit_command_registry.gd (routing flag; extension annotations) | public |
| C10 | Environment variables & CLI flags | security/auth.gd, transport/mcp_server.gd, runtime/mcp_runtime_server.gd, runtime/runtime_opt_out.gd, transport/port_config.gd, .mcp.json.template | public |
| C11 | .mcp.json file format | ui/mcp_json_sync.gd (read + write) + ui/mcp_json/server_pin_policy.gd (server pin) + ui/mcp_json_write_flow.gd (confirm-then-write) + ui/mcp_json/server_pin_move.gd (pin move after an update) | public |
| C12 | Tool group names | toolkit publishes group per command (options builder); catalogue is server-side | semi-public |
| C13 | Extension API (register; options/undo/save/ctx facades; base classes) | transport/mcp_toolkit_command_registry.gd + extensions/mcp_toolkit_extension*.gd, contract/mcp_toolkit_tool_context.gd | semi-public |
| C14 | Extension surface signaling (extensions.list/refresh; extensions.changed broadcast) | extensions/services/{extension_meta_commands,extension_watcher}.gd | semi-public |
| C15 | LSP status round-trip (reverse: server→toolkit set_lsp_status) | commands/editor/editor_commands.gd + transport/mcp_server.gd | semi-public |
| C16 | projects.json registry format (entry fields + aggregate) | registry/registry_client.gd + registry/store/* | internal |
| C17 | Project-instance hash | paths/project_paths.gd + paths/project_key.gd | internal |
| C18 | Token file discovery (token_path field) | security/auth.gd + registry/registry_client.gd | internal |
| C19 | LSP endpoint publishing (lsp_host/lsp_port) | paths/lsp_publisher.gd → registry | internal |
| C20 | Runtime discovery (runtime_port/runtime_pid) | registry/registry_client.gd + registry/store/registry_projection.gd | internal |
| C21 | Untrusted envelope | security/untrusted.gd | internal (LLM-facing) |
| C22 | ProjectSettings keys | core/settings_registration.gd, core/response_limits.gd | internal |
| C23 | Input map (event object, equivalence, input_map.list entries, revert) | commands/input_map/input_event_codec.gd, commands/input_map/input_event_equivalence.gd, commands/input_map/input_map_commands.gd, commands/input_map/input_action_settings.gd | public |
Detail
C1 — WebSocket transport & framing · public
- Toolkit shape: JSON-RPC 2.0 messages over a WebSocket text channel, one JSON object per frame.
- Mode A (editor): default scan band 6550–6560 (
PORT_MIN/PORT_MAXintransport/mcp_server.gd;GODOT_MCP_EDITOR_PORTpins an exact port bind-exact-or-fail,GODOT_MCP_EDITOR_PORT_MIN/_MAXrelocate the band — resolved by the export-cleantransport/port_config.gd, see C10), bind127.0.0.1(theBINDconst). - Mode B (runtime / in-game): default scan band 6570–6585 (
PORT_MIN/PORT_MAXinruntime/mcp_runtime_server.gd;GODOT_MCP_RUNTIME_PORTpins bind-exact-or-fail,GODOT_MCP_RUNTIME_PORT_MIN/_MAXrelocate — sametransport/port_config.gdresolver), bind127.0.0.1. The autoload setsPROCESS_MODE_ALWAYS, so it keeps polling the socket while the game tree is paused. - Peer buffer (both modes): sized in/outbound by the shared transport at peer accept (
transport/ws_transport.gd) from a size in KiB that its owning server supplies, asked once per accepted peer. Mode A passes the effectivemcp_toolkit/limits/ws_buffer_kb(the env override while one is active, else the project value; default 1024 KiB, floor 256; see C22), so a pushed env override applies from the next connection the editor accepts. Mode B passes the game project’s own project value: an env override lives in the editor process and never reaches the game.
- Mode A (editor): default scan band 6550–6560 (
- Constraint: a response frame larger than the peer buffer is dropped wholesale by the engine (
wsl_peer.cpp, 4.2 & 4.5 — no chunking), surfacing to the LLM as a hung request. The buffer-ceiling guard (C4RESPONSE_TOO_LARGE) exists to pre-empt this. - Server consumer: the bridge does not blind-scan the ranges — it is a registry-driven consumer.
createBridge(transport/bridge.ts) opens the editor channel withcreateChannel(transport/channel.ts) on the port read fromprojects.json(registry.ts), and re-reads that port when the connection drops;createRuntimeConnection(transport/runtimeConnection.ts) opens the runtime channel the same way on the entry’sruntime_port(C20). Each is aws://127.0.0.1:<port>text channel that speaks the same one-JSON-object-per-frame JSON-RPC 2.0 framing. StaticGODOT_MCP_EDITOR_PORT/GODOT_MCP_RUNTIME_PORToverrides (or the--editor-port/--runtime-portCLI flags) pin a port and skip the registry lookup (resolved byresolvePortConfiginstartup/portConfig.ts, viaresolvePortConfigOrExitinindex.ts, and handed tocreateBridgebybuildBridgeOptionsinstartup/bridgeOptions.ts), with a fail-fast desync cross-check against the registry so a pin the editor never got fails loudly instead of hanging (C10). A pinned runtime port has no registry watcher to report the game’s runtime, sogame_start’s wait for it (waitForRuntimeConnection,transport/runtimeConnection.ts) sendspingto the pinned port, again 250 ms after each failed attempt, until the runtime answers or the wait ends. The server sets no buffer size of its own: thewslibrary’s default receive limit is far above the toolkit’s buffer, so the toolkit’s peer buffer is the ceiling. The server’s one lever on it isGODOT_MCP_WS_BUFFER_LIMIT, an env override the bridge pushes after every editor auth (C10, C22). - Example: request
{"jsonrpc":"2.0","id":1,"method":"scene.create","params":{...}}→ response{"jsonrpc":"2.0","id":1,"result":{"success":true,...}}.
C2 — Auth handshake · public
- Toolkit shape: before any RPC, the client’s first WS text frame must be
{"auth":"<token>"}; optional client fields may accompany it:"version":"X.Y.Z", and from a 1.1+ server"server_version":"X.Y.Z"+"min_toolkit":"M.m"(its declared toolkit floor). The request is identical across modes; the success reply differs by mode:- Mode A (editor):
{"authed":true,"godot_version":"<M.m.p>","version":"<plugin-version>","headless":<bool>,"min_server":"<M.m>"}(the ack override,_build_auth_ackintransport/mcp_server.gd) — carries the engine + plugin version (the server’s version-gating input),headless(DisplayServer.get_name()=="headless", viaVersionUtils.is_headless()): the wire signal the server reads to branch its headless-degraded tool assertions, andmin_server, the toolkit’s declared server floor (MIN_SERVER_VERSIONinversioning/mcp_version_utils.gd, ADR 0024). - Mode B (runtime):
{"authed":true}only — the shared transport’s default ack; the runtime supplies no override (runtime/mcp_runtime_server.gd) — no version orheadlessfields. - Failure: WS close 1008 “invalid token”. Auth handling is unified in the shared transport for both modes, and it enforces two deadlines at its poll (
poll_peers,transport/ws_transport.gd):- Auth deadline: a peer that has not authenticated by the first poll more than 2000 ms after its WebSocket opened → WS close 1008 “auth timeout”. The clock starts when a poll first sees the peer open (read at that moment, so a long frame from another peer earlier in the same poll does not count against it), not at the TCP accept, and the poll reads the peer’s waiting frames before it checks, so an auth frame already waiting at that poll still counts. Each server sets the deadline (
_AUTH_TIMEOUT_MSintransport/mcp_server.gdandruntime/mcp_runtime_server.gd;_auth_timeout_msin the transport). - Open deadline: a peer whose WebSocket is still not open 5× the auth deadline (10 s) after the toolkit accepted its TCP connection is dropped without a close code (the TCP connection is closed;
_OPEN_DEADLINE_FACTOR). The poll first reads an upgrade request already waiting, so a late poll drops only a client that sent none by the deadline.
- Auth deadline: a peer that has not authenticated by the first poll more than 2000 ms after its WebSocket opened → WS close 1008 “auth timeout”. The clock starts when a poll first sees the peer open (read at that moment, so a long frame from another peer earlier in the same poll does not count against it), not at the TCP accept, and the poll reads the peer’s waiting frames before it checks, so an auth frame already waiting at that poll still counts. Each server sets the deadline (
- Client version (Mode A): after a successful auth, the editor checks the server’s version (the frame’s
server_version, else itsversion, which is all a 1.0.x server sends) in_check_peer_compat(transport/mcp_server.gd), which keeps the console output and takes the floor verdict from itstransport/peer_compat.gdchild (assess,judge_floors, and the once-per-session record of printed errors). The floors come first (floor_verdictinversioning/mcp_version_utils.gd, major.minor only, a strictmajor.minor[.patch][-tag|+build]grammar): a server belowMIN_SERVER_VERSIONlogsMCP server <v> is below this toolkit's floor (server >= <floor>). Pin the recommended server from the dock's .mcp.json panel, or set the server version in your MCP client's config., and else a toolkit below the frame’smin_toolkitlogsThis toolkit (<v>) is below the MCP server's floor (toolkit >= <floor>). Update the addon (Godot Asset Store / Asset Library), or pin an older server in .mcp.json: @npgamedev/godot-mcp-server@<version>., each as one editor error per (state, server version) for the editor session, shown in the dock too (get_peer_compat/compat_status_changed, cleared when the last peer disconnects), in place of the product-version message. Each side checks the other’s floor against its own first (own floor first): the editor judges the server againstMIN_SERVER_VERSIONbefore it judges itself againstmin_toolkit, and the server judges the toolkit againstMIN_TOOLKIT_VERSIONbefore itself againstmin_server, so with both sides below, the two consoles print different lines. A frame withoutmin_toolkit(a 1.0.x server) skips only the toolkit-floor check;MIN_SERVER_VERSIONstill applies. A floor check whose version or floor does not parse flags nothing. When no floor check flags a side, the editor falls through to the product-version message: it compares the server’s version with its own plugin version (_check_version_mismatch→version_skew). A different major logs an editor error and a different minor logs a warning. A patch difference logs nothing, because compatibility floors are declared at major.minor. A non-semver value cannot be compared and logs nothing, and a frame without a version skips the check. While a local server build is configured (themcp_toolkit/server/local_patheditor setting orGODOT_MCP_DEV_SERVER_PATH, mirrored onto the editor server’sskip_version_checkflag byplugin.gd, on start and on every editor-settings change), the editor skips all of it and logsVersion check skipped (local server path).once per connection. The result stays in the editor console and the dock, never goes on the wire, and never refuses the connection. When the floors pass, the dock also names a connected server that differs fromCOMPATIBLE_SERVER_VERSION, patch gaps included (ui/dock/status/server_version_gap.gd, read byui/dock/status/dock_status_panel.gd): an older server always, a newer one only when the update check knows a newer toolkit (latest_known_version,versioning/update_check_runner.gd; a dismissed version still counts, and with the check turned off it knows none). A non-emptymcp_toolkit/server/version, a skipped check and a version it can’t compare show nothing. The line is advice and refuses nothing. The panel repaints it oncompat_status_changedand on the dock’s 1 s timer, since a settings change or a new check result moves it with no server event.
- Mode A (editor):
- Token: 64-char lowercase hex / 256-bit,
Crypto.new().generate_random_bytes(32).hex_encode()(security/auth.gd); written raw, no trailing newline (write_token); validated by plain==(validate). Shared by both modes. - Server consumer: the bridge sends
{"auth":"<token>","version":"<server-version>","server_version":"<server-version>","min_toolkit":"<M.m>"}as the first frame (min_toolkitisMIN_TOOLKIT_VERSIONinshared/version.ts) (authenticateintransport/authHandshake.ts, called fromcreateChannel’sperformAuth), re-reading the token from disk on every connect (transport/channel.ts→readToken, C18) so it always matches whatever the editor/runtime last wrote (the standalone-game self-heal relies on this re-read). From the editor ack it parsesgodot_version→ the bridge’sgetGodotVersion()(transport/bridge.ts) and stores it (feeds the version gate, C5/C9), and likewise parsesheadless→bridge.isHeadless()(transport/bridge.ts) —undefinedpre-auth, mirroringgetGodotVersion()— which the smoke/flows suites read to branch their headless-degraded tool assertions. For Mode B (runtime) the ack carries no version (orheadless) → the bridge gets the Godot version from the registry pre-pop instead (lookupProject,transport/bridge.ts), not the handshake. The bridge also checks the editor ack’s pluginversion(intransport/channel.ts; skipped on the runtime channel). The floors come first (checkFloorinshared/version.ts, the same grammar): a toolkit belowMIN_TOOLKIT_VERSIONwrites[bridge] ERROR: toolkit <v> is below this server's floor (toolkit >= <floor>). Update the addon (Godot Asset Store / Asset Library), or pin an older server in .mcp.json: @npgamedev/godot-mcp-server@<version>., and else a server below the ack’smin_serverwrites[bridge] ERROR: server <v> is below the toolkit's floor (server >= <floor>). Pin the recommended server from the toolkit dock's .mcp.json panel, or set the server version in your MCP client's config., each in place of the product-version line; both sides name the same two routes. Otherwise it compares the versions (compareVersionsinshared/version.ts) and writes a major mismatch to stderr as an error, and a minor mismatch or a missing or non-semverversionas a warning. A patch difference is silent.GODOT_MCP_SKIP_VERSION_CHECK=1(C10) turns every one of these lines off on the editor channel, floors included. - Constraint: localhost-only + a single shared token ⇒ this is a single-user local tool (the real boundary, alongside the read-only filter and the human in the editor).
C3 — Response envelope · public
- Toolkit shape:
- Success:
MCPToolkitSuccess.ok(data)returnsdatawithsuccess=trueadded (contract/mcp_toolkit_success.gd). It mutates its argument in place (deliberate). Success payloads never carrycode. - Error:
MCPToolkitError.fail(code,message,hint)→{"success":false,"error":<message>,"code":<code>}, plus"hint"iff an explicit non-empty hint is passed orcode ∈ DEFAULT_HINTS(contract/mcp_toolkit_error.gd). Error payloads never carrystatus. remediation: string[](success-side disclosure): a successful capture that required a visible side effect to produce a usable frame lists it here —editor.screenshotemits"switched_main_screen"(switched the main screen because the viewport it reads was hidden or collapsed: from a non-2D/3D screen, or from 3D to 2D for anode_paththat is neither aCanvasItemnor aNode3D) and/or"foregrounded_editor";runtime.screenshotemits"foregrounded_game". Absent when none (a clean capture omits the key), and it is an array because un-minimize + main-screen-switch can co-occur in one call. Screenshot-only today; a general success-side “what I had to do” channel.runtime.screenshot’s"foregrounded_game"is emitted only for a top-level game — an embedded playtest (the editor Game view; Windows/X11 4.4+, macOS 4.5+) can’t be independently foregrounded, so the lever is a no-op there and instead surfaces ahint(neverforegrounded_game).- Screenshot
image_response_mode(both capture tools): an optionalimage_response_mode: "inline" | "disk" | "both"(default"inline") selects the capture-return shape. inline (default):{image_base64, mime_type, width, height, bytes, image_detail, returned}. disk (lean envelope, noimage_base64):{path, width, height, bytes, mime_type, image_detail, returned, hint}wherepathis the globalized absolute file path andbytesis the PNG byte size on disk. both: the inline shape pluspath+hint. An optionalsave_path(.png;editor.screenshotallowsres://+user://screenshots/,runtime.screenshotuser://screenshots/only) names the destination for disk/both (auto-named underuser://screenshots/when omitted); in inline mode a suppliedsave_pathis validated but not persisted.remediation(andruntime.screenshot’shint) ride all three shapes. Shaping is owned by the runtime-safecontract/screenshot_response.gdhelper. - Screenshot
image_detailcap + disclosure (both capture tools): an optionalimage_detail: "full" | "mid" | "low"(default"full", toolkit-owned) caps the inline image’s long edge —full= native,mid≈ 1024 px,low≈ 512 px — proportional, aspect-preserving, and shrink-only (never upscales) viaImage.INTERPOLATE_LANCZOS. It applies to the inline image only:image_response_mode:"disk"/"both"always persists the full-res PNG regardless. Every shape echoes the appliedimage_detailplusreturned(a"WxH"string — the returned inline image’s dims for inline/both, the full-res saved-file dims for disk), so a size reduction is never silent. disk/both add ahintdisclosing the saved file is full resolution ("Saved full-res → <path>. Read it for pixel detail without re-capturing."), which composes with (does not clobber)runtime.screenshot’s foregroundhint. The purecontract/screenshot_response.gdshaper owns theimage_detail_dimscalculator + the disclosure threading; the capture handler owns theImage.resizeand encodes a full-res buffer for disk plus a downscaled buffer for the inline base64 (both mode carries both). A badimage_detailvalue →INVALID_PARAMS.
- Success:
- Server consumer: the bridge branches on the toolkit’s
successfield:callAndWrap(registration/toolDispatch.ts) treats{success:false}→toolErrorFromPayload(shared/errorContract.ts, preservingcode+message+ the toolkithint); the happy path →stableStringify(result)(shared/stableJson.ts, key-sort only) forwarded verbatim (REFLECT — no response-schema re-encode; the WS response resolves atmessage.resultintransport/channel.ts, the single forwarding point, andcallAndWrapwraps it as{content:[{type:"text",text:…}]}). The server never replaces or prepends to a non-empty toolkit-suppliedhint; it removes one only in the case below. A server-sidesuccessHintis injected only when the toolkit set none or an empty one (shouldApplySuccessHint, shared bycallAndWrapandinjectSuccessHint,registration/toolDispatch.ts).game_start(tools/playtest.ts) keeps the toolkit’s hint too, which can name a runtime opt-out the server cannot see: await_for_runtime:falselaunch that reportsruntime_ready:falsegets the server’s nudge only when the toolkit sent no hint, and await_for_runtime:truewait that ends without a runtime appends the server’s guidance after the toolkit’s hint in the onehintstring (withServerHint). That wait polls the editor’sdebug.state(read byreadDebuggerStop,tools/debuggerStop.ts, the one readerdebugger_get_logshares) and ends early when the debugger stops the game, since a stopped game cannot connect its runtime. An error break’s guidance says the game cannot continue and, from the latestbreakentry of the editor-sidedebugger.get_log, quotes the error and names the file and line when the entry has them, and, when it has the line and the error is a failed preload, the preloaded script. A breakpoint pause’s guidance points todebug_continue, and a wait that runs out its 10 s suggests a retry. None of the three adds a field. The server takes the location from the entry’ssourceandlinefields, reading the entry once more 500 ms later when it has none yet, since the toolkit fills it from the stack dump that follows the break. It takes the error from the entry’smessageby matching the toolkit’s wording of that sentence (breakReasonPatternintools/playtest.ts, againsttransport/debug_session_tracker.gd), so rewording that sentence on either side is a wire change: a message that no longer matches loses the quoted error and the preloaded-script sentence, but keeps the hint and its file and line. Its one removal: when await_for_runtime:truelaunch’s runtime connects, the server dropshintalong withruntime_discovery. On that path the toolkit’s only hint is the opt-out one, which a connected runtime makes moot. The screenshot tools are the one non-REFLECT success path:buildScreenshotResult(registration/screenshotResponse.ts) re-shapes the capture and carriesremediation,hint,image_detail, andreturnedthrough the text metadata block (the fields would otherwise be dropped by that re-shape). For a disk capture (apathwith noimage_base64) it emits a single text-only block —{path, width, height, bytes, mime_type, image_detail, returned, remediation?, hint?}— never an empty image block; inline/both keep the image+text multi-content. scene.create_nodeinline-property outcomes: apropertiesdict supplied at create time is post-set-verified per key. A silently-dropped write (a wrong-type valueObject.set()discards — the same classnode.set_propertyrejects) is restored, excluded fromproperties_set, and reported inproperties_failed: [{name, error}](theerrormirrorsnode.set_property’s message). A bare path (ares://,uid://oruser://String on a top-level Resource property,Modules.BarePathCheck.bare_path_message) is refused before the set and reported there with the same messagenode.set_propertygives, which names the tagged form where ares://path exists. The batchnode.set_propertyfails that entry with it,scene.instantiatelists it in the instance’sproperty_errors,node.manageduplicate fails with it asINVALID_PARAMS, andresource.writewarns with it and saves the rest. An array whose elements do not fit the property’s declaredArray[T]element type is refused before the set and reported there too. An engine-adjusted write (truncate/normalize) stores and counts, adding a delta warning towarnings: string[].properties_settherefore counts only the writes that actually stored.- Example: success
{"success":true,"status":"created","path":"res://scenes/main.tscn","root_name":"main"}· error{"success":false,"error":"file exists at res://…; set if_exists:'replace'…","code":"ALREADY_EXISTS"}. - Cross-ref: the
codevocabulary and hint auto-attach list = C4.
C4 — Error-code vocabulary (CODES) · public
- Toolkit shape:
MCPToolkitError.CODESenumerates 56 codes (contract/mcp_toolkit_error.gd) — the canonical wire vocabulary (full list in source).NOT_UNIQUE(script.edit:old_stringmatches more than once andreplace_allis not set) joinsNOT_FOUNDas the surgical-edit match-failure pair.EDITOR_VIEWPORT_UNAVAILABLE(editor.screenshot: window minimized-&-not-forced, or the main-screen heal left the viewport collapsed) andRUNTIME_WINDOW_MINIMIZED(runtime.screenshot: the game window can’t render — a top-level game minimized or fully occluded, decided capability-based fromDisplayServer.window_can_drawafter a bounded frame-wait, not by mode alone; an embedded playtest keeps compositing and never trips this) both signal a viewport that cannot composite a usable frame —EDITOR_VIEWPORT_UNAVAILABLEis retryable viaforce_foreground_editor, andRUNTIME_WINDOW_MINIMIZEDviaforce_foreground_gameon a top-level game (C8).DEFAULT_HINTSauto-attach for 7 codes:TIMEOUT,UNSUPPORTED,PATH_DENIED,PARENT_NOT_FOUND,COMPILATION_FAILED,GAME_NOT_RUNNING,RESPONSE_TOO_LARGE(the two screenshot codes pass an explicit cause-specific hint instead — they are not inDEFAULT_HINTS).LOG_BUSY/LOG_UNAVAILABLEare deliberately absent fromDEFAULT_HINTS: their recovery advice is version-gated (source:"buffer"is a real fallback only on Godot 4.5+), so every emit site passes the version-gatedlog_busy_hint/log_unavailable_hintexplicitly instead of relying on a default here. fail()— dev-time gate, string-tolerant wire: a debug-buildassert(code in CODES)enforces the vocabulary at dev time (mcp_toolkit_error.gd); release builds strip the assert, so the wire stays string-tolerant and theemitted ⊆ CODESaudit describes release behavior as advisory, not enforced. (UNSUPPORTED,CLASS_MISMATCH, andUNSUPPORTED_FILE_TYPEare all inCODES.)- Server consumer (own-enum + string-tolerant): the server keeps its own
ErrorCodeunion (shared/types.ts), whose header says it must stay in sync withMCPToolkitError.CODES— but the emit path is deliberately string-tolerant:toolError(code: ErrorCode | string, …)(shared/errorContract.ts) andtoolErrorFromPayload(typeof obj.code === "string" ? obj.code : "INTERNAL") forward any unknown plugin code verbatim, never reject or remap. The union names every code inCODESplus seven that originate in the server and never travel through the plugin:AUTH_FAILED,CANCELLED,CLOSED,LSP_PORT_CONFLICT,LSP_UNAVAILABLE,RPC_ERRORandSEND_FAILED. A toolkit code the union does not name yet still passes straight through; the dual enum is documented own-enum + string-tolerant wire, not a defect.
C5 — Dispatch + concurrency notifications · public
- Toolkit shape (dispatch lives in
transport/dispatch/*+transport/notifier.gd):- JSON-RPC errors:
-32700parse and-32600for a frame that is not a JSON object (transport/mcp_server.gd, before dispatch),-32600missing method,-32601method not found / unregistered / hot-reload race (transport/dispatch/server_request_router.gd,transport/dispatch/dispatch_lane.gd),-32000mutation-watchdog timeout (server-emitted,transport/dispatch/mutation_watchdog.gd). - Server→client notifications:
_queued {"request_id":<id>}(command parked behind a mutation-lock or scene-lease) and_executing {"request_id":<id>}(mutation began) — both fromdispatch_lane.gd, sent viatransport/notifier.gd. - Client→server notifications:
_cancel {"request_id":"<id>"}(fire-and-forget cooperative cancel — triggers an in-flightctx.cancel()or flags queued entries) andecho <params>(transport diagnostic, echoes back) — both inserver_request_router.gd. - id coercion: JSON numbers parse as float; whole-float ids coerce back to int so
{"id":1}round-trips (server_request_router.gd). - Lanes: read-only commands bypass both locks; mutations serialize single-in-flight FIFO; scene-lease routing precedes both (
is_read_only/needs_serialization,transport/mcp_toolkit_command_registry.gd).
- JSON-RPC errors:
- Server consumer: the bridge owns the JSON-RPC id↔response correlation (per-request id, resolver map) in
createChannel(transport/channel.ts), which also restarts a pending call’s timeout on_queued/_executing; LSP tools are the one exception that bypasses this dispatch entirely (own TCP client, C15/C19,groups/groupToolHandlers.ts). The server is authoritative for the version-unsupported error: two layers gate before the WS forward — (1) a registration-time filter (registration/toolRegistry.ts) drops a known-incompatible tool fromtools/list; (2) a per-call defense-in-depth check returnstoolError("UNSUPPORTED", "<name> is not supported on this Godot version (connected: <maj>.<min>)", "<versionSupportText> Use classdb.get_info for alternatives.")— the version requirement rides in the hint, not the message body. On the happy path the server therefore never sees the toolkit’s-32601version-block. - Version-gating parity invariant: the server is authoritative and reports the connected version as
connected:. A version-gated built-in needs both a toolkit.with_min_godot_versiongate and a matching server-catalogue bound (the server bound is authoritative for the message). The toolkit’s own version-block branch is unreachable via live transport — the-32601 has_commandshort-circuit wins over it. Exactly one built-in is gated today:scene.close @4.5+.
C6 — Idempotency: status + if_exists · public
- Toolkit shape:
status(result discriminator): the create subset is the closed setcreated/returned(idempotent no-op) /replaced(commands/scene_commands.gd,commands/resource_commands.gd,commands/editor_helpers.gd).statusis a general result discriminator, not create-only — non-create mutations also set it (added/removedfor node-group ops incommands/node_commands.gd;already_runningincommands/playtest/playtest_control.gd). The create subset is closed; the full field is open per-command.if_exists(file-level creates):return(default → idempotent no-op,status:"returned") /fail(→ALREADY_EXISTS) /replace(→ overwrite,status:"replaced"+ metadata). An invalid value →INVALID_PARAMS.- File-level (support
if_exists):scene.create, plusasset.import,texture.generateandsound.generatethroughwrite_asset_with_settle(commands/editor_helpers.gd). File-level, return-only (noif_exists):scene.create_inherited(an existing file →returned, left unchanged). Upsert (noif_exists):resource.writeupdates an existing file’s properties in place and saves it, with nostatus; it creates a missing file only whentypeis given (→created). Node-level (return-only, noif_exists):scene.create_node(matching class →returned, elseCLASS_MISMATCH),scene.instantiate(collision →returnedor auto-rename). - Returned-path disclosure: a
status:"returned"response no longer silently drops the args it didn’t apply.scene.create_node/scene.instantiateadd awarningnaming the ignoredproperties/layout_mode/unique_name/transform;resource.write, which updates an existing file rather than returning it, appends towarnings[]naming an ignoredtype. The disclosure fires only when such an arg was actually passed, so it adds nothing to a call that passes none.
- Server consumer: pure passthrough (REFLECT).
if_existsis a request param the LLM sets (carried ininputSchema);statusis a response field the bridge forwards verbatim viacallAndWrap(registration/toolDispatch.ts) →stableStringify(shared/stableJson.ts) →message.result(transport/channel.ts) — no server-side interpretation ofcreated/returned/replaced. The toolkit owns the discriminator; the server adds no idempotency logic of its own. - Example (
scene.createwithif_exists:"replace", other fields omitted):{"success":true,"status":"replaced","path":"res://x.tscn","root_type":"Node2D","previous_root_type":"Node"}.
C7 — Type-tag coercion vocabulary · public
- Toolkit shape (
contract/coerce.gd, bidirectionalcoerce_value⟷serialize_value): complex Godot types cross JSON as tagged dicts{"type":"<Tag>",…}. 18 tags:Vector2{x,y}·Vector3{x,y,z}·Vector4{x,y,z,w}·Vector2i{x,y}·Vector3i{x,y,z}(noVector4i) ·Color{r,g,b,a}(a default 1.0) ·Rect2{x,y,w,h}·Rect2i{x,y,w,h}·Transform2D{x_axis,y_axis,origin}·Transform3D{basis{x,y,z},origin}·NodePath{path}·Resource{path[,class]}·ResourceRef{path}(alias of Resource) ·NewResource{class,properties}(input-only) ·PackedVector2Array{values:[…]}·PackedVector3Array{values:[…]}·PackedColorArray{values:[…]}·LayerMask{category="2d_physics",layers:[…]}→ int bitmask.- Unknown tag → reject with
{"_coerce_error":"Unknown type tag '<x>'. Supported: …"}— not passed through.
- Server consumer (REFLECT): the server does all coercion handling on the request path only —
inputSchemaZod with LLM string-coercion (addStringCoercion,shared/schemaCoercion.ts) so a JSON-stringified tagged dict re-parses; it does not re-encode on the response path. The tagged read-back forms (including theserialize_valuePacked* arms and thesave.read/script.readpaging fields) surface transparently throughcallAndWrap(registration/toolDispatch.ts) →stableStringify(key-sort only,shared/stableJson.ts) →message.result(transport/channel.ts). The bidirectional symmetry is therefore the toolkit’scontract/coerce.gdcontract; the server forwards both directions verbatim. (Some top-level paging keys, e.g.offset, are declared in the request Zod so the catalogue does not strip them — request-path, not a response re-encode.) - Example:
{"type":"Transform3D","basis":{"x":{"x":1,"y":0,"z":0},"y":{"x":0,"y":1,"z":0},"z":{"x":0,"y":0,"z":1}},"origin":{"x":0,"y":1,"z":0}}.
C8 — Tool names & param schemas · public
- Toolkit shape: one handler per command, across the
commands/*.gdmodules (including thecommands/{editor,input_map,playtest,tileset}/subdirs), each astatic register(registry, …)(most also take the server), nameddomain.verb(e.g.scene.create,node.set_property). Param schemas are the JSON shapes each handler reads fromparams(including the C7 tagged types). The naming conventiondomain.verb→domain_verb(snake_case tool name) is what the server mirrors. - Server consumer: the projected surface is the catalogue —
ALL_TOOL_DEFS(registration/catalogue.ts), the single deduplicated SSOT of everyToolDef {name (snake_case), method (dotted), description, describe? (the description rendered for the connected Godot version), inputSchema, annotations?, godotMin/MaxVersion?, successHint?, operationParam?, operations?, operationHints?, pathParams?}(shared/types.ts), spread fromtools/*.ts. The eager startup surface is a visibility partition =EAGER_TOOLS − GROUP_TOOL_NAMES(startup/serverMode.ts,security/profiles.ts), plus the meta toolsdiscover_toolsandextensions_refresh, registered directly ingroups/groups.ts/extensions/extensionRegistrar.ts— outsideALL_TOOL_DEFS; on-demand group tools are absent (no stubs) untildiscover_toolsactivates them. Every registration funnels through the singleregisterToolWrappedchoke point (registration/toolRegistry.ts). A CI completeness gate (test/sections/01_catalogue.ts) asserts the group / runtime / LSP names ⊆ALL_TOOL_NAMES, no dups — the naming lockstep is build-enforced. The current totals (all tools, eager, on-demand, meta, groups) come fromgodot-mcp-server --tools-count, which prints them without connecting to an editor. - Tool list lives elsewhere: the authoritative per-tool name + parameter schema list is not duplicated here — it lives in the generated tool-reference doc. This section covers the naming convention and the registration/activation mechanism only.
- Read/write split: read-only sibling tools are kept separate from their mutating verbs (command-query separation) — e.g.
audiobus.list(commands/audiobus_commands.gd),animationtree.list(commands/animation_commands.gd) andinput_map.list(commands/input_map/input_map_commands.gd, its shapes in C23) are standalone read tools, not sub-actions of an*.editverb. - Whole-file vs surgical write split:
script.write(whole-file create/overwrite) andscript.edit(surgicalold_string→new_stringreplacement) are kept as separate mutating verbs — the MCP analogue of nativeWritevsEdit— rather than one overloaded write tool (commands/script_commands.gd). Both route through the same private write/undo/index/diagnose pipeline (_commit_content), so an edit carries the identical UndoRedo entry,EditorFileSystemreindex, inline.gddiagnostics and reload of the cached script (on 4.2.2+, only when it compiles) as a whole-file write, plus areplacementscount.script.editreportsNOT_FOUND(no match),NOT_UNIQUE(multiple matches withoutreplace_all), orINVALID_PARAMS(no-op / emptyold_string). An optionaleditsarray of{old_string, new_string, replace_all?}objects replaces the top-level trio (a top-levelold_string,new_stringorreplace_all: truebeside it isINVALID_PARAMS; areplace_all: falseis ignored): the edits apply in order, each to the text the earlier ones leave, and the file is written once, or not at all when any edit fails (the error message names it,edits[N]: …);replacementsis the total. - Uniform pagination contract: read/cap tools return one self-describing envelope, built through the shared
Modules.Paginationclass (contract/pagination.gd) —returned(this page’s size), a canonicaltotal_<unit>(total_classes,total_nodes,total_cells,total_assets,total_dependencies,total_lines,total_matches,total_bytes), andhas_morealways present, plus a linear resume field (next_offset/next_start_line) where the read is resumable — or a documented cursor-less nav (path_prefix/region) where it is not — with the paginate guidance in each tool’s.describe()(paginationDoc). Response is REFLECT (no server-side response builder); the only server reads of these fields are the summary handlers (consoleSummaryHandler,debuggerLogHandler) plus theerrorContract.tscrash-context fallback, via sharedPAGE_FIELDconsts (ADR 0020 · code-standards B5). - Event-batch vocabulary:
input_simulate(input.simulate,runtime/mcp_runtime_server.gd) exposes an enumeratedevent_typeset as part of its public param schema —key | mouse_button | mouse_motion | action | click | click_node | send_text.send_textis a convenience synthesizer (a string → NInputEventKey(unicode)events delivered viaViewport.push_input+ an optionalsubmitEnter) returningfocus_target/focus_source/text_changed/text_after(secret-redacted) /chars_sent/hint. The server mirrors the vocabulary in theevent_typezod enum (twice — single-object and array-item variants);event_dataforwards untyped (z.record), so the per-field shape is the toolkit’s contract. - Screenshot foreground levers:
editor_screenshot(editor.screenshot) reads an optionalforce_foreground_editor: bool(default false) andruntime_screenshot(runtime.screenshot,runtime/mcp_runtime_server.gd) an optionalforce_foreground_game: bool(default false). When set, the tool un-minimizes + raises/focuses the target window before capturing (then discloses viaremediation, C3) instead of returning theEDITOR_VIEWPORT_UNAVAILABLE/RUNTIME_WINDOW_MINIMIZEDsignal (C4); default-off so an interactive user’s window is never yanked. The server declares both asz.boolean().optional()in the tool inputSchema with a.describe(), so they reach the toolkit (the catalogue zod strips undeclared top-level params). - Screenshot capture-return controls: both capture tools also read an optional
image_response_mode: "inline" | "disk" | "both"(z.enum(...).optional(); toolkit default"inline") andsave_path: string(the.pngdestination for disk/both; auto-named when omitted).editor.screenshot’ssave_pathallowsres://oruser://screenshots/;runtime.screenshot’s allowsuser://screenshots/only (pathParamsprefixes["user://screenshots/"]). The response shapes these select are the C3 inline/disk/both envelopes; the enum has no.default()(the toolkit owns the default, the.describe()states it). Both tools additionally read an optionalimage_detail: "full" | "mid" | "low"(z.enum(...).optional(), no.default()— toolkit-owned default"full") capping the inline image’s long edge (mid≈ 1024 px,low≈ 512 px; proportional, aspect-preserving, shrink-only; inline-only — disk/both stay full-res); the response echoes the appliedimage_detail+ areturned“WxH” (C3).editor.screenshot’s formersize{width,height}param is removed (pre-1.0, no back-compat) — it was node-focus-only exact-WxH that could aspect-distort/upscale;image_detail’s universal proportional cap supersedes it, and node framing staysnode_path’s job.
C9 — Read-only model · public
- Toolkit shape: server-authoritative. A built-in tool’s client-visible annotations (
readOnlyHint/destructiveHint) are the server catalogue’s (C8), sosave_write/save_deletecarrydestructiveHint:truethere. The toolkit publishes annotations only for extension tools: the registry maps the options builder’s friendly flags (contract/mcp_toolkit_command_options.gd) to MCP annotations in the command metadata the extension path reads (transport/mcp_toolkit_command_registry.gd). It does not gate dispatch onGODOT_MCP_READ_ONLY. It consumes its ownread_onlyflag only for (1) concurrency routing (is_read_only()→needs_serializationread-bypass,transport/mcp_toolkit_command_registry.gd) and (2) a best-effort dock/status mirror parsed from.mcp.json(ui/mcp_json_sync.gd, non-authoritative). So the server’s annotations drive read-only filtering, and the toolkit’sread_onlyflag drives the concurrency lock-bypass; each must be right on its own. - Session-lifecycle commands:
game.start/game.stopmutate, so they are not markedread_only; exclusive execution alone serializes them.debugger.get_logisread_onlyand only reads (commands/playtest/playtest_commands.gd). - Server consumer: (a) layer = filter at registration —
isExcludedByReadOnly(readOnly, annotations)(security/profiles.ts) skips the tool so it is never registered → absent fromtools/list(reg sites acrossregistration/toolRegistry.ts,groups/groupActivation.ts,groups/extensionGroups.ts,extensions/extensionRegistrar.ts,extensions/extensionChanges.ts). There is no per-call forward-time reject — the tool simply is not there. (b) semantics = STRICT:isAllowedInReadOnly(security/profiles.ts) exposes a tool iffreadOnlyHint:true ∧ ¬destructiveHint; an un-annotated tool → excluded (safe), so an un-annotated mutating tool is hidden. The server adds one server-local rule:readOnlyHint ∧ destructiveHintis a contradiction → treat-as-mutating + stderr warn. (c) test:test/unit/profiles.test.tspins the predicate, the contradiction rule included, andisExcludedByReadOnly;test/unit/groupActivation.test.tspins the group path (an all-mutation group activated under read-only registers nothing).
C10 — Environment variables & CLI flags · public
- Toolkit-consumed:
GODOT_MCP_TOKEN_PATH(overridesget_token_path(),security/auth.gd); the listen-port vars, all resolved by the export-cleantransport/port_config.gdand consumed bytransport/mcp_server.gd(editor) +runtime/mcp_runtime_server.gd(runtime):GODOT_MCP_EDITOR_PORT/GODOT_MCP_RUNTIME_PORTpin an exact listen port (bind-exact-or-fail — never scans elsewhere, bounded same-port grace then a loud error), andGODOT_MCP_EDITOR_PORT_MIN/_MAX/GODOT_MCP_RUNTIME_PORT_MIN/_MAXrelocate the scan band (defaults 6550–6560 / 6570–6585, inclusive). The two modes are exclusive (a pin ignores the band); a malformed pin / out-of-range / MIN>MAX is a clear error (dock + log in the editor; log only in the game), never a silent default.GODOT_MCP_RUNTIME=0/false/off(any case; the name and the off values live in the export-cleanruntime/runtime_opt_out.gd) keepsruntime/mcp_runtime_server.gdinert for that run: no listen, noset_runtime, and noclear_runtimeon exit, so a scripted or headless run of the project leaves the running game’s runtime entry (C20) alone; unset or any other value leaves it on.GODOT_MCP_HIDE_UNAVAILABLEis reserved/unused.GODOT_MCP_DEV_SERVER_PATHis a contributor override, the fallback for themcp_toolkit/server/local_patheditor setting (C11). The toolkit reads it when it writes.mcp.jsonor works out what a write would produce (the dock’s server row), when a self-update decides whether it may move the pin (C11; the move’s own write names its package spec and doesn’t read the variable), and to decide whether the editor skips its connect-time version check (C2):uses_local_serverinui/mcp_json_write_flow.gdanswers that from the setting and this variable, andplugin.gdmirrors the answer onto the editor server. Two test-only variables reach the self-update:GODOT_MCP_UPDATE_CHECK_HOST, anhttporhttpsloopback origin (resolve_host,versioning/update_check.gd; any other value is ignored), replaces the scheme and host of the update check’s requests and of the self-update’s downloads (the trust documents, manifest, signature and zip), and the download’s redirect rule then also accepts that origin;GODOT_MCP_UPDATE_ALLOW_HEADLESS=1(self_update/install_guards.gd) lets a headless editor settle and apply an update, which it otherwise leaves alone (self_update/update_lifecycle.gd). The recovery plugin, which puts the previous version back when an update does not load (C22), reads neither variable and always stays out of a headless editor (stays_outinself_update/recovery/recovery_journal.gd), so a headless run underGODOT_MCP_UPDATE_ALLOW_HEADLESSgets no recovery (no roll forward, roll back or restore). - npm-consumed, toolkit-owned:
npm_config_prefer_offlinein the written entry’s env. The.mcp.jsonwriter owns it (apply_owned_env,ui/mcp_json_sync.gd):"true"when the package spec names one exact version (is_exact_spec,ui/mcp_json/server_pin_policy.gd), sonpxstarts the cached copy without asking the registry, and removed for any other spec (@latest, a range, a tag) and for a local build, since it would freeze a floating spec at whatever is cached. It overrides the existing file’s value on every write. npm reads it; the server never does. - Server-consumed, toolkit-owned:
GODOT_MCP_SKIP_VERSION_CHECKin the written entry’s env. The same writer owns it (apply_owned_env):"1"when the entry is built from a local server build (themcp_toolkit/server/local_patheditor setting, elseGODOT_MCP_DEV_SERVER_PATH; keyed to that setting, never to the entry’s shape), removed otherwise, on every write. The server reads it at startup (resolveSkipVersionCheckinstartup/startupEnv.ts, handed tocreateBridgebybuildBridgeOptions): only"1"turns off the editor channel’s connect-time version check, floor lines included (C2), and the server writes[bridge] version check skipped (GODOT_MCP_SKIP_VERSION_CHECK)once on stderr. The toolkit’s own side of the opt-out reads the local-path setting (orGODOT_MCP_DEV_SERVER_PATH), never this variable (C2). - Server-consumed (the bridge reads its process env, launched from
.mcp.json):GODOT_MCP_READ_ONLY(→ the C9 registration filter,security/profiles.ts);GODOT_MCP_EDITOR_PORT/GODOT_MCP_RUNTIME_PORT(pin a channel port to dial, skip the registry lookup — resolved byresolvePortConfiginstartup/portConfig.ts(viaresolvePortConfigOrExitinindex.ts) and handed tocreateBridgebybuildBridgeOptionsinstartup/bridgeOptions.ts; the same two vars the toolkit reads to listen, so a pin inherited by both processes makes listen + dial agree);GODOT_MCP_LSP_PORT/GODOT_MCP_LSP_HOST(the top-priority LSP endpoint override, the multi-instance lever — read inlsp/lspClient.ts, C19, and instartup/portConfig.tsviaresolvePortConfig);GODOT_MCP_PROJECT_PATH(the project for registry lookup + LSP dispatch, elsecwd; an empty value counts as unset —resolveProjectPathinstartup/projectPath.ts, called fromindex.tsandgroups/groupToolHandlers.ts);GODOT_MCP_CONFIG_VERSION(set by the template, a migration marker;warnConfigVersioninstartup/startupEnv.tswarns on stderr when it is missing, not a number, older or newer than the server expects);GODOT_MCP_SCRIPT_READ_LIMIT/GODOT_MCP_WS_BUFFER_LIMIT(response caps in bytes, read byresolveResponseCapsinstartup/startupEnv.ts; after every editor auth the bridge pushes its whole set of env overrides withmeta.set_limits, in KB, as{}when neither is set, see C22; each push replaces the editor’s previous set, so an unset cap leaves the project’s ownmcp_toolkit/limits/*value in force);GODOT_MCP_RATE_LIMIT(the most tool calls the server accepts per minute, off when unset or0—startup/hooks.ts; server-local; the toolkit never sees it). The_MIN/_MAXband vars are listen-side only — the server never reads them (registry discovery covers the scanned case).GODOT_MCP_TOKEN_PATHis also the server-side operator override (C18,transport/tokenPath.ts). The deadGODOT_MCP_PROFILE/--litedeprecation stubs are removed (no-op pre-1.0). - Channel opt-out family:
GODOT_MCP_<CHANNEL>=0(alsofalse/off, any case) opts the process that reads it out of that channel.GODOT_MCP_RUNTIMEis the one built, and takes effect only on the running game’s side (the server never reads it); a game the editor launches inherits the editor’s environment, sogame.startadds a hint when the editor’s own environment carries the opt-out (commands/playtest/playtest_control.gd).GODOT_MCP_EDITOR=0is reserved and not built. - Server CLI flags (hand-rolled parser in
startup/cliArgs.ts, resolved instartup/portConfig.ts; precedence CLI > env > registry discovery > default):--editor-port <n>/--runtime-port <n>/--lsp-port <n>/--lsp-host <h>move the dial target (connect-side — CLI can’t reach the toolkit’s listen port), plus--help,--tools-countand--list-eager. - Desync cross-check: because a pin can reach one side only (e.g.
.mcp.jsonsets it for the server, a desktop-shortcut editor launch doesn’t inherit it), when a pinned editor connect or auth fails, the server does one registry read to check whether the live editor is on the pinned port (transport/bridge.ts; the healthy path never reads it); a mismatch is a precise, actionable error, never a silent hang. The toolkit publishes its real bound port in all modes (pin included) — re-published on every fresh bind, so even a pinned port that frees late after a startup conflict lands in the registry — precisely so this check has ground truth. The listen-side twin is the editor dock warning + status-row state on any not-listening condition (pinned port occupied, scan band exhausted, or invalid config). - Constraint: the
.mcp.json.templatesetsGODOT_MCP_CONFIG_VERSION(and the pinned form’snpm_config_prefer_offline) but notGODOT_MCP_TOKEN_PATH; with it unset the toolkit globalizesuser://…/mcp_tokento an absolute path before publishingtoken_path(→ C18), so the bridge does not have to derive it.
C11 — .mcp.json file format · public
- Toolkit shape: read (
ui/mcp_json_sync.gd) — readsmcpServers.<key>.env(string-coerced), keying on agodot-mcp-toolkit/godot-mcpsubstring. write (ui/mcp_json_sync.gd, invoked via theui/mcp_json_write_flow.gdconfirm helper from the dock, the wizard, the Tools menu and the enable-time prompt,ui/mcp_json_enable_prompt.gd, and directly, with no confirmation, by the self-update’s move of the toolkit’s own pin, below) — builds themcpServers.<key>entry per-OS (macOS:npx; Windows:cmd /c npx; Linux:npx) from the template’s env skeleton, preserving the existing entry’s env keys; regenerated on demand. A write replaces only the toolkit’s own entry and keeps every other server and top-level key as parsed (merge_document, key order kept). The entry isgodot-mcp-toolkit, or another key containinggodot-mcpwhose entry names@npgamedev/godot-mcp-serverin its args, runs agodot-mcp-servercommand (a global install), or carriesGODOT_MCP_CONFIG_VERSIONin its env (_find_own_key); any other server is left alone. The file is re-serialized (tab-indented), so its formatting is not preserved. A file that exists but is not a JSON object, or whosemcpServersis present and not an object, is never written, even when the caller forces it: the write reports.mcp.json isn't valid JSON, or its mcpServers isn't an object — fix or delete it, then retryand the write flow offers to open the file. The write flow asks for confirmation only when the file already holds a toolkit entry that differs from the one the write would emit (the dock, the wizard, the Tools menu and the enable-time prompt share that rule). Each passes-y @npgamedev/godot-mcp-server@<spec>tonpx, where the spec comes from themcp_toolkit/server/versionproject setting (C22,resolve_package_specin the server pin policy,ui/mcp_json/server_pin_policy.gd): empty = Pinned, the toolkit’sCOMPATIBLE_SERVER_VERSION(versioning/mcp_version_utils.gd, the same version the template carries;scripts/release.shsets both);latest(any case) = Latest; anything else is passed through as an npm version, range or tag, unvalidated. When the machine’smcp_toolkit/server/local_patheditor setting is set, or else the editor’s environment setsGODOT_MCP_DEV_SERVER_PATH, the command becomesnode <that path>instead, on every OS, for a local server build (uses_local_serverinui/mcp_json_write_flow.gdanswers whether a write would build one, from the same source the write reads). The env carries the builder-ownednpm_config_prefer_offlineand, for a local build,GODOT_MCP_SKIP_VERSION_CHECK(C10). - The last-written record: after a successful write, the write flow records the written entry’s classification (
classify_server_entryin the server pin policy:npx-bare,npx:<version part>,local:<path>orunknown; the Windows and barenpxforms classify alike) in the editor’s project metadata (sectionmcp_toolkit, keylast_written_server_spec): machine-local, never inproject.godotor the repo, never registered and never scrubbed. The dock’s.mcp.jsonpanel shows the server spec in an always-visible row whenever the file has a toolkit entry (or a local build is wanted but not yet written), and its one button switches between Pinned and Latest, saving themcp_toolkit/server/versionproject setting, then rewrites the entry through the shared write flow. The row compares the file’s entry (get_server_spec, found like the read side), that record and the spec a write would produce now (nudge_state): an entry the toolkit wrote that no longer matches gets an amber offer to update or pin it, one set by hand gets a quiet offer to restore the recommended spec, and the row rewrites nothing without the user pressing the button and confirming. An unversioned entry with no record counts as toolkit-written (an older toolkit wrote it before records existed). The unversioned form and@latestcount as the same spec. - The pin move after a self-update (
ui/mcp_json/server_pin_move.gd): when an editor start’s settle reports that an update installed (the installer’supdate_settledsignal,self_update/update_installer.gd, emitted before its first state change, or, when another editor’s exit may still be applying an update, once that apply’s 60-second window has passed), the toolkit moves its own entry to the newCOMPATIBLE_SERVER_VERSIONwithout a confirmation, since the user started the update. The entry moves only whenmcp_toolkit/server/versionis empty, no local server path is set, the new version is exact and differs from the one the previous toolkit recommended (the journal’scompatible_server), and the entry isnpxat an exact version equal to that old recommended version or to this machine’s last-written record (pin_move_targetin the server pin policy). A pin set by hand to any other version, a version setting, a local server path and an entry with no version, a range or a tag all stay; a project that wants to hold a version back sets the setting. The move rewrites the entry like any write and records it as this machine’s last write. Other servers and top-level keys stay, and so do the entry’s env keys, except the two the builder owns:npm_config_prefer_offlineis set andGODOT_MCP_SKIP_VERSION_CHECKis removed (C10). The entry is rebuilt for this OS, so any other field or arg in it is dropped, and Undo does not restore them. While the entry still runs the moved version, the update notice names both servers. It offers Undo for this editor start, until the notice is closed, while the whole file’s text is unchanged since the move. An edit that keeps the moved server leaves the line and takes Undo away; an edit that names another server takes both. Undo writes the old version back the same way, records it, and marks the update in project metadata (sectionmcp_toolkit, keypin_move_undone_for, the toolkit version whose move was undone; machine-local, never registered and never scrubbed), so a second report of the same update does not move the pin again. A file edited after the move is never written by Undo: the notice reads the file when it redraws and doesn’t watch it, so the button can still show after an edit, and a click then writes nothing, warns that the file changed and redraws. In an editor, safe save (filesystem/on_save/safe_save_on_backup_then_rename, on by default) swaps the file in insideFileAccess.close(), which returns nothing, so the writer checks for itself (_store): it refuses a target with the read-only attribute before opening it, reads the file back after closing it, and reports a failure on a mismatch. A failed write records nothing. After a failed move the notice doesn’t say the pin moved; a failed Undo reports why in a toast and marks nothing. A refusal, a failed open or a failed swap leaves the file as it was, though a swap that fails on a locked file can leave the engine’s temp file beside it; with safe save off, a write that stops partway can leave the file cut short. On Linux and macOS,chmod a-wdoesn’t stop a safe save, whoserenamereplaces the file (the engine’s behaviour), so that write succeeds and the pin moves. A malformed file (is_malformed: not a JSON object, or anmcpServersthat isn’t one) hides its pin, so the entry can’t be judged. It counts as a failed write too, with nothing written, only when every other leg of the rule allows a move (allows_pin_movein the server pin policy: the setting is empty, no local server path is set, and the new version is exact and differs from the old) and this machine hasn’t undone this update’s move. If any of those fails, the notice says nothing about the pin. Both kinds of failed write say why in the notice and offer an Update .mcp.json button that writes through the shared write flow with the panel’s confirmation text (server_change_body). After a write that failed on a well-formed file, the line and the button last, for this editor start, until the notice is closed or, at its next redraw, the entry changes. After a malformed file, they last, for this editor start, until the notice is closed or, at its next redraw, the entry runs the new version, so fixing the file keeps them; while the file is still malformed, the flow refuses and offers to open it. Before the click, when the pin would move, the editor-start update window and the badge’s offer of the release say so (previewandpreview_line), naming the release’s recommended server from its verified manifest’scompatible_server(offered_compatible_server,self_update/update_installer.gd). A manifest that names no stable server version shows no line, and the pin still moves after the install. A click after a failed first check shows no line either, since no manifest is known yet. Neither surface adds a choice. - Server consumer: the MCP client (Claude Code) reads
.mcp.jsonto launch the server with the right command + env. The server itself re-reads it on config-reload:readMcpJsonEnv(startup/configReload.ts) finds thegodot-mcp*server entry (mirroring the toolkit’s_find_server_key) andapplyEnvUpdatesets every key in that entry’senvand deletes theGODOT_MCP_*keys the entry no longer lists, so the process env outside the entry is never touched.handleConfigReload(startup/reconcile.ts) drives it, on a reconnect’sconfig_reloadedand when the connected Godot version changes major.minor (onGodotVersionChanged, wired inindex.ts), both debounced 300 ms, and at most once from the startup reconcile when the first tool surface was incomplete. Theconfig_versionmigration is a client/server matter, outside this cell’s wire shape.
C12 — Tool group names · semi-public
- Toolkit shape: each command may declare a
groupvia the options builder (contract/mcp_toolkit_command_options.gd); the registry publishes that per-commandgroup(transport/mcp_toolkit_command_registry.gd). Group membership + on-demand activation are server-side. - Server consumer: the server owns the group catalogue —
GROUPS: GroupDef[](canonical order ingroups/builtinGroups.ts, per-group defs ingroups/defs/*.ts; eachGroupDef(groups/groupTypes.ts) is{name, description, tools: string[], keywords: string[]}) + the derivedGROUP_TOOL_NAMES/RUNTIME_TOOLS/LSP_TOOLSindex sets (groups/groupCatalogue.ts).discover_toolskeyword-searches/scores/activates these group names (groups/groupMatch.tsscoring +groups/groupActivation.ts); group membership holds tool names resolved againstALL_TOOL_DEFS(registration/catalogue.ts). - Group list lives elsewhere: the authoritative group-name catalogue is not duplicated here — it lives in the generated tool-reference doc.
C13 — Extension API · semi-public
- Toolkit shape: an extension is an
MCPToolkitExtension(GDScript,extensions/mcp_toolkit_extension.gd) or anMCPToolkit*-prefixed.cs(C#) with one virtualregister(registry, server). Theregistryfacade (the single reachable surface, especially for C# which cannot await GDScript statics) exposes 7 methods (transport/mcp_toolkit_command_registry.gd):create_options(),create_extension_options(description),create_undo_action(description, context_object=null),queue_save(path=""),check_save(save_id, clear=false),fail(code,message,hint=""),require(parameters, required).- Cancellation ctx (
contract/mcp_toolkit_tool_context.gd):signal cancelled+is_cancelled() → bool. Handler arity — non-cancellable handlers get(params), cancellable get(params, ctx)(dispatch passesctxwhen the command isis_cancellable). - Safe-save (
scene/mcp_toolkit_safe_scene_ops.gd) and the undo builder (scene/mcp_toolkit_undo_redo_action.gd, headless-no-op) are the other semi-public extension surfaces — extension code depends on their method names.
- Cancellation ctx (
- Server consumer: the server projects each discovered extension command into an MCP tool.
discoverExtensions()(extensions/extensionDiscovery.ts) pulls the toolkit’s extension commands withextensions.refresh(a forced filesystem scan, so files added while the editor was unfocused are seen), falling back toextensions.listfor an older plugin without it → builds{readOnlyHint/destructiveHint/idempotentHint ?? false}annotations (extensionAnnotations,extensions/extensionCommand.ts), applies the C9 read-only skip, and registers viaregisterToolWrapped(registration/toolRegistry.ts, called fromextensions/extensionRegistrar.ts); grouped extension commands defer to a dynamic extension-group (groups/extensionGroups.tsaddExtensionGroup). Each extension cmd carries its own raw JSON-Schema, whichregisterToolWrappedturns into Zod (jsonSchemaToZodShape,shared/schemaCoercion.ts). Version bounds stay on the toolkit side: itsadd()refuses a command outside the running engine’smin/max_godot_versionrange, so a blocked command never reaches the list, and the list entry carries no bounds (C14). The server applies no version gate to an extension tool: its registrar (extensions/extensionRegistrar.ts) and the extension-group path (groups/extensionGroups.ts) callregisterToolWrappedwithout version bounds. Threat model = full-trust (ADR 0009). - Collision guard: the toolkit rejects a colliding extension
addmade while the extension’sregister()runs, so the first-loaded command wins (wire shape unchanged; anaddmade afterregister()returns is not guarded and replaces the incumbent); the server also guards explicitly —extensionNameCollides(toolName)=isBuiltinToolName(registration/catalogue.ts, covers on-demand + meta built-ins thathasToolRefmisses pre-registration) ORhasToolRef(registration/toolRefs.ts), checked at all 4 ext-registration sites (helperregistration/extensionCollision.ts; the sites are inextensions/extensionDiscovery.ts,extensions/extensionRegistrar.ts,extensions/extensionChanges.tsandgroups/extensionGroups.ts). A colliding extension name is skipped + warned; the incumbent (built-in / first-registered) always wins, never crashes. The MCP SDK’sregisterToolthrows on a dup, so the pre-check prevents that aborting the batch. The guard also covers the reconcile ledger-add and grouped activation.
C14 — Extension surface signaling · semi-public
- Toolkit shape (
extensions/extension_loader.gdis a thin facade; the work lives inextensions/services/*):extensions.list→{"success":true,"commands":[{method,description?,input_schema?,annotations?,group?,timeout_ms?}]}(extensions/services/extension_meta_commands.gd).extensions.refresh→ the same +{"refreshed":true,"hint"?}(extensions/services/extension_watcher.gd).extensions.changedbroadcast (on hot-reload add/remove/modify):{"notification":"extensions.changed","params":{"commands":[…],"removed":[…method names]}}, sent to all authed peers viaserver.broadcast_notification(extension_watcher.gd→transport/mcp_server.gd).
- Server consumer: the server declares
capabilities.tools.listChanged: true(index.ts) and emits exactly onetools/list_changedper batch viabatchToolRegistration(registration/toolRegistry.ts, the monkey-patch-then-fire-once primitive). On the toolkit’sextensions.changedbroadcast,handleExtensionsChanged()(extensions/extensionChanges.ts) reconciles the dynamic extension surface — re-adding via the idempotentaddExtensionGroup(groups/extensionGroups.ts, dedup-by-method) + re-registering ungrouped cmds — inside one batch. When that batch added or removed a tool, thediscover_toolsdescription refresh that follows (registerGroupSystem) may send one moretools/list_changed.extensions_refreshis the always-on meta-tool (extensions/extensionRegistrar.ts) the LLM calls to force a manual re-sync. - Platform caveat:
tools/list_changedis unreliable in all Claude Code modes (dropped notifications). The bridge cannot rely on the broadcast alone for live refresh;extensions_refresh+ eager-promotion of dynamic-activation-sensitive tools (security/profiles.tsEAGER_TOOLS) compensate. - Extension read pattern: extension-provided read commands follow the same uniform pagination envelope as built-ins (
returned+ canonicaltotal_<unit>+has_more, plus a resume field or cursor-less nav where applicable; C8). Like every extension response it surfaces transparently (REFLECT) — the server forwardsmessage.resultverbatim (C3/C7) — so a paginating extension read needs no server-side schema; the contract is the only convention to follow.
C15 — LSP status round-trip (reverse: server→toolkit) · semi-public
- Toolkit shape: the bridge is the LSP-liveness authority (cross-process liveness + a root-verify the editor cannot do) and pushes
set_lsp_status {state: active|conflict|unavailable, host, port, detail}back to the toolkit; the toolkit receives it as theeditor.set_lsp_statuscommand (commands/editor/editor_commands.gd) →set_reported_lsp_status(transport/mcp_server.gd) →paths/lsp_publisher.gd→ dock render. A reported verdict holds until the next report, or until an EditorSettings endpoint change re-publishes (C19): that drops it, since it described the old endpoint, and the dock shows the newly published endpoint until the server reports again. (The toolkit publishes the intended endpoint — C19; the server verifies + reports.) - Server consumer (the server is the EMITTER, not a reader): the server computes the dock verdict and pushes it. Two tiers: a fast registry verdict
getLspStatus(projectPath)(lsp/lspClient.ts, endpoint resolution plus peer-port probes, no LSP handshake), pushed byreportRegistryVerdictafter every editor auth that reports a Godot version: the first connect, each reconnect and each editor-port re-discovery (the bridge’sonEditorAuthenticatedhook intransport/bridge.ts, run from the channel’s auth intransport/channel.ts;index.tsbuilds the reporter before the first bridge call, so it sees the first auth). The second tier is a verified verdict from a real connect insideensureLsp(lsp/lspSession.ts), de-duped bystate:host:portagainst the last verdict pushed. A registry verdict that resolves after a verified one landed is dropped, so the dock never falls back from verified truth to the registry’s guess. Both go throughsendLspStatus→editor.set_lsp_status(ADR 0008,lsp/lspStatusReporter.ts).LspStatus = {state: active|conflict|unavailable, host, port, detail}(lsp/lspClient.ts). The toolkit only renders it; the server originates it (the editor cannot self-determine its own LSP bind status).
C16 — projects.json registry format · internal
- Toolkit shape: a machine-wide registry dir (NOT
user://;%APPDATA%/~/Library/Application Support/$XDG_DATA_HOME,registry/store/registry_paths.gd). Each editor writes a uniqueentries/<hash>.json(registry/registry_client.gd); a locked rebuild (_rebuild_projects_json→registry/store/registry_projection.gdmerge_by_path) fans in toprojects.jsonfor the bridge. Per-entry fields:_key(project path),port,token_path,pid,started_at,godot_version,runtime_port,runtime_pid,lsp_host,lsp_port(registry/store/registry_entry_file.gdbuild_entry). Atomic writes (entry tmp→rename; registry two-phase tmp→.bak→target). The rebuild lock (registry/store/file_lock.gd,pid:ts) goes stale by age alone (10 s). GC = port-conflict pruning only (no PID-GC:OS.is_process_runningis documented for the calling process’s own children only; Windows and Linux report every other editor as not running, and only macOS 4.3+ answers for GUI apps).registeroverwrites another PID’s entry for the same project, with a warning when it names another port (a second editor, or one that did not exit cleanly) and an info line when it names this editor’s port (a leftover). - Server consumer:
readRegistry()reads exactlyregistryPath()=…/godot-mcp-toolkit/projects.json(registry.ts) — never the per-instanceentries/dir, so any runtime-side entry split is purely toolkit-internal. The server’sRegistryEntrytype (registry.ts) matches aprojects.jsonrow field-for-field: the toolkitbuild_entryfields minus_key, which the projection removes from the row and uses as itsby_pathkey.godot_version?/lsp_*?are optional as the forward-compat seam for old-toolkit entries. Tolerance: stale editor entries linger (no PID-GC) and the server reads them; runtime-only entries (port:-1,token_path:"",lsp_port:null) are read gracefully (discoverLspEndpointreturns null onlsp_port==null); a runtime transition (a changedruntime_portorruntime_pid, C20) is applied tear-down-before-connect:runtimeTransitionsputsremovedbeforediscovered, anddiffAndNotifyfires them in that order. The path-normalization parity (normalizePath↔ toolkitcanonical()) has no shared equivalence fixture — a candidate cross-repo regression test.
C17 — Project-instance hash · internal
- Toolkit shape:
ProjectPaths.project_hash()(paths/project_paths.gd) = SHA-256 of the canonical project root →\→/→ strip trailing/→ lowercase on Win/macOS → first 12 hex (paths/project_key.gdcurrent_hash). - Server consumer: the bridge does NOT recompute the sha256 hash.
by_pathis keyed by_key= the canonical project PATH (registry/store/registry_projection.gdmerge_by_path; the frozen contract inpaths/project_key.gd— the normalized path is the_keythe TypeScript bridge reads, while the 12-char hash names the per-instance entry file). The server forms the same key bynormalizePath(projectPath)(registry.ts, used bylookupProject) — recomputing the path normalization (backslash→/, strip trailing/, lowercase on Win/macOS), not the hash. The 12-char hash is a toolkit-internal filename /user://-dir token the bridge never consumes; the only cross-repo recompute is the canonicalization recipe (the no-shared-fixture gap → the C16 test candidate).
C18 — Token file discovery (token_path) · internal
- Toolkit shape: the token is written to
<instance_dir>/mcp_token(or$GODOT_MCP_TOKEN_PATH); thetoken_pathpublished in the registry entry is the GLOBALIZED ABSOLUTE path of the token file the editor last wrote: the bind-time registration (core/plugin_composer.gd) and the LSP-endpoint re-publish (paths/lsp_publisher.gd) pass the server’sget_published_token_path()(transport/mcp_server.gd), which recordsMCPAuth.get_published_token_path()=ProjectSettings.globalize_path(get_token_path())(security/auth.gd) after each successful write and falls back to it before the first; the rename re-publish passes the globalized path of the server’stoken_rewrittensignal, which fires only after that write succeeds, so it names the same file. In-engine readers use theuser://form (get_token_path()), and the runtime autoload’s own entry file carries an emptytoken_path. Aconfig/namerename movesuser://: the editor re-writes the same token there and, once that write succeeds and its listener is bound, re-publishes the newtoken_paththroughensure_registered(registry/registry_client.gd), which refreshesportandtoken_pathon the editor’s own entry. Because every publish site names the file last written, a failed write leaves the old, still-valid path published until a Regenerate Token, which writes a new token to the new path; the next publish names that file. - Server consumer: the bridge looks up
entry.token_pathvialookupProjectand structurally validates it before opening — it does NOT recomputesha256(path)or re-derive the path.readToken(projectPath)(transport/tokenPath.ts, consumed bytransport/channel.tsperformAuthon every connect) →lookupProject(registry.ts) →assertPublishedTokenPath(transport/tokenPath.ts): absolute · no..· an existing regular file · suffix matching…/addons/godot_mcp_toolkit/project_instance_<12-hex>/mcp_token(a format check on the instance segment[0-9a-f]{12}, not a recomputed hash; lexical only).GODOT_MCP_TOKEN_PATHis an operator override read directly (absolute + existing-file; bypasses the suffix check). Every failure throws a distinct, actionableAUTH_FAILED(no silent stale-open). Becauseglobalize_pathreadsuse_custom_user_dirlive, a relocateduser://is honored. See ADR 0009 / 0011.
C19 — LSP endpoint publishing · internal
- Toolkit shape: the editor resolves the endpoint via
resolve_lsp_endpoint(EditorSettingsnetwork/language_server/remote_host/remote_port; default127.0.0.1:6005) — the logic lives inpaths/lsp_publisher.gd, delegated fromtransport/mcp_server.gd— and the composition root (_register_in_registryincore/plugin_composer.gd, run on every fresh bind) passes the resolvedlsp_host/lsp_portintoregister(). When those EditorSettings change,paths/lsp_publisher.gdre-publishes the new endpoint throughensure_registeredand tells the dock to redraw (C15).registry/registry_client.gdstays export-clean (it receives params, never touchesEditorInterface). - Server consumer: the LSP client reads
entry.lsp_host/lsp_portfromprojects.jsonviadiscoverLspEndpoint(projectPath)(registry.ts) — the middle tier of the 3-tier resolver (--lsp-port/GODOT_MCP_LSP_PORToverride, the CLI flag winning → registry → guarded-6005-never-blind;resolveLspEndpointinlsp/lspClient.ts). The registry tier applies an earliest-live-claimant ownership rule (liveLspClaimants,registry.ts: a claimant counts only when its PID is alive (isPidAlive→process.kill(pid,0), which answers for any process, unlike GDScript’sOS.is_process_running: that is documented for the calling process’s own children only; Windows and Linux report every other editor as not running, and only macOS 4.3+ answers for GUI apps) and the WS port its entry advertises does not refuse a connection (wsPortNotRefused,registryLiveness.ts); connect only if strictly the earliest such claimant bystarted_at, else{conflict}→LSP_PORT_CONFLICT). Then it verifies the live endpoint and reports the verdict → C15. Thenull-lsp_portruntime-only case returns null (no LSP), per C16.
C20 — Runtime discovery · internal
- Toolkit shape: a live game writes its own entry file,
entries/<hash>.runtime.json, on every fresh bind (registry/registry_client.gdset_runtime), carryingruntime_portandruntime_pid(its own PID). It never writes the editor’s<hash>.json. Theprojects.jsonrebuild overlays only those two fields onto the editor’s row for the same_key; with no editor entry, the runtime file’s own shape stands in (port:-1,token_path:"",lsp_port:null) (registry/store/registry_projection.gdmerge_by_path). On stop the game deletes its file (clear_runtime) and the next rebuild drops the overlay. A file left by a crashed playtest is deleted when the editor next callsregister(on its next fresh bind, normally at startup). - Server consumer: the bridge reads
runtime_portviadiscoverRuntime/getCachedRuntimePort(registry.ts), called bycallRuntimeintransport/runtimeConnection.ts, to reach the running game (Mode B,callRuntime) vs the edited scene (Mode A,call); the registry watcher (registry.ts) re-targets the runtime channel when a project’s (runtime_port,runtime_pid) pair changes, asruntimeTransitionscomputes it: the runtime band always scans from the same port, so a relaunched game often returns on the same port under a new PID. An absentruntime_pidcompares as null, so an entry that records none transitions on the port alone. Per project,removedcomes beforediscovered, so the bridge never holds two runtime channels to one project;removedfires for any previous port, anddiscoveredcarries only a port that passes the liveness check below. Editorport/godot_version/lsp_portchanges do not flow through the watcher (by design — it exists for playtest discovery). Liveness:discoverRuntime(a fresh file read),getCachedRuntimePort(the watcher’s cache) and the watcher’sdiscoveredevents share one check,usableRuntimePort(registry.ts): it rejects aruntime_portoutside 1024–65535, and one whose setruntime_pidisPidAlive(registryLiveness.ts) reports dead; a nullruntime_piddoes not block. The check is PID-only, weaker than the LSP path’s claimant rule (C19): a wrong runtime port surfaces as a failed connect (GAME_NOT_RUNNING), and the check runs on every runtime call, since eachcallRuntimere-reads the port through these lookups. - Constraint: a
config/namerename re-publishes the editor entry throughensure_registered(_republish_on_token_rewrite,core/plugin_composer.gd), notregister, whose startup reap would delete<hash>.runtime.json; the editor entry never carries runtime fields, so a game running across the rename keeps itsruntime_port/runtime_pid. Editor and runtime each write only their own file, so there is no shared read-modify-write between them.
C21 — Untrusted envelope · internal (LLM-facing)
- Toolkit shape: read-path project content is wrapped
<untrusted-{nonce} kind="…" source="…">\n{body}\n</untrusted-{nonce}>, the nonce%08x randi(), with any existing<untrusted…>tags pre-scrubbed (anti tag-breakout). Read-paths only (never writes / binary).Scrubber.scrub(security/scrubber.gd) redacts secrets from console text, a running game’s log andsave.readtext before return (3 precision regexes →[REDACTED]). - Server consumer (REFLECT verbatim): the toolkit does the primary wrapping (
security/untrusted.gdwrap, across script / scene_tree / user-file / resource / project_settings / console / animation / audiobus / game_log read paths) and the server forwards it verbatim —callAndWrap(registration/toolDispatch.ts) →stableStringify(shared/stableJson.ts) →message.result(transport/channel.ts), no double-wrap, no unwrap/parse. The server has its ownuntrustedWrap(security/untrusted.ts, an exact TS mirror — same envelope + scrub) used in exactly one place:tools/lsp.tswrapslsp_hovertext, which never transits the toolkit wrapper (it comes straight from the engine LSP over the server’s own TCP socket). The other 6 LSP tools return structured data (no free-form prose) → no wrap;lsp_completionpasses on adocumentationfield only if the engine sends one, and Godot’s completion reply carries none (it fills that field only incompletionItem/resolve, which the server never sends).
C22 — ProjectSettings keys · internal
- Toolkit shape (
core/settings_registration.gd): the three response limitsmcp_toolkit/limits/script_read_cap_kb(256),save_read_cap_kb(256) andws_buffer_kb(1024), registered from the response-limits table incore/response_limits.gd(default, floor 64 / 64 / 256, range, environment variable), plus the audit keys (auditaudit/enableddefault-on), plus the concurrency group:mcp_toolkit/concurrency/scan_idle_timeout_ms(5000 — how long a scene save/open waits for the EditorFileSystem scan before aborting) andmcp_toolkit/concurrency/mutation_watchdog_grace_ms(60000 — grace added to a mutation’s deadline before the dispatch watchdog force-clears a wedged lock; read live at dispatch time) andmcp_toolkit/concurrency/scene_lease_ttl_ms(8000 — how long the scene lease holder may go without renewing before a waiting client can steal the lease; read live by the scene lease). The four keys the dock also edits registerPROPERTY_HINT_RANGEhints that match its spin boxes —limits/script_read_cap_kbandlimits/save_read_cap_kb64,4096,64,limits/ws_buffer_kb256,8192,256(the three limit hints read from the table),audit/max_size_kb0,10240,128— so the inspector and the dock accept the same values; the concurrency keys stay unhinted (not clamped). The server pin keymcp_toolkit/server/version(string, default empty, registered but not basic, so it shows under the inspector’s Advanced toggle) is a team-shared choice of the server version.mcp.jsonruns: empty = the toolkit’s compatible version,latest, or any npm version, range or tag (C11); the dock’s.mcp.jsonrow and the setup wizard set it to empty orlatestand saveproject.godot, both through the server pin policy (ui/mcp_json/server_pin_policy.gd). A value that is not blank also keeps a self-update from moving the pin (C11) and turns off the dock’s line about a server that differs from the recommended version (C2). The update check keymcp_toolkit/updates/check_for_updates(bool, defaulttrue, basic) turns the toolkit’s daily update check off: off sends no request and hides the dock’s update badge, read live throughProjectSettings.settings_changed(versioning/update_check_runner.gd). On alone it is not enough: the consent gate (core/consent.gd) sends nothing until the user has seen the setup wizard’supdatesstep, whose checkbox edits this key (untick writesfalse, a re-tick writes the default back so the line leavesproject.godot, then saves). The check’s state lives in auser://file, never here (seedocs/dev/update-check.md). The install mode keymcp_toolkit/updates/install_mode(string,PROPERTY_HINT_ENUMmanual,ask, defaultask, basic) says whether the toolkit installs its own updates:askoffers a verified release in the dock’s update badge, and in a prompt at an editor start, and downloads it only when the user clicks Update;manualonly links to a new version, and switching to it calls off a running download or stage and deletes a staged release (self_update/update_installer.gd). The editor’s exit does not read the key again: a release still staged then installs once the exit’s checks pass, since the click on Update was the consent (self_update/update_applier.gd). A missing key reads asaskand any other value asmanual(readinself_update/install_mode.gd). The consent gate (may_install_updatesincore/consent.gd) installs nothing until the update check may run and the setup wizard’supdate_installstep has been seen; that step preselects the project’s mode and saves the choice. The backup keymcp_toolkit/updates/keep_backup(bool, defaulttrue, basic) decides what happens to the previous version after an update: on, the toolkit keeps it in the update folder until the next update is staged; off, the next start deletes it once the update has installed (KEEP_BACKUP_SETTINGinself_update/update_settler.gd). A missing key, or one that is not a boolean, keeps it. Outsidemcp_toolkit/*, the self-update writes one engine key: while an update is staged, installing or just installed,editor_plugins/enabledinproject.godotlistsres://addons/.godot_mcp_toolkit_recovery/plugin.cfg, the hidden recovery plugin that puts the previous version back at the next start when the new one does not load. Staging copies the plugin into that folder, adds the entry, saves and reads the file back (installinself_update/recovery_files.gd, called fromself_update/update_installer.gd). The editor’s exit reads the saved file and installs nothing while it lacks the entry (self_update/update_applier.gd). The toolkit’s start removes the entry and the folder once no update is in flight, and disabling the toolkit removes them too (plugin.gd). Once it has moved a version into place, the recovery plugin keeps the toolkit’s own entry in the list until the restart, and when the toolkit’s folder is gone and no update is in flight, it drops its own entry and folder (self_update/recovery/recovery_plugin.gd). Retired keys (mcp_toolkit/status,mcp_toolkit/limits/env_override_note) are no longer registered:register_all()nulls a stored copy in memory, never saving, so the next save from any source drops it fromproject.godot. Personal prefs (e.g. the unfocused-editor setting) and machine facts (themcp_toolkit/server/local_pathlocal server build, registered inplugin.gd) live in EditorSettings, not ProjectSettings. So does the setup wizard’smcp_toolkit/setup_wizard/show_optional_steps(bool, defaulttrue, registered inplugin.gd): off hides the optional setup steps a later toolkit adds, in every project on the machine, and required steps show regardless; the wizard’soptional_stepsstep and a Server Status checkbox in the dock edit it. Disabling the plugin scrubs the project key with the othermcp_toolkit/*keys, and the cleanup prompt for the machine-wide editor settings listslocal_pathandshow_optional_stepswith the rest. Live status (Node.js found/version,.mcp.jsonpresence, read-only mode) is shown in the dock only (ui/dock/dock.gd) — deliberately not persisted to ProjectSettings, since the value is machine-specific and would otherwise churnproject.godotin VCS depending on who last opened the project. - Server consumer:
meta.set_limits, the env overrides. The server never readsmcp_toolkit/*. Its one call here ismeta.set_limits, which the bridge sends after every editor auth (reconnects and editor-port re-discoveries included;transport/bridge.ts) with its whole set of env overrides:script_read_cap_kbforGODOT_MCP_SCRIPT_READ_LIMIT,ws_buffer_kbforGODOT_MCP_WS_BUFFER_LIMIT, each only when its variable holds a valid byte count (read at startup byresolveResponseCapsinstartup/startupEnv.ts, which ignores an invalid value and clamps one below the floor), and{}when neither does (save_read_cap_kbhas no variable; only a manual call pushes it). The toolkit holds env overrides outsideProjectSettings(core/response_limits.gd, written bycommands/meta_commands.gd) while the plugin runs and never saves them, so no save from any source can carry one intoproject.godot. The plugin’s teardown clears them (core/plugin_composer.gd), and the next editor auth pushes the set again. Each push replaces the whole set: a key left out ornullloses its env override, and{}clears them all. With several MCP clients on one editor, the last push wins (the handler cannot tell which peer sent it). Every reader (script.read,save.read, the editor transport’s peer buffer) takes the effective value, the env override while one is active, else the project value, with the limit’s floor applied once in the helper; the reply carries the three effective values. A pushedws_buffer_kbapplies from the next accepted connection (a peer’s buffers are fixed at its handshake, C1), and never reaches the runtime server.project.get_settingskeeps reporting the project value. The dock’s spin boxes show and edit the project value; under each field with an active env override, the field’s override line names the value in use, in exact KB, and its variable (the save cap’s line says the MCP server set it). Everything else here is honored entirely editor-side; the server learns the effect of these settings only through wire behavior (a dropped over-buffer frame, C1; thesave.readcap surfaced via response fields). The contract that the toolkit denies LLM writes tomcp_toolkit/*/mcp/*/editor/*is toolkit-enforced.
C23 — Input map · public
-
Toolkit shape — the event object (
commands/input_map/input_event_codec.gd): one object for input (input_map.event’sevent) and output (theeventof a bind or unbind response, and every event ininput_map.list), so an event read back can be passed tounbindas it is. Every object carriestype, an open set; output addsclass, the engine class.typeFields keykeycode,key_kind(physical_keycodedefault ·keycode·key_label),location(0 · 1 left · 2 right; 4.3+),shift,ctrl,alt,meta,command_or_control,device; output addskeycode_namemouse_buttonbutton_index,shift,ctrl,alt,meta,command_or_control,double_click,devicejoypad_buttonbutton_index,devicejoypad_motionaxis,axis_value,deviceunknownoutput only: class(InputEventMIDI,InputEventScreenTouch,InputEventAction, …)keycode+key_kind: a key has one code field. Output answers the field the engine matches on (keycode, elsephysical_keycode, elsekey_label) askeycode, withkey_kindnaming it; input sets only the fieldkey_kindnames.keycodetakes a symbolic name ("SPACE","KEY_F1") or an integer.command_or_controlis the engine’scommand_or_control_autoremap. Input applies it first and then ignoresctrlandmeta, which it sets itself for the platform (the engine refuses a direct ctrl or meta while it is on), so a read{ctrl: true, command_or_control: true}passes back cleanly.locationexists from Godot 4.3, detected on the event, never by a version compare. On 4.2 an inputlocationis ignored with awarningsentry and output has none.- Mouse
pressedis accepted on input with awarningsentry, and never stored or answered: an action match ignores it. device: an input without one keeps the engine’s own default for a key or mouse (0 before 4.7; 16 and 32,InputEvent.DEVICE_ID_KEYBOARD/DEVICE_ID_MOUSE, on 4.7) and -1 for a joypad event.warnings: an array of strings on a bind or unbind response, omitted when empty:"pressed has no effect on action matching; ignored","location needs Godot 4.3+; ignored". Any other invalid field (key_kind,locationout of range, adevicethat is not a number, an unknowntypeor key name) →INVALID_PARAMS.
- Toolkit shape — equivalence (
commands/input_map/input_event_equivalence.gd, the bind duplicate check and the unbind match): a key bykey_kind, code,location, the four modifiers andcommand_or_control; a mouse button bybutton_index, modifiers andcommand_or_control(notpressed, notdouble_click); a joypad button bybutton_index; a joypad motion byaxisand the sign ofaxis_value. Each also bydevice, except that an input withoutdevicematches any device, -1 on either side matches any, and on 4.7 a key or mouse device 0 on either side compares as 16 or 32, as the engine reads a saved device 0. - Toolkit shape —
input_map.list(read-only, scene-independent): paramsname?(exact; any action, built-in or not; unknown →NOT_FOUNDnaming the list call) andinclude_builtin?(default false). Answers{actions, count}, always a list, in the[input]order (ProjectSettings.get_order). Withoutname: every project action and every built-in action that differs from its default, plus the unchanged built-ins withinclude_builtin. An entry is{name, source: "builtin" | "project", deadzone, events, can_revert, default?, feature?}:can_revertis true only for a built-in action that differs from its default by the editor Input Map’s revert rule (commands/input_map/input_action_settings.gd): another deadzone (is_equal_approx), another event count, or a pair at the same index that failsInputEvent.is_match(other, true). Order counts; the event objects, device and mousepresseddo not. When true,defaultis{deadzone, events}fromProjectSettings.property_get_revert, in the same event shape.featureis set when the name has a dot: everything after the first dot, where the engine splits a feature override (input/jump.macos→"macos"; each later dot starts another tag).namestays the full name. On a built-in action’s feature entry,bind,unbind,removeandrevertanswerINVALID_PARAMS(“feature-override entries are read-only”); a project action with a dot keeps every operation. A changed built-in feature entry can answercan_revert: trueeven so:revertrefuses it in v1.
- Toolkit shape —
input_map.actionrevert: unknown name →NOT_FOUND; a project action or a built-in feature entry →INVALID_PARAMS. A setting whose value equals its revert value asProjectSettings.save()compares them (event objects by identity) →status: "returned"; any other, one rebuilt with the default’s content included, is set to the revert value exactly as the engine returns it, saved, and →status: "reverted", after whichproject.godothas no line for it. The response is the action’s list entry plusstatus.removeon a built-in action refuses and namesrevert, except on a feature entry, which it refuses as read-only. - Server consumer: the event object reaches the toolkit whole:
input_map_event’s inputSchema declareseventas a record of unknown values (tools/inputMap.ts), so no field,pressedincluded, is stripped before the toolkit validates it. Responses pass throughcallAndWrapverbatim.