unity-mcp/MCPForUnity/Editor/Services
dsarno 8eb684ddc2
fix: comprehensive performance optimizations, claude code config, and stability improvements (issue #577) (#595)
* fix: reduce per-frame GC allocations causing editor hitches (issue #577)

Eliminate memory allocations that occurred every frame, which triggered
garbage collection spikes (~28ms) approximately every second.

Changes:
- EditorStateCache: Skip BuildSnapshot() entirely when state unchanged
  (check BEFORE building). Increased poll interval from 0.25s to 1.0s.
  Cache DeepClone() results to avoid allocations on GetSnapshot().

- TransportCommandDispatcher: Early exit before lock/list allocation
  when Pending.Count == 0, eliminating per-frame allocations when idle.

- StdioBridgeHost: Same early exit pattern for commandQueue.

- MCPForUnityEditorWindow: Throttle OnEditorUpdate to 2-second intervals
  instead of every frame, preventing expensive socket checks 60+/sec.

Fixes GitHub issue #577: High performance impact even when MCP server is off

* fix: prevent multiple domain reloads when calling refresh_unity (issue #577)

Root Cause:
- send_command() had a hardcoded retry loop (min 6 attempts) on connection errors
- Each retry resent the refresh_unity command, causing Unity to reload 6 times
- retry_on_reload=False only controlled reload-state retries, not connection retries

The Fix:
1. Unity C# (MCPForUnity/Editor):
   - Added --reinstall flag to uvx commands in dev mode
   - Ensures local development changes are picked up by uvx/Claude Code
   - Applies to all client configurators (Claude Code, Codex, etc.)

2. Python Server (Server/src):
   - Added max_attempts parameter to send_command()
   - Pass max_attempts=0 when retry_on_reload=False
   - Fixed type handling in refresh_unity.py (handle MCPResponse objects)
   - Added timeout to connection error recovery conditions
   - Recovery logic now returns success instead of error to prevent client retries

Changes:
- MCPForUnity/Editor: Added --reinstall to dev mode uvx commands
- Server/refresh_unity.py: Fixed type handling, improved error recovery
- Server/unity_connection.py: Added max_attempts param, disable retries when retry_on_reload=False

Result: refresh_unity with compile=request now triggers only 1 domain reload instead of 6

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: UI and server stability improvements

Unity Editor (C#):
- Fix "Resuming..." stuck state when manually clicking End Session
  Clear ResumeStdioAfterReload and ResumeHttpAfterReload flags in
  OnConnectionToggleClicked and EndOrphanedSessionAsync to prevent
  UI from getting stuck showing "Resuming..." with disabled button
- Remove unsupported --reinstall flag from all uvx command builders
  uvx does not support --reinstall and shows warning when used
  Use --no-cache --refresh instead for dev mode cache busting

Python Server:
- Add "aborted" to connection error patterns in refresh_unity
  Handle WinError 10053 (connection aborted) gracefully during
  Unity domain reload, treating it as expected behavior
- Add WindowsSafeRotatingFileHandler to suppress log rotation errors
  Windows file locking prevents log rotation when file is open by
  another process; catch PermissionError to avoid noisy stack traces
- Fix packaging: add py-modules = ["main"] to pyproject.toml
  setuptools.packages.find only discovers packages (directories with
  __init__.py), must explicitly list standalone module files

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* docs: improve refresh_unity connection loss handling documentation

Add detailed comments and logging to clarify why connection loss during
compile is treated as success (expected domain reload behavior, not failure).
This addresses PR feedback about potentially masking real connection errors.

The logic is intentional and correct:
- Connection loss only treated as success when compile='request'
- Domain reload causing disconnect is expected Unity behavior
- Subsequent wait_for_ready loop validates Unity becomes ready
- Prevents multiple domain reload loops (issue #577)

Added logging for observability:
- Info log when expected disconnect detected
- Warning log for non-recoverable errors

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: add missing logger import in refresh_unity

Missing logger import causes NameError at runtime when connection
loss handling paths are triggered (lines 82 and 91).

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: address code review feedback on thread safety and semantics

Addresses four issues raised in code review:

1. EditorStateCache.GetSnapshot() - Remove shared cached clone
   - Revert to always returning fresh DeepClone() to prevent mutation bugs
   - Main GC optimization remains: state-change detection prevents
     unnecessary _cached rebuilds (the expensive operation)
   - Removed _cachedClone and _cachedCloneSequence fields

2. refresh_unity.py - Fix blocking reason terminology mismatch
   - Changed "asset_refresh" to "asset_import" to match activityPhase
     values from EditorStateCache.cs
   - Ensures asset import is correctly detected as blocking state

3. TransportCommandDispatcher - Fix unsynchronized Count access
   - Moved Pending.Count check inside PendingLock
   - Prevents data races and InvalidOperationException from concurrent
     dictionary access

4. StdioBridgeHost - Fix unsynchronized Count access
   - Moved commandQueue.Count check inside lockObj
   - Ensures all collection access is properly serialized

All changes maintain the GC allocation optimizations while fixing
thread safety violations and semantic contract changes.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: address code review feedback on thread safety and timeout handling

- refresh_unity.py: Track readiness explicitly and return failure on timeout
  instead of silently returning success when wait loop exits without confirming
  ready_for_tools=true

- McpClientConfiguratorBase.cs: Add thread safety guard for Configure() call
  in CheckStatusWithProjectDir(). Changed default attemptAutoRewrite to false
  and added runtime check to prevent calling Configure() from background threads.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-20 18:11:25 -08:00
..
Transport fix: comprehensive performance optimizations, claude code config, and stability improvements (issue #577) (#595) 2026-01-20 18:11:25 -08:00
BridgeControlService.cs HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499) 2026-01-01 17:08:51 -08:00
BridgeControlService.cs.meta New UI and work without MCP server embedded (#313) 2025-10-11 03:08:16 -04:00
ClientConfigurationService.cs Fix HTTP/Stdio Transport UX and Test Bug (#530) 2026-01-07 23:33:22 -04:00
ClientConfigurationService.cs.meta New UI and work without MCP server embedded (#313) 2025-10-11 03:08:16 -04:00
EditorPrefsWindowService.cs Add EditorPrefs management window for MCP configuration debugging (#491) 2025-12-29 13:30:45 -04:00
EditorPrefsWindowService.cs.meta Add EditorPrefs management window for MCP configuration debugging (#491) 2025-12-29 13:30:45 -04:00
EditorStateCache.cs fix: comprehensive performance optimizations, claude code config, and stability improvements (issue #577) (#595) 2026-01-20 18:11:25 -08:00
EditorStateCache.cs.meta Async Test Infrastructure & Editor Readiness Status + new refresh_unity tool (#507) 2026-01-03 12:42:32 -08:00
HttpBridgeReloadHandler.cs Fix manage prefabs (#405) 2025-11-28 18:47:11 -04:00
HttpBridgeReloadHandler.cs.meta HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
IBridgeControlService.cs HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
IBridgeControlService.cs.meta New UI and work without MCP server embedded (#313) 2025-10-11 03:08:16 -04:00
IClientConfigurationService.cs Simplify MCP client configs (#401) 2025-11-27 18:18:44 -04:00
IClientConfigurationService.cs.meta New UI and work without MCP server embedded (#313) 2025-10-11 03:08:16 -04:00
IPackageDeploymentService.cs [FEATURE] Deployment of local source code to Unity (#450) 2025-12-09 20:17:18 -05:00
IPackageDeploymentService.cs.meta [FEATURE] Deployment of local source code to Unity (#450) 2025-12-09 20:17:18 -05:00
IPackageUpdateService.cs HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
IPackageUpdateService.cs.meta Notify users when there's a new version (#329) 2025-10-18 20:42:18 -04:00
IPathResolverService.cs fix: resolve Claude Code HTTP Remote UV path override not being detected in System Requirements .#550 2026-01-17 18:34:40 -05:00
IPathResolverService.cs.meta New UI and work without MCP server embedded (#313) 2025-10-11 03:08:16 -04:00
IPlatformService.cs Remove old UI and do lots of cleanup (#340) 2025-10-24 00:50:29 -04:00
IPlatformService.cs.meta Remove old UI and do lots of cleanup (#340) 2025-10-24 00:50:29 -04:00
IServerManagementService.cs Fix local HTTP server UI check (#556) 2026-01-14 19:57:17 -08:00
IServerManagementService.cs.meta HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
ITestRunnerService.cs Add test filtering to run_tests tool (#462) 2025-12-17 16:59:21 -04:00
ITestRunnerService.cs.meta Add testing and move menu items to resources (#316) 2025-10-13 11:16:43 -04:00
IToolDiscoveryService.cs Optimise so startup is fast again (#494) 2025-12-29 18:39:03 -04:00
IToolDiscoveryService.cs.meta HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
MCPServiceLocator.cs [FEATURE] Deployment of local source code to Unity (#450) 2025-12-09 20:17:18 -05:00
MCPServiceLocator.cs.meta New UI and work without MCP server embedded (#313) 2025-10-11 03:08:16 -04:00
McpEditorShutdownCleanup.cs HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499) 2026-01-01 17:08:51 -08:00
McpEditorShutdownCleanup.cs.meta HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499) 2026-01-01 17:08:51 -08:00
PackageDeploymentService.cs Fixes Windows installation failures caused by long path issues when cloning the full repository via git URL (MAX_PATH 260 char limit exceeded by files in TestProjects/). (#534) 2026-01-08 07:14:44 -08:00
PackageDeploymentService.cs.meta [FEATURE] Deployment of local source code to Unity (#450) 2025-12-09 20:17:18 -05:00
PackageUpdateService.cs Fix manage prefabs (#405) 2025-11-28 18:47:11 -04:00
PackageUpdateService.cs.meta Notify users when there's a new version (#329) 2025-10-18 20:42:18 -04:00
PathResolverService.cs fix: resolve Claude Code HTTP Remote UV path override not being detected in System Requirements .#550 2026-01-17 18:34:40 -05:00
PathResolverService.cs.meta New UI and work without MCP server embedded (#313) 2025-10-11 03:08:16 -04:00
PlatformService.cs Remove old UI and do lots of cleanup (#340) 2025-10-24 00:50:29 -04:00
PlatformService.cs.meta Remove old UI and do lots of cleanup (#340) 2025-10-24 00:50:29 -04:00
ServerManagementService.cs fix: comprehensive performance optimizations, claude code config, and stability improvements (issue #577) (#595) 2026-01-20 18:11:25 -08:00
ServerManagementService.cs.meta HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
StdioBridgeReloadHandler.cs Fix HTTP/Stdio Transport UX and Test Bug (#530) 2026-01-07 23:33:22 -04:00
StdioBridgeReloadHandler.cs.meta Fix stdio reloads (#402) 2025-11-27 19:33:26 -04:00
TestJobManager.cs Fix PlayMode tests stalling when unfocused (python refresh utility), improve domain reload recovery and refresh tool (#554) 2026-01-14 15:02:40 -08:00
TestJobManager.cs.meta Async Test Infrastructure & Editor Readiness Status + new refresh_unity tool (#507) 2026-01-03 12:42:32 -08:00
TestRunStatus.cs Async Test Infrastructure & Editor Readiness Status + new refresh_unity tool (#507) 2026-01-03 12:42:32 -08:00
TestRunStatus.cs.meta Async Test Infrastructure & Editor Readiness Status + new refresh_unity tool (#507) 2026-01-03 12:42:32 -08:00
TestRunnerNoThrottle.cs Fix PlayMode tests stalling when unfocused (python refresh utility), improve domain reload recovery and refresh tool (#554) 2026-01-14 15:02:40 -08:00
TestRunnerNoThrottle.cs.meta Async Test Infrastructure & Editor Readiness Status + new refresh_unity tool (#507) 2026-01-03 12:42:32 -08:00
TestRunnerService.cs Fix PlayMode tests stalling when unfocused (python refresh utility), improve domain reload recovery and refresh tool (#554) 2026-01-14 15:02:40 -08:00
TestRunnerService.cs.meta Add testing and move menu items to resources (#316) 2025-10-13 11:16:43 -04:00
ToolDiscoveryService.cs Optimise so startup is fast again (#494) 2025-12-29 18:39:03 -04:00
ToolDiscoveryService.cs.meta HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
Transport.meta HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00