2025-03-18 19:00:50 +08:00
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
2025-04-08 18:14:13 +08:00
|
|
|
using System.IO;
|
2025-03-18 19:00:50 +08:00
|
|
|
using System.Linq;
|
|
|
|
|
using System.Net;
|
|
|
|
|
using System.Net.Sockets;
|
2025-08-08 23:08:30 +08:00
|
|
|
using System.Threading;
|
2025-03-18 19:00:50 +08:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
using Newtonsoft.Json.Linq;
|
2025-04-08 18:14:13 +08:00
|
|
|
using UnityEditor;
|
|
|
|
|
using UnityEngine;
|
2025-08-21 03:59:49 +08:00
|
|
|
using MCPForUnity.Editor.Helpers;
|
|
|
|
|
using MCPForUnity.Editor.Models;
|
|
|
|
|
using MCPForUnity.Editor.Tools;
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-08-21 03:59:49 +08:00
|
|
|
namespace MCPForUnity.Editor
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
[InitializeOnLoad]
|
2025-08-21 03:59:49 +08:00
|
|
|
public static partial class MCPForUnityBridge
|
2025-03-18 22:01:51 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
private static TcpListener listener;
|
|
|
|
|
private static bool isRunning = false;
|
|
|
|
|
private static readonly object lockObj = new();
|
2025-08-08 06:32:03 +08:00
|
|
|
private static readonly object startStopLock = new();
|
|
|
|
|
private static bool initScheduled = false;
|
2025-08-10 06:08:28 +08:00
|
|
|
private static bool ensureUpdateHooked = false;
|
|
|
|
|
private static bool isStarting = false;
|
|
|
|
|
private static double nextStartAt = 0.0f;
|
2025-08-08 23:08:30 +08:00
|
|
|
private static double nextHeartbeatAt = 0.0f;
|
2025-08-10 06:08:28 +08:00
|
|
|
private static int heartbeatSeq = 0;
|
2025-04-08 18:14:13 +08:00
|
|
|
private static Dictionary<
|
|
|
|
|
string,
|
|
|
|
|
(string commandJson, TaskCompletionSource<string> tcs)
|
|
|
|
|
> commandQueue = new();
|
2025-07-29 12:17:36 +08:00
|
|
|
private static int currentUnityPort = 6400; // Dynamic port, starts with default
|
|
|
|
|
private static bool isAutoConnectMode = false;
|
2025-08-10 06:08:28 +08:00
|
|
|
|
|
|
|
|
// Debug helpers
|
|
|
|
|
private static bool IsDebugEnabled()
|
|
|
|
|
{
|
2025-08-21 03:59:49 +08:00
|
|
|
try { return EditorPrefs.GetBool("MCPForUnity.DebugLogs", false); } catch { return false; }
|
2025-08-10 06:08:28 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void LogBreadcrumb(string stage)
|
|
|
|
|
{
|
|
|
|
|
if (IsDebugEnabled())
|
|
|
|
|
{
|
2025-08-21 03:59:49 +08:00
|
|
|
Debug.Log($"<b><color=#2EA3FF>MCP-FOR-UNITY</color></b>: [{stage}]");
|
2025-08-10 06:08:28 +08:00
|
|
|
}
|
|
|
|
|
}
|
2025-03-19 01:09:54 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
public static bool IsRunning => isRunning;
|
2025-07-29 12:17:36 +08:00
|
|
|
public static int GetCurrentPort() => currentUnityPort;
|
|
|
|
|
public static bool IsAutoConnectMode() => isAutoConnectMode;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Start with Auto-Connect mode - discovers new port and saves it
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static void StartAutoConnect()
|
|
|
|
|
{
|
|
|
|
|
Stop(); // Stop current connection
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
2025-08-09 02:23:45 +08:00
|
|
|
// Prefer stored project port and start using the robust Start() path (with retries/options)
|
2025-08-09 01:35:00 +08:00
|
|
|
currentUnityPort = PortManager.GetPortWithFallback();
|
2025-08-09 02:23:45 +08:00
|
|
|
Start();
|
2025-07-29 12:17:36 +08:00
|
|
|
isAutoConnectMode = true;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Debug.LogError($"Auto-connect failed: {ex.Message}");
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
public static bool FolderExists(string path)
|
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrEmpty(path))
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
return false;
|
2025-04-08 19:22:24 +08:00
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
if (path.Equals("Assets", StringComparison.OrdinalIgnoreCase))
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
return true;
|
2025-04-08 19:22:24 +08:00
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-04-08 18:14:13 +08:00
|
|
|
string fullPath = Path.Combine(
|
|
|
|
|
Application.dataPath,
|
2025-04-08 19:22:24 +08:00
|
|
|
path.StartsWith("Assets/") ? path[7..] : path
|
2025-04-08 18:14:13 +08:00
|
|
|
);
|
2025-03-20 19:24:31 +08:00
|
|
|
return Directory.Exists(fullPath);
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-08-21 03:59:49 +08:00
|
|
|
static MCPForUnityBridge()
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-08-10 06:08:28 +08:00
|
|
|
// Skip bridge in headless/batch environments (CI/builds)
|
|
|
|
|
if (Application.isBatchMode)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
// Defer start until the editor is idle and not compiling
|
|
|
|
|
ScheduleInitRetry();
|
|
|
|
|
// Add a safety net update hook in case delayCall is missed during reload churn
|
|
|
|
|
if (!ensureUpdateHooked)
|
|
|
|
|
{
|
|
|
|
|
ensureUpdateHooked = true;
|
|
|
|
|
EditorApplication.update += EnsureStartedOnEditorIdle;
|
|
|
|
|
}
|
2025-03-20 19:24:31 +08:00
|
|
|
EditorApplication.quitting += Stop;
|
2025-08-08 23:08:30 +08:00
|
|
|
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
|
|
|
|
|
AssemblyReloadEvents.afterAssemblyReload += OnAfterAssemblyReload;
|
2025-08-10 06:08:28 +08:00
|
|
|
// Also coalesce play mode transitions into a deferred init
|
|
|
|
|
EditorApplication.playModeStateChanged += _ => ScheduleInitRetry();
|
2025-03-20 19:24:31 +08:00
|
|
|
}
|
2025-03-19 01:09:54 +08:00
|
|
|
|
2025-08-08 06:32:03 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// Initialize the MCP bridge after Unity is fully loaded and compilation is complete.
|
|
|
|
|
/// This prevents repeated restarts during script compilation that cause port hopping.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private static void InitializeAfterCompilation()
|
2025-03-20 19:24:31 +08:00
|
|
|
{
|
2025-08-08 06:32:03 +08:00
|
|
|
initScheduled = false;
|
2025-04-08 22:33:14 +08:00
|
|
|
|
2025-08-08 06:32:03 +08:00
|
|
|
// Play-mode friendly: allow starting in play mode; only defer while compiling
|
2025-08-10 06:08:28 +08:00
|
|
|
if (IsCompiling())
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-08-08 06:32:03 +08:00
|
|
|
ScheduleInitRetry();
|
|
|
|
|
return;
|
2025-04-08 19:22:24 +08:00
|
|
|
}
|
2025-08-08 06:32:03 +08:00
|
|
|
|
|
|
|
|
if (!isRunning)
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-08-08 06:32:03 +08:00
|
|
|
Start();
|
|
|
|
|
if (!isRunning)
|
|
|
|
|
{
|
|
|
|
|
// If a race prevented start, retry later
|
|
|
|
|
ScheduleInitRetry();
|
|
|
|
|
}
|
2025-04-08 19:22:24 +08:00
|
|
|
}
|
2025-08-08 06:32:03 +08:00
|
|
|
}
|
2025-04-08 19:22:24 +08:00
|
|
|
|
2025-08-08 06:32:03 +08:00
|
|
|
private static void ScheduleInitRetry()
|
|
|
|
|
{
|
|
|
|
|
if (initScheduled)
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-04-08 18:14:13 +08:00
|
|
|
return;
|
2025-04-08 19:22:24 +08:00
|
|
|
}
|
2025-08-08 06:32:03 +08:00
|
|
|
initScheduled = true;
|
2025-08-10 06:08:28 +08:00
|
|
|
// Debounce: start ~200ms after the last trigger
|
|
|
|
|
nextStartAt = EditorApplication.timeSinceStartup + 0.20f;
|
|
|
|
|
// Ensure the update pump is active
|
|
|
|
|
if (!ensureUpdateHooked)
|
|
|
|
|
{
|
|
|
|
|
ensureUpdateHooked = true;
|
|
|
|
|
EditorApplication.update += EnsureStartedOnEditorIdle;
|
|
|
|
|
}
|
|
|
|
|
// Keep the original delayCall as a secondary path
|
2025-08-08 06:32:03 +08:00
|
|
|
EditorApplication.delayCall += InitializeAfterCompilation;
|
|
|
|
|
}
|
2025-04-08 19:22:24 +08:00
|
|
|
|
2025-08-10 06:08:28 +08:00
|
|
|
// Safety net: ensure the bridge starts shortly after domain reload when editor is idle
|
|
|
|
|
private static void EnsureStartedOnEditorIdle()
|
|
|
|
|
{
|
|
|
|
|
// Do nothing while compiling
|
|
|
|
|
if (IsCompiling())
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If already running, remove the hook
|
|
|
|
|
if (isRunning)
|
|
|
|
|
{
|
|
|
|
|
EditorApplication.update -= EnsureStartedOnEditorIdle;
|
|
|
|
|
ensureUpdateHooked = false;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Debounced start: wait until the scheduled time
|
|
|
|
|
if (nextStartAt > 0 && EditorApplication.timeSinceStartup < nextStartAt)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (isStarting)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isStarting = true;
|
|
|
|
|
// Attempt start; if it succeeds, remove the hook to avoid overhead
|
|
|
|
|
Start();
|
|
|
|
|
isStarting = false;
|
|
|
|
|
if (isRunning)
|
|
|
|
|
{
|
|
|
|
|
EditorApplication.update -= EnsureStartedOnEditorIdle;
|
|
|
|
|
ensureUpdateHooked = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Helper to check compilation status across Unity versions
|
|
|
|
|
private static bool IsCompiling()
|
|
|
|
|
{
|
|
|
|
|
if (EditorApplication.isCompiling)
|
|
|
|
|
{
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
System.Type pipeline = System.Type.GetType("UnityEditor.Compilation.CompilationPipeline, UnityEditor");
|
|
|
|
|
var prop = pipeline?.GetProperty("isCompiling", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
|
|
|
|
|
if (prop != null)
|
|
|
|
|
{
|
|
|
|
|
return (bool)prop.GetValue(null);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch { }
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-08 06:32:03 +08:00
|
|
|
public static void Start()
|
|
|
|
|
{
|
|
|
|
|
lock (startStopLock)
|
2025-04-08 21:46:52 +08:00
|
|
|
{
|
2025-08-08 06:32:03 +08:00
|
|
|
// Don't restart if already running on a working port
|
|
|
|
|
if (isRunning && listener != null)
|
2025-04-08 21:46:52 +08:00
|
|
|
{
|
2025-08-21 03:59:49 +08:00
|
|
|
Debug.Log($"<b><color=#2EA3FF>MCP-FOR-UNITY</color></b>: MCPForUnityBridge already running on port {currentUnityPort}");
|
2025-08-08 06:32:03 +08:00
|
|
|
return;
|
2025-04-08 21:46:52 +08:00
|
|
|
}
|
2025-08-08 06:32:03 +08:00
|
|
|
|
|
|
|
|
Stop();
|
|
|
|
|
|
2025-08-08 23:18:33 +08:00
|
|
|
// Attempt fast bind with stored-port preference (sticky per-project)
|
2025-08-08 06:32:03 +08:00
|
|
|
try
|
|
|
|
|
{
|
2025-08-08 23:18:33 +08:00
|
|
|
// Always consult PortManager first so we prefer the persisted project port
|
|
|
|
|
currentUnityPort = PortManager.GetPortWithFallback();
|
2025-08-08 23:08:30 +08:00
|
|
|
|
2025-08-10 06:08:28 +08:00
|
|
|
// Breadcrumb: Start
|
|
|
|
|
LogBreadcrumb("Start");
|
|
|
|
|
|
2025-08-08 23:08:30 +08:00
|
|
|
const int maxImmediateRetries = 3;
|
|
|
|
|
const int retrySleepMs = 75;
|
|
|
|
|
int attempt = 0;
|
|
|
|
|
for (;;)
|
2025-08-08 06:32:03 +08:00
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
listener = new TcpListener(IPAddress.Loopback, currentUnityPort);
|
2025-08-08 23:08:30 +08:00
|
|
|
listener.Server.SetSocketOption(
|
|
|
|
|
SocketOptionLevel.Socket,
|
|
|
|
|
SocketOptionName.ReuseAddress,
|
|
|
|
|
true
|
|
|
|
|
);
|
2025-08-10 06:08:28 +08:00
|
|
|
#if UNITY_EDITOR_WIN
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
listener.ExclusiveAddressUse = false;
|
|
|
|
|
}
|
|
|
|
|
catch { }
|
|
|
|
|
#endif
|
2025-08-08 23:08:30 +08:00
|
|
|
// Minimize TIME_WAIT by sending RST on close
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
listener.Server.LingerState = new LingerOption(true, 0);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception)
|
|
|
|
|
{
|
|
|
|
|
// Ignore if not supported on platform
|
|
|
|
|
}
|
2025-08-08 06:32:03 +08:00
|
|
|
listener.Start();
|
2025-08-08 23:08:30 +08:00
|
|
|
break;
|
2025-08-08 06:32:03 +08:00
|
|
|
}
|
2025-08-08 23:08:30 +08:00
|
|
|
catch (SocketException se) when (se.SocketErrorCode == SocketError.AddressAlreadyInUse && attempt < maxImmediateRetries)
|
2025-08-08 06:32:03 +08:00
|
|
|
{
|
2025-08-08 23:08:30 +08:00
|
|
|
attempt++;
|
|
|
|
|
Thread.Sleep(retrySleepMs);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
catch (SocketException se) when (se.SocketErrorCode == SocketError.AddressAlreadyInUse && attempt >= maxImmediateRetries)
|
|
|
|
|
{
|
|
|
|
|
currentUnityPort = PortManager.GetPortWithFallback();
|
|
|
|
|
listener = new TcpListener(IPAddress.Loopback, currentUnityPort);
|
|
|
|
|
listener.Server.SetSocketOption(
|
|
|
|
|
SocketOptionLevel.Socket,
|
|
|
|
|
SocketOptionName.ReuseAddress,
|
|
|
|
|
true
|
|
|
|
|
);
|
2025-08-10 06:08:28 +08:00
|
|
|
#if UNITY_EDITOR_WIN
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
listener.ExclusiveAddressUse = false;
|
|
|
|
|
}
|
|
|
|
|
catch { }
|
|
|
|
|
#endif
|
2025-08-08 23:08:30 +08:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
listener.Server.LingerState = new LingerOption(true, 0);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception)
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
listener.Start();
|
|
|
|
|
break;
|
2025-08-08 06:32:03 +08:00
|
|
|
}
|
|
|
|
|
}
|
2025-08-08 23:08:30 +08:00
|
|
|
|
|
|
|
|
isRunning = true;
|
|
|
|
|
isAutoConnectMode = false;
|
2025-08-25 02:28:47 +08:00
|
|
|
string platform = Application.platform.ToString();
|
|
|
|
|
string serverVer = ReadInstalledServerVersionSafe();
|
|
|
|
|
Debug.Log($"<b><color=#2EA3FF>MCP-FOR-UNITY</color></b>: MCPForUnityBridge started on port {currentUnityPort}. (OS={platform}, server={serverVer})");
|
2025-08-08 23:08:30 +08:00
|
|
|
Task.Run(ListenerLoop);
|
|
|
|
|
EditorApplication.update += ProcessCommands;
|
|
|
|
|
// Write initial heartbeat immediately
|
2025-08-10 06:08:28 +08:00
|
|
|
heartbeatSeq++;
|
|
|
|
|
WriteHeartbeat(false, "ready");
|
2025-08-08 23:08:30 +08:00
|
|
|
nextHeartbeatAt = EditorApplication.timeSinceStartup + 0.5f;
|
|
|
|
|
}
|
|
|
|
|
catch (SocketException ex)
|
|
|
|
|
{
|
|
|
|
|
Debug.LogError($"Failed to start TCP listener: {ex.Message}");
|
2025-04-08 21:46:52 +08:00
|
|
|
}
|
|
|
|
|
}
|
2025-03-20 19:24:31 +08:00
|
|
|
}
|
2025-03-19 01:09:54 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
public static void Stop()
|
|
|
|
|
{
|
2025-08-08 06:32:03 +08:00
|
|
|
lock (startStopLock)
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-08-08 06:32:03 +08:00
|
|
|
if (!isRunning)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-04-08 19:22:24 +08:00
|
|
|
|
2025-08-08 06:32:03 +08:00
|
|
|
try
|
|
|
|
|
{
|
2025-08-09 02:23:45 +08:00
|
|
|
// Mark as stopping early to avoid accept logging during disposal
|
|
|
|
|
isRunning = false;
|
2025-08-08 23:08:30 +08:00
|
|
|
// Mark heartbeat one last time before stopping
|
|
|
|
|
WriteHeartbeat(false);
|
2025-08-08 06:32:03 +08:00
|
|
|
listener?.Stop();
|
|
|
|
|
listener = null;
|
|
|
|
|
EditorApplication.update -= ProcessCommands;
|
2025-08-21 03:59:49 +08:00
|
|
|
Debug.Log("<b><color=#2EA3FF>MCP-FOR-UNITY</color></b>: MCPForUnityBridge stopped.");
|
2025-08-08 06:32:03 +08:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2025-08-21 03:59:49 +08:00
|
|
|
Debug.LogError($"Error stopping MCPForUnityBridge: {ex.Message}");
|
2025-08-08 06:32:03 +08:00
|
|
|
}
|
2025-04-08 21:46:52 +08:00
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
|
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
private static async Task ListenerLoop()
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
|
|
|
|
while (isRunning)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2025-04-08 19:22:24 +08:00
|
|
|
TcpClient client = await listener.AcceptTcpClientAsync();
|
2025-03-20 19:24:31 +08:00
|
|
|
// Enable basic socket keepalive
|
2025-04-08 18:14:13 +08:00
|
|
|
client.Client.SetSocketOption(
|
|
|
|
|
SocketOptionLevel.Socket,
|
|
|
|
|
SocketOptionName.KeepAlive,
|
|
|
|
|
true
|
|
|
|
|
);
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
// Set longer receive timeout to prevent quick disconnections
|
|
|
|
|
client.ReceiveTimeout = 60000; // 60 seconds
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
// Fire and forget each client connection
|
|
|
|
|
_ = HandleClientAsync(client);
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
2025-08-09 02:23:45 +08:00
|
|
|
catch (ObjectDisposedException)
|
|
|
|
|
{
|
|
|
|
|
// Listener was disposed during stop/reload; exit quietly
|
|
|
|
|
if (!isRunning)
|
|
|
|
|
{
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2025-04-08 18:14:13 +08:00
|
|
|
if (isRunning)
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-04-08 18:14:13 +08:00
|
|
|
Debug.LogError($"Listener error: {ex.Message}");
|
2025-04-08 19:22:24 +08:00
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
private static async Task HandleClientAsync(TcpClient client)
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
using (client)
|
2025-04-08 19:22:24 +08:00
|
|
|
using (NetworkStream stream = client.GetStream())
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-04-08 19:22:24 +08:00
|
|
|
byte[] buffer = new byte[8192];
|
2025-03-20 19:24:31 +08:00
|
|
|
while (isRunning)
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
try
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
|
2025-04-08 18:14:13 +08:00
|
|
|
if (bytesRead == 0)
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-04-08 18:14:13 +08:00
|
|
|
break; // Client disconnected
|
2025-04-08 19:22:24 +08:00
|
|
|
}
|
2025-04-08 18:14:13 +08:00
|
|
|
|
|
|
|
|
string commandText = System.Text.Encoding.UTF8.GetString(
|
|
|
|
|
buffer,
|
|
|
|
|
0,
|
|
|
|
|
bytesRead
|
|
|
|
|
);
|
2025-03-20 19:24:31 +08:00
|
|
|
string commandId = Guid.NewGuid().ToString();
|
2025-04-08 19:22:24 +08:00
|
|
|
TaskCompletionSource<string> tcs = new();
|
2025-03-20 19:24:31 +08:00
|
|
|
|
|
|
|
|
// Special handling for ping command to avoid JSON parsing
|
|
|
|
|
if (commandText.Trim() == "ping")
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
// Direct response to ping without going through JSON parsing
|
2025-04-08 18:14:13 +08:00
|
|
|
byte[] pingResponseBytes = System.Text.Encoding.UTF8.GetBytes(
|
2025-04-08 19:22:24 +08:00
|
|
|
/*lang=json,strict*/
|
2025-04-08 18:14:13 +08:00
|
|
|
"{\"status\":\"success\",\"result\":{\"message\":\"pong\"}}"
|
|
|
|
|
);
|
2025-03-20 19:24:31 +08:00
|
|
|
await stream.WriteAsync(pingResponseBytes, 0, pingResponseBytes.Length);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
lock (lockObj)
|
|
|
|
|
{
|
|
|
|
|
commandQueue[commandId] = (commandText, tcs);
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
string response = await tcs.Task;
|
|
|
|
|
byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);
|
|
|
|
|
await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
Debug.LogError($"Client handler error: {ex.Message}");
|
|
|
|
|
break;
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
2025-03-20 19:24:31 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void ProcessCommands()
|
|
|
|
|
{
|
|
|
|
|
List<string> processedIds = new();
|
|
|
|
|
lock (lockObj)
|
|
|
|
|
{
|
2025-08-08 23:08:30 +08:00
|
|
|
// Periodic heartbeat while editor is idle/processing
|
|
|
|
|
double now = EditorApplication.timeSinceStartup;
|
|
|
|
|
if (now >= nextHeartbeatAt)
|
|
|
|
|
{
|
|
|
|
|
WriteHeartbeat(false);
|
|
|
|
|
nextHeartbeatAt = now + 0.5f;
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-08 19:22:24 +08:00
|
|
|
foreach (
|
|
|
|
|
KeyValuePair<
|
|
|
|
|
string,
|
|
|
|
|
(string commandJson, TaskCompletionSource<string> tcs)
|
|
|
|
|
> kvp in commandQueue.ToList()
|
|
|
|
|
)
|
2025-03-20 19:24:31 +08:00
|
|
|
{
|
|
|
|
|
string id = kvp.Key;
|
|
|
|
|
string commandText = kvp.Value.commandJson;
|
2025-04-08 19:22:24 +08:00
|
|
|
TaskCompletionSource<string> tcs = kvp.Value.tcs;
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
try
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
// Special case handling
|
|
|
|
|
if (string.IsNullOrEmpty(commandText))
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
var emptyResponse = new
|
|
|
|
|
{
|
|
|
|
|
status = "error",
|
2025-04-08 18:14:13 +08:00
|
|
|
error = "Empty command received",
|
2025-03-20 19:24:31 +08:00
|
|
|
};
|
|
|
|
|
tcs.SetResult(JsonConvert.SerializeObject(emptyResponse));
|
|
|
|
|
processedIds.Add(id);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Trim the command text to remove any whitespace
|
|
|
|
|
commandText = commandText.Trim();
|
|
|
|
|
|
|
|
|
|
// Non-JSON direct commands handling (like ping)
|
|
|
|
|
if (commandText == "ping")
|
|
|
|
|
{
|
|
|
|
|
var pingResponse = new
|
|
|
|
|
{
|
|
|
|
|
status = "success",
|
2025-04-08 18:14:13 +08:00
|
|
|
result = new { message = "pong" },
|
2025-03-20 19:24:31 +08:00
|
|
|
};
|
|
|
|
|
tcs.SetResult(JsonConvert.SerializeObject(pingResponse));
|
|
|
|
|
processedIds.Add(id);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if the command is valid JSON before attempting to deserialize
|
|
|
|
|
if (!IsValidJson(commandText))
|
|
|
|
|
{
|
|
|
|
|
var invalidJsonResponse = new
|
|
|
|
|
{
|
|
|
|
|
status = "error",
|
|
|
|
|
error = "Invalid JSON format",
|
2025-04-08 18:14:13 +08:00
|
|
|
receivedText = commandText.Length > 50
|
2025-04-08 19:22:24 +08:00
|
|
|
? commandText[..50] + "..."
|
2025-04-08 18:14:13 +08:00
|
|
|
: commandText,
|
2025-03-20 19:24:31 +08:00
|
|
|
};
|
|
|
|
|
tcs.SetResult(JsonConvert.SerializeObject(invalidJsonResponse));
|
|
|
|
|
processedIds.Add(id);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Normal JSON command processing
|
2025-04-08 19:22:24 +08:00
|
|
|
Command command = JsonConvert.DeserializeObject<Command>(commandText);
|
2025-04-10 23:12:20 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
if (command == null)
|
|
|
|
|
{
|
|
|
|
|
var nullCommandResponse = new
|
|
|
|
|
{
|
|
|
|
|
status = "error",
|
|
|
|
|
error = "Command deserialized to null",
|
2025-04-08 18:14:13 +08:00
|
|
|
details = "The command was valid JSON but could not be deserialized to a Command object",
|
2025-03-20 19:24:31 +08:00
|
|
|
};
|
|
|
|
|
tcs.SetResult(JsonConvert.SerializeObject(nullCommandResponse));
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
string responseJson = ExecuteCommand(command);
|
|
|
|
|
tcs.SetResult(responseJson);
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
2025-03-20 19:24:31 +08:00
|
|
|
catch (Exception ex)
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
Debug.LogError($"Error processing command: {ex.Message}\n{ex.StackTrace}");
|
|
|
|
|
|
|
|
|
|
var response = new
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
|
|
|
|
status = "error",
|
2025-03-20 19:24:31 +08:00
|
|
|
error = ex.Message,
|
|
|
|
|
commandType = "Unknown (error during processing)",
|
2025-04-08 18:14:13 +08:00
|
|
|
receivedText = commandText?.Length > 50
|
2025-04-08 19:22:24 +08:00
|
|
|
? commandText[..50] + "..."
|
2025-04-08 18:14:13 +08:00
|
|
|
: commandText,
|
2025-03-18 19:00:50 +08:00
|
|
|
};
|
2025-03-20 19:24:31 +08:00
|
|
|
string responseJson = JsonConvert.SerializeObject(response);
|
2025-03-18 19:00:50 +08:00
|
|
|
tcs.SetResult(responseJson);
|
|
|
|
|
}
|
|
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
processedIds.Add(id);
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
|
|
|
|
|
2025-04-08 19:22:24 +08:00
|
|
|
foreach (string id in processedIds)
|
2025-03-20 19:24:31 +08:00
|
|
|
{
|
|
|
|
|
commandQueue.Remove(id);
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
2025-03-20 19:24:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Helper method to check if a string is valid JSON
|
|
|
|
|
private static bool IsValidJson(string text)
|
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrWhiteSpace(text))
|
2025-04-08 19:22:24 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
return false;
|
2025-04-08 19:22:24 +08:00
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
text = text.Trim();
|
2025-04-08 18:14:13 +08:00
|
|
|
if (
|
|
|
|
|
(text.StartsWith("{") && text.EndsWith("}"))
|
|
|
|
|
|| // Object
|
|
|
|
|
(text.StartsWith("[") && text.EndsWith("]"))
|
|
|
|
|
) // Array
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
JToken.Parse(text);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
return false;
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return false;
|
2025-03-20 19:24:31 +08:00
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
private static string ExecuteCommand(Command command)
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
if (string.IsNullOrEmpty(command.type))
|
|
|
|
|
{
|
|
|
|
|
var errorResponse = new
|
|
|
|
|
{
|
|
|
|
|
status = "error",
|
|
|
|
|
error = "Command type cannot be empty",
|
2025-04-08 18:14:13 +08:00
|
|
|
details = "A valid command type is required for processing",
|
2025-03-20 19:24:31 +08:00
|
|
|
};
|
|
|
|
|
return JsonConvert.SerializeObject(errorResponse);
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
// Handle ping command for connection verification
|
2025-03-31 03:58:01 +08:00
|
|
|
if (command.type.Equals("ping", StringComparison.OrdinalIgnoreCase))
|
2025-03-20 19:24:31 +08:00
|
|
|
{
|
2025-04-08 18:14:13 +08:00
|
|
|
var pingResponse = new
|
|
|
|
|
{
|
|
|
|
|
status = "success",
|
|
|
|
|
result = new { message = "pong" },
|
|
|
|
|
};
|
2025-03-20 19:24:31 +08:00
|
|
|
return JsonConvert.SerializeObject(pingResponse);
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
|
2025-03-31 03:58:01 +08:00
|
|
|
// Use JObject for parameters as the new handlers likely expect this
|
|
|
|
|
JObject paramsObject = command.@params ?? new JObject();
|
|
|
|
|
|
|
|
|
|
// Route command based on the new tool structure from the refactor plan
|
2025-03-20 19:24:31 +08:00
|
|
|
object result = command.type switch
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-31 03:58:01 +08:00
|
|
|
// Maps the command type (tool name) to the corresponding handler's static HandleCommand method
|
|
|
|
|
// Assumes each handler class has a static method named 'HandleCommand' that takes JObject parameters
|
|
|
|
|
"manage_script" => ManageScript.HandleCommand(paramsObject),
|
|
|
|
|
"manage_scene" => ManageScene.HandleCommand(paramsObject),
|
|
|
|
|
"manage_editor" => ManageEditor.HandleCommand(paramsObject),
|
|
|
|
|
"manage_gameobject" => ManageGameObject.HandleCommand(paramsObject),
|
|
|
|
|
"manage_asset" => ManageAsset.HandleCommand(paramsObject),
|
2025-07-14 13:42:16 +08:00
|
|
|
"manage_shader" => ManageShader.HandleCommand(paramsObject),
|
2025-03-31 03:58:01 +08:00
|
|
|
"read_console" => ReadConsole.HandleCommand(paramsObject),
|
|
|
|
|
"execute_menu_item" => ExecuteMenuItem.HandleCommand(paramsObject),
|
2025-04-08 18:14:13 +08:00
|
|
|
_ => throw new ArgumentException(
|
|
|
|
|
$"Unknown or unsupported command type: {command.type}"
|
|
|
|
|
),
|
2025-03-18 19:00:50 +08:00
|
|
|
};
|
|
|
|
|
|
2025-03-31 03:58:01 +08:00
|
|
|
// Standard success response format
|
2025-03-20 19:24:31 +08:00
|
|
|
var response = new { status = "success", result };
|
|
|
|
|
return JsonConvert.SerializeObject(response);
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
2025-03-20 19:24:31 +08:00
|
|
|
catch (Exception ex)
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-31 03:58:01 +08:00
|
|
|
// Log the detailed error in Unity for debugging
|
2025-04-08 18:14:13 +08:00
|
|
|
Debug.LogError(
|
|
|
|
|
$"Error executing command '{command?.type ?? "Unknown"}': {ex.Message}\n{ex.StackTrace}"
|
|
|
|
|
);
|
2025-03-31 03:58:01 +08:00
|
|
|
|
|
|
|
|
// Standard error response format
|
2025-03-20 19:24:31 +08:00
|
|
|
var response = new
|
|
|
|
|
{
|
|
|
|
|
status = "error",
|
2025-03-31 03:58:01 +08:00
|
|
|
error = ex.Message, // Provide the specific error message
|
|
|
|
|
command = command?.type ?? "Unknown", // Include the command type if available
|
|
|
|
|
stackTrace = ex.StackTrace, // Include stack trace for detailed debugging
|
2025-04-08 18:14:13 +08:00
|
|
|
paramsSummary = command?.@params != null
|
|
|
|
|
? GetParamsSummary(command.@params)
|
|
|
|
|
: "No parameters", // Summarize parameters for context
|
2025-03-20 19:24:31 +08:00
|
|
|
};
|
|
|
|
|
return JsonConvert.SerializeObject(response);
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
|
|
|
|
|
2025-03-20 19:24:31 +08:00
|
|
|
// Helper method to get a summary of parameters for error reporting
|
|
|
|
|
private static string GetParamsSummary(JObject @params)
|
2025-03-18 19:00:50 +08:00
|
|
|
{
|
2025-03-20 19:24:31 +08:00
|
|
|
try
|
|
|
|
|
{
|
2025-04-08 19:22:24 +08:00
|
|
|
return @params == null || !@params.HasValues
|
|
|
|
|
? "No parameters"
|
|
|
|
|
: string.Join(
|
|
|
|
|
", ",
|
|
|
|
|
@params
|
|
|
|
|
.Properties()
|
|
|
|
|
.Select(static p =>
|
|
|
|
|
$"{p.Name}: {p.Value?.ToString()?[..Math.Min(20, p.Value?.ToString()?.Length ?? 0)]}"
|
|
|
|
|
)
|
|
|
|
|
);
|
2025-03-20 19:24:31 +08:00
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
return "Could not summarize parameters";
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
2025-08-08 23:08:30 +08:00
|
|
|
|
|
|
|
|
// Heartbeat/status helpers
|
|
|
|
|
private static void OnBeforeAssemblyReload()
|
|
|
|
|
{
|
2025-08-10 06:08:28 +08:00
|
|
|
// Stop cleanly before reload so sockets close and clients see 'reloading'
|
|
|
|
|
try { Stop(); } catch { }
|
|
|
|
|
WriteHeartbeat(true, "reloading");
|
|
|
|
|
LogBreadcrumb("Reload");
|
2025-08-08 23:08:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void OnAfterAssemblyReload()
|
|
|
|
|
{
|
|
|
|
|
// Will be overwritten by Start(), but mark as alive quickly
|
2025-08-10 06:08:28 +08:00
|
|
|
WriteHeartbeat(false, "idle");
|
|
|
|
|
LogBreadcrumb("Idle");
|
|
|
|
|
// Schedule a safe restart after reload to avoid races during compilation
|
|
|
|
|
ScheduleInitRetry();
|
2025-08-08 23:08:30 +08:00
|
|
|
}
|
|
|
|
|
|
2025-08-10 06:08:28 +08:00
|
|
|
private static void WriteHeartbeat(bool reloading, string reason = null)
|
2025-08-08 23:08:30 +08:00
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".unity-mcp");
|
|
|
|
|
Directory.CreateDirectory(dir);
|
|
|
|
|
string filePath = Path.Combine(dir, $"unity-mcp-status-{ComputeProjectHash(Application.dataPath)}.json");
|
|
|
|
|
var payload = new
|
|
|
|
|
{
|
|
|
|
|
unity_port = currentUnityPort,
|
|
|
|
|
reloading,
|
2025-08-10 06:08:28 +08:00
|
|
|
reason = reason ?? (reloading ? "reloading" : "ready"),
|
|
|
|
|
seq = heartbeatSeq,
|
2025-08-08 23:08:30 +08:00
|
|
|
project_path = Application.dataPath,
|
|
|
|
|
last_heartbeat = DateTime.UtcNow.ToString("O")
|
|
|
|
|
};
|
2025-08-24 18:57:11 +08:00
|
|
|
File.WriteAllText(filePath, JsonConvert.SerializeObject(payload), new System.Text.UTF8Encoding(false));
|
2025-08-08 23:08:30 +08:00
|
|
|
}
|
|
|
|
|
catch (Exception)
|
|
|
|
|
{
|
|
|
|
|
// Best-effort only
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-25 02:28:47 +08:00
|
|
|
private static string ReadInstalledServerVersionSafe()
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
string serverSrc = ServerInstaller.GetServerPath();
|
|
|
|
|
string verFile = Path.Combine(serverSrc, "server_version.txt");
|
|
|
|
|
if (File.Exists(verFile))
|
|
|
|
|
{
|
|
|
|
|
string v = File.ReadAllText(verFile)?.Trim();
|
|
|
|
|
if (!string.IsNullOrEmpty(v)) return v;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch { }
|
|
|
|
|
return "unknown";
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-08 23:08:30 +08:00
|
|
|
private static string ComputeProjectHash(string input)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var sha1 = System.Security.Cryptography.SHA1.Create();
|
|
|
|
|
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input ?? string.Empty);
|
|
|
|
|
byte[] hashBytes = sha1.ComputeHash(bytes);
|
|
|
|
|
var sb = new System.Text.StringBuilder();
|
|
|
|
|
foreach (byte b in hashBytes)
|
|
|
|
|
{
|
|
|
|
|
sb.Append(b.ToString("x2"));
|
|
|
|
|
}
|
|
|
|
|
return sb.ToString()[..8];
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
return "default";
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-03-18 19:00:50 +08:00
|
|
|
}
|
2025-03-31 03:58:01 +08:00
|
|
|
}
|