unity-mcp/MCPForUnity/Editor/Tools/ManageGameObject.cs

2401 lines
108 KiB
C#
Raw Normal View History

#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MCPForUnity.Editor.Helpers; // For Response class
using MCPForUnity.Runtime.Serialization;
using Newtonsoft.Json; // Added for JsonSerializationException
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEditor.Compilation; // For CompilationPipeline
using UnityEditor.SceneManagement;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace MCPForUnity.Editor.Tools
{
/// <summary>
/// Handles GameObject manipulation within the current scene (CRUD, find, components).
/// </summary>
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-25 11:21:06 +08:00
[McpForUnityTool("manage_gameobject", AutoRegister = false)]
public static class ManageGameObject
{
// Shared JsonSerializer to avoid per-call allocation overhead
feat: Add `manage_material` tool for dedicated material manipulation (#440) * WIP: Material management tool implementation and tests - Add ManageMaterial tool for creating and modifying materials - Add MaterialOps helper for material property operations - Add comprehensive test suite for material management - Add string parameter parsing support for material properties - Update related tools (ManageGameObject, manage_asset, etc.) - Add test materials and scenes for material testing * refactor: unify material property logic into MaterialOps - Move and logic from to - Update to delegate to - Update to use enhanced for creation and property setting - Add texture path loading support to * Add parameter aliasing support: accept 'name' as alias for 'target' in manage_gameobject modify action * Refactor ManageMaterial and fix code review issues - Fix Python server tools (redundant imports, exception handling, string formatting) - Clean up documentation and error reports - Improve ManageMaterial.cs (overwrite checks, error handling) - Enhance MaterialOps.cs (robustness, logging, dead code removal) - Update tests (assertions, unused imports) - Fix manifest.json relative path - Remove temporary test artifacts and manual setup scripts * Remove test scene * remove extra mat * Remove unnecessary SceneTemplateSettings.json * Remove unnecessary SceneTemplateSettings.json * Fix MaterialOps issues * Fix: Case-insensitive material property lookup and missing HasProperty checks * Rabbit fixes * Improve material ops logging and test coverage * Fix: NormalizePath now handles backslashes correctly using AssetPathUtility * Fix: Address multiple nitpicks (test robustness, shader resolution, HasProperty checks) * Add manage_material tool documentation and fix MaterialOps texture property checks - Add comprehensive ManageMaterial tool documentation to MCPForUnity/README.md - Add manage_material to tools list in README.md and README-zh.md - Fix MaterialOps.cs to check HasProperty before SetTexture calls to prevent Unity warnings - Ensures consistency with other property setters in MaterialOps * Fix ManageMaterial shader reflection for Unity 6 and improve texture logging
2025-12-08 11:39:52 +08:00
internal static readonly JsonSerializer InputSerializer = JsonSerializer.Create(new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new Vector3Converter(),
new Vector2Converter(),
new QuaternionConverter(),
new ColorConverter(),
new RectConverter(),
new BoundsConverter(),
new UnityEngineObjectConverter()
}
});
// --- Main Handler ---
public static object HandleCommand(JObject @params)
{
if (@params == null)
{
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-25 11:21:06 +08:00
return new ErrorResponse("Parameters cannot be null.");
}
string action = @params["action"]?.ToString().ToLower();
if (string.IsNullOrEmpty(action))
{
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-25 11:21:06 +08:00
return new ErrorResponse("Action parameter is required.");
}
// Parameters used by various actions
JToken targetToken = @params["target"]; // Can be string (name/path) or int (instanceID)
string name = @params["name"]?.ToString();
feat: Add `manage_material` tool for dedicated material manipulation (#440) * WIP: Material management tool implementation and tests - Add ManageMaterial tool for creating and modifying materials - Add MaterialOps helper for material property operations - Add comprehensive test suite for material management - Add string parameter parsing support for material properties - Update related tools (ManageGameObject, manage_asset, etc.) - Add test materials and scenes for material testing * refactor: unify material property logic into MaterialOps - Move and logic from to - Update to delegate to - Update to use enhanced for creation and property setting - Add texture path loading support to * Add parameter aliasing support: accept 'name' as alias for 'target' in manage_gameobject modify action * Refactor ManageMaterial and fix code review issues - Fix Python server tools (redundant imports, exception handling, string formatting) - Clean up documentation and error reports - Improve ManageMaterial.cs (overwrite checks, error handling) - Enhance MaterialOps.cs (robustness, logging, dead code removal) - Update tests (assertions, unused imports) - Fix manifest.json relative path - Remove temporary test artifacts and manual setup scripts * Remove test scene * remove extra mat * Remove unnecessary SceneTemplateSettings.json * Remove unnecessary SceneTemplateSettings.json * Fix MaterialOps issues * Fix: Case-insensitive material property lookup and missing HasProperty checks * Rabbit fixes * Improve material ops logging and test coverage * Fix: NormalizePath now handles backslashes correctly using AssetPathUtility * Fix: Address multiple nitpicks (test robustness, shader resolution, HasProperty checks) * Add manage_material tool documentation and fix MaterialOps texture property checks - Add comprehensive ManageMaterial tool documentation to MCPForUnity/README.md - Add manage_material to tools list in README.md and README-zh.md - Fix MaterialOps.cs to check HasProperty before SetTexture calls to prevent Unity warnings - Ensures consistency with other property setters in MaterialOps * Fix ManageMaterial shader reflection for Unity 6 and improve texture logging
2025-12-08 11:39:52 +08:00
// --- Usability Improvement: Alias 'name' to 'target' for modification actions ---
// If 'target' is missing but 'name' is provided, and we aren't creating a new object,
// assume the user meant "find object by name".
if (targetToken == null && !string.IsNullOrEmpty(name) && action != "create")
{
targetToken = name;
// We don't update @params["target"] because we use targetToken locally mostly,
// but some downstream methods might parse @params directly. Let's update @params too for safety.
@params["target"] = name;
}
// -------------------------------------------------------------------------------
string searchMethod = @params["searchMethod"]?.ToString().ToLower();
string tag = @params["tag"]?.ToString();
string layer = @params["layer"]?.ToString();
JToken parentToken = @params["parent"];
Harden MCP tool parameter handling + add material workflow tests (TDD) (#343) * Add TDD tests for MCP material management issues - MCPMaterialTests.cs: Tests for material creation, assignment, and data reading - MCPParameterHandlingTests.cs: Tests for JSON parameter parsing issues - SphereMaterialWorkflowTests.cs: Tests for complete sphere material workflow These tests document the current issues with: - JSON parameter parsing in manage_asset and manage_gameobject tools - Material creation with properties - Material assignment to GameObjects - Material component data reading All tests currently fail (Red phase of TDD) and serve as specifications for what needs to be fixed in the MCP system. * Refine TDD tests to focus on actual MCP tool parameter parsing issues - Removed redundant tests that verify working functionality (GameObjectSerializer, Unity APIs) - Kept focused tests that document the real issue: MCP tool parameter validation - Tests now clearly identify the root cause: JSON string parsing in MCP tools - Tests specify exactly what needs to be fixed: parameter type flexibility The issue is NOT in Unity APIs or serialization (which work fine), but in MCP tool parameter validation being too strict. * Fix port discovery protocol mismatch - Update _try_probe_unity_mcp to recognize Unity bridge welcome message - Unity bridge sends 'WELCOME UNITY-MCP' instead of JSON pong response - Maintains backward compatibility with JSON pong format - Fixes MCP server connection to Unity Editor * Resolve merge: unify manage_gameobject param coercion and schema widening * Tests: add MaterialParameterToolTests; merge port probe fix; widen tool schemas for JSON-string params * refactor: extract JSON coercion helper; docs + exception narrowing\nfix: fail fast on bad component_properties JSON\ntest: unify setup, avoid test-to-test calls\nchore: use relative MCP package path * chore(tests): track MCPToolParameterTests.cs.meta to keep GUID stable * test: decouple MaterialParameterToolTests with helpers (no inter-test calls)
2025-10-24 08:57:27 +08:00
// Coerce string JSON to JObject for 'componentProperties' if provided as a JSON string
Material tools: support direct shader property keys + add EditMode coverage (#344) * Add TDD tests for MCP material management issues - MCPMaterialTests.cs: Tests for material creation, assignment, and data reading - MCPParameterHandlingTests.cs: Tests for JSON parameter parsing issues - SphereMaterialWorkflowTests.cs: Tests for complete sphere material workflow These tests document the current issues with: - JSON parameter parsing in manage_asset and manage_gameobject tools - Material creation with properties - Material assignment to GameObjects - Material component data reading All tests currently fail (Red phase of TDD) and serve as specifications for what needs to be fixed in the MCP system. * Refine TDD tests to focus on actual MCP tool parameter parsing issues - Removed redundant tests that verify working functionality (GameObjectSerializer, Unity APIs) - Kept focused tests that document the real issue: MCP tool parameter validation - Tests now clearly identify the root cause: JSON string parsing in MCP tools - Tests specify exactly what needs to be fixed: parameter type flexibility The issue is NOT in Unity APIs or serialization (which work fine), but in MCP tool parameter validation being too strict. * Fix port discovery protocol mismatch - Update _try_probe_unity_mcp to recognize Unity bridge welcome message - Unity bridge sends 'WELCOME UNITY-MCP' instead of JSON pong response - Maintains backward compatibility with JSON pong format - Fixes MCP server connection to Unity Editor * Resolve merge: unify manage_gameobject param coercion and schema widening * Tests: add MaterialParameterToolTests; merge port probe fix; widen tool schemas for JSON-string params * feat(material): support direct shader property keys and texture paths; add EditMode tests * chore(tests): track required .meta files; remove ephemeral Assets/Editor test helper * fix(manage_gameobject): validate parsed component_properties is a dict; return clear error
2025-10-24 09:25:29 +08:00
var componentPropsToken = @params["componentProperties"];
if (componentPropsToken != null && componentPropsToken.Type == JTokenType.String)
{
try
{
var parsed = JObject.Parse(componentPropsToken.ToString());
@params["componentProperties"] = parsed;
}
catch (Exception e)
{
Debug.LogWarning($"[ManageGameObject] Could not parse 'componentProperties' JSON string: {e.Message}");
}
}
Harden MCP tool parameter handling + add material workflow tests (TDD) (#343) * Add TDD tests for MCP material management issues - MCPMaterialTests.cs: Tests for material creation, assignment, and data reading - MCPParameterHandlingTests.cs: Tests for JSON parameter parsing issues - SphereMaterialWorkflowTests.cs: Tests for complete sphere material workflow These tests document the current issues with: - JSON parameter parsing in manage_asset and manage_gameobject tools - Material creation with properties - Material assignment to GameObjects - Material component data reading All tests currently fail (Red phase of TDD) and serve as specifications for what needs to be fixed in the MCP system. * Refine TDD tests to focus on actual MCP tool parameter parsing issues - Removed redundant tests that verify working functionality (GameObjectSerializer, Unity APIs) - Kept focused tests that document the real issue: MCP tool parameter validation - Tests now clearly identify the root cause: JSON string parsing in MCP tools - Tests specify exactly what needs to be fixed: parameter type flexibility The issue is NOT in Unity APIs or serialization (which work fine), but in MCP tool parameter validation being too strict. * Fix port discovery protocol mismatch - Update _try_probe_unity_mcp to recognize Unity bridge welcome message - Unity bridge sends 'WELCOME UNITY-MCP' instead of JSON pong response - Maintains backward compatibility with JSON pong format - Fixes MCP server connection to Unity Editor * Resolve merge: unify manage_gameobject param coercion and schema widening * Tests: add MaterialParameterToolTests; merge port probe fix; widen tool schemas for JSON-string params * refactor: extract JSON coercion helper; docs + exception narrowing\nfix: fail fast on bad component_properties JSON\ntest: unify setup, avoid test-to-test calls\nchore: use relative MCP package path * chore(tests): track MCPToolParameterTests.cs.meta to keep GUID stable * test: decouple MaterialParameterToolTests with helpers (no inter-test calls)
2025-10-24 08:57:27 +08:00
// --- Prefab Redirection Check ---
string targetPath =
targetToken?.Type == JTokenType.String ? targetToken.ToString() : null;
if (
!string.IsNullOrEmpty(targetPath)
&& targetPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)
)
{
// Allow 'create' (instantiate), 'find' (?), 'get_components' (?)
if (action == "modify" || action == "set_component_property")
{
Debug.Log(
$"[ManageGameObject->ManageAsset] Redirecting action '{action}' for prefab '{targetPath}' to ManageAsset."
);
// Prepare params for ManageAsset.ModifyAsset
JObject assetParams = new JObject();
assetParams["action"] = "modify"; // ManageAsset uses "modify"
assetParams["path"] = targetPath;
// Extract properties.
// For 'set_component_property', combine componentName and componentProperties.
// For 'modify', directly use componentProperties.
JObject properties = null;
if (action == "set_component_property")
{
string compName = @params["componentName"]?.ToString();
JObject compProps = @params["componentProperties"]?[compName] as JObject; // Handle potential nesting
if (string.IsNullOrEmpty(compName))
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-25 11:21:06 +08:00
return new ErrorResponse(
"Missing 'componentName' for 'set_component_property' on prefab."
);
if (compProps == null)
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Missing or invalid 'componentProperties' for component '{compName}' for 'set_component_property' on prefab."
);
properties = new JObject();
properties[compName] = compProps;
}
else // action == "modify"
{
properties = @params["componentProperties"] as JObject;
if (properties == null)
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-25 11:21:06 +08:00
return new ErrorResponse(
"Missing 'componentProperties' for 'modify' action on prefab."
);
}
assetParams["properties"] = properties;
// Call ManageAsset handler
return ManageAsset.HandleCommand(assetParams);
}
else if (
action == "delete"
|| action == "add_component"
|| action == "remove_component"
|| action == "get_components"
) // Added get_components here too
{
// Explicitly block other modifications on the prefab asset itself via manage_gameobject
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Action '{action}' on a prefab asset ('{targetPath}') should be performed using the 'manage_asset' command."
);
}
// Allow 'create' (instantiation) and 'find' to proceed, although finding a prefab asset by path might be less common via manage_gameobject.
// No specific handling needed here, the code below will run.
}
// --- End Prefab Redirection Check ---
try
{
switch (action)
{
🎮 GameObject Toolset Redesign and Streamlining (#518) * feat: Redesign GameObject API for better LLM ergonomics ## New Tools - find_gameobjects: Search GameObjects, returns paginated instance IDs only - manage_components: Component lifecycle (add, remove, set_property) ## New Resources - unity://scene/gameobject/{id}: Single GameObject data (no component serialization) - unity://scene/gameobject/{id}/components: All components (paginated) - unity://scene/gameobject/{id}/component/{name}: Single component by type ## Updated - manage_scene get_hierarchy: Now includes componentTypes array - manage_gameobject: Slimmed to lifecycle only (create, modify, delete) - Legacy actions (find, get_components, etc.) log deprecation warnings ## Extracted Utilities - ParamCoercion: Centralized int/bool/float/string coercion - VectorParsing: Vector3/Vector2/Quaternion/Color parsing - GameObjectLookup: Centralized GameObject search logic ## Test Coverage - 76 new Unity EditMode tests for ManageGameObject actions - 21 new pytest tests for Python tools/resources - New NL/T CI suite for GameObject API (GO-0 to GO-5) Addresses LLM confusion with parameter overload by splitting into focused tools and read-only resources. * feat: Add static gameobject_api helper resource for UI discoverability Adds unity://scene/gameobject-api resource that: - Shows in Cursor's resource list UI (no parameters needed) - Documents the parameterized gameobject resources - Explains the workflow: find_gameobjects → read resource - Lists examples and related tools * feat: Add GO tests to main NL/T CI workflow - Adds GO pass (GO-0 to GO-5) after T pass in claude-nl-suite.yml - Includes retry logic for incomplete GO tests - Updates all regex patterns to recognize GO-* test IDs - Updates DESIRED lists to include all 21 tests (NL-0..4, T-A..J, GO-0..5) - Updates default_titles for GO tests in markdown summary - Keeps separate claude-gameobject-suite.yml for standalone runs * feat: Add GameObject API stress tests and NL/T suite updates Stress Tests (12 new tests): - BulkCreate small/medium batches - FindGameObjects pagination with by_component search - AddComponents to single object - GetComponents with full serialization - SetComponentProperties (complex Rigidbody) - Deep hierarchy creation and path lookup - GetHierarchy with large scenes - Resource read performance tests - RapidFire create-modify-delete cycles NL/T Suite Updates: - Added GO-0..GO-10 tests in nl-gameobject-suite.md - Fixed tool naming: mcp__unity__ → mcp__UnityMCP__ Other: - Fixed LongUnityScriptClaudeTest.cs compilation errors - Added reports/, .claude/local/, scripts/local-test/ to .gitignore All 254 EditMode tests pass (250 run, 4 explicit skips) * fix: Address code review feedback - ParamCoercion: Use CultureInfo.InvariantCulture for float parsing - ManageComponents: Move Transform removal check before GetComponent - ManageGameObjectFindTests: Use try-finally for LogAssert.ignoreFailingMessages - VectorParsing: Document that quaternions are not auto-normalized - gameobject.py: Prefix unused ctx parameter with underscore * fix: Address additional code review feedback - ManageComponents: Reuse GameObjectLookup.FindComponentType instead of duplicate - ManageComponents: Log warnings when SetPropertiesOnComponent fails - GameObjectLookup: Make FindComponentType public for reuse - gameobject.py: Extract _normalize_response helper to reduce duplication - gameobject.py: Add TODO comment for unused typed response classes * fix: Address more code review feedback NL/T Prompt Fixes: - nl-gameobject-suite.md: Remove non-existent list_resources/read_resource from AllowedTools - nl-gameobject-suite.md: Fix parameter names (component_type, properties) - nl-unity-suite-nl.md: Remove unused manage_editor from AllowedTools Test Fixes: - GameObjectAPIStressTests: Add null check to ToJObject helper - GameObjectAPIStressTests: Clarify AudioSource usage comment - ManageGameObjectFindTests: Use built-in 'UI' layer instead of 'Water' - LongUnityScriptClaudeTest: Clean up NL/T test artifacts (Counte42 typo, HasTarget) * docs: Add documentation for API limitations and behaviors - GameObjectLookup.SearchByPath: Document and warn that includeInactive has no effect (Unity API limitation) - ManageComponents.TrySetProperty: Document case-insensitive lookup behavior * More test fixes and tighten parameters on python tools * fix: Align test expectation with implementation error message case * docs: update README tools and resources lists - Add missing tools: manage_components, batch_execute, find_gameobjects, refresh_unity - Add missing resources: gameobject_api, editor_state_v2 - Make descriptions more concise across all tools and resources - Ensure documentation matches current MCP server functionality * fix: Address code review feedback - ParamCoercion: Use InvariantCulture for int/double parsing consistency - ManageComponents: Remove redundant Undo.RecordObject (AddComponent handles undo) - ManageScene: Replace deprecated FindObjectsOfType with FindObjectsByType - GameObjectLookup: Add explanatory comment to empty catch block - gameobject.py: Extract _validate_instance_id helper to reduce duplication - Tests: Fix assertion for instanceID (Unity IDs can be negative) * chore: Remove accidentally committed test artifacts - Remove Materials folder (40 .mat files from interactive testing) - Remove Shaders folder (5 noise shaders from testing) - Remove test scripts (Bounce*, CylinderBounce* from testing) - Remove Temp.meta and commit.sh * test: Improve delete tests to verify actual deletion - Delete_ByTag_DeletesMatchingObjects: Verify objects are actually destroyed - Delete_ByLayer_DeletesMatchingObjects: Assert deletion using Unity null check - Delete_MultipleObjectsSameName_DeletesCorrectly: Document first-match behavior - Delete_Success_ReturnsDeletedCount: Verify count value if present All tests now verify deletion occurred rather than just checking for a result. * refactor: remove deprecated manage_gameobject actions - Remove deprecated switch cases: find, get_components, get_component, add_component, remove_component, set_component_property - Remove deprecated wrapper methods (423 lines deleted from ManageGameObject.cs) - Delete ManageGameObjectFindTests.cs (tests deprecated 'find' action) - Remove deprecated test methods from ManageGameObjectTests.cs - Add GameObject resource URIs to README documentation - Add batch_execute performance tips to README, tool description, and gameobject_api resource - Enhance batch_execute description to emphasize 10-100x performance gains Total: ~1200 lines removed. New API (find_gameobjects, manage_components, resources) is the recommended path forward. * fix: Remove starlette stubs from conftest.py Starlette is now a proper dependency via the mcp package, so we don't need to stub it anymore. The real package handles all HTTP transport needs.
2026-01-07 02:13:45 +08:00
// --- Primary lifecycle actions (kept in manage_gameobject) ---
case "create":
return CreateGameObject(@params);
case "modify":
return ModifyGameObject(@params, targetToken, searchMethod);
case "delete":
return DeleteGameObject(targetToken, searchMethod);
case "duplicate":
return DuplicateGameObject(@params, targetToken, searchMethod);
case "move_relative":
return MoveRelativeToObject(@params, targetToken, searchMethod);
default:
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-25 11:21:06 +08:00
return new ErrorResponse($"Unknown action: '{action}'.");
}
}
catch (Exception e)
{
Debug.LogError($"[ManageGameObject] Action '{action}' failed: {e}");
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-25 11:21:06 +08:00
return new ErrorResponse($"Internal error processing action '{action}': {e.Message}");
}
}
// --- Action Implementations ---
private static object CreateGameObject(JObject @params)
{
string name = @params["name"]?.ToString();
if (string.IsNullOrEmpty(name))
{
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-25 11:21:06 +08:00
return new ErrorResponse("'name' parameter is required for 'create' action.");
}
// Get prefab creation parameters
bool saveAsPrefab = @params["saveAsPrefab"]?.ToObject<bool>() ?? false;
string prefabPath = @params["prefabPath"]?.ToString();
string tag = @params["tag"]?.ToString(); // Get tag for creation
string primitiveType = @params["primitiveType"]?.ToString(); // Keep primitiveType check
GameObject newGo = null; // Initialize as null
// --- Try Instantiating Prefab First ---
string originalPrefabPath = prefabPath; // Keep original for messages
if (!string.IsNullOrEmpty(prefabPath))
{
// If no extension, search for the prefab by name
if (
!prefabPath.Contains("/")
&& !prefabPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)
)
{
string prefabNameOnly = prefabPath;
Debug.Log(
$"[ManageGameObject.Create] Searching for prefab named: '{prefabNameOnly}'"
);
string[] guids = AssetDatabase.FindAssets($"t:Prefab {prefabNameOnly}");
if (guids.Length == 0)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Prefab named '{prefabNameOnly}' not found anywhere in the project."
);
}
else if (guids.Length > 1)
{
string foundPaths = string.Join(
", ",
guids.Select(g => AssetDatabase.GUIDToAssetPath(g))
);
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Multiple prefabs found matching name '{prefabNameOnly}': {foundPaths}. Please provide a more specific path."
);
}
else // Exactly one found
{
prefabPath = AssetDatabase.GUIDToAssetPath(guids[0]); // Update prefabPath with the full path
Debug.Log(
$"[ManageGameObject.Create] Found unique prefab at path: '{prefabPath}'"
);
}
}
else if (!prefabPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase))
{
// If it looks like a path but doesn't end with .prefab, assume user forgot it and append it.
Debug.LogWarning(
$"[ManageGameObject.Create] Provided prefabPath '{prefabPath}' does not end with .prefab. Assuming it's missing and appending."
);
prefabPath += ".prefab";
// Note: This path might still not exist, AssetDatabase.LoadAssetAtPath will handle that.
}
// The logic above now handles finding or assuming the .prefab extension.
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
if (prefabAsset != null)
{
try
{
// Instantiate the prefab, initially place it at the root
// Parent will be set later if specified
newGo = PrefabUtility.InstantiatePrefab(prefabAsset) as GameObject;
if (newGo == null)
{
// This might happen if the asset exists but isn't a valid GameObject prefab somehow
Debug.LogError(
$"[ManageGameObject.Create] Failed to instantiate prefab at '{prefabPath}', asset might be corrupted or not a GameObject."
);
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Failed to instantiate prefab at '{prefabPath}'."
);
}
// Name the instance based on the 'name' parameter, not the prefab's default name
if (!string.IsNullOrEmpty(name))
{
newGo.name = name;
}
// Register Undo for prefab instantiation
Undo.RegisterCreatedObjectUndo(
newGo,
$"Instantiate Prefab '{prefabAsset.name}' as '{newGo.name}'"
);
Debug.Log(
$"[ManageGameObject.Create] Instantiated prefab '{prefabAsset.name}' from path '{prefabPath}' as '{newGo.name}'."
);
}
catch (Exception e)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Error instantiating prefab '{prefabPath}': {e.Message}"
);
}
}
else
{
// Only return error if prefabPath was specified but not found.
// If prefabPath was empty/null, we proceed to create primitive/empty.
Debug.LogWarning(
$"[ManageGameObject.Create] Prefab asset not found at path: '{prefabPath}'. Will proceed to create new object if specified."
);
// Do not return error here, allow fallback to primitive/empty creation
}
}
// --- Fallback: Create Primitive or Empty GameObject ---
bool createdNewObject = false; // Flag to track if we created (not instantiated)
if (newGo == null) // Only proceed if prefab instantiation didn't happen
{
if (!string.IsNullOrEmpty(primitiveType))
{
try
{
PrimitiveType type = (PrimitiveType)
Enum.Parse(typeof(PrimitiveType), primitiveType, true);
newGo = GameObject.CreatePrimitive(type);
// Set name *after* creation for primitives
if (!string.IsNullOrEmpty(name))
{
newGo.name = name;
}
else
{
UnityEngine.Object.DestroyImmediate(newGo); // cleanup leak
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-25 11:21:06 +08:00
return new ErrorResponse(
"'name' parameter is required when creating a primitive."
);
}
createdNewObject = true;
}
catch (ArgumentException)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Invalid primitive type: '{primitiveType}'. Valid types: {string.Join(", ", Enum.GetNames(typeof(PrimitiveType)))}"
);
}
catch (Exception e)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Failed to create primitive '{primitiveType}': {e.Message}"
);
}
}
else // Create empty GameObject
{
if (string.IsNullOrEmpty(name))
{
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-25 11:21:06 +08:00
return new ErrorResponse(
"'name' parameter is required for 'create' action when not instantiating a prefab or creating a primitive."
);
}
newGo = new GameObject(name);
createdNewObject = true;
}
// Record creation for Undo *only* if we created a new object
if (createdNewObject)
{
Undo.RegisterCreatedObjectUndo(newGo, $"Create GameObject '{newGo.name}'");
}
}
// --- Common Setup (Parent, Transform, Tag, Components) - Applied AFTER object exists ---
if (newGo == null)
{
// Should theoretically not happen if logic above is correct, but safety check.
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-25 11:21:06 +08:00
return new ErrorResponse("Failed to create or instantiate the GameObject.");
}
// Record potential changes to the existing prefab instance or the new GO
// Record transform separately in case parent changes affect it
Undo.RecordObject(newGo.transform, "Set GameObject Transform");
Undo.RecordObject(newGo, "Set GameObject Properties");
// Set Parent
JToken parentToken = @params["parent"];
if (parentToken != null)
{
GameObject parentGo = FindObjectInternal(parentToken, "by_id_or_name_or_path"); // Flexible parent finding
if (parentGo == null)
{
UnityEngine.Object.DestroyImmediate(newGo); // Clean up created object
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-25 11:21:06 +08:00
return new ErrorResponse($"Parent specified ('{parentToken}') but not found.");
}
newGo.transform.SetParent(parentGo.transform, true); // worldPositionStays = true
}
// Set Transform
Vector3? position = ParseVector3(@params["position"] as JArray);
Vector3? rotation = ParseVector3(@params["rotation"] as JArray);
Vector3? scale = ParseVector3(@params["scale"] as JArray);
if (position.HasValue)
newGo.transform.localPosition = position.Value;
if (rotation.HasValue)
newGo.transform.localEulerAngles = rotation.Value;
if (scale.HasValue)
newGo.transform.localScale = scale.Value;
// Set Tag (added for create action)
if (!string.IsNullOrEmpty(tag))
{
// Similar logic as in ModifyGameObject for setting/creating tags
string tagToSet = string.IsNullOrEmpty(tag) ? "Untagged" : tag;
try
{
newGo.tag = tagToSet;
}
catch (UnityException ex)
{
if (ex.Message.Contains("is not defined"))
{
Debug.LogWarning(
$"[ManageGameObject.Create] Tag '{tagToSet}' not found. Attempting to create it."
);
try
{
InternalEditorUtility.AddTag(tagToSet);
newGo.tag = tagToSet; // Retry
Debug.Log(
$"[ManageGameObject.Create] Tag '{tagToSet}' created and assigned successfully."
);
}
catch (Exception innerEx)
{
UnityEngine.Object.DestroyImmediate(newGo); // Clean up
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Failed to create or assign tag '{tagToSet}' during creation: {innerEx.Message}."
);
}
}
else
{
UnityEngine.Object.DestroyImmediate(newGo); // Clean up
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Failed to set tag to '{tagToSet}' during creation: {ex.Message}."
);
}
}
}
// Set Layer (new for create action)
string layerName = @params["layer"]?.ToString();
if (!string.IsNullOrEmpty(layerName))
{
int layerId = LayerMask.NameToLayer(layerName);
if (layerId != -1)
{
newGo.layer = layerId;
}
else
{
Debug.LogWarning(
$"[ManageGameObject.Create] Layer '{layerName}' not found. Using default layer."
);
}
}
// Add Components
if (@params["componentsToAdd"] is JArray componentsToAddArray)
{
foreach (var compToken in componentsToAddArray)
{
string typeName = null;
JObject properties = null;
if (compToken.Type == JTokenType.String)
{
typeName = compToken.ToString();
}
else if (compToken is JObject compObj)
{
typeName = compObj["typeName"]?.ToString();
properties = compObj["properties"] as JObject;
}
if (!string.IsNullOrEmpty(typeName))
{
var addResult = AddComponentInternal(newGo, typeName, properties);
if (addResult != null) // Check if AddComponentInternal returned an error object
{
UnityEngine.Object.DestroyImmediate(newGo); // Clean up
return addResult; // Return the error response
}
}
else
{
Debug.LogWarning(
$"[ManageGameObject] Invalid component format in componentsToAdd: {compToken}"
);
}
}
}
// Save as Prefab ONLY if we *created* a new object AND saveAsPrefab is true
GameObject finalInstance = newGo; // Use this for selection and return data
if (createdNewObject && saveAsPrefab)
{
string finalPrefabPath = prefabPath; // Use a separate variable for saving path
// This check should now happen *before* attempting to save
if (string.IsNullOrEmpty(finalPrefabPath))
{
// Clean up the created object before returning error
UnityEngine.Object.DestroyImmediate(newGo);
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-25 11:21:06 +08:00
return new ErrorResponse(
"'prefabPath' is required when 'saveAsPrefab' is true and creating a new object."
);
}
// Ensure the *saving* path ends with .prefab
if (!finalPrefabPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase))
{
Debug.Log(
$"[ManageGameObject.Create] Appending .prefab extension to save path: '{finalPrefabPath}' -> '{finalPrefabPath}.prefab'"
);
finalPrefabPath += ".prefab";
}
try
{
// Ensure directory exists using the final saving path
string directoryPath = System.IO.Path.GetDirectoryName(finalPrefabPath);
if (
!string.IsNullOrEmpty(directoryPath)
&& !System.IO.Directory.Exists(directoryPath)
)
{
System.IO.Directory.CreateDirectory(directoryPath);
Async Test Infrastructure & Editor Readiness Status + new refresh_unity tool (#507) * Add editor readiness v2, refresh tool, and preflight guards * Detect external package changes and harden refresh retry * feat: add TestRunnerNoThrottle and async test running with background stall prevention - Add TestRunnerNoThrottle.cs: Sets editor to 'No Throttling' mode during test runs with SessionState persistence across domain reload - Add run_tests_async and get_test_job tools for non-blocking test execution - Add TestJobManager for async test job tracking with progress monitoring - Add ForceSynchronousImport to all AssetDatabase.Refresh() calls to prevent stalls - Mark DomainReloadResilienceTests as [Explicit] with documentation explaining the test infrastructure limitation (internal coroutine waits vs MCP socket polling) - MCP workflow is unaffected - socket messages provide external stimulus that keeps Unity responsive even when backgrounded * refactor: simplify and clean up code - Remove unused Newtonsoft.Json.Linq import from TestJobManager - Add throttling to SessionState persistence (once per second) to reduce overhead - Critical job state changes (start/finish) still persist immediately - Fix duplicate XML summary tag in DomainReloadResilienceTests * docs: add async test tools to README, document domain reload limitation - Add run_tests_async and get_test_job to main README tools list - Document background stall limitation for domain reload tests in DEV readme * ci: add separate job for domain reload tests Run [Explicit] domain_reload tests in their own job using -testCategory * ci: run domain reload tests in same job as regular tests Combines into single job with two test steps to reuse cached Library * fix: address coderabbit review issues - Fix TOCTOU race in TestJobManager.StartJob (single lock scope for check-and-set) - Store TestRunnerApi reference with HideAndDontSave to prevent GC/serialization issues * docs: update tool descriptions to prefer run_tests_async - run_tests_async is now marked as preferred for long-running suites - run_tests description notes it blocks and suggests async alternative * docs: update README screenshot to v8.6 UI * docs: add v8.6 UI screenshot * Update README for MCP version and instructions for v8.7 * fix: handle preflight busy signals and derive job status from test results - manage_asset, manage_gameobject, manage_scene now check preflight return value and propagate busy/retry signals to clients (fixes Sourcery #1) - TestJobManager.FinalizeCurrentJobFromRunFinished now sets job status to Failed when resultPayload.Failed > 0, not always Succeeded (fixes Sourcery #2) * fix: increase HTTP server startup timeout for dev mode When 'Force fresh server install' is enabled, uvx uses --no-cache --refresh which rebuilds the package and takes significantly longer to start. - Increase timeout from 10s to 45s when dev mode is enabled - Add informative log message explaining the longer startup time - Show actual timeout value in warning message * fix: derive job status from test results in FinalizeFromTask fallback Apply same logic as FinalizeCurrentJobFromRunFinished: check result.Failed > 0 to correctly mark jobs as Failed when tests fail, even in the fallback path when RunFinished callback is not delivered.
2026-01-04 04:42:32 +08:00
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); // Refresh asset database to recognize the new folder
Debug.Log(
$"[ManageGameObject.Create] Created directory for prefab: {directoryPath}"
);
}
// Use SaveAsPrefabAssetAndConnect with the final saving path
finalInstance = PrefabUtility.SaveAsPrefabAssetAndConnect(
newGo,
finalPrefabPath,
InteractionMode.UserAction
);
if (finalInstance == null)
{
// Destroy the original if saving failed somehow (shouldn't usually happen if path is valid)
UnityEngine.Object.DestroyImmediate(newGo);
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Failed to save GameObject '{name}' as prefab at '{finalPrefabPath}'. Check path and permissions."
);
}
Debug.Log(
$"[ManageGameObject.Create] GameObject '{name}' saved as prefab to '{finalPrefabPath}' and instance connected."
);
// Mark the new prefab asset as dirty? Not usually necessary, SaveAsPrefabAsset handles it.
// EditorUtility.SetDirty(finalInstance); // Instance is handled by SaveAsPrefabAssetAndConnect
}
catch (Exception e)
{
// Clean up the instance if prefab saving fails
UnityEngine.Object.DestroyImmediate(newGo); // Destroy the original attempt
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-25 11:21:06 +08:00
return new ErrorResponse($"Error saving prefab '{finalPrefabPath}': {e.Message}");
}
}
// Select the instance in the scene (either prefab instance or newly created/saved one)
Selection.activeGameObject = finalInstance;
// Determine appropriate success message using the potentially updated or original path
string messagePrefabPath =
finalInstance == null
? originalPrefabPath
: AssetDatabase.GetAssetPath(
PrefabUtility.GetCorrespondingObjectFromSource(finalInstance)
?? (UnityEngine.Object)finalInstance
);
string successMessage;
if (!createdNewObject && !string.IsNullOrEmpty(messagePrefabPath)) // Instantiated existing prefab
{
successMessage =
$"Prefab '{messagePrefabPath}' instantiated successfully as '{finalInstance.name}'.";
}
else if (createdNewObject && saveAsPrefab && !string.IsNullOrEmpty(messagePrefabPath)) // Created new and saved as prefab
{
successMessage =
$"GameObject '{finalInstance.name}' created and saved as prefab to '{messagePrefabPath}'.";
}
else // Created new primitive or empty GO, didn't save as prefab
{
successMessage =
$"GameObject '{finalInstance.name}' created successfully in scene.";
}
// Use the new serializer helper
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-25 11:21:06 +08:00
//return new SuccessResponse(successMessage, GetGameObjectData(finalInstance));
return new SuccessResponse(successMessage, Helpers.GameObjectSerializer.GetGameObjectData(finalInstance));
}
private static object ModifyGameObject(
JObject @params,
JToken targetToken,
string searchMethod
)
{
GameObject targetGo = FindObjectInternal(targetToken, searchMethod);
if (targetGo == null)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? "default"}'."
);
}
// Record state for Undo *before* modifications
Undo.RecordObject(targetGo.transform, "Modify GameObject Transform");
Undo.RecordObject(targetGo, "Modify GameObject Properties");
bool modified = false;
// Rename (using consolidated 'name' parameter)
string name = @params["name"]?.ToString();
if (!string.IsNullOrEmpty(name) && targetGo.name != name)
{
targetGo.name = name;
modified = true;
}
// Change Parent (using consolidated 'parent' parameter)
JToken parentToken = @params["parent"];
if (parentToken != null)
{
GameObject newParentGo = FindObjectInternal(parentToken, "by_id_or_name_or_path");
// Check for hierarchy loops
if (
newParentGo == null
&& !(
parentToken.Type == JTokenType.Null
|| (
parentToken.Type == JTokenType.String
&& string.IsNullOrEmpty(parentToken.ToString())
)
)
)
{
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-25 11:21:06 +08:00
return new ErrorResponse($"New parent ('{parentToken}') not found.");
}
if (newParentGo != null && newParentGo.transform.IsChildOf(targetGo.transform))
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Cannot parent '{targetGo.name}' to '{newParentGo.name}', as it would create a hierarchy loop."
);
}
if (targetGo.transform.parent != (newParentGo?.transform))
{
targetGo.transform.SetParent(newParentGo?.transform, true); // worldPositionStays = true
modified = true;
}
}
// Set Active State
bool? setActive = @params["setActive"]?.ToObject<bool?>();
if (setActive.HasValue && targetGo.activeSelf != setActive.Value)
{
targetGo.SetActive(setActive.Value);
modified = true;
}
// Change Tag (using consolidated 'tag' parameter)
string tag = @params["tag"]?.ToString();
// Only attempt to change tag if a non-null tag is provided and it's different from the current one.
// Allow setting an empty string to remove the tag (Unity uses "Untagged").
if (tag != null && targetGo.tag != tag)
{
// Ensure the tag is not empty, if empty, it means "Untagged" implicitly
string tagToSet = string.IsNullOrEmpty(tag) ? "Untagged" : tag;
try
{
targetGo.tag = tagToSet;
modified = true;
}
catch (UnityException ex)
{
// Check if the error is specifically because the tag doesn't exist
if (ex.Message.Contains("is not defined"))
{
Debug.LogWarning(
$"[ManageGameObject] Tag '{tagToSet}' not found. Attempting to create it."
);
try
{
// Attempt to create the tag using internal utility
InternalEditorUtility.AddTag(tagToSet);
// Wait a frame maybe? Not strictly necessary but sometimes helps editor updates.
// yield return null; // Cannot yield here, editor script limitation
// Retry setting the tag immediately after creation
targetGo.tag = tagToSet;
modified = true;
Debug.Log(
$"[ManageGameObject] Tag '{tagToSet}' created and assigned successfully."
);
}
catch (Exception innerEx)
{
// Handle failure during tag creation or the second assignment attempt
Debug.LogError(
$"[ManageGameObject] Failed to create or assign tag '{tagToSet}' after attempting creation: {innerEx.Message}"
);
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Failed to create or assign tag '{tagToSet}': {innerEx.Message}. Check Tag Manager and permissions."
);
}
}
else
{
// If the exception was for a different reason, return the original error
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-25 11:21:06 +08:00
return new ErrorResponse($"Failed to set tag to '{tagToSet}': {ex.Message}.");
}
}
}
// Change Layer (using consolidated 'layer' parameter)
string layerName = @params["layer"]?.ToString();
if (!string.IsNullOrEmpty(layerName))
{
int layerId = LayerMask.NameToLayer(layerName);
if (layerId == -1 && layerName != "Default")
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Invalid layer specified: '{layerName}'. Use a valid layer name."
);
}
if (layerId != -1 && targetGo.layer != layerId)
{
targetGo.layer = layerId;
modified = true;
}
}
// Transform Modifications
Vector3? position = ParseVector3(@params["position"] as JArray);
Vector3? rotation = ParseVector3(@params["rotation"] as JArray);
Vector3? scale = ParseVector3(@params["scale"] as JArray);
if (position.HasValue && targetGo.transform.localPosition != position.Value)
{
targetGo.transform.localPosition = position.Value;
modified = true;
}
if (rotation.HasValue && targetGo.transform.localEulerAngles != rotation.Value)
{
targetGo.transform.localEulerAngles = rotation.Value;
modified = true;
}
if (scale.HasValue && targetGo.transform.localScale != scale.Value)
{
targetGo.transform.localScale = scale.Value;
modified = true;
}
// --- Component Modifications ---
// Note: These might need more specific Undo recording per component
// Remove Components
if (@params["componentsToRemove"] is JArray componentsToRemoveArray)
{
foreach (var compToken in componentsToRemoveArray)
{
// ... (parsing logic as in CreateGameObject) ...
string typeName = compToken.ToString();
if (!string.IsNullOrEmpty(typeName))
{
var removeResult = RemoveComponentInternal(targetGo, typeName);
if (removeResult != null)
return removeResult; // Return error if removal failed
modified = true;
}
}
}
// Add Components (similar to create)
if (@params["componentsToAdd"] is JArray componentsToAddArrayModify)
{
foreach (var compToken in componentsToAddArrayModify)
{
string typeName = null;
JObject properties = null;
if (compToken.Type == JTokenType.String)
typeName = compToken.ToString();
else if (compToken is JObject compObj)
{
typeName = compObj["typeName"]?.ToString();
properties = compObj["properties"] as JObject;
}
if (!string.IsNullOrEmpty(typeName))
{
var addResult = AddComponentInternal(targetGo, typeName, properties);
if (addResult != null)
return addResult;
modified = true;
}
}
}
// Set Component Properties
var componentErrors = new List<object>();
if (@params["componentProperties"] is JObject componentPropertiesObj)
{
foreach (var prop in componentPropertiesObj.Properties())
{
string compName = prop.Name;
JObject propertiesToSet = prop.Value as JObject;
if (propertiesToSet != null)
{
var setResult = SetComponentPropertiesInternal(
targetGo,
compName,
propertiesToSet
);
if (setResult != null)
{
componentErrors.Add(setResult);
}
else
{
modified = true;
}
}
}
}
// Return component errors if any occurred (after processing all components)
if (componentErrors.Count > 0)
{
// Aggregate flattened error strings to make tests/API assertions simpler
var aggregatedErrors = new System.Collections.Generic.List<string>();
foreach (var errorObj in componentErrors)
{
try
{
var dataProp = errorObj?.GetType().GetProperty("data");
var dataVal = dataProp?.GetValue(errorObj);
if (dataVal != null)
{
var errorsProp = dataVal.GetType().GetProperty("errors");
var errorsEnum = errorsProp?.GetValue(dataVal) as System.Collections.IEnumerable;
if (errorsEnum != null)
{
foreach (var item in errorsEnum)
{
var s = item?.ToString();
if (!string.IsNullOrEmpty(s)) aggregatedErrors.Add(s);
}
}
}
}
catch { }
}
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-25 11:21:06 +08:00
return new ErrorResponse(
$"One or more component property operations failed on '{targetGo.name}'.",
new { componentErrors = componentErrors, errors = aggregatedErrors }
);
}
if (!modified)
{
// Use the new serializer helper
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-25 11:21:06 +08:00
// return new SuccessResponse(
// $"No modifications applied to GameObject '{targetGo.name}'.",
// GetGameObjectData(targetGo));
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-25 11:21:06 +08:00
return new SuccessResponse(
$"No modifications applied to GameObject '{targetGo.name}'.",
Helpers.GameObjectSerializer.GetGameObjectData(targetGo)
);
}
EditorUtility.SetDirty(targetGo); // Mark scene as dirty
// Use the new serializer helper
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-25 11:21:06 +08:00
return new SuccessResponse(
$"GameObject '{targetGo.name}' modified successfully.",
Helpers.GameObjectSerializer.GetGameObjectData(targetGo)
);
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-25 11:21:06 +08:00
// return new SuccessResponse(
// $"GameObject '{targetGo.name}' modified successfully.",
// GetGameObjectData(targetGo));
}
/// <summary>
/// Duplicates a GameObject with all its properties, components, and children.
/// </summary>
private static object DuplicateGameObject(JObject @params, JToken targetToken, string searchMethod)
{
GameObject sourceGo = FindObjectInternal(targetToken, searchMethod);
if (sourceGo == null)
{
return new ErrorResponse(
$"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? "default"}'."
);
}
// Optional parameters
string newName = @params["new_name"]?.ToString();
Vector3? position = ParseVector3(@params["position"] as JArray);
Vector3? offset = ParseVector3(@params["offset"] as JArray);
JToken parentToken = @params["parent"];
// Duplicate the object
GameObject duplicatedGo = UnityEngine.Object.Instantiate(sourceGo);
Undo.RegisterCreatedObjectUndo(duplicatedGo, $"Duplicate {sourceGo.name}");
// Set name (default: SourceName_Copy or SourceName (1))
if (!string.IsNullOrEmpty(newName))
{
duplicatedGo.name = newName;
}
else
{
// Remove "(Clone)" suffix added by Instantiate and add "_Copy"
duplicatedGo.name = sourceGo.name.Replace("(Clone)", "").Trim() + "_Copy";
}
// Handle positioning
if (position.HasValue)
{
// Absolute position specified
duplicatedGo.transform.position = position.Value;
}
else if (offset.HasValue)
{
// Offset from original
duplicatedGo.transform.position = sourceGo.transform.position + offset.Value;
}
// else: keeps the same position as the original (default Instantiate behavior)
// Handle parent
if (parentToken != null)
{
if (parentToken.Type == JTokenType.Null ||
(parentToken.Type == JTokenType.String && string.IsNullOrEmpty(parentToken.ToString())))
{
// Explicit null parent - move to root
duplicatedGo.transform.SetParent(null);
}
else
{
GameObject newParent = FindObjectInternal(parentToken, "by_id_or_name_or_path");
if (newParent != null)
{
duplicatedGo.transform.SetParent(newParent.transform, true);
}
else
{
Debug.LogWarning($"[ManageGameObject.Duplicate] Parent '{parentToken}' not found. Keeping original parent.");
}
}
}
else
{
// Default: same parent as source
duplicatedGo.transform.SetParent(sourceGo.transform.parent, true);
}
// Mark scene dirty
EditorUtility.SetDirty(duplicatedGo);
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
Selection.activeGameObject = duplicatedGo;
return new SuccessResponse(
$"Duplicated '{sourceGo.name}' as '{duplicatedGo.name}'.",
new
{
originalName = sourceGo.name,
originalId = sourceGo.GetInstanceID(),
duplicatedObject = Helpers.GameObjectSerializer.GetGameObjectData(duplicatedGo)
}
);
}
/// <summary>
/// Moves a GameObject relative to another reference object.
/// Supports directional offsets (left, right, up, down, forward, back) and distance.
/// </summary>
private static object MoveRelativeToObject(JObject @params, JToken targetToken, string searchMethod)
{
GameObject targetGo = FindObjectInternal(targetToken, searchMethod);
if (targetGo == null)
{
return new ErrorResponse(
$"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? "default"}'."
);
}
// Get reference object (required for relative movement)
JToken referenceToken = @params["reference_object"];
if (referenceToken == null)
{
return new ErrorResponse("'reference_object' parameter is required for 'move_relative' action.");
}
GameObject referenceGo = FindObjectInternal(referenceToken, "by_id_or_name_or_path");
if (referenceGo == null)
{
return new ErrorResponse($"Reference object '{referenceToken}' not found.");
}
// Get movement parameters
string direction = @params["direction"]?.ToString()?.ToLower();
float distance = @params["distance"]?.ToObject<float>() ?? 1f;
Vector3? customOffset = ParseVector3(@params["offset"] as JArray);
bool useWorldSpace = @params["world_space"]?.ToObject<bool>() ?? true;
// Record for undo
Undo.RecordObject(targetGo.transform, $"Move {targetGo.name} relative to {referenceGo.name}");
Vector3 newPosition;
if (customOffset.HasValue)
{
// Custom offset vector provided
if (useWorldSpace)
{
newPosition = referenceGo.transform.position + customOffset.Value;
}
else
{
// Offset in reference object's local space
newPosition = referenceGo.transform.TransformPoint(customOffset.Value);
}
}
else if (!string.IsNullOrEmpty(direction))
{
// Directional movement
Vector3 directionVector = GetDirectionVector(direction, referenceGo.transform, useWorldSpace);
newPosition = referenceGo.transform.position + directionVector * distance;
}
else
{
return new ErrorResponse("Either 'direction' or 'offset' parameter is required for 'move_relative' action.");
}
targetGo.transform.position = newPosition;
// Mark scene dirty
EditorUtility.SetDirty(targetGo);
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
return new SuccessResponse(
$"Moved '{targetGo.name}' relative to '{referenceGo.name}'.",
new
{
movedObject = targetGo.name,
referenceObject = referenceGo.name,
newPosition = new[] { targetGo.transform.position.x, targetGo.transform.position.y, targetGo.transform.position.z },
direction = direction,
distance = distance,
gameObject = Helpers.GameObjectSerializer.GetGameObjectData(targetGo)
}
);
}
/// <summary>
/// Converts a direction string to a Vector3.
/// </summary>
private static Vector3 GetDirectionVector(string direction, Transform referenceTransform, bool useWorldSpace)
{
if (useWorldSpace)
{
// World space directions
switch (direction)
{
case "right": return Vector3.right;
case "left": return Vector3.left;
case "up": return Vector3.up;
case "down": return Vector3.down;
case "forward": case "front": return Vector3.forward;
case "back": case "backward": case "behind": return Vector3.back;
default:
Debug.LogWarning($"[ManageGameObject.MoveRelative] Unknown direction '{direction}', defaulting to forward.");
return Vector3.forward;
}
}
else
{
// Reference object's local space directions
switch (direction)
{
case "right": return referenceTransform.right;
case "left": return -referenceTransform.right;
case "up": return referenceTransform.up;
case "down": return -referenceTransform.up;
case "forward": case "front": return referenceTransform.forward;
case "back": case "backward": case "behind": return -referenceTransform.forward;
default:
Debug.LogWarning($"[ManageGameObject.MoveRelative] Unknown direction '{direction}', defaulting to forward.");
return referenceTransform.forward;
}
}
}
private static object DeleteGameObject(JToken targetToken, string searchMethod)
{
// Find potentially multiple objects if name/tag search is used without find_all=false implicitly
List<GameObject> targets = FindObjectsInternal(targetToken, searchMethod, true); // find_all=true for delete safety
if (targets.Count == 0)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Target GameObject(s) ('{targetToken}') not found using method '{searchMethod ?? "default"}'."
);
}
List<object> deletedObjects = new List<object>();
foreach (var targetGo in targets)
{
if (targetGo != null)
{
string goName = targetGo.name;
int goId = targetGo.GetInstanceID();
// Use Undo.DestroyObjectImmediate for undo support
Undo.DestroyObjectImmediate(targetGo);
deletedObjects.Add(new { name = goName, instanceID = goId });
}
}
if (deletedObjects.Count > 0)
{
string message =
targets.Count == 1
? $"GameObject '{deletedObjects[0].GetType().GetProperty("name").GetValue(deletedObjects[0])}' deleted successfully."
: $"{deletedObjects.Count} GameObjects deleted successfully.";
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-25 11:21:06 +08:00
return new SuccessResponse(message, deletedObjects);
}
else
{
// Should not happen if targets.Count > 0 initially, but defensive check
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-25 11:21:06 +08:00
return new ErrorResponse("Failed to delete target GameObject(s).");
}
}
// --- Internal Helpers ---
/// <summary>
/// Parses a JArray like [x, y, z] into a Vector3.
/// </summary>
private static Vector3? ParseVector3(JArray array)
{
if (array != null && array.Count == 3)
{
try
{
return new Vector3(
array[0].ToObject<float>(),
array[1].ToObject<float>(),
array[2].ToObject<float>()
);
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to parse JArray as Vector3: {array}. Error: {ex.Message}");
}
}
return null;
}
/// <summary>
/// Finds a single GameObject based on token (ID, name, path) and search method.
/// </summary>
private static GameObject FindObjectInternal(
JToken targetToken,
string searchMethod,
JObject findParams = null
)
{
// If find_all is not explicitly false, we still want only one for most single-target operations.
bool findAll = findParams?["findAll"]?.ToObject<bool>() ?? false;
// If a specific target ID is given, always find just that one.
if (
targetToken?.Type == JTokenType.Integer
|| (searchMethod == "by_id" && int.TryParse(targetToken?.ToString(), out _))
)
{
findAll = false;
}
List<GameObject> results = FindObjectsInternal(
targetToken,
searchMethod,
findAll,
findParams
);
return results.Count > 0 ? results[0] : null;
}
/// <summary>
/// Core logic for finding GameObjects based on various criteria.
/// </summary>
private static List<GameObject> FindObjectsInternal(
JToken targetToken,
string searchMethod,
bool findAll,
JObject findParams = null
)
{
List<GameObject> results = new List<GameObject>();
string searchTerm = findParams?["searchTerm"]?.ToString() ?? targetToken?.ToString(); // Use searchTerm if provided, else the target itself
bool searchInChildren = findParams?["searchInChildren"]?.ToObject<bool>() ?? false;
bool searchInactive = findParams?["searchInactive"]?.ToObject<bool>() ?? false;
// Default search method if not specified
if (string.IsNullOrEmpty(searchMethod))
{
if (targetToken?.Type == JTokenType.Integer)
searchMethod = "by_id";
else if (!string.IsNullOrEmpty(searchTerm) && searchTerm.Contains('/'))
searchMethod = "by_path";
else
searchMethod = "by_name"; // Default fallback
}
GameObject rootSearchObject = null;
// If searching in children, find the initial target first
if (searchInChildren && targetToken != null)
{
rootSearchObject = FindObjectInternal(targetToken, "by_id_or_name_or_path"); // Find the root for child search
if (rootSearchObject == null)
{
Debug.LogWarning(
$"[ManageGameObject.Find] Root object '{targetToken}' for child search not found."
);
return results; // Return empty if root not found
}
}
switch (searchMethod)
{
case "by_id":
if (int.TryParse(searchTerm, out int instanceId))
{
// EditorUtility.InstanceIDToObject is slow, iterate manually if possible
// GameObject obj = EditorUtility.InstanceIDToObject(instanceId) as GameObject;
var allObjects = GetAllSceneObjects(searchInactive); // More efficient
GameObject obj = allObjects.FirstOrDefault(go =>
go.GetInstanceID() == instanceId
);
if (obj != null)
results.Add(obj);
}
break;
case "by_name":
var searchPoolName = rootSearchObject
? rootSearchObject
.GetComponentsInChildren<Transform>(searchInactive)
.Select(t => t.gameObject)
: GetAllSceneObjects(searchInactive);
results.AddRange(searchPoolName.Where(go => go.name == searchTerm));
break;
case "by_path":
// Path is relative to scene root or rootSearchObject
Transform foundTransform = rootSearchObject
? rootSearchObject.transform.Find(searchTerm)
: GameObject.Find(searchTerm)?.transform;
if (foundTransform != null)
results.Add(foundTransform.gameObject);
break;
case "by_tag":
var searchPoolTag = rootSearchObject
? rootSearchObject
.GetComponentsInChildren<Transform>(searchInactive)
.Select(t => t.gameObject)
: GetAllSceneObjects(searchInactive);
results.AddRange(searchPoolTag.Where(go => go.CompareTag(searchTerm)));
break;
case "by_layer":
var searchPoolLayer = rootSearchObject
? rootSearchObject
.GetComponentsInChildren<Transform>(searchInactive)
.Select(t => t.gameObject)
: GetAllSceneObjects(searchInactive);
if (int.TryParse(searchTerm, out int layerIndex))
{
results.AddRange(searchPoolLayer.Where(go => go.layer == layerIndex));
}
else
{
int namedLayer = LayerMask.NameToLayer(searchTerm);
if (namedLayer != -1)
results.AddRange(searchPoolLayer.Where(go => go.layer == namedLayer));
}
break;
case "by_component":
Type componentType = FindType(searchTerm);
if (componentType != null)
{
// Determine FindObjectsInactive based on the searchInactive flag
FindObjectsInactive findInactive = searchInactive
? FindObjectsInactive.Include
: FindObjectsInactive.Exclude;
// Replace FindObjectsOfType with FindObjectsByType, specifying the sorting mode and inactive state
var searchPoolComp = rootSearchObject
? rootSearchObject
.GetComponentsInChildren(componentType, searchInactive)
.Select(c => (c as Component).gameObject)
: UnityEngine
.Object.FindObjectsByType(
componentType,
findInactive,
FindObjectsSortMode.None
)
.Select(c => (c as Component).gameObject);
results.AddRange(searchPoolComp.Where(go => go != null)); // Ensure GO is valid
}
else
{
Debug.LogWarning(
$"[ManageGameObject.Find] Component type not found: {searchTerm}"
);
}
break;
case "by_id_or_name_or_path": // Helper method used internally
if (int.TryParse(searchTerm, out int id))
{
var allObjectsId = GetAllSceneObjects(true); // Search inactive for internal lookup
GameObject objById = allObjectsId.FirstOrDefault(go =>
go.GetInstanceID() == id
);
if (objById != null)
{
results.Add(objById);
break;
}
}
GameObject objByPath = GameObject.Find(searchTerm);
if (objByPath != null)
{
results.Add(objByPath);
break;
}
var allObjectsName = GetAllSceneObjects(true);
results.AddRange(allObjectsName.Where(go => go.name == searchTerm));
break;
default:
Debug.LogWarning(
$"[ManageGameObject.Find] Unknown search method: {searchMethod}"
);
break;
}
// If only one result is needed, return just the first one found.
if (!findAll && results.Count > 1)
{
return new List<GameObject> { results[0] };
}
return results.Distinct().ToList(); // Ensure uniqueness
}
// Helper to get all scene objects efficiently
private static IEnumerable<GameObject> GetAllSceneObjects(bool includeInactive)
{
// SceneManager.GetActiveScene().GetRootGameObjects() is faster than FindObjectsOfType<GameObject>()
var rootObjects = SceneManager.GetActiveScene().GetRootGameObjects();
var allObjects = new List<GameObject>();
foreach (var root in rootObjects)
{
allObjects.AddRange(
root.GetComponentsInChildren<Transform>(includeInactive)
.Select(t => t.gameObject)
);
}
return allObjects;
}
/// <summary>
/// Adds a component by type name and optionally sets properties.
/// Returns null on success, or an error response object on failure.
/// </summary>
private static object AddComponentInternal(
GameObject targetGo,
string typeName,
JObject properties
)
{
Type componentType = FindType(typeName);
if (componentType == null)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Component type '{typeName}' not found or is not a valid Component."
);
}
if (!typeof(Component).IsAssignableFrom(componentType))
{
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-25 11:21:06 +08:00
return new ErrorResponse($"Type '{typeName}' is not a Component.");
}
// Prevent adding Transform again
if (componentType == typeof(Transform))
{
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-25 11:21:06 +08:00
return new ErrorResponse("Cannot add another Transform component.");
}
// Check for 2D/3D physics component conflicts
bool isAdding2DPhysics =
typeof(Rigidbody2D).IsAssignableFrom(componentType)
|| typeof(Collider2D).IsAssignableFrom(componentType);
bool isAdding3DPhysics =
typeof(Rigidbody).IsAssignableFrom(componentType)
|| typeof(Collider).IsAssignableFrom(componentType);
if (isAdding2DPhysics)
{
// Check if the GameObject already has any 3D Rigidbody or Collider
if (
targetGo.GetComponent<Rigidbody>() != null
|| targetGo.GetComponent<Collider>() != null
)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Cannot add 2D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 3D Rigidbody or Collider."
);
}
}
else if (isAdding3DPhysics)
{
// Check if the GameObject already has any 2D Rigidbody or Collider
if (
targetGo.GetComponent<Rigidbody2D>() != null
|| targetGo.GetComponent<Collider2D>() != null
)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Cannot add 3D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 2D Rigidbody or Collider."
);
}
}
try
{
// Use Undo.AddComponent for undo support
Component newComponent = Undo.AddComponent(targetGo, componentType);
if (newComponent == null)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Failed to add component '{typeName}' to '{targetGo.name}'. It might be disallowed (e.g., adding script twice)."
);
}
// Set default values for specific component types
if (newComponent is Light light)
{
// Default newly added lights to directional
light.type = LightType.Directional;
}
// Set properties if provided
if (properties != null)
{
var setResult = SetComponentPropertiesInternal(
targetGo,
typeName,
properties,
newComponent
); // Pass the new component instance
if (setResult != null)
{
// If setting properties failed, maybe remove the added component?
Undo.DestroyObjectImmediate(newComponent);
return setResult; // Return the error from setting properties
}
}
return null; // Success
}
catch (Exception e)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Error adding component '{typeName}' to '{targetGo.name}': {e.Message}"
);
}
}
/// <summary>
/// Removes a component by type name.
/// Returns null on success, or an error response object on failure.
/// </summary>
private static object RemoveComponentInternal(GameObject targetGo, string typeName)
{
Type componentType = FindType(typeName);
if (componentType == null)
{
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-25 11:21:06 +08:00
return new ErrorResponse($"Component type '{typeName}' not found for removal.");
}
// Prevent removing essential components
if (componentType == typeof(Transform))
{
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-25 11:21:06 +08:00
return new ErrorResponse("Cannot remove the Transform component.");
}
Component componentToRemove = targetGo.GetComponent(componentType);
if (componentToRemove == null)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Component '{typeName}' not found on '{targetGo.name}' to remove."
);
}
try
{
// Use Undo.DestroyObjectImmediate for undo support
Undo.DestroyObjectImmediate(componentToRemove);
return null; // Success
}
catch (Exception e)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Error removing component '{typeName}' from '{targetGo.name}': {e.Message}"
);
}
}
/// <summary>
/// Sets properties on a component.
/// Returns null on success, or an error response object on failure.
/// </summary>
private static object SetComponentPropertiesInternal(
GameObject targetGo,
string compName,
JObject propertiesToSet,
Component targetComponentInstance = null
)
{
Component targetComponent = targetComponentInstance;
if (targetComponent == null)
{
if (ComponentResolver.TryResolve(compName, out var compType, out var compError))
{
targetComponent = targetGo.GetComponent(compType);
}
else
{
targetComponent = targetGo.GetComponent(compName); // fallback to string-based lookup
}
}
if (targetComponent == null)
{
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-25 11:21:06 +08:00
return new ErrorResponse(
$"Component '{compName}' not found on '{targetGo.name}' to set properties."
);
}
Undo.RecordObject(targetComponent, "Set Component Properties");
var failures = new List<string>();
foreach (var prop in propertiesToSet.Properties())
{
string propName = prop.Name;
JToken propValue = prop.Value;
try
{
bool setResult = SetProperty(targetComponent, propName, propValue);
if (!setResult)
{
var availableProperties = ComponentResolver.GetAllComponentProperties(targetComponent.GetType());
var suggestions = ComponentResolver.GetAIPropertySuggestions(propName, availableProperties);
var msg = suggestions.Any()
? $"Property '{propName}' not found. Did you mean: {string.Join(", ", suggestions)}? Available: [{string.Join(", ", availableProperties)}]"
: $"Property '{propName}' not found. Available: [{string.Join(", ", availableProperties)}]";
Debug.LogWarning($"[ManageGameObject] {msg}");
failures.Add(msg);
}
}
catch (Exception e)
{
Debug.LogError(
$"[ManageGameObject] Error setting property '{propName}' on '{compName}': {e.Message}"
);
failures.Add($"Error setting '{propName}': {e.Message}");
}
}
EditorUtility.SetDirty(targetComponent);
return failures.Count == 0
? null
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-25 11:21:06 +08:00
: new ErrorResponse($"One or more properties failed on '{compName}'.", new { errors = failures });
}
/// <summary>
/// Helper to set a property or field via reflection, handling basic types.
/// </summary>
private static bool SetProperty(object target, string memberName, JToken value)
{
Type type = target.GetType();
BindingFlags flags =
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;
// Use shared serializer to avoid per-call allocation
var inputSerializer = InputSerializer;
try
{
// Handle special case for materials with dot notation (material.property)
// Examples: material.color, sharedMaterial.color, materials[0].color
if (memberName.Contains('.') || memberName.Contains('['))
{
// Pass the inputSerializer down for nested conversions
return SetNestedProperty(target, memberName, value, inputSerializer);
}
PropertyInfo propInfo = type.GetProperty(memberName, flags);
if (propInfo != null && propInfo.CanWrite)
{
// Use the inputSerializer for conversion
object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType, inputSerializer);
if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null
{
propInfo.SetValue(target, convertedValue);
return true;
}
else
{
Debug.LogWarning($"[SetProperty] Conversion failed for property '{memberName}' (Type: {propInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}");
}
}
else
{
FieldInfo fieldInfo = type.GetField(memberName, flags);
if (fieldInfo != null) // Check if !IsLiteral?
{
// Use the inputSerializer for conversion
object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType, inputSerializer);
if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null
{
fieldInfo.SetValue(target, convertedValue);
return true;
}
else
{
Debug.LogWarning($"[SetProperty] Conversion failed for field '{memberName}' (Type: {fieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}");
}
}
else
{
// Try NonPublic [SerializeField] fields
var npField = type.GetField(memberName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (npField != null && npField.GetCustomAttribute<SerializeField>() != null)
{
object convertedValue = ConvertJTokenToType(value, npField.FieldType, inputSerializer);
if (convertedValue != null || value.Type == JTokenType.Null)
{
npField.SetValue(target, convertedValue);
return true;
}
}
}
}
}
catch (Exception ex)
{
Debug.LogError(
$"[SetProperty] Failed to set '{memberName}' on {type.Name}: {ex.Message}\nToken: {value.ToString(Formatting.None)}"
);
}
return false;
}
/// <summary>
/// Sets a nested property using dot notation (e.g., "material.color") or array access (e.g., "materials[0]")
/// </summary>
// Pass the input serializer for conversions
//Using the serializer helper
private static bool SetNestedProperty(object target, string path, JToken value, JsonSerializer inputSerializer)
{
try
{
// Split the path into parts (handling both dot notation and array indexing)
string[] pathParts = SplitPropertyPath(path);
if (pathParts.Length == 0)
return false;
object currentObject = target;
Type currentType = currentObject.GetType();
BindingFlags flags =
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;
// Traverse the path until we reach the final property
for (int i = 0; i < pathParts.Length - 1; i++)
{
string part = pathParts[i];
bool isArray = false;
int arrayIndex = -1;
// Check if this part contains array indexing
if (part.Contains("["))
{
int startBracket = part.IndexOf('[');
int endBracket = part.IndexOf(']');
if (startBracket > 0 && endBracket > startBracket)
{
string indexStr = part.Substring(
startBracket + 1,
endBracket - startBracket - 1
);
if (int.TryParse(indexStr, out arrayIndex))
{
isArray = true;
part = part.Substring(0, startBracket);
}
}
}
// Get the property/field
PropertyInfo propInfo = currentType.GetProperty(part, flags);
FieldInfo fieldInfo = null;
if (propInfo == null)
{
fieldInfo = currentType.GetField(part, flags);
if (fieldInfo == null)
{
Debug.LogWarning(
$"[SetNestedProperty] Could not find property or field '{part}' on type '{currentType.Name}'"
);
return false;
}
}
// Get the value
currentObject =
propInfo != null
? propInfo.GetValue(currentObject)
: fieldInfo.GetValue(currentObject);
//Need to stop if current property is null
if (currentObject == null)
{
Debug.LogWarning(
$"[SetNestedProperty] Property '{part}' is null, cannot access nested properties."
);
return false;
}
// If this part was an array or list, access the specific index
if (isArray)
{
if (currentObject is Material[])
{
var materials = currentObject as Material[];
if (arrayIndex < 0 || arrayIndex >= materials.Length)
{
Debug.LogWarning(
$"[SetNestedProperty] Material index {arrayIndex} out of range (0-{materials.Length - 1})"
);
return false;
}
currentObject = materials[arrayIndex];
}
else if (currentObject is System.Collections.IList)
{
var list = currentObject as System.Collections.IList;
if (arrayIndex < 0 || arrayIndex >= list.Count)
{
Debug.LogWarning(
$"[SetNestedProperty] Index {arrayIndex} out of range (0-{list.Count - 1})"
);
return false;
}
currentObject = list[arrayIndex];
}
else
{
Debug.LogWarning(
$"[SetNestedProperty] Property '{part}' is not an array or list, cannot access by index."
);
return false;
}
}
currentType = currentObject.GetType();
}
// Set the final property
string finalPart = pathParts[pathParts.Length - 1];
// Special handling for Material properties (shader properties)
if (currentObject is Material material && finalPart.StartsWith("_"))
{
feat: Add `manage_material` tool for dedicated material manipulation (#440) * WIP: Material management tool implementation and tests - Add ManageMaterial tool for creating and modifying materials - Add MaterialOps helper for material property operations - Add comprehensive test suite for material management - Add string parameter parsing support for material properties - Update related tools (ManageGameObject, manage_asset, etc.) - Add test materials and scenes for material testing * refactor: unify material property logic into MaterialOps - Move and logic from to - Update to delegate to - Update to use enhanced for creation and property setting - Add texture path loading support to * Add parameter aliasing support: accept 'name' as alias for 'target' in manage_gameobject modify action * Refactor ManageMaterial and fix code review issues - Fix Python server tools (redundant imports, exception handling, string formatting) - Clean up documentation and error reports - Improve ManageMaterial.cs (overwrite checks, error handling) - Enhance MaterialOps.cs (robustness, logging, dead code removal) - Update tests (assertions, unused imports) - Fix manifest.json relative path - Remove temporary test artifacts and manual setup scripts * Remove test scene * remove extra mat * Remove unnecessary SceneTemplateSettings.json * Remove unnecessary SceneTemplateSettings.json * Fix MaterialOps issues * Fix: Case-insensitive material property lookup and missing HasProperty checks * Rabbit fixes * Improve material ops logging and test coverage * Fix: NormalizePath now handles backslashes correctly using AssetPathUtility * Fix: Address multiple nitpicks (test robustness, shader resolution, HasProperty checks) * Add manage_material tool documentation and fix MaterialOps texture property checks - Add comprehensive ManageMaterial tool documentation to MCPForUnity/README.md - Add manage_material to tools list in README.md and README-zh.md - Fix MaterialOps.cs to check HasProperty before SetTexture calls to prevent Unity warnings - Ensures consistency with other property setters in MaterialOps * Fix ManageMaterial shader reflection for Unity 6 and improve texture logging
2025-12-08 11:39:52 +08:00
return MaterialOps.TrySetShaderProperty(material, finalPart, value, inputSerializer);
}
// For standard properties (not shader specific)
PropertyInfo finalPropInfo = currentType.GetProperty(finalPart, flags);
if (finalPropInfo != null && finalPropInfo.CanWrite)
{
// Use the inputSerializer for conversion
object convertedValue = ConvertJTokenToType(value, finalPropInfo.PropertyType, inputSerializer);
if (convertedValue != null || value.Type == JTokenType.Null)
{
finalPropInfo.SetValue(currentObject, convertedValue);
return true;
}
else
{
Debug.LogWarning($"[SetNestedProperty] Final conversion failed for property '{finalPart}' (Type: {finalPropInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}");
}
}
else
{
FieldInfo finalFieldInfo = currentType.GetField(finalPart, flags);
if (finalFieldInfo != null)
{
// Use the inputSerializer for conversion
object convertedValue = ConvertJTokenToType(value, finalFieldInfo.FieldType, inputSerializer);
if (convertedValue != null || value.Type == JTokenType.Null)
{
finalFieldInfo.SetValue(currentObject, convertedValue);
return true;
}
else
{
Debug.LogWarning($"[SetNestedProperty] Final conversion failed for field '{finalPart}' (Type: {finalFieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}");
}
}
else
{
Debug.LogWarning(
$"[SetNestedProperty] Could not find final writable property or field '{finalPart}' on type '{currentType.Name}'"
);
}
}
}
catch (Exception ex)
{
Debug.LogError(
$"[SetNestedProperty] Error setting nested property '{path}': {ex.Message}\nToken: {value.ToString(Formatting.None)}"
);
}
return false;
}
/// <summary>
/// Split a property path into parts, handling both dot notation and array indexers
/// </summary>
private static string[] SplitPropertyPath(string path)
{
// Handle complex paths with both dots and array indexers
List<string> parts = new List<string>();
int startIndex = 0;
bool inBrackets = false;
for (int i = 0; i < path.Length; i++)
{
char c = path[i];
if (c == '[')
{
inBrackets = true;
}
else if (c == ']')
{
inBrackets = false;
}
else if (c == '.' && !inBrackets)
{
// Found a dot separator outside of brackets
parts.Add(path.Substring(startIndex, i - startIndex));
startIndex = i + 1;
}
}
if (startIndex < path.Length)
{
parts.Add(path.Substring(startIndex));
}
return parts.ToArray();
}
/// <summary>
/// Simple JToken to Type conversion for common Unity types, using JsonSerializer.
/// </summary>
// Pass the input serializer
private static object ConvertJTokenToType(JToken token, Type targetType, JsonSerializer inputSerializer)
{
if (token == null || token.Type == JTokenType.Null)
{
if (targetType.IsValueType && Nullable.GetUnderlyingType(targetType) == null)
{
Debug.LogWarning($"Cannot assign null to non-nullable value type {targetType.Name}. Returning default value.");
return Activator.CreateInstance(targetType);
}
return null;
}
try
{
// Use the provided serializer instance which includes our custom converters
return token.ToObject(targetType, inputSerializer);
}
catch (JsonSerializationException jsonEx)
{
Debug.LogError($"JSON Deserialization Error converting token to {targetType.FullName}: {jsonEx.Message}\nToken: {token.ToString(Formatting.None)}");
// Optionally re-throw or return null/default
// return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
throw; // Re-throw to indicate failure higher up
}
catch (ArgumentException argEx)
{
Debug.LogError($"Argument Error converting token to {targetType.FullName}: {argEx.Message}\nToken: {token.ToString(Formatting.None)}");
throw;
}
catch (Exception ex)
{
Debug.LogError($"Unexpected error converting token to {targetType.FullName}: {ex}\nToken: {token.ToString(Formatting.None)}");
throw;
}
// If ToObject succeeded, it would have returned. If it threw, we wouldn't reach here.
// This fallback logic is likely unreachable if ToObject covers all cases or throws on failure.
// Debug.LogWarning($"Conversion failed for token to {targetType.FullName}. Token: {token.ToString(Formatting.None)}");
// return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
// --- ParseJTokenTo... helpers are likely redundant now with the serializer approach ---
// Keep them temporarily for reference or if specific fallback logic is ever needed.
private static Vector3 ParseJTokenToVector3(JToken token)
{
// ... (implementation - likely replaced by Vector3Converter) ...
// Consider removing these if the serializer handles them reliably.
if (token is JObject obj && obj.ContainsKey("x") && obj.ContainsKey("y") && obj.ContainsKey("z"))
{
return new Vector3(obj["x"].ToObject<float>(), obj["y"].ToObject<float>(), obj["z"].ToObject<float>());
}
if (token is JArray arr && arr.Count >= 3)
{
return new Vector3(arr[0].ToObject<float>(), arr[1].ToObject<float>(), arr[2].ToObject<float>());
}
Debug.LogWarning($"Could not parse JToken '{token}' as Vector3 using fallback. Returning Vector3.zero.");
return Vector3.zero;
}
private static Vector2 ParseJTokenToVector2(JToken token)
{
// ... (implementation - likely replaced by Vector2Converter) ...
if (token is JObject obj && obj.ContainsKey("x") && obj.ContainsKey("y"))
{
return new Vector2(obj["x"].ToObject<float>(), obj["y"].ToObject<float>());
}
if (token is JArray arr && arr.Count >= 2)
{
return new Vector2(arr[0].ToObject<float>(), arr[1].ToObject<float>());
}
Debug.LogWarning($"Could not parse JToken '{token}' as Vector2 using fallback. Returning Vector2.zero.");
return Vector2.zero;
}
private static Quaternion ParseJTokenToQuaternion(JToken token)
{
// ... (implementation - likely replaced by QuaternionConverter) ...
if (token is JObject obj && obj.ContainsKey("x") && obj.ContainsKey("y") && obj.ContainsKey("z") && obj.ContainsKey("w"))
{
return new Quaternion(obj["x"].ToObject<float>(), obj["y"].ToObject<float>(), obj["z"].ToObject<float>(), obj["w"].ToObject<float>());
}
if (token is JArray arr && arr.Count >= 4)
{
return new Quaternion(arr[0].ToObject<float>(), arr[1].ToObject<float>(), arr[2].ToObject<float>(), arr[3].ToObject<float>());
}
Debug.LogWarning($"Could not parse JToken '{token}' as Quaternion using fallback. Returning Quaternion.identity.");
return Quaternion.identity;
}
private static Color ParseJTokenToColor(JToken token)
{
// ... (implementation - likely replaced by ColorConverter) ...
if (token is JObject obj && obj.ContainsKey("r") && obj.ContainsKey("g") && obj.ContainsKey("b") && obj.ContainsKey("a"))
{
return new Color(obj["r"].ToObject<float>(), obj["g"].ToObject<float>(), obj["b"].ToObject<float>(), obj["a"].ToObject<float>());
}
if (token is JArray arr && arr.Count >= 4)
{
return new Color(arr[0].ToObject<float>(), arr[1].ToObject<float>(), arr[2].ToObject<float>(), arr[3].ToObject<float>());
}
Debug.LogWarning($"Could not parse JToken '{token}' as Color using fallback. Returning Color.white.");
return Color.white;
}
private static Rect ParseJTokenToRect(JToken token)
{
// ... (implementation - likely replaced by RectConverter) ...
if (token is JObject obj && obj.ContainsKey("x") && obj.ContainsKey("y") && obj.ContainsKey("width") && obj.ContainsKey("height"))
{
return new Rect(obj["x"].ToObject<float>(), obj["y"].ToObject<float>(), obj["width"].ToObject<float>(), obj["height"].ToObject<float>());
}
if (token is JArray arr && arr.Count >= 4)
{
return new Rect(arr[0].ToObject<float>(), arr[1].ToObject<float>(), arr[2].ToObject<float>(), arr[3].ToObject<float>());
}
Debug.LogWarning($"Could not parse JToken '{token}' as Rect using fallback. Returning Rect.zero.");
return Rect.zero;
}
private static Bounds ParseJTokenToBounds(JToken token)
{
// ... (implementation - likely replaced by BoundsConverter) ...
if (token is JObject obj && obj.ContainsKey("center") && obj.ContainsKey("size"))
{
// Requires Vector3 conversion, which should ideally use the serializer too
Vector3 center = ParseJTokenToVector3(obj["center"]); // Or use obj["center"].ToObject<Vector3>(inputSerializer)
Vector3 size = ParseJTokenToVector3(obj["size"]); // Or use obj["size"].ToObject<Vector3>(inputSerializer)
return new Bounds(center, size);
}
// Array fallback for Bounds is less intuitive, maybe remove?
// if (token is JArray arr && arr.Count >= 6)
// {
// return new Bounds(new Vector3(arr[0].ToObject<float>(), arr[1].ToObject<float>(), arr[2].ToObject<float>()), new Vector3(arr[3].ToObject<float>(), arr[4].ToObject<float>(), arr[5].ToObject<float>()));
// }
Debug.LogWarning($"Could not parse JToken '{token}' as Bounds using fallback. Returning new Bounds(Vector3.zero, Vector3.zero).");
return new Bounds(Vector3.zero, Vector3.zero);
}
// --- End Redundant Parse Helpers ---
/// <summary>
/// Finds a specific UnityEngine.Object based on a find instruction JObject.
/// Primarily used by UnityEngineObjectConverter during deserialization.
/// </summary>
// Made public static so UnityEngineObjectConverter can call it. Moved from ConvertJTokenToType.
public static UnityEngine.Object FindObjectByInstruction(JObject instruction, Type targetType)
{
string findTerm = instruction["find"]?.ToString();
string method = instruction["method"]?.ToString()?.ToLower();
string componentName = instruction["component"]?.ToString(); // Specific component to get
if (string.IsNullOrEmpty(findTerm))
{
Debug.LogWarning("Find instruction missing 'find' term.");
return null;
}
// Use a flexible default search method if none provided
string searchMethodToUse = string.IsNullOrEmpty(method) ? "by_id_or_name_or_path" : method;
// If the target is an asset (Material, Texture, ScriptableObject etc.) try AssetDatabase first
if (typeof(Material).IsAssignableFrom(targetType) ||
typeof(Texture).IsAssignableFrom(targetType) ||
typeof(ScriptableObject).IsAssignableFrom(targetType) ||
targetType.FullName.StartsWith("UnityEngine.U2D") || // Sprites etc.
typeof(AudioClip).IsAssignableFrom(targetType) ||
typeof(AnimationClip).IsAssignableFrom(targetType) ||
typeof(Font).IsAssignableFrom(targetType) ||
typeof(Shader).IsAssignableFrom(targetType) ||
typeof(ComputeShader).IsAssignableFrom(targetType) ||
typeof(GameObject).IsAssignableFrom(targetType) && findTerm.StartsWith("Assets/")) // Prefab check
{
// Try loading directly by path/GUID first
UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(findTerm, targetType);
if (asset != null) return asset;
asset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(findTerm); // Try generic if type specific failed
if (asset != null && targetType.IsAssignableFrom(asset.GetType())) return asset;
// If direct path failed, try finding by name/type using FindAssets
string searchFilter = $"t:{targetType.Name} {System.IO.Path.GetFileNameWithoutExtension(findTerm)}"; // Search by type and name
string[] guids = AssetDatabase.FindAssets(searchFilter);
if (guids.Length == 1)
{
asset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]), targetType);
if (asset != null) return asset;
}
else if (guids.Length > 1)
{
Debug.LogWarning($"[FindObjectByInstruction] Ambiguous asset find: Found {guids.Length} assets matching filter '{searchFilter}'. Provide a full path or unique name.");
// Optionally return the first one? Or null? Returning null is safer.
return null;
}
// If still not found, fall through to scene search (though unlikely for assets)
}
// --- Scene Object Search ---
// Find the GameObject using the internal finder
GameObject foundGo = FindObjectInternal(new JValue(findTerm), searchMethodToUse);
if (foundGo == null)
{
// Don't warn yet, could still be an asset not found above
// Debug.LogWarning($"Could not find GameObject using instruction: {instruction}");
return null;
}
// Now, get the target object/component from the found GameObject
if (targetType == typeof(GameObject))
{
return foundGo; // We were looking for a GameObject
}
else if (typeof(Component).IsAssignableFrom(targetType))
{
Type componentToGetType = targetType;
if (!string.IsNullOrEmpty(componentName))
{
Type specificCompType = FindType(componentName);
if (specificCompType != null && typeof(Component).IsAssignableFrom(specificCompType))
{
componentToGetType = specificCompType;
}
else
{
Debug.LogWarning($"Could not find component type '{componentName}' specified in find instruction. Falling back to target type '{targetType.Name}'.");
}
}
Component foundComp = foundGo.GetComponent(componentToGetType);
if (foundComp == null)
{
Debug.LogWarning($"Found GameObject '{foundGo.name}' but could not find component of type '{componentToGetType.Name}'.");
}
return foundComp;
}
else
{
Debug.LogWarning($"Find instruction handling not implemented for target type: {targetType.Name}");
return null;
}
}
/// <summary>
/// Robust component resolver that avoids Assembly.LoadFrom and works with asmdefs.
/// Searches already-loaded assemblies, prioritizing runtime script assemblies.
/// </summary>
private static Type FindType(string typeName)
{
if (ComponentResolver.TryResolve(typeName, out Type resolvedType, out string error))
{
return resolvedType;
}
// Log the resolver error if type wasn't found
if (!string.IsNullOrEmpty(error))
{
Debug.LogWarning($"[FindType] {error}");
}
return null;
}
}
/// <summary>
/// Robust component resolver that avoids Assembly.LoadFrom and supports assembly definitions.
/// Prioritizes runtime (Player) assemblies over Editor assemblies.
/// </summary>
internal static class ComponentResolver
{
private static readonly Dictionary<string, Type> CacheByFqn = new(StringComparer.Ordinal);
private static readonly Dictionary<string, Type> CacheByName = new(StringComparer.Ordinal);
/// <summary>
/// Resolve a Component/MonoBehaviour type by short or fully-qualified name.
/// Prefers runtime (Player) script assemblies; falls back to Editor assemblies.
/// Never uses Assembly.LoadFrom.
/// </summary>
public static bool TryResolve(string nameOrFullName, out Type type, out string error)
{
error = string.Empty;
type = null!;
// Handle null/empty input
if (string.IsNullOrWhiteSpace(nameOrFullName))
{
error = "Component name cannot be null or empty";
return false;
}
// 1) Exact cache hits
if (CacheByFqn.TryGetValue(nameOrFullName, out type)) return true;
if (!nameOrFullName.Contains(".") && CacheByName.TryGetValue(nameOrFullName, out type)) return true;
type = Type.GetType(nameOrFullName, throwOnError: false);
if (IsValidComponent(type)) { Cache(type); return true; }
// 2) Search loaded assemblies (prefer Player assemblies)
var candidates = FindCandidates(nameOrFullName);
if (candidates.Count == 1) { type = candidates[0]; Cache(type); return true; }
if (candidates.Count > 1) { error = Ambiguity(nameOrFullName, candidates); type = null!; return false; }
#if UNITY_EDITOR
// 3) Last resort: Editor-only TypeCache (fast index)
var tc = TypeCache.GetTypesDerivedFrom<Component>()
.Where(t => NamesMatch(t, nameOrFullName));
candidates = PreferPlayer(tc).ToList();
if (candidates.Count == 1) { type = candidates[0]; Cache(type); return true; }
if (candidates.Count > 1) { error = Ambiguity(nameOrFullName, candidates); type = null!; return false; }
#endif
error = $"Component type '{nameOrFullName}' not found in loaded runtime assemblies. " +
"Use a fully-qualified name (Namespace.TypeName) and ensure the script compiled.";
type = null!;
return false;
}
private static bool NamesMatch(Type t, string q) =>
t.Name.Equals(q, StringComparison.Ordinal) ||
(t.FullName?.Equals(q, StringComparison.Ordinal) ?? false);
private static bool IsValidComponent(Type t) =>
t != null && typeof(Component).IsAssignableFrom(t);
private static void Cache(Type t)
{
if (t.FullName != null) CacheByFqn[t.FullName] = t;
CacheByName[t.Name] = t;
}
private static List<Type> FindCandidates(string query)
{
bool isShort = !query.Contains('.');
var loaded = AppDomain.CurrentDomain.GetAssemblies();
#if UNITY_EDITOR
// Names of Player (runtime) script assemblies (asmdefs + Assembly-CSharp)
var playerAsmNames = new HashSet<string>(
UnityEditor.Compilation.CompilationPipeline.GetAssemblies(UnityEditor.Compilation.AssembliesType.Player).Select(a => a.name),
StringComparer.Ordinal);
IEnumerable<System.Reflection.Assembly> playerAsms = loaded.Where(a => playerAsmNames.Contains(a.GetName().Name));
IEnumerable<System.Reflection.Assembly> editorAsms = loaded.Except(playerAsms);
#else
IEnumerable<System.Reflection.Assembly> playerAsms = loaded;
IEnumerable<System.Reflection.Assembly> editorAsms = Array.Empty<System.Reflection.Assembly>();
#endif
static IEnumerable<Type> SafeGetTypes(System.Reflection.Assembly a)
{
try { return a.GetTypes(); }
catch (ReflectionTypeLoadException rtle) { return rtle.Types.Where(t => t != null)!; }
}
Func<Type, bool> match = isShort
? (t => t.Name.Equals(query, StringComparison.Ordinal))
: (t => t.FullName!.Equals(query, StringComparison.Ordinal));
var fromPlayer = playerAsms.SelectMany(SafeGetTypes)
.Where(IsValidComponent)
.Where(match);
var fromEditor = editorAsms.SelectMany(SafeGetTypes)
.Where(IsValidComponent)
.Where(match);
var list = new List<Type>(fromPlayer);
if (list.Count == 0) list.AddRange(fromEditor);
return list;
}
#if UNITY_EDITOR
private static IEnumerable<Type> PreferPlayer(IEnumerable<Type> seq)
{
var player = new HashSet<string>(
UnityEditor.Compilation.CompilationPipeline.GetAssemblies(UnityEditor.Compilation.AssembliesType.Player).Select(a => a.name),
StringComparer.Ordinal);
return seq.OrderBy(t => player.Contains(t.Assembly.GetName().Name) ? 0 : 1);
}
#endif
private static string Ambiguity(string query, IEnumerable<Type> cands)
{
var lines = cands.Select(t => $"{t.FullName} (assembly {t.Assembly.GetName().Name})");
return $"Multiple component types matched '{query}':\n - " + string.Join("\n - ", lines) +
"\nProvide a fully qualified type name to disambiguate.";
}
/// <summary>
/// Gets all accessible property and field names from a component type.
/// </summary>
public static List<string> GetAllComponentProperties(Type componentType)
{
if (componentType == null) return new List<string>();
var properties = componentType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && p.CanWrite)
.Select(p => p.Name);
var fields = componentType.GetFields(BindingFlags.Public | BindingFlags.Instance)
.Where(f => !f.IsInitOnly && !f.IsLiteral)
.Select(f => f.Name);
// Also include SerializeField private fields (common in Unity)
var serializeFields = componentType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.GetCustomAttribute<SerializeField>() != null)
.Select(f => f.Name);
return properties.Concat(fields).Concat(serializeFields).Distinct().OrderBy(x => x).ToList();
}
/// <summary>
/// Uses AI to suggest the most likely property matches for a user's input.
/// </summary>
public static List<string> GetAIPropertySuggestions(string userInput, List<string> availableProperties)
{
if (string.IsNullOrWhiteSpace(userInput) || !availableProperties.Any())
return new List<string>();
// Simple caching to avoid repeated AI calls for the same input
var cacheKey = $"{userInput.ToLowerInvariant()}:{string.Join(",", availableProperties)}";
if (PropertySuggestionCache.TryGetValue(cacheKey, out var cached))
return cached;
try
{
var prompt = $"A Unity developer is trying to set a component property but used an incorrect name.\n\n" +
$"User requested: \"{userInput}\"\n" +
$"Available properties: [{string.Join(", ", availableProperties)}]\n\n" +
$"Find 1-3 most likely matches considering:\n" +
$"- Unity Inspector display names vs actual field names (e.g., \"Max Reach Distance\" → \"maxReachDistance\")\n" +
$"- camelCase vs PascalCase vs spaces\n" +
$"- Similar meaning/semantics\n" +
$"- Common Unity naming patterns\n\n" +
$"Return ONLY the matching property names, comma-separated, no quotes or explanation.\n" +
$"If confidence is low (<70%), return empty string.\n\n" +
$"Examples:\n" +
$"- \"Max Reach Distance\" → \"maxReachDistance\"\n" +
$"- \"Health Points\" → \"healthPoints, hp\"\n" +
$"- \"Move Speed\" → \"moveSpeed, movementSpeed\"";
// For now, we'll use a simple rule-based approach that mimics AI behavior
// This can be replaced with actual AI calls later
var suggestions = GetRuleBasedSuggestions(userInput, availableProperties);
PropertySuggestionCache[cacheKey] = suggestions;
return suggestions;
}
catch (Exception ex)
{
Debug.LogWarning($"[AI Property Matching] Error getting suggestions for '{userInput}': {ex.Message}");
return new List<string>();
}
}
private static readonly Dictionary<string, List<string>> PropertySuggestionCache = new();
/// <summary>
/// Rule-based suggestions that mimic AI behavior for property matching.
/// This provides immediate value while we could add real AI integration later.
/// </summary>
private static List<string> GetRuleBasedSuggestions(string userInput, List<string> availableProperties)
{
var suggestions = new List<string>();
var cleanedInput = userInput.ToLowerInvariant().Replace(" ", "").Replace("-", "").Replace("_", "");
foreach (var property in availableProperties)
{
var cleanedProperty = property.ToLowerInvariant().Replace(" ", "").Replace("-", "").Replace("_", "");
// Exact match after cleaning
if (cleanedProperty == cleanedInput)
{
suggestions.Add(property);
continue;
}
// Check if property contains all words from input
var inputWords = userInput.ToLowerInvariant().Split(new[] { ' ', '-', '_' }, StringSplitOptions.RemoveEmptyEntries);
if (inputWords.All(word => cleanedProperty.Contains(word.ToLowerInvariant())))
{
suggestions.Add(property);
continue;
}
// Levenshtein distance for close matches
if (LevenshteinDistance(cleanedInput, cleanedProperty) <= Math.Max(2, cleanedInput.Length / 4))
{
suggestions.Add(property);
}
}
// Prioritize exact matches, then by similarity
return suggestions.OrderBy(s => LevenshteinDistance(cleanedInput, s.ToLowerInvariant().Replace(" ", "")))
.Take(3)
.ToList();
}
/// <summary>
/// Calculates Levenshtein distance between two strings for similarity matching.
/// </summary>
private static int LevenshteinDistance(string s1, string s2)
{
if (string.IsNullOrEmpty(s1)) return s2?.Length ?? 0;
if (string.IsNullOrEmpty(s2)) return s1.Length;
var matrix = new int[s1.Length + 1, s2.Length + 1];
for (int i = 0; i <= s1.Length; i++) matrix[i, 0] = i;
for (int j = 0; j <= s2.Length; j++) matrix[0, j] = j;
for (int i = 1; i <= s1.Length; i++)
{
for (int j = 1; j <= s2.Length; j++)
{
int cost = (s2[j - 1] == s1[i - 1]) ? 0 : 1;
matrix[i, j] = Math.Min(Math.Min(
matrix[i - 1, j] + 1, // deletion
matrix[i, j - 1] + 1), // insertion
matrix[i - 1, j - 1] + cost); // substitution
}
}
return matrix[s1.Length, s2.Length];
}
// Removed duplicate ParseVector3 - using the one at line 1114
// Removed GetGameObjectData, GetComponentData, and related private helpers/caching/serializer setup.
// They are now in Helpers.GameObjectSerializer
}
}