A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(editor): hold Unity-MCP to local Custom mode with token auth
eyalgolanb7f95c81855b
diff --git a/unity/Assets/Editor/UnityMcpGuard.cs b/unity/Assets/Editor/UnityMcpGuard.csindex 40e4047ab..a5af60e8e 100644--- a/unity/Assets/Editor/UnityMcpGuard.cs+++ b/unity/Assets/Editor/UnityMcpGuard.cs@@ -1,5 +1,6 @@#nullable enableusing System;+using System.Collections.Generic;using System.Linq;using System.Reflection;using UnityEditor;@@ -8,32 +9,39 @@ using UnityEngine;namespace Statecraft.Game.EditorTools{- /// <summary>Keeps Unity-MCP (com.ivanmurzak.unity.mcp, the AI-agent bridge; CONTRIBUTING.md) to the interactive editor.- /// - 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, 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.+ /// <summary>Holds Unity-MCP (com.ivanmurzak.unity.mcp, the AI-agent bridge; CONTRIBUTING.md) to this project's policy.+ /// - Every editor: ConnectionMode Custom (the plugin's default is Cloud, an anonymous connection to ai-game.dev on the+ /// first open) and AuthOption token (the local server checks a Bearer token; Configure writes it into the agent's+ /// config). Both are recorded as the plugin's own runtime overrides, so they never reach the user's+ /// UserSettings/AI-Game-Developer-Config.json, and choosing Cloud or another auth in the window snaps back on save.+ /// The plugin's explicit knobs UNITY_MCP_CONNECTION_MODE and UNITY_MCP_AUTH_OPTION (env var or -arg) are respected.+ /// The interactive editor keeps the user's Server URL, Connect and Keep-server-running choices.+ /// - Batch mode (tests, builds): also KeepConnected and KeepServerRunning false (no connection, no local server), and+ /// no plugin window or update check: its first-run window and update popup open on screen even in batch mode, and+ /// the first-run window's server panel started the local server in a test run./// - 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>+ /// (IFilterBuildAssemblies). The game never calls them; the plugin offers no switch of its own for this.+ /// Reflection, not a reference: on a fresh clone the plugin compiles only after its resolver has fetched its NuGet DLLs.+ /// The plugin also keeps two keys in this project's editor PlayerPrefs (Unity-MCP.MainWindow.Initialized,+ /// Unity_MCP_SelectedAiAgent); a PlayerPrefs.DeleteAll() in editor code would bring its first-run window back.</summary>[InitializeOnLoad]public sealed class UnityMcpGuard : IFilterBuildAssemblies{const string PluginEditorAssembly = "com.IvanMurzak.Unity.MCP.Editor";const string PluginEditorType = "com.IvanMurzak.Unity.MCP.UnityMcpPluginEditor";- static readonly string[] Overrides = { "KeepConnected", "KeepServerRunning" };const BindingFlags Any = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;- /// <summary>What the batch-mode hold did: "held offline", "interactive editor", "plugin not loaded" or why it failed.</summary>+ /// <summary>"held local" (interactive editor), "held offline" (batch mode), "plugin not loaded", or why it failed.</summary>public static string Status = "not run";+ /// <summary>The plugin callbacks taken off the editor loop in batch mode, as "Type.Method".</summary>+ public static readonly List<string> Unhooked = new List<string>();+static UnityMcpGuard(){- Status = Application.isBatchMode ? HoldOffline() : "interactive editor";- if (Status != "held offline" && Status != "interactive editor" && Status != "plugin not loaded")- Debug.LogWarning("UnityMcpGuard: could not hold Unity-MCP offline in batch mode: " + Status);+ Status = Hold(Application.isBatchMode);+ if (Status != "held offline" && Status != "held local" && Status != "plugin not loaded")+ Debug.LogWarning("UnityMcpGuard: could not hold Unity-MCP to local Custom mode" + (Application.isBatchMode ? " and offline" : "") + ": " + Status);}/// <summary>The plugin's editor type if its assembly is loaded in this domain, else null. Never Type.GetType: that@@ -42,7 +50,12 @@ namespace Statecraft.Game.EditorToolspublic static Type? LoadedPluginEditorType() =>AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == PluginEditorAssembly)?.GetType(PluginEditorType);- static string HoldOffline()+ /// <summary>True when the plugin's own knob for this field is set, as an env var or a -NAME command-line argument.</summary>+ static bool ExplicitKnob(string name) =>+ !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(name))+ || Environment.GetCommandLineArgs().Any(a => a.TrimStart('-').Split('=')[0] == name);++ static string Hold(bool batch){var editor = LoadedPluginEditorType();if (editor == null) return "plugin not loaded";@@ -54,26 +67,33 @@ namespace Statecraft.Game.EditorToolsvar track = record?.GetType().GetMethod("Track", Any);var baselines = record?.GetType().GetProperty("BaselineValues")?.GetValue(record) as System.Collections.IDictionary;if (config == null || record == null || track == null) return "plugin internals changed";- foreach (var name in Overrides)++ string? Override(string name, Func<Type, object> value){var p = config.GetType().GetProperty(name);if (p == null) return "plugin internals changed: no " + name;+ var target = value(p.PropertyType);// Keep the on-disk value as the baseline the plugin saves, even if an env var already overrode it.var baseline = baselines != null && baselines.Contains(name) ? baselines[name] : p.GetValue(config);- track.Invoke(record, new[] { name, baseline, (object)false });- p.SetValue(config, false);+ track.Invoke(record, new[] { name, baseline, target });+ p.SetValue(config, target);+ return null;}- // 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();++ var failed = (ExplicitKnob("UNITY_MCP_CONNECTION_MODE") ? null : Override("ConnectionMode", t => Enum.Parse(t, "Custom")))+ ?? (ExplicitKnob("UNITY_MCP_AUTH_OPTION") ? null : Override("AuthOption", t => Enum.Parse(t, "token")));+ if (failed != null) return failed;+ if (!batch) return "held local";++ failed = Override("KeepConnected", _ => false) ?? Override("KeepServerRunning", _ => false);+ if (failed != null) return failed;+ // Run each static constructor first (it queues the callback), or the unhook could come before the queueing.+ failed = Unhook(editor.Assembly, "com.IvanMurzak.Unity.MCP.Editor.UI.MainWindowInitializer", "PerformInitialization", runCctorOf: null, update: true)+ ?? Unhook(editor.Assembly, "com.IvanMurzak.Unity.MCP.Editor.Utils.UpdateChecker", "CheckForUpdatesOnStartup",+ runCctorOf: "com.IvanMurzak.Unity.MCP.Editor.Startup", update: false);+ if (failed != null) return failed;+ foreach (var w in Resources.FindObjectsOfTypeAll<EditorWindow>().Where(w => w.GetType().Assembly == editor.Assembly).ToList())+ w.Close();return "held offline";}catch (Exception e)@@ -82,6 +102,21 @@ namespace Statecraft.Game.EditorTools}}+ /// <summary>Takes a plugin callback off EditorApplication.update (or delayCall), after running the static+ /// constructor that queues it (the type's own, or runCctorOf's).</summary>+ static string? Unhook(Assembly plugin, string typeName, string method, string? runCctorOf, bool update)+ {+ var type = plugin.GetType(typeName);+ var m = type?.GetMethod(method, Any);+ var queuer = runCctorOf == null ? type : plugin.GetType(runCctorOf);+ if (m == null || queuer == null) return $"plugin internals changed: no {typeName}.{method}";+ System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(queuer.TypeHandle);+ var d = (EditorApplication.CallbackFunction)Delegate.CreateDelegate(typeof(EditorApplication.CallbackFunction), m);+ if (update) EditorApplication.update -= d; else EditorApplication.delayCall -= d;+ Unhooked.Add(type!.Name + "." + method);+ return null;+ }+/// <summary>True for the plugin's own assemblies, its PlayerPrefsEx dependency, and any DLL under/// Assets/Plugins/NuGet (the folder the plugin's resolver owns).</summary>public static bool IsPluginAssembly(string path)diff --git a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.csindex 8f1a082c9..1337fd80e 100644--- a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs+++ b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs@@ -1,15 +1,22 @@#nullable enableusing System;+using System.Collections.Generic;+using System.Linq;using System.Reflection;using NUnit.Framework;+using UnityEditor;+using UnityEditor.Compilation;using UnityEngine;namespace Statecraft.Tests.EditMode{- /// <summary>Unity-MCP (com.ivanmurzak.unity.mcp) is an interactive-editor tool. In batch mode (tests and builds) it must- /// not connect anywhere or start its local server, and no part of it may ship in a player build.</summary>+ /// <summary>Unity-MCP (com.ivanmurzak.unity.mcp) is held to local Custom mode with token auth in every editor; in batch+ /// mode (tests and builds) it must not connect anywhere, start its local server or open a window; and no part of it may+ /// ship in a player build.</summary>public sealed class UnityMcpGuardTests{+ const BindingFlags Any = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;+static Type Guard(){var t = Type.GetType("Statecraft.Game.EditorTools.UnityMcpGuard, Assembly-CSharp-Editor");@@ -20,6 +27,11 @@ namespace Statecraft.Tests.EditModestatic string[] Filter(params string[] assemblies) =>(string[])Guard().GetMethod("Filter", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, new object[] { assemblies })!;+ static Type? PluginEditor() =>+ (Type?)Guard().GetMethod("LoadedPluginEditorType", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, null);++ static string Status() => (string)Guard().GetField("Status", Any)!.GetValue(null)!;+[Test]public void PlayerBuildsDropThePluginAndTheDllsItsResolverDownloaded(){@@ -43,32 +55,85 @@ namespace Statecraft.Tests.EditMode}[Test]- public void InBatchModeThePluginStaysOfflineForThisProcessOnly()+ public void PlayerBuildsDropEveryRealPluginAssemblyAndDll()+ {+ if (PluginEditor() == null) { Assert.AreEqual("plugin not loaded", Status()); return; }+ // Every player assembly compiled from the plugin's packages, and every managed plugin DLL a WebGL build would+ // take that is not ours, must be dropped by the filter (by its real output name and asset path).+ var fromPackages = CompilationPipeline.GetAssemblies(AssembliesType.PlayerWithoutTestAssemblies)+ .Where(a => a.sourceFiles.Any(f => f.StartsWith("Packages/com.ivanmurzak.unity.mcp/", StringComparison.Ordinal)+ || f.StartsWith("Packages/extensions.unity.playerprefsex/", StringComparison.Ordinal)))+ .Select(a => "Library/Bee/PlayerScriptAssemblies/" + System.IO.Path.GetFileName(a.outputPath))+ .ToList();+ CollectionAssert.IsNotEmpty(fromPackages, "the plugin compiles player assemblies");+ var dlls = PluginImporter.GetAllImporters()+ .Where(p => !p.isNativePlugin && p.assetPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)+ && (p.GetCompatibleWithPlatform(BuildTarget.WebGL)+ || (p.GetCompatibleWithAnyPlatform() && !p.GetExcludeFromAnyPlatform(BuildTarget.WebGL)))+ && p.assetPath.StartsWith("Assets/", StringComparison.Ordinal)+ && !p.assetPath.StartsWith("Assets/Plugins/Statecraft/", StringComparison.Ordinal))+ .Select(p => p.assetPath)+ .ToList();+ CollectionAssert.IsNotEmpty(dlls, "the resolver's runtime DLLs are WebGL-compatible");+ var all = fromPackages.Concat(dlls).ToArray();+ CollectionAssert.IsEmpty(Filter(all), "kept by the player-build filter");+ }++ [Test]+ public void ThePluginIsHeldToLocalCustomModeWithTokenAuth(){- const BindingFlags any = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;- var status = (string)Guard().GetField("Status", any)!.GetValue(null)!;- var editor = (Type?)Guard().GetMethod("LoadedPluginEditorType", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, null);- // Not Assume: Unity's runner exits 2 on an inconclusive test. The interactive editor is left alone, and on a- // fresh clone's first run the plugin compiles after its resolver, so the tests run before a reload loads it.- if (!Application.isBatchMode) { Assert.AreEqual("interactive editor", status); return; }- if (editor == null) { Assert.AreEqual("plugin not loaded", status); return; }- Assert.AreEqual("held offline", status);- var instance = editor!.GetProperty("Instance", any)!.GetValue(null);- var config = editor.GetField("unityConnectionConfig", any)!.GetValue(instance)!;- Assert.IsFalse((bool)config.GetType().GetProperty("KeepConnected")!.GetValue(config)!, "no connection");- Assert.IsFalse((bool)config.GetType().GetProperty("KeepServerRunning")!.GetValue(config)!, "no local server");+ var editor = PluginEditor();+#if UNITY_MCP_READY+ // The gate defines are in place, so the plugin compiled and must be loaded; a renamed type or assembly would+ // otherwise turn every check below into a silent pass.+ Assert.IsNotNull(editor, "UNITY_MCP_READY is defined but the plugin editor type is not loaded");+#endif+ // On a fresh clone's first run the plugin compiles after its resolver, so the tests run before a reload loads it.+ if (editor == null) { Assert.AreEqual("plugin not loaded", Status()); return; }+ Assert.AreEqual(Application.isBatchMode ? "held offline" : "held local", Status());+ var instance = editor.GetProperty("Instance", Any)!.GetValue(null);+ var config = editor.GetField("unityConnectionConfig", Any)!.GetValue(instance)!;+ object Get(string name) => config.GetType().GetProperty(name)!.GetValue(config)!;+ // The plugin's own UNITY_MCP_CONNECTION_MODE / UNITY_MCP_AUTH_OPTION knobs are an explicit opt-out the guard respects.+ if (Environment.GetEnvironmentVariable("UNITY_MCP_CONNECTION_MODE") == null)+ Assert.AreEqual("Custom", Get("ConnectionMode").ToString(), "never the plugin's cloud service");+ if (Environment.GetEnvironmentVariable("UNITY_MCP_AUTH_OPTION") == null)+ Assert.AreEqual("token", Get("AuthOption").ToString(), "the local server checks a token");// Recorded as runtime overrides, so the plugin never writes them into the user's own settings file.- var record = editor.GetProperty("RuntimeOverrides", any)!.GetValue(instance)!;- 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 record = editor.GetProperty("RuntimeOverrides", Any)!.GetValue(instance)!;+ bool Tracked(string name) => (bool)record.GetType().GetMethod("Contains")!.Invoke(record, new object[] { name })!;+ if (Environment.GetEnvironmentVariable("UNITY_MCP_CONNECTION_MODE") == null) Assert.IsTrue(Tracked("ConnectionMode"));+ if (Environment.GetEnvironmentVariable("UNITY_MCP_AUTH_OPTION") == null) Assert.IsTrue(Tracked("AuthOption"));+ if (!Application.isBatchMode) return; // the interactive editor keeps the user's connect and server choices+ Assert.IsFalse((bool)Get("KeepConnected"), "no connection");+ Assert.IsFalse((bool)Get("KeepServerRunning"), "no local server");+ Assert.IsTrue(Tracked("KeepConnected") && Tracked("KeepServerRunning"));+ }++ [Test]+ public void InBatchModeThePluginOpensNoWindowStartsNoServerAndSkipsItsUpdateCheck()+ {+ var editor = PluginEditor();+ if (!Application.isBatchMode || editor == null) { CollectionAssert.Contains(new[] { "held local", "plugin not loaded" }, Status()); return; }+ // The first-run window opened on screen in a batch test run (2026-10-10) and its server panel started the+ // local server; the update popup is the same kind of window.+ var windows = Resources.FindObjectsOfTypeAll<EditorWindow>().Where(w => w.GetType().Assembly == editor.Assembly);+ CollectionAssert.IsEmpty(windows.Select(w => w.GetType().FullName), "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");+ var unhooked = (IReadOnlyCollection<string>)Guard().GetField("Unhooked", Any)!.GetValue(null)!;+ CollectionAssert.IsSupersetOf(unhooked, new[] { "MainWindowInitializer.PerformInitialization", "UpdateChecker.CheckForUpdatesOnStartup" });+ }++ [Test]+ public void TheTeamKillSwitchForTheUpdatePopupIsOn()+ {+ var editor = PluginEditor();+ if (editor == null) { Assert.AreEqual("plugin not loaded", Status()); return; }+ var checker = editor.Assembly.GetType("com.IvanMurzak.Unity.MCP.Editor.Utils.UpdateChecker")!;+ Assert.IsTrue((bool)checker.GetProperty("IsDisabledForProject")!.GetValue(null)!,+ "ProjectSettings/AI-Game-Developer-UpdateSettings.asset turns the update popup off for the team");}}}diff --git a/unity/ProjectSettings/AI-Game-Developer-UpdateSettings.asset b/unity/ProjectSettings/AI-Game-Developer-UpdateSettings.assetnew file mode 100644index 000000000..e53bbdd29--- /dev/null+++ b/unity/ProjectSettings/AI-Game-Developer-UpdateSettings.asset@@ -0,0 +1,15 @@+%YAML 1.1+%TAG !u! tag:unity3d.com,2011:+--- !u!114 &1+MonoBehaviour:+ m_ObjectHideFlags: 53+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_GameObject: {fileID: 0}+ m_Enabled: 1+ m_EditorHideFlags: 0+ m_Script: {fileID: 11500000, guid: 984cc7c4404e4b5194c6f03fa57697c2, type: 3}+ m_Name:+ m_EditorClassIdentifier: com.IvanMurzak.Unity.MCP.Editor::com.IvanMurzak.Unity.MCP.Editor.Utils.UnityMcpUpdateProjectSettings+ disableUpdateNotificationsForTeam: 1