forked from IvanMurzak/Unity-MCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMcpServerManager.cs
More file actions
1210 lines (1045 loc) · 48.2 KB
/
Copy pathMcpServerManager.cs
File metadata and controls
1210 lines (1045 loc) · 48.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
┌──────────────────────────────────────────────────────────────────┐
│ Author: Ivan Murzak (https://github.com/IvanMurzak) │
│ Repository: GitHub (https://github.com/IvanMurzak/Unity-MCP) │
│ Copyright (c) 2025 Ivan Murzak │
│ Licensed under the Apache License, Version 2.0. │
│ See the LICENSE file in the project root for more information. │
└──────────────────────────────────────────────────────────────────┘
*/
#nullable enable
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using com.IvanMurzak.ReflectorNet.Utils;
using com.IvanMurzak.Unity.MCP.Editor.UI;
using com.IvanMurzak.Unity.MCP.Editor.Utils;
using com.IvanMurzak.Unity.MCP.Runtime.Utils;
using com.IvanMurzak.Unity.MCP.Utils;
using Microsoft.Extensions.Logging;
using R3;
using UnityEditor;
using UnityEngine;
using McpConsts = com.IvanMurzak.McpPlugin.Common.Consts;
namespace com.IvanMurzak.Unity.MCP.Editor
{
using static com.IvanMurzak.McpPlugin.Common.Consts.MCP.Server;
using Consts = McpPlugin.Common.Consts;
using ILogger = Microsoft.Extensions.Logging.ILogger;
public enum McpServerStatus
{
Stopped,
Starting,
Running,
Stopping,
External
}
/// <summary>
/// Manages the MCP server binary and process lifecycle independently from UI.
/// Provides cross-platform support for Windows, macOS, and Linux.
/// </summary>
[InitializeOnLoad]
public static class McpServerManager
{
const string ProcessIdKey = "McpServerManager_ProcessId";
const string McpServerProcessName = "unity-mcp-server";
static readonly ILogger _logger = UnityLoggerFactory.LoggerFactory.CreateLogger(typeof(McpServerManager));
static readonly ReactiveProperty<McpServerStatus> _serverStatus = new(McpServerStatus.Stopped);
static readonly object _processMutex = new();
static Process? _serverProcess;
public static ReadOnlyReactiveProperty<McpServerStatus> ServerStatus => _serverStatus;
public static bool IsRunning => _serverStatus.CurrentValue == McpServerStatus.Running;
public static bool IsStarting => _serverStatus.CurrentValue == McpServerStatus.Starting;
static McpServerManager()
{
// Register for editor quit to clean up the server process
EditorApplication.quitting += OnEditorQuitting;
// Check if server process is still running (e.g., after domain reload)
EditorApplication.update += CheckExistingProcess;
DownloadServerBinaryIfNeeded()
.ContinueWith(task =>
{
if (task.IsFaulted || !task.Result)
return; // Failed to download binaries, skip auto-start
if (!task.Result)
return; // No binaries available (either in CI or failed to download), skip auto-start
if (EnvironmentUtils.IsCi())
return; // Skip auto-start in CI environment
EditorApplication.update += StartServerIfNeeded;
});
}
#region Binary Metadata
public const string ExecutableName = "unity-mcp-server";
public static string McpServerName
=> string.IsNullOrEmpty(Application.productName)
? "Unity Unknown"
: $"Unity {Application.productName}";
public static string OperationSystem =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "win" :
RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "osx" :
RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "linux" :
"unknown";
public static string CpuArch => RuntimeInformation.ProcessArchitecture switch
{
Architecture.X86 => "x86",
Architecture.X64 => "x64",
Architecture.Arm => "arm",
Architecture.Arm64 => "arm64",
_ => "unknown"
};
public static string PlatformName => $"{OperationSystem}-{CpuArch}";
// Server executable file name
// Sample (mac linux): unity-mcp-server
// Sample (windows): unity-mcp-server.exe
public static string ExecutableFullName
=> ExecutableName.ToLowerInvariant() + (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? ".exe"
: string.Empty);
// Full path to the server executable
// Sample (mac linux): ../Library/mcp-server
// Sample (windows): ../Library/mcp-server
public static string ExecutableFolderRootPath
=> Path.GetFullPath(
Path.Combine(
Application.dataPath,
"../Library",
"mcp-server"
)
);
// Full path to the server executable
// Sample (mac linux): ../Library/mcp-server/osx-x64
// Sample (windows): ../Library/mcp-server/win-x64
public static string ExecutableFolderPath
=> Path.GetFullPath(
Path.Combine(
ExecutableFolderRootPath,
PlatformName
)
);
// Full path to the server executable
// Sample (mac linux): ../Library/mcp-server/osx-x64/unity-mcp-server
// Sample (windows): ../Library/mcp-server/win-x64/unity-mcp-server.exe
public static string ExecutableFullPath
=> Path.GetFullPath(
Path.Combine(
ExecutableFolderPath,
ExecutableFullName
)
);
public static string VersionFullPath
=> Path.GetFullPath(
Path.Combine(
ExecutableFolderPath,
"version"
)
);
public static string ExecutableZipUrl
=> $"https://github.com/IvanMurzak/Unity-MCP/releases/download/{UnityMcpPlugin.Version}/{ExecutableName.ToLowerInvariant()}-{PlatformName}.zip";
#endregion // Binary Metadata
#region Binary Lifecycle
public static bool IsBinaryExists()
{
if (string.IsNullOrEmpty(ExecutableFullPath))
return false;
return File.Exists(ExecutableFullPath);
}
public static string? GetBinaryVersion()
{
if (!File.Exists(VersionFullPath))
return null;
return File.ReadAllText(VersionFullPath);
}
public static bool IsVersionMatches()
{
var binaryVersion = GetBinaryVersion();
if (binaryVersion == null)
return false;
return binaryVersion == UnityMcpPlugin.Version;
}
public static bool DeleteBinaryFolderIfExists()
{
if (Directory.Exists(ExecutableFolderRootPath))
{
// Intentional infinite loop:
// - Deletion can fail while the MCP server binaries are in use (e.g., server still running).
// - On the first failure, we automatically attempt to stop the server process via McpServerManager.
// - The retry/exit behavior is fully controlled by the user via the dialog below.
// - We do not impose a fixed maximum retry count so the user can take as long as needed
// to shut down their MCP client and release file locks before trying again.
// - The loop terminates when the user selects "Skip", at which point the exception is rethrown.
var silentRetries = 0;
while (true)
{
try
{
Directory.Delete(ExecutableFolderRootPath, recursive: true);
UnityEngine.Debug.Log($"Deleted existing MCP server folder: <color=orange>{ExecutableFolderRootPath}</color>");
return true;
}
catch (Exception ex)
{
// First failure: try to stop the running server process that may be locking files
if (silentRetries == 0)
{
silentRetries++;
UnityEngine.Debug.Log($"Failed to delete MCP server folder. Attempting to stop the server process...");
try
{
if (!StopServer(force: true))
{
UnityEngine.Debug.LogWarning($"No running MCP server process found to stop.");
}
else
{
UnityEngine.Debug.Log($"Stop signal sent to MCP server process. Retrying deletion...");
Thread.Sleep(2000); // Wait a moment for the process to exit and release file locks
}
}
catch (Exception stopEx)
{
UnityEngine.Debug.LogWarning($"Failed to stop MCP server: {stopEx.Message}");
}
continue; // Retry deletion after stopping the server
}
// Second failure: retry once more silently (OS may need time to release file locks)
if (silentRetries <= 1)
{
silentRetries++;
continue;
}
var retry = EditorUtility.DisplayDialog(
title: "Failed to Delete MCP Server Binaries",
message: $"The current unity-mcp-server binaries can't be deleted. " +
$"This is very likely because the MCP server is currently running.\n\n" +
$"Please close your MCP client to make sure the server is not running, then click \"Retry\".\n\n" +
$"Path: {ExecutableFolderRootPath}\n\n" +
$"Error: {ex.Message}",
ok: "Retry",
cancel: "Skip"
);
if (!retry)
{
throw;
}
// If retry is true, loop continues and tries again
}
}
}
return false;
}
public static Task<bool> DownloadServerBinaryIfNeeded()
{
if (EnvironmentUtils.IsCi())
{
// Ignore in CI environment
UnityEngine.Debug.Log($"Ignore MCP server downloading in CI environment");
return Task.FromResult(false);
}
if (IsBinaryExists() && IsVersionMatches())
return Task.FromResult(true);
return DownloadAndUnpackBinary();
}
public static async Task<bool> DownloadAndUnpackBinary()
{
UnityEngine.Debug.Log($"Downloading Unity-MCP-Server binary from: <color=yellow>{ExecutableZipUrl}</color>");
try
{
var previousKeepServerRunning = UnityMcpPluginEditor.KeepServerRunning;
// Clear existed server folder
DeleteBinaryFolderIfExists();
// Create folder if needed
if (!Directory.Exists(ExecutableFolderPath))
Directory.CreateDirectory(ExecutableFolderPath);
var archiveFilePath = Path.GetFullPath($"{Application.temporaryCachePath}/{ExecutableName.ToLowerInvariant()}-{PlatformName}-{UnityMcpPlugin.Version}.zip");
UnityEngine.Debug.Log($"Temporary archive file path: <color=yellow>{archiveFilePath}</color>");
// Download the zip file from the GitHub release notes
using (var client = new WebClient())
{
await client.DownloadFileTaskAsync(ExecutableZipUrl, archiveFilePath);
}
// Unpack zip archive
UnityEngine.Debug.Log($"Unpacking Unity-MCP-Server binary to: <color=yellow>{ExecutableFolderPath}</color>");
ZipFile.ExtractToDirectory(archiveFilePath, ExecutableFolderRootPath, overwriteFiles: true);
if (!File.Exists(ExecutableFullPath))
{
UnityEngine.Debug.LogError($"Failed to unpack server binary to: {ExecutableFolderRootPath}");
UnityEngine.Debug.LogError($"Binary file not found at: {ExecutableFullPath}");
return false;
}
UnityEngine.Debug.Log($"Downloaded and unpacked Unity-MCP-Server binary to: <color=green>{ExecutableFullPath}</color>");
// Set executable permission on macOS and Linux
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
UnityEngine.Debug.Log($"Setting executable permission for: <color=green>{ExecutableFullPath}</color>");
UnixUtils.Set0755(ExecutableFullPath);
}
File.WriteAllText(VersionFullPath, UnityMcpPlugin.Version);
UnityEngine.Debug.Log($"MCP server version file created at: <color=green><b>COMPLETED</b></color>");
var binaryExists = IsBinaryExists();
var versionMatches = IsVersionMatches();
var success = binaryExists && versionMatches;
if (success && previousKeepServerRunning)
{
if (!StartServer())
UnityEngine.Debug.LogError($"Failed to start MCP server after updating binary. Please try starting the server manually.");
}
NotificationPopupWindow.Show(
windowTitle: success
? "Updated"
: "Update Failed",
height: 235,
minHeight: 235,
title: success
? "Server Binary Updated"
: "Server Binary Update Failed",
message: success
? "The MCP server binary was successfully downloaded and updated. \n\n" +
$"Version: {GetBinaryVersion()}\n\n" +
"You may need to restart your AI agent to reconnect to the updated server."
: "Failed to download and update the MCP server binary. Please check the logs for details.");
return success;
}
catch (Exception ex)
{
UnityEngine.Debug.LogException(ex);
UnityEngine.Debug.LogError($"Failed to download and unpack server binary: {ex.Message}");
return false;
}
}
#endregion // Binary Lifecycle
#region Client Configuration
/// <summary>
/// Generates a JSON configuration for stdio transport.
/// <code>
/// {
/// "mcpServers": {
/// "Unity ProjectName": {
/// "type": "...", // optional, only if provided
/// "command": "path/to/unity-mcp-server",
/// "args": ["port=...", "plugin-timeout=...", "client-transport=stdio" /*, "token=..." if auth required */]
/// }
/// }
/// }
/// </code>
/// </summary>
public static JsonNode RawJsonConfigurationStdio(
int port,
string bodyPath = "mcpServers",
int timeoutMs = Consts.Hub.DefaultTimeoutMs,
string? type = null)
{
var pathSegments = BodyPathSegments(bodyPath);
// Build innermost content first
var serverConfig = new JsonObject();
if (type != null)
serverConfig["type"] = type;
serverConfig["command"] = ExecutableFullPath.Replace('\\', '/');
var args = new JsonArray
{
$"{Args.Port}={port}",
$"{Args.PluginTimeout}={timeoutMs}",
$"{Args.ClientTransportMethod}={TransportMethod.stdio}",
$"{Args.Authorization}={UnityMcpPluginEditor.AuthOption}"
};
var authRequired = UnityMcpPluginEditor.AuthOption == AuthOption.required;
if (authRequired && !string.IsNullOrEmpty(UnityMcpPluginEditor.Token))
args.Add($"{Args.Token}={UnityMcpPluginEditor.Token}");
serverConfig["args"] = args;
var innerContent = new JsonObject
{
[AiAgentConfig.DefaultMcpServerName] = serverConfig
};
// Build nested structure from innermost to outermost
var result = innerContent;
for (int i = pathSegments.Length - 1; i >= 0; i--)
{
result = new JsonObject { [pathSegments[i]] = result };
}
return result;
}
/// <summary>
/// Generates a JSON configuration for HTTP transport.
/// <code>
/// {
/// "mcpServers": {
/// "Unity ProjectName": {
/// "type": "...", // optional, only if provided
/// "url": "http://localhost:port",
/// "headers": { // only if token is provided
/// "Authorization": "Bearer token"
/// }
/// }
/// }
/// }
/// </code>
/// </summary>
public static JsonNode RawJsonConfigurationHttp(
string url,
string bodyPath = "mcpServers",
string? type = null)
{
var pathSegments = BodyPathSegments(bodyPath);
// Build innermost content first
var serverConfig = new JsonObject();
if (type != null)
serverConfig["type"] = type;
serverConfig["url"] = url;
var authRequired = UnityMcpPluginEditor.AuthOption == AuthOption.required;
if (authRequired && !string.IsNullOrEmpty(UnityMcpPluginEditor.Token))
{
serverConfig["headers"] = new JsonObject
{
["Authorization"] = $"Bearer {UnityMcpPluginEditor.Token}"
};
}
var innerContent = new JsonObject
{
[AiAgentConfig.DefaultMcpServerName] = serverConfig
};
// Build nested structure from innermost to outermost
var result = innerContent;
for (int i = pathSegments.Length - 1; i >= 0; i--)
{
result = new JsonObject { [pathSegments[i]] = result };
}
return result;
}
public static string DockerSetupRunCommand()
{
var dockerPortMapping = $"-p {UnityMcpPluginEditor.Port}:{UnityMcpPluginEditor.Port}";
var dockerEnvVars =
$"-e {Env.ClientTransportMethod}={TransportMethod.streamableHttp} " +
$"-e {Env.Port}={UnityMcpPluginEditor.Port} " +
$"-e {Env.PluginTimeout}={UnityMcpPluginEditor.TimeoutMs} " +
$"-e {Env.Authorization}={UnityMcpPluginEditor.AuthOption}";
var authRequired = UnityMcpPluginEditor.AuthOption == AuthOption.required;
var token = UnityMcpPluginEditor.Token;
if (authRequired && !string.IsNullOrEmpty(token))
dockerEnvVars += $" -e {Env.Token}={token}";
var dockerContainer = $"--name unity-mcp-server-{UnityMcpPluginEditor.Port}";
var dockerImage = $"ivanmurzakdev/unity-mcp-server:{UnityMcpPlugin.Version}";
return $"docker run -d {dockerPortMapping} {dockerEnvVars} {dockerContainer} {dockerImage}";
}
public static string DockerRunCommand()
{
return $"docker start unity-mcp-server-{UnityMcpPluginEditor.Port}";
}
public static string DockerStopCommand()
{
return $"docker stop unity-mcp-server-{UnityMcpPluginEditor.Port}";
}
public static string DockerRemoveCommand()
{
return $"docker rm unity-mcp-server-{UnityMcpPluginEditor.Port}";
}
#endregion // Client Configuration
#region Process Lifecycle
static void CheckExistingProcess()
{
EditorApplication.update -= CheckExistingProcess;
// Try to find an existing server process by checking if our tracked PID is still running
// This helps maintain state across domain reloads
var savedPid = EditorPrefs.GetInt(ProcessIdKey, -1);
if (savedPid > 0)
{
try
{
var process = Process.GetProcessById(savedPid);
if (process != null && !process.HasExited)
{
var processName = process.ProcessName.ToLowerInvariant();
if (processName.Contains(McpServerProcessName))
{
_serverProcess = process;
_serverStatus.Value = McpServerStatus.Running;
_logger.LogInformation("Reconnected to existing MCP server process (PID: {pid})", savedPid);
// Re-attach exit handler
process.EnableRaisingEvents = true;
process.Exited += OnProcessExited;
// Schedule verification check to detect if process crashes shortly after reconnection
ScheduleStartupVerification(savedPid);
return;
}
}
}
catch (Exception ex)
{
_logger.LogDebug("Could not reconnect to previous process: {message}", ex.Message);
}
// Clear stale PID
EditorPrefs.DeleteKey(ProcessIdKey);
}
}
static void OnEditorQuitting()
{
StopServer(force: true);
}
public static bool StartServer()
{
lock (_processMutex)
{
if (_serverStatus.CurrentValue == McpServerStatus.Running ||
_serverStatus.CurrentValue == McpServerStatus.Starting ||
_serverStatus.CurrentValue == McpServerStatus.Stopping)
{
_logger.LogWarning("MCP server is already {status}", _serverStatus.CurrentValue);
return false;
}
if (!IsBinaryExists())
{
_logger.LogError("MCP server binary not found at: {path}", ExecutableFullPath);
return false;
}
_serverStatus.Value = McpServerStatus.Starting;
// Kill any orphaned server processes to free the port
KillOrphanedServerProcesses();
try
{
var executablePath = ExecutableFullPath;
var arguments = BuildArguments();
_logger.LogInformation("Starting MCP server: {path} {args}", executablePath, arguments);
var startInfo = new ProcessStartInfo
{
FileName = executablePath,
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = ExecutableFolderPath
};
// Set executable permissions on Unix-like systems
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
UnixUtils.Set0755(executablePath);
}
_serverProcess = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true
};
_serverProcess.Exited += OnProcessExited;
_serverProcess.OutputDataReceived += OnOutputDataReceived;
_serverProcess.ErrorDataReceived += OnErrorDataReceived;
if (!_serverProcess.Start())
{
_logger.LogError("Failed to start MCP server process");
CleanupProcess();
return false;
}
_serverProcess.BeginOutputReadLine();
_serverProcess.BeginErrorReadLine();
// Save PID for reconnection after domain reload
EditorPrefs.SetInt(ProcessIdKey, _serverProcess.Id);
// Keep status as Starting - it will be set to Running after verification
_logger.LogInformation("MCP server process started (PID: {pid}), awaiting verification...", _serverProcess.Id);
// Schedule a delayed check to verify the process is still running
// This catches early crashes that might not trigger the Exited event reliably
// Status will be set to Running only after successful verification
ScheduleStartupVerification(_serverProcess.Id);
return true;
}
catch (Exception ex)
{
_logger.LogError("Failed to start MCP server: {message}", ex.Message);
CleanupProcess();
return false;
}
}
}
/// <summary>
/// Stops the MCP server process.
/// By default, this method is non-blocking: it sends the kill/terminate signal
/// and lets the Exited event handler perform cleanup asynchronously.
/// When force is true (e.g., editor quitting), it blocks until the process exits.
/// </summary>
public static bool StopServer(bool force = false)
{
lock (_processMutex)
{
if (_serverStatus.CurrentValue == McpServerStatus.Stopped ||
_serverStatus.CurrentValue == McpServerStatus.Stopping)
{
_logger.LogDebug("MCP server is already stopped or stopping");
return true;
}
if (_serverProcess == null)
{
_serverStatus.Value = McpServerStatus.Stopped;
EditorPrefs.DeleteKey(ProcessIdKey);
return true;
}
_serverStatus.Value = McpServerStatus.Stopping;
try
{
_logger.LogInformation("Stopping MCP server (PID: {pid})", _serverProcess.Id);
if (!_serverProcess.HasExited)
{
SendTerminateSignal();
}
if (force)
{
// Synchronous path: block until exit (used during editor quitting)
WaitForExitAndForceKillIfNeeded();
CleanupProcess();
}
else
{
if (_serverProcess.HasExited)
{
CleanupProcess();
}
else
{
// Non-blocking path: schedule background wait + force kill safety net.
// CleanupProcess will be called by OnProcessExited or the background task.
ScheduleForceKillIfNeeded();
}
}
_logger.LogInformation("MCP server stop initiated");
return true;
}
catch (Exception ex)
{
_logger.LogError("Error stopping MCP server: {message}", ex.Message);
CleanupProcess();
return false;
}
}
}
/// <summary>
/// Sends the platform-appropriate terminate signal without waiting for exit.
/// </summary>
static void SendTerminateSignal()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_serverProcess!.Kill();
}
else
{
// On Unix-like systems, send SIGTERM for graceful shutdown
try
{
using var killProcess = Process.Start(new ProcessStartInfo
{
FileName = "kill",
Arguments = $"-TERM {_serverProcess!.Id}",
UseShellExecute = false,
CreateNoWindow = true
});
killProcess?.WaitForExit(1000);
}
catch (Exception ex)
{
_logger.LogDebug("SIGTERM failed, falling back to Kill(): {message}", ex.Message);
_serverProcess!.Kill();
}
}
}
/// <summary>
/// Blocking wait for process exit, with force-kill fallback.
/// Used only during editor quitting to prevent orphaned processes.
/// </summary>
static void WaitForExitAndForceKillIfNeeded()
{
if (_serverProcess == null || _serverProcess.HasExited)
return;
if (!_serverProcess.WaitForExit(5000))
{
_logger.LogWarning("MCP server did not exit gracefully, forcing termination");
try
{
_serverProcess.Kill();
_serverProcess.WaitForExit(2000);
}
catch (Exception ex)
{
_logger.LogDebug("Force kill failed: {message}", ex.Message);
}
}
}
/// <summary>
/// Background safety net: waits for the process to exit and force-kills after timeout.
/// Calls CleanupProcess on the main thread when done.
/// </summary>
static void ScheduleForceKillIfNeeded()
{
var process = _serverProcess;
if (process == null)
return;
Task.Run(() =>
{
try
{
if (!process.HasExited && !process.WaitForExit(5000))
{
_logger.LogWarning("MCP server did not exit gracefully, forcing termination");
try
{
process.Kill();
process.WaitForExit(2000);
}
catch (Exception ex)
{
_logger.LogDebug("Force kill error: {message}", ex.Message);
}
}
}
catch (InvalidOperationException ex)
{
_logger.LogDebug("Process already exited or disposed while waiting for exit: {message}", ex.Message);
}
// Ensure cleanup on the main thread.
// Safe to call even if OnProcessExited already triggered cleanup.
MainThread.Instance.Run(CleanupProcess);
});
}
/// <summary>
/// Kills an orphaned unity-mcp-server process that is occupying this project's port.
/// Only targets the specific process listening on <see cref="UnityMcpPluginEditor.Port"/>.
/// If the port owner cannot be determined, does nothing (fails safe).
/// </summary>
static void KillOrphanedServerProcesses()
{
try
{
var port = UnityMcpPluginEditor.Port;
var currentPid = _serverProcess?.Id ?? -1;
var listeningPid = GetPidListeningOnPort(port);
if (listeningPid <= 0)
{
_logger.LogDebug("No process found listening on port {port}, port is available", port);
return;
}
if (listeningPid == currentPid)
{
_logger.LogDebug("Our own server process (PID: {pid}) is listening on port {port}", listeningPid, port);
return;
}
try
{
using var process = Process.GetProcessById(listeningPid);
if (process == null || process.HasExited)
{
_logger.LogDebug("Process (PID: {pid}) on port {port} has already exited", listeningPid, port);
return;
}
var processName = process.ProcessName.ToLowerInvariant();
if (!processName.Contains(McpServerProcessName))
{
_logger.LogWarning(
"Port {port} is occupied by a non-MCP process '{processName}' (PID: {pid}). " +
"The MCP server may fail to start. Please free the port or change the port in settings.",
port, process.ProcessName, listeningPid);
return;
}
_logger.LogWarning("Killing orphaned MCP server process (PID: {pid}) occupying port {port}", listeningPid, port);
process.Kill();
if (!process.WaitForExit(3000))
_logger.LogWarning("Orphaned MCP server process (PID: {pid}) did not exit within 3 seconds after kill", listeningPid);
else
_logger.LogDebug("Orphaned MCP server process (PID: {pid}) exited successfully", listeningPid);
}
catch (ArgumentException)
{
_logger.LogDebug("Process (PID: {pid}) on port {port} no longer exists", listeningPid, port);
}
catch (InvalidOperationException)
{
_logger.LogDebug("Process (PID: {pid}) on port {port} exited before it could be terminated", listeningPid, port);
}
catch (Exception ex)
{
_logger.LogDebug("Failed to kill orphaned process (PID: {pid}) on port {port}: {message}", listeningPid, port, ex.Message);
}
}
catch (Exception ex)
{
_logger.LogDebug("Error in orphaned server process cleanup: {message}", ex.Message);
}
}
/// <summary>
/// Returns the PID of the process listening on the specified TCP port,
/// or -1 if no process is found or the lookup fails.
/// </summary>
static int GetPidListeningOnPort(int port)
{
try
{
var startInfo = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? new ProcessStartInfo
{
FileName = "netstat",
Arguments = "-ano -p tcp",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
}
: new ProcessStartInfo
{
FileName = "lsof",
Arguments = $"-ti tcp:{port} -sTCP:LISTEN",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using var process = Process.Start(startInfo);
if (process == null) return -1;
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit(5000);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var portSuffix = $":{port}";
foreach (var line in output.Split('\n'))
{
var trimmed = line.Trim();
if (!trimmed.Contains("LISTENING"))
continue;
var parts = trimmed.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 5)
continue;
var localAddress = parts[1];
if (localAddress.EndsWith(portSuffix) && int.TryParse(parts[parts.Length - 1], out var pid))
return pid;
}
}
else
{
var trimmed = output.Trim();
if (string.IsNullOrEmpty(trimmed))
return -1;
var firstLine = trimmed.Split('\n')[0].Trim();
if (int.TryParse(firstLine, out var pid))
return pid;
}
}
catch (Exception ex)
{
_logger.LogDebug("Failed to determine PID listening on port {port}: {message}", port, ex.Message);
}
return -1;
}
static string BuildArguments()
{
var port = UnityMcpPluginEditor.Port;
var timeout = UnityMcpPluginEditor.TimeoutMs;
var transportMethod = TransportMethod.streamableHttp; // always must be streamableHttp for launching the server.
var token = UnityMcpPluginEditor.Token;
var authOption = UnityMcpPluginEditor.AuthOption;
// Arguments format: port=XXXXX plugin-timeout=XXXXX client-transport=<TransportMethod> token=<Token>
var args =
$"{Args.Port}={port} " +
$"{Args.PluginTimeout}={timeout} " +
$"{Args.ClientTransportMethod}={transportMethod} " +
$"{Args.Authorization}={authOption}";
if (authOption == AuthOption.required && !string.IsNullOrEmpty(token))
args += $" {Args.Token}={token}";
return args;
}
/// <summary>
/// Schedules a verification check 5 seconds after startup to detect early crashes.
/// If the process is still running after verification, the status is set to Running.
/// If the process has exited and no longer exists, the status is set to Stopped.
/// </summary>
static void ScheduleStartupVerification(int processId)
{
var startTime = DateTime.UtcNow;
const double verificationDelaySeconds = 5.0;
void CheckProcess()
{
// If status is no longer Starting (e.g., OnProcessExited already cleaned up), unsubscribe
if (_serverStatus.CurrentValue != McpServerStatus.Starting)
{