Skip to content

Commit 46df725

Browse files
committed
attempted ManageScene debugging for hang
1 parent c1bde80 commit 46df725

File tree

2 files changed

+53
-7
lines changed

2 files changed

+53
-7
lines changed

UnityMcpBridge/Editor/MCPForUnityBridge.cs

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,10 @@ private static async Task HandleClientAsync(TcpClient client, CancellationToken
575575
response = JsonConvert.SerializeObject(errorResponse);
576576
}
577577

578+
if (IsDebugEnabled())
579+
{
580+
try { MCPForUnity.Editor.Helpers.McpLog.Info("[MCP] sending framed response", always: false); } catch { }
581+
}
578582
byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);
579583
await WriteFrameAsync(stream, responseBytes);
580584
}
@@ -858,6 +862,12 @@ private static object InvokeOnMainThreadWithTimeout(Func<object> func, int timeo
858862
if (func == null) return null;
859863
try
860864
{
865+
// If mainThreadId is unknown, assume we're on main thread to avoid blocking the editor.
866+
if (mainThreadId == 0)
867+
{
868+
try { return func(); }
869+
catch (Exception ex) { throw new InvalidOperationException($"Main thread handler error: {ex.Message}", ex); }
870+
}
861871
// If we are already on the main thread, execute directly to avoid deadlocks
862872
try
863873
{
@@ -895,13 +905,13 @@ private static object InvokeOnMainThreadWithTimeout(Func<object> func, int timeo
895905
}
896906
if (captured != null)
897907
{
898-
return Response.Error($"Main thread handler error: {captured.Message}");
908+
throw new InvalidOperationException($"Main thread handler error: {captured.Message}", captured);
899909
}
900910
return result;
901911
}
902912
catch (Exception ex)
903913
{
904-
return Response.Error($"Failed to invoke on main thread: {ex.Message}");
914+
throw new InvalidOperationException($"Failed to invoke on main thread: {ex.Message}", ex);
905915
}
906916
}
907917

@@ -969,8 +979,9 @@ private static string ExecuteCommand(Command command)
969979
// Maps the command type (tool name) to the corresponding handler's static HandleCommand method
970980
// Assumes each handler class has a static method named 'HandleCommand' that takes JObject parameters
971981
"manage_script" => ManageScript.HandleCommand(paramsObject),
972-
// Run scene operations on the main thread to avoid deadlocks/hangs
973-
"manage_scene" => InvokeOnMainThreadWithTimeout(() => ManageScene.HandleCommand(paramsObject), FrameIOTimeoutMs) ?? Response.Error("manage_scene timed out on main thread"),
982+
// Run scene operations on the main thread to avoid deadlocks/hangs (with diagnostics under debug flag)
983+
"manage_scene" => HandleManageScene(paramsObject)
984+
?? throw new TimeoutException($"manage_scene timed out after {FrameIOTimeoutMs} ms on main thread"),
974985
"manage_editor" => ManageEditor.HandleCommand(paramsObject),
975986
"manage_gameobject" => ManageGameObject.HandleCommand(paramsObject),
976987
"manage_asset" => ManageAsset.HandleCommand(paramsObject),
@@ -1008,6 +1019,23 @@ private static string ExecuteCommand(Command command)
10081019
}
10091020
}
10101021

1022+
private static object HandleManageScene(JObject paramsObject)
1023+
{
1024+
try
1025+
{
1026+
if (IsDebugEnabled()) Debug.Log("[MCP] manage_scene: dispatching to main thread");
1027+
var sw = System.Diagnostics.Stopwatch.StartNew();
1028+
var r = InvokeOnMainThreadWithTimeout(() => ManageScene.HandleCommand(paramsObject), FrameIOTimeoutMs);
1029+
sw.Stop();
1030+
if (IsDebugEnabled()) Debug.Log($"[MCP] manage_scene: completed in {sw.ElapsedMilliseconds} ms");
1031+
return r ?? Response.Error("manage_scene returned null (timeout or error)");
1032+
}
1033+
catch (Exception ex)
1034+
{
1035+
return Response.Error($"manage_scene dispatch error: {ex.Message}");
1036+
}
1037+
}
1038+
10111039
// Helper method to get a summary of parameters for error reporting
10121040
private static string GetParamsSummary(JObject @params)
10131041
{

UnityMcpBridge/Editor/Tools/ManageScene.cs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ public static class ManageScene
2121
/// </summary>
2222
public static object HandleCommand(JObject @params)
2323
{
24+
try { McpLog.Info("[ManageScene] HandleCommand: start", always: false); } catch { }
2425
string action = @params["action"]?.ToString().ToLower();
2526
string name = @params["name"]?.ToString();
2627
string path = @params["path"]?.ToString(); // Relative to Assets/
@@ -76,6 +77,7 @@ public static object HandleCommand(JObject @params)
7677
}
7778

7879
// Route action
80+
try { McpLog.Info($"[ManageScene] Route action='{action}' name='{name}' path='{path}' buildIndex={(buildIndex.HasValue ? buildIndex.Value.ToString() : "null")}", always: false); } catch { }
7981
switch (action)
8082
{
8183
case "create":
@@ -98,9 +100,15 @@ public static object HandleCommand(JObject @params)
98100
// Save current scene, optionally to a new path
99101
return SaveScene(fullPath, relativePath);
100102
case "get_hierarchy":
101-
return GetSceneHierarchy();
103+
try { McpLog.Info("[ManageScene] get_hierarchy: entering", always: false); } catch { }
104+
var gh = GetSceneHierarchy();
105+
try { McpLog.Info("[ManageScene] get_hierarchy: exiting", always: false); } catch { }
106+
return gh;
102107
case "get_active":
103-
return GetActiveSceneInfo();
108+
try { McpLog.Info("[ManageScene] get_active: entering", always: false); } catch { }
109+
var ga = GetActiveSceneInfo();
110+
try { McpLog.Info("[ManageScene] get_active: exiting", always: false); } catch { }
111+
return ga;
104112
case "get_build_settings":
105113
return GetBuildSettingsScenes();
106114
// Add cases for modifying build settings, additive loading, unloading etc.
@@ -294,7 +302,9 @@ private static object GetActiveSceneInfo()
294302
{
295303
try
296304
{
305+
try { McpLog.Info("[ManageScene] get_active: querying EditorSceneManager.GetActiveScene", always: false); } catch { }
297306
Scene activeScene = EditorSceneManager.GetActiveScene();
307+
try { McpLog.Info($"[ManageScene] get_active: got scene valid={activeScene.IsValid()} loaded={activeScene.isLoaded} name='{activeScene.name}'", always: false); } catch { }
298308
if (!activeScene.IsValid())
299309
{
300310
return Response.Error("No active scene found.");
@@ -314,6 +324,7 @@ private static object GetActiveSceneInfo()
314324
}
315325
catch (Exception e)
316326
{
327+
try { McpLog.Error($"[ManageScene] get_active: exception {e.Message}"); } catch { }
317328
return Response.Error($"Error getting active scene info: {e.Message}");
318329
}
319330
}
@@ -348,24 +359,31 @@ private static object GetSceneHierarchy()
348359
{
349360
try
350361
{
362+
try { McpLog.Info("[ManageScene] get_hierarchy: querying EditorSceneManager.GetActiveScene", always: false); } catch { }
351363
Scene activeScene = EditorSceneManager.GetActiveScene();
364+
try { McpLog.Info($"[ManageScene] get_hierarchy: got scene valid={activeScene.IsValid()} loaded={activeScene.isLoaded} name='{activeScene.name}'", always: false); } catch { }
352365
if (!activeScene.IsValid() || !activeScene.isLoaded)
353366
{
354367
return Response.Error(
355368
"No valid and loaded scene is active to get hierarchy from."
356369
);
357370
}
358371

372+
try { McpLog.Info("[ManageScene] get_hierarchy: fetching root objects", always: false); } catch { }
359373
GameObject[] rootObjects = activeScene.GetRootGameObjects();
374+
try { McpLog.Info($"[ManageScene] get_hierarchy: rootCount={rootObjects?.Length ?? 0}", always: false); } catch { }
360375
var hierarchy = rootObjects.Select(go => GetGameObjectDataRecursive(go)).ToList();
361376

362-
return Response.Success(
377+
var resp = Response.Success(
363378
$"Retrieved hierarchy for scene '{activeScene.name}'.",
364379
hierarchy
365380
);
381+
try { McpLog.Info("[ManageScene] get_hierarchy: success", always: false); } catch { }
382+
return resp;
366383
}
367384
catch (Exception e)
368385
{
386+
try { McpLog.Error($"[ManageScene] get_hierarchy: exception {e.Message}"); } catch { }
369387
return Response.Error($"Error getting scene hierarchy: {e.Message}");
370388
}
371389
}

0 commit comments

Comments
 (0)