Skip to content
Merged
Changes from 2 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,37 @@ public WebSocketTransportClient(IToolDiscoveryService toolDiscoveryService = nul
public string TransportName => TransportDisplayName;
public TransportState State => _state;

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

// Register cancellation to break the deadlock if StopAsync is called while waiting for main thread
var registration = token.Register(() => tcs.TrySetCanceled());

EditorApplication.delayCall += () =>
{
try
{
// Clean up the registration once we're running
registration.Dispose();

if (tcs.Task.IsCompleted)
{
return;
}

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

return tcs.Task;
}

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

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

Expand Down