Commit Graph

626 Commits (ecb091eb9ef378ed2d72f7333461d535a798d65a)

Author SHA1 Message Date
Marcus Sanatan 06c1dfe2f4
Fix CLI entry point path in pyproject.toml (#407)
Update mcp-for-unity script entry point from "main:main" to "src.main:main" to match the actual module structure after moving main.py into the src directory.
2025-11-28 22:43:00 -04:00
Marcus Sanatan adfc6f5e84
Fix manage prefabs (#405)
* Standardize import ordering and whitespace in plugin

The whitespace gave a warning in the asset store submission

* Fix manage_prefab tool structure

* Fix manage_editor actions

* Add get_component singular to manage_gameobject

* Improve uv cache clear error handling with lock detection and combined output

Replace simple stderr-only error reporting with combined stdout/stderr output. Add detection for "currently in-use" lock errors with helpful hint about waiting or using --force flag. Provide fallback message when command fails with no output.

* Improve error message formatting in uv cache clear failure logging
2025-11-28 18:47:11 -04:00
Marcus Sanatan 2f63405069 Remove automatic version bumping from README files and switch to unversioned git URLs
Unity doesn't update users who install with a fixed version

- Remove sed commands that update version references in README.md and README-zh.md
- Update git add command to exclude README files from version bump commits
- Change README installation URLs from versioned (#v8.1.0) to unversioned (no tag)
- Add documentation showing how to use tagged URLs for users who need fixed versions
2025-11-28 00:16:04 -04:00
GitHub Actions db2f068fc2 chore: bump version to 8.1.0 2025-11-28 02:41:45 +00:00
Marcus Sanatan c50e583300
Add distribution settings for Asset Store vs git defaults (#404)
* Add distribution settings for Asset Store vs git defaults

Introduce McpDistributionSettings ScriptableObject to configure different defaults for Asset Store and git distributions without code forking. Add skipSetupWindowWhenRemoteDefault flag to bypass setup wizard when shipping with hosted MCP URL. Replace hardcoded localhost:8080 defaults with configurable defaultHttpBaseUrl from distribution settings in HttpEndpointUtility and WebSocketTransportClient.

* Improve local address detection in McpDistributionSettings with comprehensive IP range checks

Replace simple string-based localhost/127.0.0.1 checks with robust IsLocalAddress method that validates loopback addresses, private IPv4 ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16), IPv6 link-local and loopback addresses, and .local hostnames using proper URI parsing and IPAddress validation.

* Fix error
2025-11-27 22:10:21 -04:00
Marcus Sanatan bd620e04be
Add CodeBuddy CLI configurator (#403)
Closes #392
2025-11-27 21:17:09 -04:00
Marcus Sanatan 17cd543fab
Fix stdio reloads (#402)
* First pass at MCP client refactor

* Restore original text instructions

Well most of them, I modified a few

* Move configurators to their own folder

It's less clusterd

* Remvoe override for Windsurf because we no longer need to use it

* Add Antigravity configs

Works like Windsurf, but it sucks ass

* Add some docs for properties

* Add comprehensive MCP client configurators documentation

* Add missing imports (#7)

* Handle Linux paths when unregistering CLI commands

* Construct a JSON error in a much more secure fashion

* Fix stdio auto-reconnect after domain reloads

We mirror what we've done with the HTTP/websocket connection

We also ensure the states from the stdio/HTTP connections are handled separately. Things now work as expected

* Fix ActiveMode to return resolved transport mode instead of preferred mode

The ActiveMode property now calls ResolvePreferredMode() to return the actual active transport mode rather than just the preferred mode setting.

* Minor improvements for stdio bridge

- Consolidated the !useHttp && isRunning checks into a single shouldResume flag.
- Wrapped the fire-and-forget StopAsync in a continuation that logs faults (matching the HTTP handler pattern).
- Wrapped StartAsync in a continuation that logs failures and only triggers the health check on success.

* Refactor TransportManager to use switch expressions and improve error handling

- Replace if-else chains with switch expressions for better readability and exhaustiveness checking
- Add GetClient() helper method to centralize client retrieval logic
- Wrap StopAsync in try-catch to log failures when stopping a failed transport
- Use client.TransportName instead of mode.ToString() for consistent naming in error messages
2025-11-27 19:33:26 -04:00
Marcus Sanatan f94cb2460a
Simplify MCP client configs (#401)
* First pass at MCP client refactor

* Restore original text instructions

Well most of them, I modified a few

* Move configurators to their own folder

It's less clusterd

* Remvoe override for Windsurf because we no longer need to use it

* Add Antigravity configs

Works like Windsurf, but it sucks ass

* Add some docs for properties

* Add comprehensive MCP client configurators documentation

* Add missing imports (#7)

* Handle Linux paths when unregistering CLI commands

* Construct a JSON error in a much more secure fashion
2025-11-27 18:18:44 -04:00
GitHub Actions 7b25f7ce3e chore: bump version to 8.0.1 2025-11-26 01:40:55 +00:00
Marcus Sanatan 2f50962b58
Harden PlayMode test runs (#396)
* Harden PlayMode test runs

- Guard against starting tests while already in Play Mode.
- Pre-save dirty scenes before PlayMode runs to avoid SaveModifiedSceneTask failures.
- Temporarily disable domain reload during PlayMode tests to keep the MCP bridge alive; restore settings afterward.
- Avoid runSynchronously because it can freeze Unity

* Handle the not too uncommon case where we have an empty scene
2025-11-25 17:08:33 -04:00
Marcus Sanatan be6c387327
Enable the `rmcp_client` feature so it works with Codex CLI (#395) 2025-11-25 17:08:24 -04:00
GitHub Actions dbe5f33cb0 chore: bump version to 8.0.0 2025-11-25 03:22:14 +00:00
Marcus Sanatan a034ab0b21
HTTP Server, uvx, C# only custom tools (#375)
* Remove temp folder from repo

* Ignore boot.config

* Remove buttons to download or rebuild the server

* Remove embedded MCP server in plugin

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

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

* feat: migrate to uvx-based server configuration

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

* Cleanup the temp folders created by tests

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

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

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

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

* refactor: use dynamic package version instead of hardcoded value

* Update CI so it only updates the Server folder

* feat: implement uvx package source path resolution

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

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

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

* feat: add HTTP transport support and cache management

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

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

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

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

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

* refactor: move MCP menu items under Window menu

* feat: restructure config generation for HTTP transport mode

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

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

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

* fix: remove automatic HTTP protocol prefix from URL field

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

* feat: implement proper MCP session lifecycle with HTTP transport

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

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

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

* feat: improve text wrapping in editor window UI

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

* refactor: refresh git URL override from EditorPrefs on validation

* fix: improve responsive layout for editor window settings

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

* refactor: improve thread safety in tool registration

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

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

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

* refactor: centralize HTTP endpoint URL management

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

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

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

* feat: add dynamic custom tool registration system

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

* feat: add AutoRegister flag to control tool registration

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

* feat: add function signature generation for dynamic tools

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

* refactor: remove unused custom tool registry endpoints

* test: add transport configuration validation for MCP client tests

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

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

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

* feat: use serverUrl property for Windsurf HTTP transport

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

* feat: ensure client configurations stay current on each setup

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

* feat: add automatic migration for legacy embedded server configuration

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

* feat: add automatic stdio config migration on package updates

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

* Centralize where editor prefs are defined

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

* Update custom tools docs

* refactor: consolidate server management UI into main editor window

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

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

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

* Don't double register tools on startup

* feat: switch to HTTP transport as default connection method

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

* Automatically bump the versions in the READMEs.

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

* docs: add HTTP transport configuration examples

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

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

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

* refactor: consolidate Unity instance discovery with shared registry

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

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

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

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

* refactor: simplify port management and improve port field validation

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

* Launch the actual local webserver via the button

* Autoformat

* Minor fixes so the server can start

* Make clear uvx button work

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

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

* We no longer need a Python importer

* This folder has nothing in it

* Cleanup whitespace

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

* We no longer need this folder

* refactor: move MCPForUnityBridge to StdioBridgeHost and reorganize transport layer

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

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

* Fix VS Code configured status in UI

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

* Stop blocking the main thread when connecting via HTTP

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

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

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

* Add a debug log line

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

* Add HTTP bridge auto-resume after domain reload

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

* Add health verification after HTTP bridge auto-resume

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

* Add name and path fields to code coverage settings

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

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

* Convert custom tool handlers to async functions

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

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

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

* Make some clarifications for custom tools in docs

* Use `async_send_with_unity_instance` instead of `send_with_unity_instance`

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

* Fix calls to async_send_with_unity_instance in manage_script

* Rename async_send_with_unity_instance to send_with_unity_instance

* Fix clear uv cache command

Helps a lot with local development

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

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

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

Might as well be able to close the window as well

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

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

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

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

* Update plugin README

* Convert integration tests to async/await pattern

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

* Update image with new UI

* Remove unused HttpTransportClient client

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

* Remove copyright notice

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

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

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

* Organize imports and remove redundant import statements

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

* Minor edits

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

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

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

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

* Make the server work in Docker

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

* Cache project identity on initialization to avoid repeated computation

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

* Fix typos

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

* Remove Foldout UI elements and simplify HTTP server command section

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

* Reduce height of HTTP command box

* Refresh HTTP server command display when Git URL override changes

* Make the box a bit smaller

* Split up main window into various components

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

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

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

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

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

* Detect Codex configuration when using HTTP or stdio configs

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

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

* Fix and add tests for building configs

* Handle Unity reload gaps by retrying plugin session resolution

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

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

* Polish domain reload resilience tests and docs

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

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

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

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

* Update guide on what's changed in v8

Lots of feedback, lots of changes

* Update custom tool docs to use new response objects

* Update image used in README

Slightly more up to date but not final

* Restructure backend

Just make it more organized, like typical Python projects

* Remove server_version.txt

* Feature/http instance routing (#5)

* Fix HTTP instance routing and per-project session IDs

* Drop confusing log message

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

* Fix test imports

* Update refs in docs

---------

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

* Generate the session ID from the server

We also make the identifying hashes longer

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

OK, this is outright the best OSS Unity MCP available

* Fix tests caused by changes in session management

* Whitespace update

* Exclude stale builds so users always get the latest version

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

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

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

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

* Replace Dict type hints with modern dict syntax throughout codebase

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

* Remove unused type imports across codebase

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

* Remove the old telemetry test

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

* Clean up stupid imports

No AI slop here lol

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

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

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

No AI slop here!

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

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

* Register custom tools via websockets

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

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

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

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

* Whitespace

* Move import of get_unity_instance_from_context to module level in unity_transport

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

* Remove the tool that reads resources

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

* We have buttons for starting and stopping local servers

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

* Consolidate cache management into ServerManagementService and remove standalone CacheManagementService

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

* Update MCPForUnity/Editor/Helpers/ProjectIdentityUtility.cs

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

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

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

* Cancel existing background loops before starting a new connection

Nice bug found from CodeRabbit

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

* Some better error handling when stopping a server

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

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

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

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

* Minor fixes

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

* Rename functions that capitalized "UV"

* Ensure WebSocket transport is properly stopped before disposing shared resources

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

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

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

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

* Consolidate some of the update/refresh logic

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

* Add error dialog when Unity socket port persistence fails

* Rename WebSocketSessionId to SessionId in EditorPrefKeys

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

* No need to send session ID in pong payload

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

* Remove unused function

* Remove the unused verifyPath argument

* Simplify server management logic

* Remove unused `GetUvxCommand()` function

We construct it in parts now

* Remove `IsUvxDetected()`

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

* Add input validation and improve shell escaping in CreateTerminalProcessStartInfo

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

* Update technical changes guide

* Add custom_tools resource and execute_custom_tool to README documentation

* Update v8 docs

* Update docs UI image

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

* Fix backend tests

---------

Co-authored-by: David Sarno <david@lighthaus.us>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-11-24 23:21:06 -04:00
Shutong Wu edd7817d40
[CUSTOM TOOLS] Roslyn Runtime Compilation Feature (#371)
* Update .Bat file and Bug fix on ManageScript

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

* Further changes

String to Int for consistency

* [Custom Tool] Roslyn Runtime Compilation

Allows users to generate/compile codes during Playmode

* Fix based on CR
2025-11-10 09:38:38 -05:00
GitHub Actions 14b11ba073 chore: bump version to 7.0.0 2025-11-05 20:38:45 +00:00
Marcus Sanatan 9b809f5363 Manually bump the server to v7
We're still testing the uvx configuration. By updating the version beforehand, when we test with uvx on v7.0.0 - it should work.

Ideally by the next PR this will be out.
2025-11-05 16:12:54 -04:00
Marcus Sanatan 2619644a3b Update mirror backend with latest code 2025-11-05 16:08:59 -04:00
Marcus Sanatan 2649d9c379
Move Get commands to editor resources + Run Python tests every update (#368)
* Add a function to reload the domain

Closes #357

* feat: restructure server instructions into workflow-focused format

- Reorganized instructions from flat bullet list into categorized workflow sections
- Emphasized critical script management workflow with numbered steps
- Improved readability and scannability for AI agents using the MCP server

It doesn't make sense to repeat the fucnction tools, they're already parsed

* docs: reorder tool list alphabetically in README + add reload_domain tool

* feat: add Unity editor state and project info resources

- Implemented resources for querying active tool, editor state, prefab stage, selection, and open windows
- Added project configuration resources for layers and project metadata
- Organized new resources into Editor and Project namespaces for better structure

* feat: clarify script management workflow in system prompt

- Expanded guidance to include scripts created by any tool, not just manage_script
- Added "etc" to tools examples for better clarity

* refactor: remove reload_domain tool and update script management workflow

- Removed reload_domain tool as Unity automatically recompiles scripts when modified
- Updated script management instructions to rely on editor_state polling and console checking instead of manual domain reload
- Simplified workflow by removing unnecessary manual recompilation step

* Change name of menu items resource as the LLM seems it

* refactor: reorganize tests into src/tests/integration directory

- Moved all test files from root tests/ to MCPForUnity/UnityMcpServer~/src/tests/integration/ for better organization
- Added conftest.py with telemetry and dependency stubs to simplify test setup
- Removed redundant path manipulation and module loading code from individual test files

* feat: expand Unity test workflow triggers

- Run tests on all branches instead of only main
- Add pull request trigger to catch issues before merge
- Maintain path filtering to run only when relevant files change

* chore: add GitHub Actions workflow for Python tests

- Configured automated testing on push and pull requests using pytest
- Set up uv for dependency management and Python 3.10 environment
- Added test results artifact upload for debugging failed runs

* refactor: update import path for fastmcp Context

* docs: update development setup instructions to use uv

- Changed installation commands from pip to uv pip for better dependency management
- Updated test running instructions to use uv run pytest
- Added examples for running integration and unit tests separately

* Formatting [skip ci]

* refactor: optimize CI workflow with path filters and dependency installation

- Added path filters to only trigger tests when Python source or workflow files change
- Split dependency installation into sync and dev install steps for better clarity
- Fixed YAML indentation for improved readability

* Update .github/workflows/python-tests.yml

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

* fix: standardize test mode values to match Unity's naming convention

- Changed default mode from "edit" to "EditMode" in C# code
- Updated Python tool to use "EditMode" and "PlayMode" instead of lowercase variants

* refactor: convert test imports to relative imports

- Changed absolute imports to relative imports in integration tests for better package structure
- Removed test packages from pyproject.toml package list

* refactor: use Field with default_factory for mutable default in TagsResponse

* refactor: remove duplicate PrefabStageUtility call

* Update this as well [skip ci]

* Update MCPForUnity/UnityMcpServer~/src/tests/integration/test_script_tools.py

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

* chore: remove pull_request triggers from test workflows [skip ci]

It's already covered by pushes

* refactor: update resource function return types to include MCPResponse union

* refactor: remove manual domain reload tool

- Removed reload_domain tool as Unity handles script recompilation automatically
- Updated documentation to reflect automatic compilation workflow
- Simplified script management workflow instructions in server description

* refactor: add context support to resource handlers

- Updated all resource handlers to accept Context parameter for Unity instance routing
- Replaced direct async_send_command_with_retry calls with async_send_with_unity_instance wrapper
- Added imports for get_unity_instance_from_context and async_send_with_unity_instance helpers

* fix: correct grammar in menu items documentation

* docs: update README with expanded tools and resources documentation

- Added new tools: manage_prefabs, create_script, delete_script, get_sha
- Added new resources: editor state, windows, project info, layers, and tags
- Clarified manage_script as compatibility router with recommendation to use newer edit tools
- Fixed run_test to run_tests for consistency

* refactor: convert unity_instances function to async [skip ci]

- Changed function signature from synchronous to async
- Added await keywords to ctx.info() and ctx.error() calls to properly handle async context methods

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-11-05 16:06:48 -04:00
dsarno f667582505
Feature/session based instance routing (#369)
* Add support for multiple Unity instances

* fix port detection

* add missing unity_instance parameter

* add instance params for resources

* Fix CodeRabbit review feedback

- Fix partial framed response handling in port discovery
  Add _recv_exact() helper to ensure complete frame reading
  Prevents healthy Unity instances from being misidentified as offline

- Remove unused default_conn variables in server.py (2 files)
  Fixes Ruff F841 lint error that would block CI/CD

- Preserve sync/async nature of resources in wrapper
  Check if original function is coroutine before wrapping
  Prevents 'dict object is not awaitable' runtime errors

- Fix reconnection to preserve instance_id
  Add instance_id tracking to UnityConnection dataclass
  Reconnection now targets the same Unity instance instead of any available one
  Prevents operations from being applied to wrong project

- Add instance logging to manage_asset for debugging
  Helps troubleshoot multi-instance scenarios

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>

* Fix CodeRabbit feedback: reconnection fallback and annotations safety

Address 3 CodeRabbit review comments:

1. Critical: Guard reconnection fallback to prevent wrong instance routing
   - When instance_id is set but rediscovery fails, now raises ConnectionError
   - Added 'from e' to preserve exception chain for better debugging
   - Prevents silently connecting to different Unity instance
   - Ensures multi-instance routing integrity

2. Minor: Guard __annotations__ access in resource registration
   - Use getattr(func, '__annotations__', {}) instead of direct access
   - Prevents AttributeError for functions without type hints

3. Minor: Remove unused get_type_hints import
   - Clean up unused import in resources/__init__.py

All changes applied to both Server/ and MCPForUnity/ directories.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* Fix instance sorting and logging issues

- Fix sorting logic for instances without heartbeat data: use epoch timestamp instead of current time to properly deprioritize instances with None last_heartbeat
- Use logger.exception() instead of logger.error() in disconnect_all() to include stack traces for better debugging

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* update uv.lock to prepare for merging into main

* Restore Python 3.10 lockfiles and package list_unity_instances tool

* Deduplicate Unity instance discovery by port

* Scope status-file reload checks to the active instance

* refactor: implement FastMCP middleware for session-based instance routing

Replaces module-level session_state.py with UnityInstanceMiddleware class
that follows FastMCP best practices. Middleware intercepts all tool calls
via on_call_tool hook and injects active Unity instance into request state.

Key changes:
- Add UnityInstanceMiddleware class with on_call_tool hook
- Tools now use ctx.get_state("unity_instance") instead of direct session_state calls
- Remove unity_instance parameter from all tool schemas to prevent LLM hallucination
- Convert list_unity_instances tool to unity_instances resource (read-only data)
- Update error messages to reference unity://instances resource
- Add set_state/get_state methods to DummyContext test helper
- All 67 tests passing (55 passed, 5 skipped, 7 xpassed)

Architecture benefits:
- Centralized session management in middleware
- Standard FastMCP patterns (middleware + request state)
- Cleaner separation of concerns
- Prevents AI hallucination of invalid instance IDs

* fix: convert resource templates to static resources for discoverability

Convert MCP resources from URI templates with query parameters to static
resources to fix discoverability in MCP clients like Claude Code.

Changes:
- Remove {?force_refresh} from unity://instances
- Remove {?unity_instance} from mcpforunity://menu-items
- Remove {?unity_instance} from mcpforunity://tests
- Keep {mode} path parameter in mcpforunity://tests/{mode} (legitimate)

Root cause: Query parameters {?param} trigger ResourceTemplate registration,
which are listed via resources/templates/list instead of resources/list.
Claude Code's ListMcpResourcesTool only queries resources/list, making
templates undiscoverable.

Solution: Remove optional query parameters from URIs. Instance routing is
handled by middleware/context, and force_refresh was cache control that
doesn't belong in resource identity.

Impact: Resources now discoverable via standard resources/list endpoint and
work with all MCP clients including Claude Code and Cursor.

Requires FastMCP >=2.13.0 for proper RFC 6570 query parameter support.

* feat: improve material properties and sync Server resources

Material Property Improvements (ManageAsset.cs):
- Add GetMainColorPropertyName() helper that auto-detects shader color properties
- Tries _BaseColor (URP), _Color (Standard), _MainColor, _Tint, _TintColor
- Update both named and array color property handling to use auto-detection
- Add warning messages when color properties don't exist on materials
- Split HasProperty check from SetColor to enable error reporting

This fixes the issue where simple color array format [r,g,b,a] defaulted to
_Color property, causing silent failures with URP Lit shader which uses _BaseColor.

Server Resource Sync:
- Sync Server/resources with MCPForUnity/UnityMcpServer~/src/resources
- Remove query parameters from resource URIs for discoverability
- Use session-based instance routing via get_unity_instance_from_context()

* fix: repair instance routing and simplify get_unity_instance_from_context

PROBLEM:
Instance routing was failing - scripts went to wrong Unity instances.
Script1 (intended: ramble) -> went to UnityMCPTests 
Script2 (intended: UnityMCPTests) -> went to ramble 

ROOT CAUSE:
Two incompatible approaches for accessing active instance:
1. Middleware: ctx.set_state() / ctx.get_state() - used by most tools
2. Legacy: ctx.request_context.meta - used by script tools
Script tools were reading from wrong location, middleware had no effect.

FIX:
1. Updated get_unity_instance_from_context() to read from ctx.get_state()
2. Removed legacy request_context.meta code path (98 lines removed)
3. Single source of truth: middleware state only

TESTING:
- Added comprehensive test suite (21 tests) covering all scenarios
- Tests middleware state management, session isolation, race conditions
- Tests reproduce exact 4-script failure scenario
- All 88 tests pass (76 passed + 5 skipped + 7 xpassed)
- Verified fix with live 4-script test: 100% success rate

Files changed:
- Server/tools/__init__.py: Simplified from 75 lines to 15 lines
- MCPForUnity/UnityMcpServer~/src/tools/__init__.py: Same simplification
- tests/test_instance_routing_comprehensive.py: New comprehensive test suite

* refactor: standardize instance extraction and remove dead imports

- Standardize all 18 tools to use get_unity_instance_from_context() helper
  instead of direct ctx.get_state() calls for consistency
- Remove dead session_state imports from with_unity_instance decorator
  that would cause ModuleNotFoundError at runtime
- Update README.md with concise instance routing documentation

* fix: critical timezone and import bugs from code review

- Remove incorrect port safety check that treated reclaimed ports as errors
  (GetPortWithFallback may legitimately return same port if it became available)
- Fix timezone-aware vs naive datetime mixing in unity_connection.py sorting
  (use timestamp() for comparison to avoid TypeError)
- Normalize all datetime comparisons in port_discovery.py to UTC
  (file_mtime and last_heartbeat now consistently timezone-aware)
- Add missing send_with_unity_instance import in Server/tools/manage_script.py
  (was causing NameError at runtime on lines 108 and 488)

All 88 tests pass (76 passed + 5 skipped + 7 xpassed)

---------

Co-authored-by: Sakura <sakurachan@qq.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-11-05 09:43:36 -08:00
Marcus Sanatan 5e4b554e70
It's time to let go, all dev for the plugin happens in MCPForUnity (#365) 2025-11-03 15:58:00 -04:00
dsarno e4904ad0d7
Revert "Server: Robust shutdown on stdio detach (signals, stdin/parent monitor, forced exit) (#363)" (#364)
This reverts commit ca01fc7610.
2025-11-01 09:17:04 -07:00
dsarno ca01fc7610
Server: Robust shutdown on stdio detach (signals, stdin/parent monitor, forced exit) (#363)
* Server: robust shutdown on stdio detach (signals, stdin/parent monitor, forced exit)\nTests: move telemetry tests to tests/ and convert to asserts

* Server: simplify _force_exit to os._exit; guard exit timers to avoid duplicates; fix Windows ValueError in parent monitor; tests: add autouse cwd fixture for telemetry to locate pyproject.toml

* Server: add DEBUG logs for transient stdin checks and monitor thread errors

* Mirror shutdown improvements: signal handlers, stdin/parent monitor, guarded exit timers, and os._exit force-exit in UnityMcpServer~ entry points
2025-10-31 21:38:24 -07:00
Marcus Sanatan 040eb6d701
feat: lower minimum Python requirement to 3.10+ (#362)
* feat: lower minimum Python requirement to 3.10+

- Updated Python version requirement from 3.11+ to 3.10+ across all platform detectors
- Added Python 3.10 to MacOS framework search paths for broader compatibility
- Modified version validation logic to accept Python 3.10 or higher
- Updated documentation and error messages to reflect new minimum Python version
- Changed pyproject.toml requires-python field to ">=3.10"
- Updated badges and requirements in README files to show Python 3.10 support

* feat: add Python 3.10 and 3.11 to Windows path detection

- Added Python 3.10 installation path to LocalApplicationData search locations
- Added Python 3.10 and 3.11 paths to ProgramFiles search locations
- Expanded Python version compatibility to support older installations while maintaining support for newer versions

* feat: add Python 3.14 support and update path detection

- Added Python 3.14 installation paths to Windows and macOS platform detectors
- Removed legacy Python 3.9 paths from Windows path detection
- Updated Windows installation recommendations to suggest Python 3.10 or higher
- Added additional Python framework paths (3.10, 3.11) for macOS UV package manager detection
- Extended UV executable path detection to include Python 3.14 locations on both platforms

* Reduce size of README img

* Revert "Reduce size of README img"

This reverts commit 6fb99c7047bdef3610fb94dd3741c71c9e3ffcc1.

* Adjust size in README to maintain quality but be smaller
2025-10-31 15:44:10 -04:00
Shutong Wu 8f227ff5be
Update .Bat file and Bug fix on ManageScript (#355)
* Update .Bat file and Bug fix on ManageScript

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

* Further changes

String to Int for consistency
2025-10-25 12:27:07 -04:00
Marcus Sanatan 0f506e4bee
Copy the MCP server to the top level (#354)
I want to experiment with using `uvx` from this location, and if it manages all the use cases correctly, we won't clone and copy the server code
2025-10-25 00:53:53 -04:00
dsarno 697e0fb69b
tests(editmode): pre-create texture asset in texture assignment test for CI stability (#352) 2025-10-24 11:57:18 -07:00
dsarno faf9affc36
fix: JSON material property handling + tests (manage_asset) #90 (#349)
* feat: add JSON property handling for materials; add tests for JSON coercion and end-to-end; update test project manifest and ProjectVersion

* fix(manage_asset): support structured texture blocks case-insensitively; resolve _BaseMap/_MainTex automatically and apply when missing name

* Update MCPForUnity/Editor/Tools/ManageAsset.cs

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* refactor(manage_asset): remove goto; reuse alias resolver for structured texture (supports 'albedo'); tests: self-sufficient texture asset and _BaseColor/_Color guards; python: assert success in invalid JSON case

* chore(manage_asset): remove duplicate return in modify case

* tests: fix mocks/patching for manage_asset/manage_gameobject; make invalid-json case tolerant; ensure prefab modify test patches transport correctly

* ci: allow manual dispatch for Unity EditMode tests (workflow_dispatch)

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2025-10-24 11:43:26 -07:00
GitHub Actions 4643802a16 chore: bump version to 6.3.0 2025-10-24 15:52:57 +00:00
Jos van der Westhuizen dbda5ea46e
server instruction cleanup (#345)
* clean up unused prompt and add server instructions

* simplify claude code instructions with global installation
2025-10-24 01:01:26 -04:00
Marcus Sanatan bbf6cacfe2
Remove old UI and do lots of cleanup (#340)
* Remove legacy UI and correct priority ordering of menu items

* Remove old UI screen

Users now have the new UI alone, less confusing and more predictable

* Remove unused config files

* Remove test for window that doesn't exist

* Remove unused code

* Remove dangling .meta file

* refactor: remove client configuration step from setup wizard

* refactor: remove menu item attributes and manual window actions from Python tool sync

* feat: update minimum Python version requirement from 3.10 to 3.11

The docs have 3.12. However, feature wise it seems that 3.11 is required

* fix: replace emoji warning symbol with unicode character in setup wizard dialogs

* docs: reorganize images into docs/images directory and update references

* docs: add UI preview image to README

* docs: add run_test function and resources section to available tools list

The recent changes should close #311

* fix: add SystemRoot env var to Windows config to support Python path resolution

Closes #315

* refactor: consolidate package installation and detection into unified lifecycle manager

Duplicate code for pretty much no reason, as they both initialized there was a small chance of a race condition as well. Consolidating made sense here

* Doc fixes from CodeRabbit

* Excellent bug catch from CodeRabbit

* fix: preserve existing environment variables when updating codex server config

* Update docs so the paths match the original name

* style: fix list indentation in README-DEV.md development docs

* refactor: simplify env table handling in CodexConfigHelper by removing preservation logic

* refactor: simplify configuration logic by removing redundant change detection

Always overwrite configs

* feat: ensure config directory exists before writing config files

* feat: persist server installation errors and show retry UI instead of auto-marking as handled

* refactor: consolidate configuration helpers by merging McpConfigFileHelper into McpConfigurationHelper

* Small fixes from CodeRabbit

* Remove test because we overwrite Codex configs

* Remove unused function

* feat: improve server cleanup and process handling on Windows

- Added DeleteDirectoryWithRetry helper to handle Windows file locking with retries and readonly attribute clearing
- Implemented KillWindowsUvProcesses to safely terminate Python processes in virtual environments using WMIC
- Extended TryKillUvForPath to work on Windows, preventing file handle locks during server deletion
- Improved error messages to be more descriptive about file locking issues
- Replaced direct Directory.Delete calls with

* fix: improve TCP socket cleanup to prevent CLOSE_WAIT states

- Added proper socket shutdown sequence using Socket.Shutdown() before closing connections
- Enhanced error handling with specific catches for SocketException vs general exceptions
- Added debug logging for socket shutdown errors to help diagnose connection issues
- Restructured HandleClientAsync to ensure socket cleanup happens in the correct order
- Implemented proper socket teardown in both client handling and connection cleanup paths
2025-10-24 00:50:29 -04:00
David Sarno 9796f8eda9 fix: add missing JsonUtil.cs.meta file to resolve package import errors 2025-10-23 19:42:58 -07:00
David Sarno 15952d11a8 fix: specify MCPForUnity subdirectory in GitHub URL for package resolution 2025-10-23 19:40:40 -07:00
David Sarno 04bf2bd19d fix: update manifest.json to use GitHub repo instead of local path for CI compatibility 2025-10-23 19:12:28 -07:00
GitHub Actions 4e6577cbd5 chore: bump version to 6.2.5 2025-10-24 01:44:16 +00:00
dsarno 075d68dba3
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-23 18:25:29 -07:00
dsarno a0287afbbc
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-23 17:57:27 -07:00
dsarno 15bf79391f
Fix port discovery protocol mismatch (#341)
- 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
2025-10-23 16:51:58 -07:00
GitHub Actions 26eafbfe11 chore: bump version to 6.2.4 2025-10-23 01:43:22 +00:00
dsarno c866e0625b
Harden MCP tool parameter handling to eliminate “invalid param” errors (#339)
* feat: migrate to FastMCP 2.0 (v2.12.5)

- Update pyproject.toml to use fastmcp>=2.12.5 instead of mcp[cli]
- Replace all imports from mcp.server.fastmcp to fastmcp
- Maintain MCP protocol compliance with mcp>=1.16.0
- All 15 files updated with new import statements
- Server and tools registration working with FastMCP 2.0

* chore: bump MCP for Unity to 6.2.2 and widen numeric tool params (asset search/read_resource/run_tests) for better LLM compatibility

* chore: bump installed server_version.txt to 6.2.2 so Unity installer logs correct version

* fix(parameters): apply parameter hardening to read_console, manage_editor, and manage_gameobject

- read_console: accept int|str for count parameter with coercion
- manage_editor: accept bool|str for wait_for_completion with coercion
- manage_gameobject: accept bool|str for all boolean parameters with coercion
- All tools now handle string parameters gracefully and convert to proper types internally

* chore(deps): drop fastmcp, use mcp>=1.18.0; update imports to mcp.server.fastmcp

* chore(deps): re-add fastmcp>=2.12.5, relax mcp to >=1.16.0

Adds fastmcp as explicit dependency for FastMCP 2.0 migration.
Relaxes mcp version constraint to support broader compatibility.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* test: remove obsolete mcp stubs for FastMCP 2.0 compatibility

Removes stub mcp modules from test files that were conflicting with
the real mcp and fastmcp packages now installed as dependencies.
Adds tests/__init__.py to make tests a proper Python package.

This fixes test collection errors after migrating to FastMCP 2.0.

Test results: 40 passed, 7 xpassed, 5 skipped, 1 failed (pre-existing)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* fix: complete FastMCP 2.0 migration with correct import paths

Updates all remaining files to use `from fastmcp import` instead of
the old `from mcp.server.fastmcp import` path.

Changes:
- server.py: Update FastMCP import
- tools/__init__.py: Update FastMCP import
- resources/__init__.py: Update FastMCP import
- tools/manage_script.py, read_console.py, resource_tools.py: Update imports
- test stubs: Update to stub `fastmcp` instead of `mcp.server.fastmcp`

Addresses PR review feedback about incomplete migration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* fix: harden parameter type handling and resolve PR feedback

Parameter Type Improvements:
- Broaden count in read_console.py to accept int | str
- Broaden build_index in manage_scene.py to accept int | str
- Harden vector parsing in manage_gameobject.py with NaN/Inf checks
- Add whitespace-delimited vector support (e.g., "1 2 3")
- Narrow exception handling from Exception to (ValueError, TypeError)

Test Improvements:
- Harden _load_module in test files with spec/loader validation
- Fix test_manage_gameobject_boolean_and_tag_mapping by mapping tag→search_term

Bug Fixes:
- Fix syntax error in manage_shader.py (remove stray 'x')

Version: Bump to 6.2.3

All tests pass: 41 passed, 5 skipped, 7 xpassed

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-22 18:42:46 -07:00
Marcus Sanatan 9ccf70bd7b
Update logo, use it locally (#338) 2025-10-22 18:54:29 -04:00
Bilal ARIKAN d4214cefa7
Update to support Trae (#337) 2025-10-22 17:38:20 -04:00
Marcus Sanatan 558f9232d3
Allow the MCP server to be run by `uvx` remotely (#336)
* feat: add entry point script and additional Python modules to server package

Now we can run this server with `uvx`

* refactor: improve package version detection to support both installed and development environments

* refactor: simplify release workflow by removing server packaging step
2025-10-22 17:36:24 -04:00
dsarno e3e5485d39
Fix/replace pytest anyio with pytest asyncio (#333)
* mcp_source.py: use MCPForUnity path and show branch in options

* dev(deps): replace pytest-anyio (stub) with pytest-asyncio for tests
2025-10-21 13:56:59 -07:00
dsarno 0397887204
test: Consolidate pytest suite to MCPForUnity and improve test infrastructure (#332)
* Update github-repo-stats.yml

* pytest: make harness MCPForUnity-only; remove UnityMcpBridge paths from tests; route tools.manage_script via unity_connection for reliable monkeypatching; fix ctx usage; all tests green (39 pass, 5 skip, 7 xpass)

* Add missing meta for MaterialMeshInstantiationTests.cs (Assets)

* bridge/tools/manage_script: fix missing unity_connection prefix in validate_script; tests: tidy manage_script_uri unused symbols and arg names

* tests: rename to script_apply_edits_module; extract DummyContext to tests/test_helpers and import; add telemetry stubs in tests to avoid pyproject I/O

* tests: import cleanup and helper extraction; telemetry: prefer plain config and opt-in env override; test stubs and CWD fixes; exclude Bridge from pytest discovery

* chore: remove unintended .wt-origin-main gitlink and ignore folder

* tests: nit fixes (unused-arg stubs, import order, path-normalized ignore hook); telemetry: validate config endpoint; read_console: action optional

* Add development dependencies to pyproject.toml

- Add [project.optional-dependencies] section with dev group
- Include pytest>=8.0.0 and pytest-anyio>=0.6.0
- Add Development Setup section to README-DEV.md with installation and testing instructions

* Revert "Update github-repo-stats.yml"

This reverts commit 8ae595d2f4f2525b0e44ece948883ea37138add4.

* test: improve test clarity and modernize asyncio usage

- Add explanation for 200ms timeout in backpressure test
- Replace manual event loop creation with asyncio.run()
- Add assertion message with actual elapsed time for easier debugging

* refactor: remove duplicate DummyContext definitions across test files

Replace 7 duplicate DummyContext class definitions with imports from tests.test_helpers.
This follows DRY principles and ensures consistency across the test suite.

* chore: remove unused _load function from test_edit_strict_and_warnings.py

Dead code cleanup - function was no longer used after refactoring to dynamic tool registration.

* docs: add comment explaining CWD manipulation in telemetry test

Clarify why os.chdir() is necessary: telemetry.py calls get_package_version()
at module load time, which reads pyproject.toml using a relative path.
Acknowledges the fragility while explaining why it's currently required.
2025-10-21 10:42:55 -07:00
GitHub Actions a81e130a6b chore: bump version to 6.2.1 2025-10-21 16:30:17 +00:00
dsarno f4d62e4da0
Fix material mesh instantiation warnings (#331)
* Editor: prevent material/mesh instantiation in edit mode

- GameObjectSerializer: in edit mode, normalize material/mesh access
  - material -> sharedMaterial
  - materials -> sharedMaterials
  - mesh -> sharedMesh
  - also guard materials/sharedMaterial/sharedMaterials property names
- Tests: add strong instanceID equality checks for Renderer/MeshFilter
  - prove no instantiation by shared instanceID before/after
  - cover multi-material, null cases; prune brittle presence/console tests
- Clean up and relax ManageGameObject tests to avoid false negatives

* Address review: simplify edit-mode guard; include protected/internal [SerializeField]; fix tests to destroy temp primitives and use dictionary access; strengthen instanceID assertions

* Fix resource leaks in test files

- ManageGameObjectTests.cs: Destroy temporary primitive GameObject after extracting sharedMesh
- MaterialMeshInstantiationTests.cs: Destroy instantiated uniqueMesh after test completion

These fixes prevent resource leaks in Unity test files by properly cleaning up temporary objects created during tests.

* Fix reflection bug in GetComponentData tests

- Replace incorrect reflection-based field access with proper dictionary key access
- GetComponentData() returns Dictionary<string, object> where 'properties' is a key, not a field
- Tests now properly access the properties dictionary and run assertions
- Fixes ineffective tests that were silently failing due to reflection returning null
2025-10-20 18:34:33 -07:00
Shutong Wu be7ade8020 Merge branch 'main' of https://github.com/CoplayDev/unity-mcp 2025-10-19 23:12:11 -04:00
Shutong Wu 15c35ae174 Update certain file GUIDs to prevent conflict
Resolve Issue#330 by replacing AI-generated guids with random generated.
2025-10-19 23:09:38 -04:00
GitHub Actions fdf8482323 chore: bump version to 6.2.0 2025-10-19 00:47:51 +00:00
Marcus Sanatan 673456b701
Notify users when there's a new version (#329)
* feat: add package update service with version check and GitHub integration

* feat: add migration warning banner and dialog for legacy package users

* test: remove redundant cache expiration and clearing tests from PackageUpdateService

* test: add package update service tests for expired cache and asset store installations
2025-10-18 20:42:18 -04:00