Commit Graph

7 Commits (cb1a7dd2a14c95fce50c399f9932e86414d030b7)

Author SHA1 Message Date
dsarno cb1a7dd2a1
feat: improve editor window UI + add transport mismatch warning (#613) 2026-01-22 22:48:03 -08:00
Marcus Sanatan 810d756be9
Minor fixes (#602)
* Log a message with implicit URI changes

Small update for #542

* Log a message with implicit URI changes

Small update for #542

* Add helper scripts to update forks

* fix: improve HTTP Local URL validation UX and styling specificity

- Rename CSS class from generic "error" to "http-local-url-error" for better specificity
- Rename "invalid-url" class to "http-local-invalid-url" for clarity
- Disable httpServerCommandField when URL is invalid or transport not HTTP Local
- Clear field value and tooltip when showing validation errors
- Ensure field is re-enabled when URL becomes valid
2026-01-21 14:41:16 -04:00
Alex Hvesuk 1cc582636d
Add localhost setup feedback and remove UI issues (#587) 2026-01-21 14:14:13 -04:00
whatevertogo 322a3d1846
fix: resolve Claude Code HTTP Remote UV path override not being detected in System Requirements .#550
* fix: resolve UV path override not being detected in System Requirements

Fixes #538

The System Requirements panel showed "UV Package Manager: Not Found" even
when a valid UV path override was configured in Advanced Settings.

Root cause: PlatformDetectorBase.DetectUv() only searched PATH with bare
command names ("uvx", "uv") and never consulted PathResolverService which
respects the user's override setting.

Changes:
- Refactor DetectUv() to use PathResolverService.GetUvxPath() which checks
  override path first, then system PATH, then falls back to "uvx"
- Add TryValidateUvExecutable() to verify executables by running --version
  instead of just checking File.Exists
- Prioritize PATH environment variable in EnumerateUvxCandidates() for
  better compatibility with official uv install scripts
- Fix process output read order (ReadToEnd before WaitForExit) to prevent
  potential deadlocks

Co-Authored-By: ChatGLM 4.7 <noreply@zhipuai.com>

* fix: improve uv/uvx detection robustness on macOS and Linux

- Read both stdout and stderr when validating uv/uvx executables
- Respect WaitForExit timeout return value instead of ignoring it
- Fix version parsing to handle extra tokens like "(Homebrew 2025-01-01)"
- Resolve bare commands ("uv"/"uvx") to absolute paths after validation
- Rename FindExecutableInPath to FindUvxExecutableInPath for clarity

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

* refactor: unify process execution with ExecPath.TryRun and add Windows PATH augmentation

Replace direct Process.Start calls with ExecPath.TryRun across all platform detectors.
This change:
- Fixes potential deadlocks by using async output reading
- Adds proper timeout handling with process termination
- Removes redundant fallback logic and simplifies version parsing
- Adds Windows PATH augmentation with common uv, npm, and Python installation paths

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

* fix: improve version parsing to handle both spaces and parentheses

The version extraction logic now properly handles outputs like:
- "uvx 0.9.18" -> "0.9.18"
- "uvx 0.9.18 (hash date)" -> "0.9.18"
- "uvx 0.9.18 extra info" -> "0.9.18"

Uses Math.Min to find the first occurrence of either space or parenthesis.

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

* refactor: improve platform detectors with absolute path resolution

- Add absolute path resolution in TryValidatePython and TryValidateUvWithPath for better UI display
- Fix BuildAugmentedPath to avoid PATH duplication
- Add comprehensive comments for version parsing logic
- Ensure cross-platform consistency across all three detectors
- Fix override path validation logic with clear state handling
- Fix platform detector path resolution and Python version detection
- Use UserProfile consistently in GetClaudeCliPath instead of Personal
- All platforms now use protected BuildAugmentedPath method

This change improves user experience by displaying full paths in the UI
while maintaining robust fallback behavior if path resolution fails.

Co-Authored-By: GLM4.7 <noreply@zhipuai.com>

* fix: improve error handling in PathResolverService by logging exceptions

* Remove .meta files added after fork and update .gitignore

* Update .gitignore

* save .meta

* refactor: unify uv/uvx naming and path detection across platforms

- Rename TryValidateUvExecutable -> TryValidateUvxExecutable for consistency
- Add cross-platform FindInPath() helper in ExecPath.cs
- Remove platform-specific where/which implementations in favor of unified helper
- Add Windows-specific DetectUv() override with enhanced uv/uvx detection
- Add WinGet shim path support for Windows uvx installation
- Update UI labels: "UV Path" -> "UVX Path"
- Only show uvx path status when override is configured

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

* fix: improve validation light(uvxPathStatus) logic for UVX path overrides and system paths

* refactor: streamline UV version validation and unify path detection methods across platform detectors

* fix: add type handling for Claude Code client in config JSON builder

* fix: correct command from 'uvx' to 'uv' for Python version listing in WindowsPlatformDetector

* feat: add uvx path fallback with warning UI

  - When override path is invalid, automatically fall back to system path
  - Add HasUvxPathFallback flag to track fallback state
  - Show yellow warning indicator when using fallback
  - Display clear messages for invalid override paths
  - Updated all platform detectors (Windows, macOS, Linux) to support fallback logic

* refactor: remove GetDetails method from PlatformDetectorBase

* Update ExecPath.cs

update Windows Path lookup

---------

Co-authored-by: ChatGLM 4.7 <noreply@zhipuai.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Shutong Wu <51266340+Scriptwonder@users.noreply.github.com>
2026-01-17 18:34:40 -05:00
dsarno c2a6b0ac7a
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus

* Fix Claude Code registration to remove existing server before re-registering

When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.

Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.

* Fix Claude Code transport validation to parse CLI output format correctly

The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.

Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change

This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.

* Fix Claude Code registration UI blocking and thread safety issues

This commit resolves three issues with Claude Code registration:

1. UI blocking: Removed synchronous CheckStatus() call after registration
   that was blocking the editor. Status is now set immediately with async
   verification happening in the background.

2. Thread safety: Fixed "can only be called from the main thread" errors
   by capturing Application.dataPath and EditorPrefs.GetBool() on the main
   thread before spawning async status check tasks.

3. Transport mismatch detection: Transport mode changes now trigger immediate
   status checks to detect HTTP/stdio mismatches, instead of waiting for the
   45-second refresh interval.

The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.

* Enforce thread safety for Claude Code status checks at compile time

Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:

1. Made projectDir and useHttpTransport parameters non-nullable to prevent
   accidental background thread calls without captured values

2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
   thread safety violations if called from background threads

3. Added ArgumentNullException for null projectDir instead of falling back
   to Application.dataPath (which is main-thread only)

4. Added XML documentation clearly stating threading contracts:
   - CheckStatus() must be called from main thread
   - CheckStatusWithProjectDir() is safe for background threads

5. Removed unreachable else branch in async status check code

These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.

* Consolidate local HTTP Start/Stop and auto-start session

* HTTP improvements: Unity-owned server lifecycle + UI polish

* Deterministic HTTP stop via pidfile+token; spawn server in terminal

* Fix review feedback: token validation, host normalization, safer casts

* Fix stop heuristics edge cases; remove dead pid capture

* Fix unity substring guard in stop heuristics

* Fix local server cleanup and connection checks

* Fix read_console default limits; cleanup Unity-managed server vestiges

* Fix unfocused reconnect stalls; fast-fail retryable Unity commands

* Simplify PluginHub reload handling; honor run_tests timeout

* Fix Windows Claude CLI status check threading
2026-01-01 17:08:51 -08:00
Shutong Wu 7f8ca2a3bd
[FEATURE] Custom Tool Fix and Add inspection window for all the tools (#414)
* Update .Bat file and Bug fix on ManageScript

* Update the .Bat file to include runtime folder
* Fix the inconsistent EditorPrefs variable so the GUI change on Script Validation could cause real change.

* Further changes

String to Int for consistency

* [Custom Tool] Roslyn Runtime Compilation

Allows users to generate/compile codes during Playmode

* Fix based on CR

* Create claude_skill_unity.zip

Upload the unity_claude_skill that can be uploaded to Claude for a combo of unity-mcp-skill.

* Update for Custom_Tool Fix and Detection

1. Fix Original Roslyn Compilation Custom Tool to fit the V8 standard
2. Add a new panel in the GUI to see and toggle/untoggle the tools. The toggle feature will be implemented in the future, right now its implemented here to discuss with the team if this is a good feature to add;
3. Add few missing summary in certain tools

* Revert "Update for Custom_Tool Fix and Detection"

This reverts commit ae8cfe5e256c70ac4a16c79d50341a39cbac18ba.

* Update README.md

* Reapply "Update for Custom_Tool Fix and Detection"

This reverts commit f423c2f25e9ccff4f3b89d1d360ee9cf13143733.

* Update ManageScript.cs

Fix the layout problem of manage_script in the panel

* Update

To comply with the current server setting

* Update on Batch

Tested object generation/modification with batch and it works perfectly! We should push and let users test for a while and see

PS: I tried both VS Copilot and Claude Desktop. Claude Desktop works but VS Copilot does not due to the nested structure of batch. Will look into it more.

* Revert "Merge pull request #1 from Scriptwonder/batching"

This reverts commit 55ee76810be161d414e1f5f5abaa5ee30ddd0052, reversing
changes made to ae2eedd7fb2c6a66ff008bacac481aefb1b0d176.
2025-12-07 19:38:32 -05:00
Marcus Sanatan a034ab0b21
HTTP Server, uvx, C# only custom tools (#375)
* Remove temp folder from repo

* Ignore boot.config

* Remove buttons to download or rebuild the server

* Remove embedded MCP server in plugin

We'll reference the remote server in GitHub and configure clients to use `uvx`

* As much as possible, rip out logic that installs a server

* feat: migrate to uvx-based server configuration

- Replaced local server execution with uvx package-based configuration for improved reliability
- Added GetUvxCommand helper to generate correct package version command string
- Updated config generation to use `uvx mcp-for-unity` instead of local Python server
- Modified Codex and client configuration validation to support uvx-based setup
- Removed unused server source directory handling and related preferences
- Updated tests to verify uvx command generation

* Cleanup the temp folders created by tests

We don't commit temp folders, tests are expected to clean up after themselves

* The test kept failing but the results looked correct, floating point comparisons are not precise

* feat: migrate from local server to uvx-based configuration

- Replaced local server path detection with uvx-based package installation from git repository
- Updated all configuration generators to use structured uvx command parts (command, --from URL, package)
- Renamed UV path references to UVX for clarity and consistency
- Added GetUvxCommandParts() helper to centralize uvx command generation
- Added GetMcpServerGitUrl() to handle git repository URL construction
- Updated client configuration validation

* refactor: use dynamic package version instead of hardcoded value

* Update CI so it only updates the Server folder

* feat: implement uvx package source path resolution

- Added GetUvxPackageSourcePath method to locate unity-mcp package in uv cache by traversing git checkouts
- Replaced hardcoded "Dummy" path in PythonToolSyncProcessor with dynamic path resolution
- Added validation for Server directory structure and pyproject.toml to ensure correct package location

* refactor: replace Python tool syncing with custom tool registration system

- Removed PythonToolsAsset and file-based sync processor in favor of attribute-based tool discovery
- Implemented CustomToolRegistrationProcessor with automatic registration on startup and script reload
- Added registration enable/disable preference and force re-registration capability

* feat: add HTTP transport support and cache management

- Implemented HTTP transport option with configurable URL/port alongside existing stdio mode
- Added cache management service with menu item to clear uvx package cache
- Updated config builder to generate transport-specific arguments and VSCode type field based on selected mode

* refactor: simplify HTTP configuration to use URL-based approach

- Replaced separate host/port arguments with single --http-url parameter for cleaner configuration
- Updated server to parse URL and allow individual host/port overrides when needed
- Consolidated HTTP client implementation with connection testing and tool execution support

* refactor: standardize transport configuration with explicit --transport flag

- Replaced --enable-http-server flag with --transport choice parameter (stdio/http) for clearer intent
- Removed redundant HTTP port field from UI since HTTP mode uses the same URL/port as MCP client
- Simplified server startup logic by consolidating transport mode determination

* refactor: move MCP menu items under Window menu

* feat: restructure config generation for HTTP transport mode

- Changed HTTP mode to use URL-based configuration instead of command-line arguments
- Added proper cleanup of incompatible fields when switching between stdio and HTTP transports
- Moved uvx command parsing inside stdio-specific block to avoid unnecessary processing in HTTP mode

* feat: add local HTTP server management with Git URL override

- Implemented server management service with menu item to start local HTTP server in new terminal window
- Added Git URL override setting in advanced configuration to allow custom server source for uvx --from
- Integrated server management into service locator with validation for local-only server startup

* fix: remove automatic HTTP protocol prefix from URL field

- Removed auto-prefixing logic that added "http://" to URLs without protocol
- Added placeholder text to guide users on expected URL format
- Created dedicated url-field style class for better URL input styling

* feat: implement proper MCP session lifecycle with HTTP transport

- Added initialize, ping, and disconnect methods to HttpMcpClient for proper MCP protocol session management
- Implemented session ID tracking and header management for stateful HTTP connections
- Added cross-platform terminal launcher support for Windows and Linux (previously macOS-only)

* feat: implement JSON-RPC protocol for MCP tool execution

- Added proper JSON-RPC 2.0 request/response handling with request ID tracking
- Included MCP protocol headers (version, session ID) for standard compliance
- Added error handling for JSON-RPC error responses

* feat: improve text wrapping in editor window UI

- Added white-space: normal and flex-shrink properties to section headers and override labels to prevent text overflow
- Created new help-text style class for consistent formatting of help text elements

* refactor: refresh git URL override from EditorPrefs on validation

* fix: improve responsive layout for editor window settings

- Added flex-wrap to setting rows to prevent overflow on narrow windows
- Set flex-shrink: 0 on labels to maintain consistent width
- Replaced max-width and margin-left with flex-basis for better flex behavior

* refactor: improve thread safety in tool registration

- Capture Unity API calls on main thread before async operations to prevent threading issues
- Update RegisterAllTools to use Task.Run pattern instead of GetAwaiter().GetResult() to avoid potential deadlocks
- Add optional projectId parameter to RegisterAllToolsAsync for pre-captured values

* refactor: replace MCP tool calls with direct HTTP endpoints for tool registration

- Removed synchronous registration method and unused MCP bridge logic from CustomToolRegistrationService
- Changed tool registration to use direct HTTP POST to /register-tools endpoint instead of MCP protocol
- Added FastAPI HTTP routes alongside existing MCP tools for more flexible tool management access

* refactor: centralize HTTP endpoint URL management

- Created HttpEndpointUtility to normalize and manage base URLs consistently
- Replaced scattered EditorPrefs calls with utility methods that handle URL normalization
- Ensured base URL storage excludes trailing paths like "/mcp" for cleaner configuration

* refactor: simplify custom tools management with in-memory registry

- Removed CustomToolsManager and fastmcp_tool_registry modules in favor of inline implementation
- Replaced class-based tool management with direct HTTP route handlers using FastMCP's custom_route decorator
- Consolidated tool registration logic into simple dictionary-based storage with helper functions

* feat: add dynamic custom tool registration system

- Implemented CustomToolService to manage project-scoped tool registration with validation and conflict detection
- Added HTTP endpoints for registering, listing, and unregistering custom tools with proper error handling
- Converted health and registry endpoints from HTTP routes to MCP tools for better integration

* feat: add AutoRegister flag to control tool registration

- Added AutoRegister property to McpForUnityToolAttribute (defaults to true)
- Modified registration service to filter and only register tools with AutoRegister enabled
- Disabled auto-registration for all built-in tools that already exist server-side

* feat: add function signature generation for dynamic tools

- Implemented _build_signature method to create proper inspect.Signature objects for dynamically created tools
- Signature includes Context parameter and all tool parameters with correct required/optional defaults
- Attached generated signature to dynamic_tool functions to improve introspection and type checking

* refactor: remove unused custom tool registry endpoints

* test: add transport configuration validation for MCP client tests

- Added HTTP transport preference setup in test fixtures to ensure consistent behavior
- Implemented AssertTransportConfiguration helper to validate both HTTP and stdio transport modes
- Added tests to verify stdio transport fallback when HTTP preference is disabled

* refactor: simplify uvx path resolution to use PATH by default

- Removed complex platform-specific path detection logic and verification
- Changed to rely on system PATH environment variable instead of searching common installation locations
- Streamlined override handling to only use EditorPrefs when explicitly set by user

* feat: use serverUrl property for Windsurf HTTP transport

- Changed Windsurf configs to use "serverUrl" instead of "url" for HTTP transport to match Windsurf's expected format
- Added cleanup logic to remove stale transport properties when switching between HTTP and stdio modes
- Updated Windsurf to exclude "env" block (only required for Kiro), while preserving it for clients that need it

* feat: ensure client configurations stay current on each setup

- Removed skip logic for already-configured clients to force re-validation of core fields
- Added forced re-registration for ClaudeCode clients to keep transport settings up-to-date

* feat: add automatic migration for legacy embedded server configuration

- Created LegacyServerSrcMigration to detect and migrate old EditorPrefs keys on startup
- Automatically reconfigures all detected clients to use new uvx/stdio path
- Removes legacy keys only after successful migration to prevent data loss

* feat: add automatic stdio config migration on package updates

- Implemented StdIoVersionMigration to detect package version changes and refresh stdio MCP client configurations
- Added support for detecting stdio usage across different client types (Codex, VSCode, and generic JSON configs)
- Integrated version tracking via EditorPrefs to prevent redundant migrations

* Centralize where editor prefs are defined

It's really hard to get a view of all the editor prfes in use.
This should help humans and AI know what's going on at a glance

* Update custom tools docs

* refactor: consolidate server management UI into main editor window

- Removed server and maintenance menu items from top-level menu
- Moved "Start Local HTTP Server" and "Clear UVX Cache" buttons into editor window settings
- Added dynamic button state management based on transport protocol and server availability

* Don't show error logs when custom tools are already registerd with the server

* Only autoconnect to port 6400 if the user is using stdio for connections

* Don't double register tools on startup

* feat: switch to HTTP transport as default connection method

- Changed default transport from stdio to HTTP with server running on localhost:8080
- Added UI controls to start/stop local HTTP server directly from Unity window
- Updated all documentation and configuration examples to reflect HTTP-first approach with stdio as fallback option

* Automatically bump the versions in the READMEs.

The `main` branch gets updated before we do a release. Using versions helps users get a stable, tested installation

* docs: add HTTP transport configuration examples

- Added HTTP transport setup instructions alongside existing stdio examples
- Included port mapping and URL configuration for Docker deployments
- Reorganized client configuration sections to clearly distinguish between HTTP and stdio transports

* feat: add WebSocket-based plugin hub for Unity connections

- Implemented persistent WebSocket connections with session management, heartbeat monitoring, and command routing
- Created PluginRegistry for tracking active Unity instances with hash-based lookup and automatic reconnect handling
- Added HTTP endpoints for session listing and health checks, plus middleware integration for instance-based routing

* refactor: consolidate Unity instance discovery with shared registry

- Introduced StdioPortRegistry for centralized caching of Unity instance discovery results
- Refactored UnityConnection to use stdio_port_registry instead of direct PortDiscovery calls
- Improved error handling with specific exception types and enhanced logging clarity

* Use websockets so that local and remote MCP servers can communicate with Unity

The MCP server supports HTTP and stdio protocols, and the MCP clients use them to communicate.
However, communication from the MCP server to Unity is done on the local port 6400, that's somewhat hardcoded.
So we add websockets so oure remotely hosted MCP server has a valid connection to the Unity plugin, and can communicate with

- Created ProjectIdentityUtility for centralized project hash, name, and session ID management
- Moved command processing logic from MCPForUnityBridge to new TransportCommandDispatcher service
- Added WebSocket session ID and URL override constants to EditorPrefKeys
- Simplified command queue processing with async/await pattern and timeout handling
- Removed duplicate command execution code in favor of shared dispatcher implementation

* refactor: simplify port management and improve port field validation

- Removed automatic port discovery and fallback logic from GetPortWithFallback()
- Changed GetPortWithFallback() to return stored port or default without availability checks
- Added SetPreferredPort() method for explicit port persistence with validation
- Replaced Debug.Log calls with McpLog.Info/Warn for consistent logging
- Added port field validation on blur and Enter key press with error handling
- Removed automatic port waiting

* Launch the actual local webserver via the button

* Autoformat

* Minor fixes so the server can start

* Make clear uvx button work

* Don't show a dialog after clearing cache/starting server successfully

It's annoying, we can just log when successful, and popup if something failed

* We no longer need a Python importer

* This folder has nothing in it

* Cleanup whitespace

Most AI generated code contains extra space, unless they're hooked up to a linter. So I'm just cleaning up what's there

* We no longer need this folder

* refactor: move MCPForUnityBridge to StdioBridgeHost and reorganize transport layer

- Renamed MCPForUnityBridge class to StdioBridgeHost and moved to Services.Transport.Transports namespace
- Updated all references to StdioBridgeHost throughout codebase (BridgeControlService, TelemetryHelper, GitHub workflow)
- Changed telemetry bridge_version to use AssetPathUtility.GetPackageVersion() instead of hardcoded version
- Removed extensive inline comments and documentation throughout StdioBridgeHost

* Skip tools registration if the user is not connected to an HTTP server

* Fix VS Code configured status in UI

Serializing the config as dynamic and then reading null properties (in this case, args) caused the error. So we just walk through the properities and use JObject, handling null value explicitily

* Stop blocking the main thread when connecting via HTTP

Now that the bridge service is asynchronous, messages back and forth the server work well (including the websocket connection)

* Separate socket keep-alive interval from application keep-alive interval

Split the keep-alive configuration into two distinct intervals: _keepAliveInterval for application-level keep-alive and _socketKeepAliveInterval for WebSocket-level keep-alive. This allows independent control of socket timeout behavior based on server configuration while maintaining the application's keep-alive settings.

* Add a debug log line

* Fix McpLog.Debug method, so it actually reads the checkbox value from the user

* Add HTTP bridge auto-resume after domain reload

Implement HttpBridgeReloadHandler to automatically resume HTTP/HttpPush transports after Unity domain reloads, matching the behavior of the legacy stdio bridge. Add ResumeHttpAfterReload EditorPref key to persist state across reloads and expose ActiveMode property in IBridgeControlService to check current transport mode.

* Add health verification after HTTP bridge auto-resume

Trigger health check in all open MCPForUnityEditorWindow instances after successful HTTP bridge resume following domain reload. Track open windows using static HashSet and schedule async health verification via EditorApplication.delayCall to ensure UI updates reflect the restored connection state.

* Add name and path fields to code coverage settings

Initialize m_Name and m_Path fields in code coverage Settings.json to match Unity's expected settings file structure.

* Only register custom tools AFTER we established a healthy HTTP connection

* Convert custom tool handlers to async functions

Update dynamic_tool wrapper to use async/await pattern and replace synchronous send_with_unity_instance/send_command_with_retry calls with their async counterparts (async_send_with_unity_instance/async_send_command_with_retry).

* Correctly parse responses from Unity in the server so tools and resources can process them

We also move the logic to better places than the __init__.py file for tools, since they're shared across many files, including resources

* Make some clarifications for custom tools in docs

* Use `async_send_with_unity_instance` instead of `send_with_unity_instance`

The HTTP protocol doesn't working with blocking commands, so now we have our tools set up to work with HTTP and stdio fullly. It's coming together :-)

* Fix calls to async_send_with_unity_instance in manage_script

* Rename async_send_with_unity_instance to send_with_unity_instance

* Fix clear uv cache command

Helps a lot with local development

* Refactor HTTP server command generation into reusable method and display in UI

Extract HTTP server command building logic from StartLocalHttpServer into new TryGetLocalHttpServerCommand method. Add collapsible foldout in editor window to display the generated command with copy button, allowing users to manually start the server if preferred. Update UI state management to refresh command display when transport or URL settings change.

* Ctrl/Cmd + Shift + M now toggles the window

Might as well be able to close the window as well

* Fallback to a git URL that points to the main branch for the MCP git URL used by uvx

* Add test setup/teardown to preserve and reset Git URL override EditorPref

Implement OneTimeSetUp/OneTimeTearDown to save and restore the GitUrlOverride EditorPref state, and add SetUp to delete the key before each test. This ensures tests run with deterministic Git URLs while preserving developer overrides between test runs.

* Update docs, scripts and GH workflows to use the new MCP server code location

* Update plugin README

* Convert integration tests to async/await pattern

Update all integration tests to use pytest.mark.asyncio decorator and async/await syntax. Change test functions to async, update fake_send/fake_read mocks to async functions with **kwargs parameter, and patch async_send_command_with_retry instead of send_command_with_retry. Add await to all tool function calls that now return coroutines.

* Update image with new UI

* Remove unused HttpTransportClient client

Before I had the realization that I needed webscokets, this was my first attempt

* Remove copyright notice

* Add a guide to all the changes made for this version

A lot of code was written by AI, so I think it's important that humans can step through how all these new systems work, and know where to find things.

All of these docs were written by hand, as a way to vet that I understand what the code I wrote and generated are doing, but also to make ti easy to read for you.

* Organize imports and remove redundant import statements

Clean up import organization by moving imports to the top of the file, removing duplicate imports scattered throughout the code, and sorting imports alphabetically within their groups (standard library, third-party, local). Remove unnecessary import aliases and consolidate duplicate urlparse and time imports.

* Minor edits

* Fix stdio serializer to use the new type parameter like HTTP

* Fix: Automatic bridge reconnection after domain reload without requiring Unity focus

- Add immediate restart attempt in OnAfterAssemblyReload() when Unity is not compiling
- Enhanced compile detection to check both EditorApplication.isCompiling and CompilationPipeline.isCompiling
- Add brief port release wait in StdioBridgeHost before switching ports to reduce port thrash
- Fallback to delayCall/update loop only when Unity is actively compiling

This fixes the issue where domain reloads (e.g., script edits) would cause connection loss until Unity window was refocused, as EditorApplication.update only fires when Unity has focus.

* Make the server work in Docker

We use HTTP mode by default in docker, this is what will be hosted remotely if one chooses to.
We needed to update the uvicorn package to a version with websockets, at least so the right version is explicitly retrieved

* Cache project identity on initialization to avoid repeated computation

Add static constructor with [InitializeOnLoad] attribute to cache project hash and name at startup. Introduce volatile _identityCached flag and cached values (_cachedProjectName, _cachedProjectHash) to store computed identity. Schedule cache refresh on initialization and when project changes via EditorApplication.projectChanged event. Extract ComputeProjectHash and ComputeProjectName as private methods that perform the actual computation. Update public

* Fix typos

* Add unity_instance_middleware to py-modules list in pyproject.toml

* Remove Foldout UI elements and simplify HTTP server command section

Replace Foldout with VisualElement for http-server-command-section to display HTTP server command directly without collapsible wrapper. Remove unused manualConfigFoldout field and associated CSS styles. Remove unused _identityCached volatile flag from ProjectIdentityUtility as caching logic no longer requires it.

* Reduce height of HTTP command box

* Refresh HTTP server command display when Git URL override changes

* Make the box a bit smaller

* Split up main window into various components

Trying to avoid to monolithic files, this is easier to work, for humans and LLMs

* Update the setup wizard to be a simple setup popup built with UI toolkit

We also fix the Python/uv detectors. Instead of searching for binaries, we just test that they're available in the PATH

* Ensure that MCP configs are updated when users switch between HTTP and stdio

These only work for JSON configs, we'll have to handle Codex and Claude Code separately

* Detect Codex configuration when using HTTP or stdio configs

* Use Claude Code's list command to detect whether this MCP is configured

It's better than checking the JSON and it can verify both HTTP and stdio setups

* Fix and add tests for building configs

* Handle Unity reload gaps by retrying plugin session resolution

* Add polling support for long-running tools with state persistence

Introduce polling middleware to handle long-running operations that may span domain reloads. Add McpJobStateStore utility to persist tool state in Library folder across reloads. Extend McpForUnityToolAttribute with RequiresPolling and PollAction properties. Update Response helper with Pending method for standardized polling responses. Implement Python-side polling logic in custom_tool_service.py with configurable intervals and 10-minute timeout.

* Polish domain reload resilience tests and docs

* Refactor Response helper to use strongly-typed classes instead of anonymous objects

Replace static Response.Success/Error/Pending methods with SuccessResponse, ErrorResponse, and PendingResponse classes. Add IMcpResponse interface for type safety. Include JsonProperty attributes for serialization and JsonIgnore properties for backward compatibility with reflection-based tests. Update all tool and resource classes to use new response types.

* Rename Setup Wizard to Setup Window and improve UV detection on macOS/Linux

Rename SetupWizard class to SetupWindowService and update all references throughout the codebase. Implement platform-specific UV detection for macOS and Linux with augmented PATH support, including TryValidateUv methods and BuildAugmentedPath helpers. Split single "Open Installation Links" button into separate Python and UV install buttons. Update UI styling to improve installation section layout with proper containers and button

* Update guide on what's changed in v8

Lots of feedback, lots of changes

* Update custom tool docs to use new response objects

* Update image used in README

Slightly more up to date but not final

* Restructure backend

Just make it more organized, like typical Python projects

* Remove server_version.txt

* Feature/http instance routing (#5)

* Fix HTTP instance routing and per-project session IDs

* Drop confusing log message

* Ensure lock file references later version of uvicorn with key fixes

* Fix test imports

* Update refs in docs

---------

Co-authored-by: David Sarno <david@lighthaus.us>

* Generate the session ID from the server

We also make the identifying hashes longer

* Force LLMs to choose a Unity instance when multiple are connected

OK, this is outright the best OSS Unity MCP available

* Fix tests caused by changes in session management

* Whitespace update

* Exclude stale builds so users always get the latest version

* Set Pythonpath env var so Python looks at the src folder for modules

Not required for the fix, but it's a good guarantee regardless of the working directory

* Replace Optional type hints with modern union syntax (Type | None)

Update all Optional[Type] annotations to use the PEP 604 union syntax Type | None throughout the transport layer and mcp_source.py script

* Replace Dict type hints with modern dict syntax throughout codebase

Update all Dict[K, V] annotations to use the built-in dict[K, V] syntax across services, transport layer, and models for consistency with PEP 585

* Remove unused type imports across codebase

Clean up unused imports of Dict, List, and Path types that are no longer needed after migration to modern type hint syntax

* Remove the old telemetry test

It's working, we have a better integration test in any case

* Clean up stupid imports

No AI slop here lol

* Replace dict-based session data with Pydantic models for type safety

Introduce Pydantic models for all WebSocket messages and session data structures. Replace dict.get() calls with direct attribute access throughout the codebase. Add validation and error handling for incoming messages in PluginHub.

* Correctly call `ctx.info` with `await`

No AI slop here!

* Replace printf-style logging with f-string formatting across transport and telemetry modules

Convert all logger calls using %-style string formatting to use f-strings for consistency with modern Python practices. Update telemetry configuration logging, port discovery debug messages, and Unity connection logging throughout the codebase.

* Register custom tools via websockets

Since we'll end up using websockets for HTTP and stdio, this will ensure custom tools are available to both.
We want to compartmentalize the custom tools to the session. Custom tools in 1 unity project don't apply to another one.
To work with our multi-instance logic, we hide the custom tools behind a custom tool function tool. This is the execute_custom_tool function.
The downside is that the LLM has to query before using it.
The upside is that the execute_custom_tool function goes through the standard routing in plugin_hub, so custom tools are always isolated by project.

* Add logging decorator to track tool and resource execution with arguments and return values

Create a new logging_decorator module that wraps both sync and async functions to log their inputs, outputs, and exceptions. Apply this decorator to all tools and resources before the telemetry decorator to provide detailed execution traces for debugging.

* Fix JSONResponse serialization by converting Pydantic model to dict in plugin sessions endpoint

* Whitespace

* Move import of get_unity_instance_from_context to module level in unity_transport

Relocate the import from inside the with_unity_instance decorator function to the top of the file with other imports for better code organization and to avoid repeated imports on each decorator call.

* Remove the tool that reads resources

They don't perform well at all, and confuses the models most times.
However, if they're required, we'll revert

* We have buttons for starting and stopping local servers

Instead of a button to clear uv cache, we have start and stop buttons.
The start button pulls the latest version of the server as well.
The stop button finds the local process of the server and kills.
Need to test on Windows but it works well

* Consolidate cache management into ServerManagementService and remove standalone CacheManagementService

Move the ClearUvxCache method from CacheManagementService into ServerManagementService since cache clearing is primarily used during server operations. Remove the separate ICacheManagementService interface and CacheManagementService class along with their service locator registration. Update StartLocalServer to call the local ClearUvxCache method instead of going through the service locator.

* Update MCPForUnity/Editor/Helpers/ProjectIdentityUtility.cs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update .github/workflows/claude-nl-suite.yml

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Cancel existing background loops before starting a new connection

Nice bug found from CodeRabbit

* Try to kill all processes using the port of the local webserver

* Some better error handling when stopping a server

* Cache fallback session ID to maintain consistency when EditorPrefs are unavailable

Store the fallback session ID in a static field instead of generating a new GUID on each call when EditorPrefs are unavailable during batch tests. Clear the cached fallback ID when resetting the session to ensure a fresh ID is generated on the next session.

* Clean up empty parent temp folder after domain reload tests complete

Check if Assets/Temp folder is empty after deleting test-specific temp directories and remove it if no other files or directories remain. Also remove trailing blank lines from the file.

* Minor fixes

* Change "UV" to "uv" in strings. Capitlization looks weird

* Rename functions that capitalized "UV"

* Ensure WebSocket transport is properly stopped before disposing shared resources

Add disposal guard and call StopAsync() in Dispose() to prevent race conditions when disposing the WebSocket transport while background loops are still running. Log warnings if cleanup fails but continue with resource disposal.

* Replace volatile bool with Interlocked operations for reconnection flag to prevent race conditions

* Replace byte array allocation with ArrayPool to reduce GC pressure in WebSocket message receiving

Rent buffer from ArrayPool<byte>.Shared instead of allocating new byte arrays for each receive operation. Pre-size MemoryStream to 8192 bytes and ensure rented buffer is returned in finally block to prevent memory leaks.

* Consolidate some of the update/refresh logic

* UI tweak disable start/stop buttons while they code is being fired

* Add error dialog when Unity socket port persistence fails

* Rename WebSocketSessionId to SessionId in EditorPrefKeys

By the next version stdio will use Websockets as well, so why be redundant

* No need to send session ID in pong payload

* Add a debug message when we don't have an override for the uvx path

* Remove unused function

* Remove the unused verifyPath argument

* Simplify server management logic

* Remove unused `GetUvxCommand()` function

We construct it in parts now

* Remove `IsUvxDetected()`

The flow changed so it checks editor prefs and then defaults to the command line default. So it's always true.

* Add input validation and improve shell escaping in CreateTerminalProcessStartInfo

- Validate command is not empty before processing
- Strip carriage returns and newlines from command
- macOS: Use osascript directly instead of bash to avoid shell injection, escape backslashes and quotes for AppleScript
- Windows: Add window title and escape quotes in command
- Linux: Properly escape single quotes for bash -c and double quotes for process arguments

* Update technical changes guide

* Add custom_tools resource and execute_custom_tool to README documentation

* Update v8 docs

* Update docs UI image

* Handle when properties are sent as a JSON string in manage_asset

* Fix backend tests

---------

Co-authored-by: David Sarno <david@lighthaus.us>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-11-24 23:21:06 -04:00