-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathServerManagementService.cs
More file actions
947 lines (841 loc) · 37.9 KB
/
ServerManagementService.cs
File metadata and controls
947 lines (841 loc) · 37.9 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using MCPForUnity.Editor.Constants;
using MCPForUnity.Editor.Helpers;
using MCPForUnity.Editor.Services.Server;
using UnityEditor;
using UnityEngine;
namespace MCPForUnity.Editor.Services
{
/// <summary>
/// Service for managing MCP server lifecycle
/// </summary>
public class ServerManagementService : IServerManagementService
{
private readonly IProcessDetector _processDetector;
private readonly IPidFileManager _pidFileManager;
private readonly IProcessTerminator _processTerminator;
private readonly IServerCommandBuilder _commandBuilder;
private readonly ITerminalLauncher _terminalLauncher;
/// <summary>
/// Creates a new ServerManagementService with default dependencies.
/// </summary>
public ServerManagementService() : this(null, null, null, null, null) { }
/// <summary>
/// Creates a new ServerManagementService with injected dependencies (for testing).
/// </summary>
/// <param name="processDetector">Process detector implementation (null for default)</param>
/// <param name="pidFileManager">PID file manager implementation (null for default)</param>
/// <param name="processTerminator">Process terminator implementation (null for default)</param>
/// <param name="commandBuilder">Server command builder implementation (null for default)</param>
/// <param name="terminalLauncher">Terminal launcher implementation (null for default)</param>
public ServerManagementService(
IProcessDetector processDetector,
IPidFileManager pidFileManager = null,
IProcessTerminator processTerminator = null,
IServerCommandBuilder commandBuilder = null,
ITerminalLauncher terminalLauncher = null)
{
_processDetector = processDetector ?? new ProcessDetector();
_pidFileManager = pidFileManager ?? new PidFileManager();
_processTerminator = processTerminator ?? new ProcessTerminator(_processDetector);
_commandBuilder = commandBuilder ?? new ServerCommandBuilder();
_terminalLauncher = terminalLauncher ?? new TerminalLauncher();
}
private string QuoteIfNeeded(string s)
{
return _commandBuilder.QuoteIfNeeded(s);
}
private string NormalizeForMatch(string s)
{
return _processDetector.NormalizeForMatch(s);
}
private void ClearLocalServerPidTracking()
{
_pidFileManager.ClearTracking();
}
private void StoreLocalHttpServerHandshake(string pidFilePath, string instanceToken)
{
_pidFileManager.StoreHandshake(pidFilePath, instanceToken);
}
private bool TryGetLocalHttpServerHandshake(out string pidFilePath, out string instanceToken)
{
return _pidFileManager.TryGetHandshake(out pidFilePath, out instanceToken);
}
private string GetLocalHttpServerPidFilePath(int port)
{
return _pidFileManager.GetPidFilePath(port);
}
private bool TryReadPidFromPidFile(string pidFilePath, out int pid)
{
return _pidFileManager.TryReadPid(pidFilePath, out pid);
}
private bool TryProcessCommandLineContainsInstanceToken(int pid, string instanceToken, out bool containsToken)
{
containsToken = false;
if (pid <= 0 || string.IsNullOrEmpty(instanceToken))
{
return false;
}
try
{
string tokenNeedle = instanceToken.ToLowerInvariant();
if (Application.platform == RuntimePlatform.WindowsEditor)
{
// Query full command line so we can validate token (reduces PID reuse risk).
// Use CIM via PowerShell (wmic is deprecated).
string ps = $"(Get-CimInstance Win32_Process -Filter \\\"ProcessId={pid}\\\").CommandLine";
bool ok = ExecPath.TryRun("powershell", $"-NoProfile -Command \"{ps}\"", Application.dataPath, out var stdout, out var stderr, 5000);
string combined = ((stdout ?? string.Empty) + "\n" + (stderr ?? string.Empty)).ToLowerInvariant();
containsToken = combined.Contains(tokenNeedle);
return ok;
}
if (TryGetUnixProcessArgs(pid, out var argsLowerNow))
{
containsToken = argsLowerNow.Contains(NormalizeForMatch(tokenNeedle));
return true;
}
}
catch { }
return false;
}
private string ComputeShortHash(string input)
{
return _pidFileManager.ComputeShortHash(input);
}
private bool TryGetStoredLocalServerPid(int expectedPort, out int pid)
{
return _pidFileManager.TryGetStoredPid(expectedPort, out pid);
}
private string GetStoredArgsHash()
{
return _pidFileManager.GetStoredArgsHash();
}
/// <summary>
/// Clear the local uvx cache for the MCP server package
/// </summary>
/// <returns>True if successful, false otherwise</returns>
public bool ClearUvxCache()
{
try
{
string uvxPath = MCPServiceLocator.Paths.GetUvxPath();
string uvCommand = BuildUvPathFromUvx(uvxPath);
// Get the package name
string packageName = "mcp-for-unity";
// Run uvx cache clean command
string args = $"cache clean {packageName}";
bool success;
string stdout;
string stderr;
success = ExecuteUvCommand(uvCommand, args, out stdout, out stderr);
if (success)
{
McpLog.Info($"uv cache cleared successfully: {stdout}");
return true;
}
string combinedOutput = string.Join(
Environment.NewLine,
new[] { stderr, stdout }.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()));
string lockHint = (!string.IsNullOrEmpty(combinedOutput) &&
combinedOutput.IndexOf("currently in-use", StringComparison.OrdinalIgnoreCase) >= 0)
? "Another uv process may be holding the cache lock; wait a moment and try again or clear with '--force' from a terminal."
: string.Empty;
if (string.IsNullOrEmpty(combinedOutput))
{
combinedOutput = "Command failed with no output. Ensure uv is installed, on PATH, or set an override in Advanced Settings.";
}
McpLog.Error(
$"Failed to clear uv cache using '{uvCommand} {args}'. " +
$"Details: {combinedOutput}{(string.IsNullOrEmpty(lockHint) ? string.Empty : " Hint: " + lockHint)}");
return false;
}
catch (Exception ex)
{
McpLog.Error($"Error clearing uv cache: {ex.Message}");
return false;
}
}
private bool ExecuteUvCommand(string uvCommand, string args, out string stdout, out string stderr)
{
stdout = null;
stderr = null;
string uvxPath = MCPServiceLocator.Paths.GetUvxPath();
string uvPath = BuildUvPathFromUvx(uvxPath);
if (!string.Equals(uvCommand, uvPath, StringComparison.OrdinalIgnoreCase))
{
return ExecPath.TryRun(uvCommand, args, Application.dataPath, out stdout, out stderr, 30000);
}
string command = $"{uvPath} {args}";
string extraPathPrepend = GetPlatformSpecificPathPrepend();
if (Application.platform == RuntimePlatform.WindowsEditor)
{
return ExecPath.TryRun("cmd.exe", $"/c {command}", Application.dataPath, out stdout, out stderr, 30000, extraPathPrepend);
}
string shell = File.Exists("/bin/bash") ? "/bin/bash" : "/bin/sh";
if (!string.IsNullOrEmpty(shell) && File.Exists(shell))
{
string escaped = command.Replace("\"", "\\\"");
return ExecPath.TryRun(shell, $"-lc \"{escaped}\"", Application.dataPath, out stdout, out stderr, 30000, extraPathPrepend);
}
return ExecPath.TryRun(uvPath, args, Application.dataPath, out stdout, out stderr, 30000, extraPathPrepend);
}
private string BuildUvPathFromUvx(string uvxPath)
{
return _commandBuilder.BuildUvPathFromUvx(uvxPath);
}
private string GetPlatformSpecificPathPrepend()
{
return _commandBuilder.GetPlatformSpecificPathPrepend();
}
/// <summary>
/// Start the local HTTP server in a separate terminal window.
/// Stops any existing server on the port and clears the uvx cache first.
/// </summary>
public bool StartLocalHttpServer(bool quiet = false)
{
/// Clean stale Python build artifacts when using a local dev server path
AssetPathUtility.CleanLocalServerBuildArtifacts();
if (!TryGetLocalHttpServerCommandParts(out _, out _, out var displayCommand, out var error))
{
if (!quiet)
{
EditorUtility.DisplayDialog(
"Cannot Start HTTP Server",
error ?? "The server command could not be constructed with the current settings.",
"OK");
}
return false;
}
// First, try to stop any existing server (quietly; we'll only warn if the port remains occupied).
StopLocalHttpServerInternal(quiet: true);
// If the port is still occupied, don't start and explain why (avoid confusing "refusing to stop" warnings).
try
{
string httpUrl = HttpEndpointUtility.GetLocalServerLaunchBaseUrl();
if (Uri.TryCreate(httpUrl, UriKind.Absolute, out var uri) && uri.Port > 0)
{
var remaining = GetListeningProcessIdsForPort(uri.Port);
if (remaining.Count > 0)
{
if (!quiet)
{
EditorUtility.DisplayDialog(
"Port In Use",
$"Cannot start the local HTTP server because port {uri.Port} is already in use by PID(s): " +
$"{string.Join(", ", remaining)}\n\n" +
"MCP For Unity will not terminate unrelated processes. Stop the owning process manually or change the HTTP URL.",
"OK");
}
return false;
}
}
}
catch { }
// Note: Dev mode cache-busting is handled by `uvx --no-cache --refresh` in the generated command.
// Create a per-launch token + pidfile path so Stop can be deterministic without relying on port/PID heuristics.
string baseUrlForPid = HttpEndpointUtility.GetLocalServerLaunchBaseUrl();
Uri.TryCreate(baseUrlForPid, UriKind.Absolute, out var uriForPid);
int portForPid = uriForPid?.Port ?? 0;
string instanceToken = Guid.NewGuid().ToString("N");
string pidFilePath = portForPid > 0 ? GetLocalHttpServerPidFilePath(portForPid) : null;
string launchCommand = displayCommand;
if (!string.IsNullOrEmpty(pidFilePath))
{
launchCommand = $"{displayCommand} --pidfile {QuoteIfNeeded(pidFilePath)} --unity-instance-token {instanceToken}";
}
if (!quiet && !EditorUtility.DisplayDialog(
"Start Local HTTP Server",
$"This will start the MCP server in HTTP mode in a new terminal window:\n\n{launchCommand}\n\n" +
"Continue?",
"Start Server",
"Cancel"))
{
return false;
}
try
{
// Clear any stale handshake state from prior launches.
ClearLocalServerPidTracking();
// Best-effort: delete stale pidfile if it exists.
try
{
if (!string.IsNullOrEmpty(pidFilePath) && File.Exists(pidFilePath))
{
DeletePidFile(pidFilePath);
}
}
catch { }
// Launch the server in a new terminal window (keeps user-visible logs).
var startInfo = CreateTerminalProcessStartInfo(launchCommand);
System.Diagnostics.Process.Start(startInfo);
if (!string.IsNullOrEmpty(pidFilePath))
{
StoreLocalHttpServerHandshake(pidFilePath, instanceToken);
}
McpLog.Info($"Started local HTTP server in terminal: {launchCommand}");
return true;
}
catch (Exception ex)
{
McpLog.Error($"Failed to start server: {ex.Message}");
if (!quiet)
{
EditorUtility.DisplayDialog(
"Error",
$"Failed to start server: {ex.Message}",
"OK");
}
return false;
}
}
/// <summary>
/// Stop the local HTTP server by finding the process listening on the configured port
/// </summary>
public bool StopLocalHttpServer()
{
return StopLocalHttpServerInternal(quiet: false);
}
public bool StopManagedLocalHttpServer()
{
if (!TryGetLocalHttpServerHandshake(out var pidFilePath, out _))
{
return false;
}
int port = 0;
if (!TryGetPortFromPidFilePath(pidFilePath, out port) || port <= 0)
{
string baseUrl = HttpEndpointUtility.GetLocalServerLaunchBaseUrl();
if (IsLocalUrl(baseUrl)
&& Uri.TryCreate(baseUrl, UriKind.Absolute, out var uri)
&& uri.Port > 0)
{
port = uri.Port;
}
}
if (port <= 0)
{
return false;
}
return StopLocalHttpServerInternal(quiet: true, portOverride: port, allowNonLocalUrl: true);
}
public bool IsLocalHttpServerRunning()
{
try
{
string httpUrl = HttpEndpointUtility.GetLocalServerLaunchBaseUrl();
if (!IsLocalUrl(httpUrl))
{
return false;
}
if (!Uri.TryCreate(httpUrl, UriKind.Absolute, out var uri) || uri.Port <= 0)
{
return false;
}
int port = uri.Port;
// Handshake path: if we have a pidfile+token and the PID is still the listener, treat as running.
if (TryGetLocalHttpServerHandshake(out var pidFilePath, out var instanceToken)
&& TryReadPidFromPidFile(pidFilePath, out var pidFromFile)
&& pidFromFile > 0)
{
var pidsNow = GetListeningProcessIdsForPort(port);
if (pidsNow.Contains(pidFromFile))
{
return true;
}
}
var pids = GetListeningProcessIdsForPort(port);
if (pids.Count == 0)
{
return false;
}
// Strong signal: stored PID is still the listener.
if (TryGetStoredLocalServerPid(port, out int storedPid) && storedPid > 0)
{
if (pids.Contains(storedPid))
{
return true;
}
}
// Best-effort: if anything listening looks like our server, treat as running.
foreach (var pid in pids)
{
if (pid <= 0) continue;
if (LooksLikeMcpServerProcess(pid))
{
return true;
}
}
return false;
}
catch
{
return false;
}
}
public bool IsLocalHttpServerReachable()
{
try
{
string httpUrl = HttpEndpointUtility.GetLocalServerLaunchBaseUrl();
if (!IsLocalUrl(httpUrl))
{
return false;
}
if (!Uri.TryCreate(httpUrl, UriKind.Absolute, out var uri) || uri.Port <= 0)
{
return false;
}
return TryConnectToLocalPort(uri.Host, uri.Port, timeoutMs: 50);
}
catch
{
return false;
}
}
private static bool TryConnectToLocalPort(string host, int port, int timeoutMs)
{
try
{
foreach (string target in BuildLocalProbeHosts(host))
{
try
{
using (var client = new TcpClient())
{
var connectTask = client.ConnectAsync(target, port);
if (connectTask.Wait(timeoutMs) && client.Connected)
{
return true;
}
}
}
catch
{
// Ignore per-host failures.
}
}
}
catch
{
// Ignore probe failures and treat as unreachable.
}
return false;
}
private static IReadOnlyList<string> BuildLocalProbeHosts(string host)
{
if (string.IsNullOrWhiteSpace(host))
{
host = "127.0.0.1";
}
else
{
host = host.Trim();
}
var hosts = new List<string>();
AddHostCandidate(hosts, host);
if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase))
{
// Probe both loopback families for localhost to avoid false negatives on systems where
// localhost resolution prefers an address family different from the server bind.
AddHostCandidate(hosts, "127.0.0.1");
AddHostCandidate(hosts, "::1");
}
else if (string.Equals(host, "0.0.0.0", StringComparison.OrdinalIgnoreCase))
{
AddHostCandidate(hosts, "127.0.0.1");
}
else if (string.Equals(host, "::", StringComparison.OrdinalIgnoreCase) ||
string.Equals(host, "0:0:0:0:0:0:0:0", StringComparison.OrdinalIgnoreCase))
{
AddHostCandidate(hosts, "::1");
}
return hosts;
}
private static void AddHostCandidate(List<string> hosts, string candidate)
{
if (string.IsNullOrWhiteSpace(candidate))
{
return;
}
if (hosts.Any(existing => string.Equals(existing, candidate, StringComparison.OrdinalIgnoreCase)))
{
return;
}
hosts.Add(candidate);
}
private bool StopLocalHttpServerInternal(bool quiet, int? portOverride = null, bool allowNonLocalUrl = false)
{
string httpUrl = HttpEndpointUtility.GetLocalServerLaunchBaseUrl();
if (!allowNonLocalUrl && !IsLocalUrl(httpUrl))
{
if (!quiet)
{
McpLog.Warn("Cannot stop server: URL is not local.");
}
return false;
}
try
{
int port = 0;
if (portOverride.HasValue)
{
port = portOverride.Value;
}
else
{
var uri = new Uri(httpUrl);
port = uri.Port;
}
if (port <= 0)
{
if (!quiet)
{
McpLog.Warn("Cannot stop server: Invalid port.");
}
return false;
}
// Guardrails:
// - Never terminate the Unity Editor process.
// - Only terminate processes that look like the MCP server (uv/uvx/python running mcp-for-unity).
// This prevents accidental termination of unrelated services (including Unity itself).
int unityPid = GetCurrentProcessIdSafe();
bool stoppedAny = false;
// Preferred deterministic stop path: if we have a pidfile+token from a Unity-managed launch,
// validate and terminate exactly that PID.
if (TryGetLocalHttpServerHandshake(out var pidFilePath, out var instanceToken))
{
// Prefer deterministic stop when Unity started the server (pidfile+token).
// If the pidfile isn't available yet (fast quit after start), we can optionally fall back
// to port-based heuristics when a port override was supplied (managed-stop path).
if (!TryReadPidFromPidFile(pidFilePath, out var pidFromFile) || pidFromFile <= 0)
{
if (!portOverride.HasValue)
{
if (!quiet)
{
McpLog.Warn(
$"Cannot stop local HTTP server on port {port}: pidfile not available yet at '{pidFilePath}'. " +
"If you just started the server, wait a moment and try again.");
}
return false;
}
// Managed-stop fallback: proceed with port-based heuristics below.
// We intentionally do NOT clear handshake state here; it will be cleared if we successfully
// stop a server process and/or the port is freed.
}
else
{
// Never kill Unity/Hub.
if (unityPid > 0 && pidFromFile == unityPid)
{
if (!quiet)
{
McpLog.Warn($"Refusing to stop port {port}: pidfile PID {pidFromFile} is the Unity Editor process.");
}
}
else
{
var listeners = GetListeningProcessIdsForPort(port);
if (listeners.Count == 0)
{
// Nothing is listening anymore; clear stale handshake state.
try { DeletePidFile(pidFilePath); } catch { }
ClearLocalServerPidTracking();
if (!quiet)
{
McpLog.Info($"No process found listening on port {port}");
}
return false;
}
bool pidIsListener = listeners.Contains(pidFromFile);
bool tokenQueryOk = TryProcessCommandLineContainsInstanceToken(pidFromFile, instanceToken, out bool tokenMatches);
bool allowKill;
if (tokenQueryOk)
{
allowKill = tokenMatches;
}
else
{
// If token validation is unavailable (e.g. Windows CIM permission issues),
// fall back to a stricter heuristic: only allow stop if the PID still looks like our server.
allowKill = LooksLikeMcpServerProcess(pidFromFile);
}
if (pidIsListener && allowKill)
{
if (TerminateProcess(pidFromFile))
{
stoppedAny = true;
try { DeletePidFile(pidFilePath); } catch { }
ClearLocalServerPidTracking();
if (!quiet)
{
McpLog.Info($"Stopped local HTTP server on port {port} (PID: {pidFromFile})");
}
return true;
}
if (!quiet)
{
McpLog.Warn($"Failed to terminate local HTTP server on port {port} (PID: {pidFromFile}).");
}
return false;
}
// If the pidfile PID is no longer the active listener, treat handshake state as stale
// and continue with guarded port-based heuristics below.
if (!pidIsListener)
{
if (!quiet)
{
McpLog.Warn(
$"Stale pidfile for port {port}: pidfile PID {pidFromFile} is not the current listener " +
$"(tokenMatch={tokenMatches}, tokenQueryOk={tokenQueryOk}). Falling back to guarded port heuristics.");
}
try { DeletePidFile(pidFilePath); } catch { }
ClearLocalServerPidTracking();
}
else
{
// PID still owns the listener, but identity validation failed.
// Fail closed to avoid terminating unrelated processes.
if (!quiet)
{
McpLog.Warn(
$"Refusing to stop port {port}: pidfile PID {pidFromFile} failed validation " +
$"(listener={pidIsListener}, tokenMatch={tokenMatches}, tokenQueryOk={tokenQueryOk}).");
}
return false;
}
}
}
}
var pids = GetListeningProcessIdsForPort(port);
if (pids.Count == 0)
{
if (stoppedAny)
{
// We stopped what Unity started; the port is now free.
if (!quiet)
{
McpLog.Info($"Stopped local HTTP server on port {port}");
}
ClearLocalServerPidTracking();
return true;
}
if (!quiet)
{
McpLog.Info($"No process found listening on port {port}");
}
ClearLocalServerPidTracking();
return false;
}
// Prefer killing the PID that we previously observed binding this port (if still valid).
if (TryGetStoredLocalServerPid(port, out int storedPid))
{
if (pids.Contains(storedPid))
{
string expectedHash = string.Empty;
expectedHash = GetStoredArgsHash();
// Prefer a fingerprint match (reduces PID reuse risk). If missing (older installs),
// fall back to a looser check to avoid leaving orphaned servers after domain reload.
if (TryGetUnixProcessArgs(storedPid, out var storedArgsLowerNow))
{
// Never kill Unity/Hub.
// Note: "mcp-for-unity" includes "unity", so detect MCP indicators first.
bool storedMentionsMcp = storedArgsLowerNow.Contains("mcp-for-unity")
|| storedArgsLowerNow.Contains("mcp_for_unity")
|| storedArgsLowerNow.Contains("mcpforunity");
if (storedArgsLowerNow.Contains("unityhub")
|| storedArgsLowerNow.Contains("unity hub")
|| (storedArgsLowerNow.Contains("unity") && !storedMentionsMcp))
{
if (!quiet)
{
McpLog.Warn($"Refusing to stop port {port}: stored PID {storedPid} appears to be a Unity process.");
}
}
else
{
bool allowKill = false;
if (!string.IsNullOrEmpty(expectedHash))
{
allowKill = string.Equals(expectedHash, ComputeShortHash(storedArgsLowerNow), StringComparison.OrdinalIgnoreCase);
}
else
{
// Older versions didn't store a fingerprint; accept common server indicators.
allowKill = storedArgsLowerNow.Contains("uvicorn")
|| storedArgsLowerNow.Contains("fastmcp")
|| storedArgsLowerNow.Contains("mcpforunity")
|| storedArgsLowerNow.Contains("mcp-for-unity")
|| storedArgsLowerNow.Contains("mcp_for_unity")
|| storedArgsLowerNow.Contains("uvx")
|| storedArgsLowerNow.Contains("python");
}
if (allowKill && TerminateProcess(storedPid))
{
if (!quiet)
{
McpLog.Info($"Stopped local HTTP server on port {port} (PID: {storedPid})");
}
stoppedAny = true;
ClearLocalServerPidTracking();
// Refresh the PID list to avoid double-work.
pids = GetListeningProcessIdsForPort(port);
}
else if (!allowKill && !quiet)
{
McpLog.Warn($"Refusing to stop port {port}: stored PID {storedPid} did not match expected server fingerprint.");
}
}
}
}
else
{
// Stale PID (no longer listening). Clear.
ClearLocalServerPidTracking();
}
}
foreach (var pid in pids)
{
if (pid <= 0) continue;
if (unityPid > 0 && pid == unityPid)
{
if (!quiet)
{
McpLog.Warn($"Refusing to stop port {port}: owning PID appears to be the Unity Editor process (PID {pid}).");
}
continue;
}
if (!LooksLikeMcpServerProcess(pid))
{
if (!quiet)
{
McpLog.Warn($"Refusing to stop port {port}: owning PID {pid} does not look like mcp-for-unity.");
}
continue;
}
if (TerminateProcess(pid))
{
McpLog.Info($"Stopped local HTTP server on port {port} (PID: {pid})");
stoppedAny = true;
}
else
{
if (!quiet)
{
McpLog.Warn($"Failed to stop process PID {pid} on port {port}");
}
}
}
if (stoppedAny)
{
ClearLocalServerPidTracking();
}
return stoppedAny;
}
catch (Exception ex)
{
if (!quiet)
{
McpLog.Error($"Failed to stop server: {ex.Message}");
}
return false;
}
}
private bool TryGetUnixProcessArgs(int pid, out string argsLower)
{
return _processDetector.TryGetProcessCommandLine(pid, out argsLower);
}
private bool TryGetPortFromPidFilePath(string pidFilePath, out int port)
{
return _pidFileManager.TryGetPortFromPidFilePath(pidFilePath, out port);
}
private void DeletePidFile(string pidFilePath)
{
_pidFileManager.DeletePidFile(pidFilePath);
}
private List<int> GetListeningProcessIdsForPort(int port)
{
return _processDetector.GetListeningProcessIdsForPort(port);
}
private int GetCurrentProcessIdSafe()
{
return _processDetector.GetCurrentProcessId();
}
private bool LooksLikeMcpServerProcess(int pid)
{
return _processDetector.LooksLikeMcpServerProcess(pid);
}
private bool TerminateProcess(int pid)
{
return _processTerminator.Terminate(pid);
}
/// <summary>
/// Attempts to build the command used for starting the local HTTP server
/// </summary>
public bool TryGetLocalHttpServerCommand(out string command, out string error)
{
command = null;
error = null;
if (!TryGetLocalHttpServerCommandParts(out var fileName, out var args, out var displayCommand, out error))
{
return false;
}
// Maintain existing behavior: return a single command string suitable for display/copy.
command = displayCommand;
return true;
}
private bool TryGetLocalHttpServerCommandParts(out string fileName, out string arguments, out string displayCommand, out string error)
{
return _commandBuilder.TryBuildCommand(out fileName, out arguments, out displayCommand, out error);
}
/// <summary>
/// Check if the configured HTTP URL is a local address
/// </summary>
public bool IsLocalUrl()
{
string httpUrl = HttpEndpointUtility.GetLocalServerLaunchBaseUrl();
return IsLocalUrl(httpUrl);
}
/// <summary>
/// Check if a URL is local or bind-all (localhost/loopback and 0.0.0.0/::).
/// This helper is intentionally broader than local-launch policy checks.
/// </summary>
private static bool IsLocalUrl(string url)
{
if (string.IsNullOrEmpty(url)) return false;
try
{
var uri = new Uri(url);
string host = uri.Host;
return HttpEndpointUtility.IsLoopbackHost(host) || HttpEndpointUtility.IsBindAllInterfacesHost(host);
}
catch
{
return false;
}
}
/// <summary>
/// Check if the local HTTP server can be started
/// </summary>
public bool CanStartLocalServer()
{
bool useHttpTransport = EditorConfigurationCache.Instance.UseHttpTransport;
if (!useHttpTransport)
{
return false;
}
string httpUrl = HttpEndpointUtility.GetLocalServerLaunchBaseUrl();
return HttpEndpointUtility.IsLanScope()
? HttpEndpointUtility.IsHttpLanUrlAllowedForLaunch(httpUrl, out _)
: HttpEndpointUtility.IsHttpLocalUrlAllowedForLaunch(httpUrl, out _);
}
private System.Diagnostics.ProcessStartInfo CreateTerminalProcessStartInfo(string command)
{
return _terminalLauncher.CreateTerminalProcessStartInfo(command);
}
}
}