Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

fix(editor): no Unity-MCP window or server in batch mode

eyalgoland041a459224c
diff --git a/BUILDING.md b/BUILDING.md
index 07eb2f4e5..3eeb34a61 100644
--- a/BUILDING.md
+++ b/BUILDING.md
@@ -50,6 +50,7 @@ Troubleshooting:
- **Choose your agent** and click **Configure**, or click **Generate** to write skill files instead. The files these steps write (`.mcp.json`, `unity/.claude/` and the other agent folders) are git-ignored; don't commit them.
- **The rules still apply:** no game rules in Unity (they live in the sim), tests first, sources for every fact in `content/`, and disclose the AI assistance in your pull request (see "Rules every change follows" and "AI-assisted contributions" in [CONTRIBUTING.md](CONTRIBUTING.md)).
- **Security:** the local server lets the agent run editor actions, including editing files and executing code in the editor. Keep it local: never expose port 27766 (no port forwarding, tunnels or `0.0.0.0` binds), and stop the server when you're done.
+- **Not connecting?** Connect only works in an interactive editor: in batch mode (tests and builds) the plugin is held offline on purpose, and its window doesn't open. Check that the Server URL port matches the running server (the plugin's default port is derived from the project path, which is why everyone sets 27766), that the server shows Running, then click Connect. The first attempt can fail while the server is still starting; the plugin retries. If the editor is stopped without quitting, the `gamedev-mcp-server` process can stay behind on the port: stop it with the window's Stop button or by its PID.
- **Batch mode and builds:** `UnityMcpGuard` (`unity/Assets/Editor/UnityMcpGuard.cs`) keeps the plugin from connecting or starting its server in batch mode (tests and builds), and drops its assemblies from every player build. The browser build's golden hashes don't change.
- **Leave one change uncommitted:** the plugin adds `UNITY_MCP_READY;UNITY_MCP_DEPS_7` to the scripting defines in `unity/ProjectSettings/ProjectSettings.asset` once its DLLs are in place. Don't commit that change: on a fresh clone the defines would arrive before the DLLs, and the plugin wouldn't compile. A policy test refuses it. The post-build cleanup (`git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`) drops the defines too; the plugin adds them back on the next open, at the cost of one extra compile.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 93ffa11fd..a509f655c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -69,6 +69,7 @@ AI-assisted work is welcome. Say so in the pull request: which parts, and how yo
- **Choose your agent** and click **Configure**, or click **Generate** to write skill files instead. The files these steps write (`.mcp.json`, `unity/.claude/` and the other agent folders) are git-ignored; don't commit them.
- **The rules still apply:** no game rules in Unity (they live in the sim), tests first, sources for every fact in `content/`, and disclose the AI assistance in your pull request (see "Rules every change follows" and "AI-assisted contributions" above).
- **Security:** the local server lets the agent run editor actions, including editing files and executing code in the editor. Keep it local: never expose port 27766 (no port forwarding, tunnels or `0.0.0.0` binds), and stop the server when you're done.
+- **Not connecting?** Connect only works in an interactive editor: in batch mode (tests and builds) the plugin is held offline on purpose, and its window doesn't open. Check that the Server URL port matches the running server (the plugin's default port is derived from the project path, which is why everyone sets 27766), that the server shows Running, then click Connect. The first attempt can fail while the server is still starting; the plugin retries. If the editor is stopped without quitting, the `gamedev-mcp-server` process can stay behind on the port: stop it with the window's Stop button or by its PID.
- **Batch mode and builds:** `UnityMcpGuard` (`unity/Assets/Editor/UnityMcpGuard.cs`) keeps the plugin from connecting or starting its server in batch mode (tests and builds), and drops its assemblies from every player build. The browser build's golden hashes don't change.
- **Leave one change uncommitted:** the plugin adds `UNITY_MCP_READY;UNITY_MCP_DEPS_7` to the scripting defines in `unity/ProjectSettings/ProjectSettings.asset` once its DLLs are in place. Don't commit that change: on a fresh clone the defines would arrive before the DLLs, and the plugin wouldn't compile. A policy test refuses it. The post-build cleanup (`git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`) drops the defines too; the plugin adds them back on the next open, at the cost of one extra compile.
diff --git a/README.he.md b/README.he.md
index 427585ab4..3bca5e453 100644
--- a/README.he.md
+++ b/README.he.md
@@ -80,6 +80,7 @@
- **הסוכן:** בחרו את הסוכן שלכם ולחצו Configure, או לחצו Generate כדי ליצור קובצי skills. הקבצים שנוצרים (<span dir="ltr">`.mcp.json`</span> ותיקיות הסוכנים) נמצאים מחוץ ל־git; אל תוסיפו אותם.
- **הכללים בתוקף:** כללי המשחק נשארים בסימולציה ולא ב־Unity, בדיקות קודם, מקור לכל עובדה, ומצהירים בבקשת המיזוג על הסיוע של בינה מלאכותית.
- **אבטחה:** השרת המקומי מאפשר לסוכן להריץ פעולות בעורך, כולל עריכת קבצים והרצת קוד. השאירו אותו מקומי ולעולם אל תחשפו את הפורט 27766 החוצה.
+- **אין חיבור?** Connect עובד רק בעורך אינטראקטיבי: במצב batch (בדיקות ובנייה) התוסף מנותק בכוונה, והחלון שלו לא נפתח. ודאו שהפורט בכתובת השרת תואם לשרת שרץ (פורט ברירת המחדל של התוסף נגזר מנתיב הפרויקט, ולכן כולם מגדירים 27766), שהשרת מסומן Running, ולחצו Connect. הניסיון הראשון יכול להיכשל בזמן שהשרת עולה; התוסף מנסה שוב. אם העורך נעצר בלי יציאה מסודרת, התהליך <span dir="ltr">`gamedev-mcp-server`</span> עלול להישאר על הפורט: עצרו אותו בכפתור Stop בחלון או לפי ה־PID שלו.
- **שינוי שלא מוסיפים ל־git:** אחרי שקובצי ה־DLL במקומם, התוסף מוסיף את <span dir="ltr">`UNITY_MCP_READY;UNITY_MCP_DEPS_7`</span> להגדרות הסקריפטים ב־<span dir="ltr">`unity/ProjectSettings/ProjectSettings.asset`</span>. אל תוסיפו את השינוי הזה ל־commit: בשכפול חדש ההגדרות יגיעו לפני קובצי ה־DLL והתוסף לא יתקמפל. בדיקת מדיניות חוסמת אותו.
## שימוש בבינה מלאכותית
diff --git a/scripts/oss/tests/test_readme.py b/scripts/oss/tests/test_readme.py
index f70cf3d7b..da394958d 100644
--- a/scripts/oss/tests/test_readme.py
+++ b/scripts/oss/tests/test_readme.py
@@ -187,7 +187,8 @@ def test_unity_mcp_section_is_in_contributing_and_building_with_the_same_facts()
"Generate", "Cloud", "sign in", "UserSettings/AI-Game-Developer-Config.json",
"no game rules in Unity", "tests first", "sources", "AI assistance",
"editor actions", "never expose", "batch mode", "UnityMcpGuard", "player build",
- "ProjectSettings.asset", "UNITY_MCP_READY", "nuget.org"):
+ "ProjectSettings.asset", "UNITY_MCP_READY", "nuget.org", "Not connecting?", "gamedev-mcp-server",
+ "PID"):
assert fact in text, (rel, fact)
@@ -195,7 +196,7 @@ def test_hebrew_readme_carries_the_unity_mcp_facts():
he = section(read("README.he.md"), "## איך משתתפים")
for fact in ("Unity-MCP", "0.93.3", "Window → AI Game Developer", "Custom", "http://localhost:27766", "http",
"Configure", "Generate", "Cloud", "UserSettings/AI-Game-Developer-Config.json", "ProjectSettings.asset",
- "UNITY_MCP_READY", "nuget.org"):
+ "UNITY_MCP_READY", "nuget.org", "gamedev-mcp-server", "PID", "batch"):
assert fact in he, fact
for idea in ("כללי המשחק", "בדיקות", "מקור", "בינה מלאכותית", "פורט"):
assert idea in he, idea
diff --git a/scripts/oss/tests/test_unity_mcp.py b/scripts/oss/tests/test_unity_mcp.py
index deffe1339..b16ed65e8 100644
--- a/scripts/oss/tests/test_unity_mcp.py
+++ b/scripts/oss/tests/test_unity_mcp.py
@@ -2,6 +2,7 @@
how it is installed, so a fresh clone resolves it with no manual steps (a missing OpenUPM scope gave contributors
`error CS0246 'PlayerPrefsBool'`)."""
import json
+import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
@@ -40,8 +41,10 @@ def test_lock_resolves_the_pinned_plugin_from_openupm():
def test_project_settings_do_not_commit_the_plugin_gate_defines():
# The plugin's resolver downloads its NuGet DLLs, then adds UNITY_MCP_READY and UNITY_MCP_DEPS_<n> on each
# machine. Committed, the defines reach a fresh clone before the DLLs do, and the plugin fails to compile
- # (error CS0234 'System.Text.Json', ...), which stops batch mode. Leave that local change uncommitted.
- text = (ROOT / "unity/ProjectSettings/ProjectSettings.asset").read_text(encoding="utf-8")
+ # (error CS0234 'System.Text.Json', ...), which stops batch mode. Leave that local change uncommitted: this reads
+ # the committed file, so a contributor's own working copy (which has the defines) still passes.
+ text = subprocess.run(["git", "-C", str(ROOT), "show", "HEAD:unity/ProjectSettings/ProjectSettings.asset"],
+ capture_output=True, check=True, text=True).stdout
assert "UNITY_MCP_" not in text
diff --git a/unity/Assets/Editor/UnityMcpGuard.cs b/unity/Assets/Editor/UnityMcpGuard.cs
index 3408c1e8a..40e4047ab 100644
--- a/unity/Assets/Editor/UnityMcpGuard.cs
+++ b/unity/Assets/Editor/UnityMcpGuard.cs
@@ -12,7 +12,9 @@ namespace Statecraft.Game.EditorTools
/// - Batch mode (tests, builds): the plugin would otherwise connect on every domain reload (by default to its cloud
/// service, whose refusal is logged as an error and fails whichever test is running) or start its local server.
/// This sets KeepConnected and KeepServerRunning to false for this process only, recorded as the plugin's own
- /// runtime overrides so they never reach the user's UserSettings/AI-Game-Developer-Config.json. Reflection, not a
+ /// runtime overrides so they never reach the user's UserSettings/AI-Game-Developer-Config.json, and stops the
+ /// plugin's first-run window from opening (it appears on screen even in batch mode, and its server panel starts
+ /// the local server). Reflection, not a
/// reference: on a fresh clone the plugin compiles only after its resolver has fetched its NuGet DLLs.
/// - Player builds: drops the plugin's runtime assemblies and the NuGet DLLs its resolver put in Assets/Plugins/NuGet
/// (IFilterBuildAssemblies). The game never calls them; the plugin offers no switch of its own for this.</summary>
@@ -61,6 +63,17 @@ namespace Statecraft.Game.EditorTools
track.Invoke(record, new[] { name, baseline, (object)false });
p.SetValue(config, false);
}
+ // The plugin's first-run window (MainWindowInitializer, queued on EditorApplication.update) opens on screen
+ // even in batch mode, and its server panel starts the local server. Unhook it, and close any already open.
+ var initializer = editor.Assembly.GetType("com.IvanMurzak.Unity.MCP.Editor.UI.MainWindowInitializer");
+ var perform = initializer?.GetMethod("PerformInitialization", Any);
+ if (perform == null) return "plugin internals changed: no MainWindowInitializer.PerformInitialization";
+ // Run its static constructor first (it queues the window), or the unhook could come before the queueing.
+ System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(initializer!.TypeHandle);
+ EditorApplication.update -= (EditorApplication.CallbackFunction)Delegate.CreateDelegate(typeof(EditorApplication.CallbackFunction), perform);
+ var window = editor.Assembly.GetType("com.IvanMurzak.Unity.MCP.Editor.UI.MainWindowEditor");
+ if (window != null)
+ foreach (var w in Resources.FindObjectsOfTypeAll(window)) ((EditorWindow)w).Close();
return "held offline";
}
catch (Exception e)
diff --git a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs
index f23151e57..8f1a082c9 100644
--- a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs
+++ b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs
@@ -62,6 +62,13 @@ namespace Statecraft.Tests.EditMode
var contains = record.GetType().GetMethod("Contains")!;
Assert.IsTrue((bool)contains.Invoke(record, new object[] { "KeepConnected" })!);
Assert.IsTrue((bool)contains.Invoke(record, new object[] { "KeepServerRunning" })!);
+ // The plugin's first-run window would otherwise open on screen in batch mode, and its server panel starts
+ // the local server (seen in a fresh clone's test run, 2026-10-10).
+ var window = editor.Assembly.GetType("com.IvanMurzak.Unity.MCP.Editor.UI.MainWindowEditor")!;
+ Assert.IsEmpty(Resources.FindObjectsOfTypeAll(window), "no plugin window in batch mode");
+ var server = editor.Assembly.GetType("com.IvanMurzak.Unity.MCP.Editor.McpServerManager")!;
+ Assert.IsFalse((bool)server.GetProperty("IsRunning")!.GetValue(null)!, "no local server process");
+ Assert.IsFalse((bool)server.GetProperty("IsStarting")!.GetValue(null)!, "no local server starting");
}
}
}