Skip to content

Commit 208cbf4

Browse files
committed
feat: Implement async method to retrieve enabled tools on the main thread
1 parent fd44ab3 commit 208cbf4

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@
88
using System.Threading.Tasks;
99
using MCPForUnity.Editor.Config;
1010
using MCPForUnity.Editor.Helpers;
11+
using MCPForUnity.Editor.Services;
1112
using MCPForUnity.Editor.Services.Transport;
1213
using Newtonsoft.Json;
1314
using Newtonsoft.Json.Linq;
15+
using UnityEditor;
1416
using UnityEngine;
1517

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

70+
private Task<List<ToolMetadata>> GetEnabledToolsOnMainThreadAsync()
71+
{
72+
var tcs = new TaskCompletionSource<List<ToolMetadata>>(TaskCreationOptions.RunContinuationsAsynchronously);
73+
74+
EditorApplication.delayCall += () =>
75+
{
76+
try
77+
{
78+
var tools = _toolDiscoveryService?.GetEnabledTools() ?? new List<ToolMetadata>();
79+
tcs.TrySetResult(tools);
80+
}
81+
catch (Exception ex)
82+
{
83+
tcs.TrySetException(ex);
84+
}
85+
};
86+
87+
return tcs.Task;
88+
}
89+
6890
public async Task<bool> StartAsync()
6991
{
7092
// Capture identity values on the main thread before any async context switching
@@ -421,7 +443,9 @@ private async Task SendRegisterToolsAsync(CancellationToken token)
421443
{
422444
if (_toolDiscoveryService == null) return;
423445

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

0 commit comments

Comments
 (0)