Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
using System.Threading.Tasks;
using MCPForUnity.Editor.Config;
using MCPForUnity.Editor.Helpers;
using MCPForUnity.Editor.Services;
using MCPForUnity.Editor.Services.Transport;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;

namespace MCPForUnity.Editor.Services.Transport.Transports
Expand Down Expand Up @@ -65,6 +67,26 @@ public WebSocketTransportClient(IToolDiscoveryService toolDiscoveryService = nul
public string TransportName => TransportDisplayName;
public TransportState State => _state;

private Task<List<ToolMetadata>> GetEnabledToolsOnMainThreadAsync()
{
var tcs = new TaskCompletionSource<List<ToolMetadata>>(TaskCreationOptions.RunContinuationsAsynchronously);

EditorApplication.delayCall += () =>
{
try
{
var tools = _toolDiscoveryService?.GetEnabledTools() ?? new List<ToolMetadata>();
tcs.TrySetResult(tools);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
};

return tcs.Task;
}
Comment on lines +70 to +88
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Consider adding cancellation/timeout safeguards to prevent hanging.

The implementation correctly marshals tool discovery to Unity's main thread. However, if EditorApplication.delayCall callback never executes (e.g., during Unity shutdown or domain reload), the TaskCompletionSource would hang indefinitely, potentially blocking Dispose() which awaits the receive loop.

Consider registering a cancellation callback to handle scenarios where Unity stops executing delayCall callbacks:

-private Task<List<ToolMetadata>> GetEnabledToolsOnMainThreadAsync()
+private Task<List<ToolMetadata>> GetEnabledToolsOnMainThreadAsync(CancellationToken cancellationToken = default)
 {
     var tcs = new TaskCompletionSource<List<ToolMetadata>>(TaskCreationOptions.RunContinuationsAsynchronously);
+    
+    // Register cancellation to prevent indefinite hanging
+    if (cancellationToken.CanBeCanceled)
+    {
+        cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken));
+    }
 
     EditorApplication.delayCall += () =>
     {
         try
         {
             var tools = _toolDiscoveryService?.GetEnabledTools() ?? new List<ToolMetadata>();
             tcs.TrySetResult(tools);
         }
         catch (Exception ex)
         {
             tcs.TrySetException(ex);
         }
     };
 
     return tcs.Task;
 }

Then update the call site:

 token.ThrowIfCancellationRequested();
-var tools = await GetEnabledToolsOnMainThreadAsync().ConfigureAwait(false);
+var tools = await GetEnabledToolsOnMainThreadAsync(token).ConfigureAwait(false);
 token.ThrowIfCancellationRequested();

Committable suggestion skipped: line range outside the PR's diff.


public async Task<bool> StartAsync()
{
// Capture identity values on the main thread before any async context switching
Expand Down Expand Up @@ -421,7 +443,9 @@ private async Task SendRegisterToolsAsync(CancellationToken token)
{
if (_toolDiscoveryService == null) return;

var tools = _toolDiscoveryService.GetEnabledTools();
token.ThrowIfCancellationRequested();
var tools = await GetEnabledToolsOnMainThreadAsync().ConfigureAwait(false);
token.ThrowIfCancellationRequested();
McpLog.Info($"[WebSocket] Preparing to register {tools.Count} tool(s) with the bridge.");
var toolsArray = new JArray();

Expand Down