Commit Graph

549 Commits (2a1e56a5eeab7d8875741503019ba5d8e79a74fe)

Author SHA1 Message Date
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
Marcus Sanatan 350337813b
refactor: use Tommy TOML library directly for config file manipulation (#328)
Before discovering the Tommy library I tried to parse TOML files directly. Some of the methods lingered from that time, which were messing up configuration on Windows.

Now we use Tommy more, it should work. Also consolidated some code with fresh eyes

Closes #311
2025-10-18 13:08:41 -04:00
Marcus Sanatan dbdaa76d75
test: remove unused tests for stale file cleanup in Python tools syncing (#327) 2025-10-18 00:56:57 -04:00
Marcus Sanatan 85cc93f33c
Allow users to easily add tools in the Asset folder (#324)
* Fix issue #308: Find py files in MCPForUnityTools and version.txt

This allows for auto finding new tools. A good dir on a custom tool would look like this:
CustomTool/
├── CustomTool.MCPEnabler.asmdef
├── CustomTool.MCPEnabler.asmdef.meta
├── ExternalAssetToolFunction.cs
├── ExternalAssetToolFunction.cs.meta
├── external_asset_tool_function.py
├── external_asset_tool_function.py.meta
├── version.txt
└── version.txt.meta

CS files are left in the tools folder. The asmdef is recommended to allow for dependency on MCPForUnity when MCP For Unity is installed:

asmdef example
{
    "name": "CustomTool.MCPEnabler",
    "rootNamespace": "MCPForUnity.Editor.Tools",
    "references": [
        "CustomTool",
        "MCPForUnity.Editor"
    ],
    "includePlatforms": [
        "Editor"
    ],
    "excludePlatforms": [],
    "allowUnsafeCode": false,
    "overrideReferences": false,
    "precompiledReferences": [],
    "autoReferenced": true,
    "defineConstraints": [],
    "versionDefines": [],
    "noEngineReferences": false
}

* Follow-up: address CodeRabbit feedback for #308 (<GetToolsFolderIdentifier was duplicated>)

* Follow-up: address CodeRabbit feedback for #308 – centralize GetToolsFolderIdentifier, fix tools copy dir, and limit scan scope

* Fixing so the MCP don't removes _skipDirs e.g. __pycache__

* skip empty folders with no py files

* Rabbit: "Fix identifier collision between different package roots."

* Update MCPForUnity/Editor/Helpers/ServerInstaller.cs

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

* Rabbbit: Cleanup may delete server’s built-in tool subfolders — restrict to managed names.

* Fixed minor + missed onadding rabit change

* Revert "Fixed minor + missed onadding rabit change"

This reverts commit 571ca8c5de3d07da3791dad558677909a07e886d.

* refactor: remove Unity project tools copying and version tracking functionality

* refactor: consolidate module discovery logic into shared utility function

* Remove unused imports

* feat: add Python tool registry and sync system for MCP server integration

* feat: add auto-sync processor for Python tools with Unity editor integration

* feat: add menu item to reimport all Python files in project

Good to give users a manual option

* Fix infinite loop error

Don't react to PythonToolAsset changes - it only needs to react to Python file changes.
And we also batch asset edits to minimise the DB refreshes

* refactor: move Python tool sync menu items under Window/MCP For Unity/Tool Sync

* Update docs

* Remove duplicate header

* feat: add OnValidate handler to sync Python tools when asset is modified

This fixes the issue with deletions in the asset, now file removals are synced

* test: add unit tests for Python tools asset and sync services

* Update MCPForUnity/Editor/Helpers/PythonToolSyncProcessor.cs

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

* style: remove trailing whitespace from Python tool sync files

* test: remove incomplete unit tests from ToolSyncServiceTests

* perf: optimize Python file reimport by using AssetDatabase.FindAssets instead of GetAllAssetPaths

---------

Co-authored-by: Johan Holtby <72528418+JohanHoltby@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-10-18 00:18:25 -04:00
Shutong Wu 4a0e6336b2
Update to support Codex CLI (#325)
Fix the JSON installation on Codex in Wizard;
Adding the lines to support Codex CLI on windows temporarily, thanks to https://github.com/openai/codex/issues/4180
2025-10-17 15:51:06 -04:00
Shutong Wu 3d9860eb72 Update to support Codex CLI
Fix the JSON installation on Codex in Wizard;
Adding the lines to support Codex CLI on windows temporarily, thanks to https://github.com/openai/codex/issues/4180
2025-10-17 15:40:18 -04:00
Marcus Sanatan 90911aa4d7
Use secure unity version (#321)
* chore: update Unity version from 2021.3.45f1 to 2021.3.45f2

Older Unity version had the security vulnerability, so we update it

* feat: add dynamic version display in editor window settings

* refactor: remove manual license file handling from Unity test workflow

* Revert "refactor: remove manual license file handling from Unity test workflow"

This reverts commit a6ab3d982e792039c01a4afd353e61c7e22a2c3c.

* feat: add Unity license credentials to Docker containers in CI workflow

* refactor: replace manual Unity license activation with game-ci/unity-activator

* refactor: simplify Unity CI setup by removing game-ci activation and using built-in license handling

* fix: improve Unity license activation in CI by using unityci image's built-in activation flow

* refactor:  activate once in a temporary container, then reuse the license in the long-running container

Now we got the license secret to be read, we got this error: "Machine bindings don't match". So it seems that the license I generated locally can't be used.

So we need to activate the license within the container

* Revert "refactor:  activate once in a temporary container, then reuse the license in the long-running container"

This reverts commit f6a9aa68f910df37cede6f83d535098be2a9f80b.

* Revert "fix: improve Unity license activation in CI by using unityci image's built-in activation flow"

This reverts commit a9f4c0223bc3467442be6dafa1d9303479623a7c.

* Revert "refactor: simplify Unity CI setup by removing game-ci activation and using built-in license handling"

This reverts commit 4e5ffc0051a7b15b9d87ecaa06fa646f8b13b0b9.

* Revert "refactor: replace manual Unity license activation with game-ci/unity-activator"

This reverts commit e9520ee768c4e9d48efc81b1a9c3cac3986cc96a.

* Revert "feat: add Unity license credentials to Docker containers in CI workflow"

This reverts commit 01b8879e35baaf88239988b51e6d4f1e5daaa1cf.
2025-10-17 13:35:47 -04:00
Marcus Sanatan 6c00294231 feat: add tomli dependency and dynamic version lookup from pyproject.toml for legacy project 2025-10-13 11:44:25 -04:00
Marcus Sanatan 2d8e251e01 fix: apply telemetry decorator before MCP tool registration to ensure proper wrapping order for the old repo 2025-10-13 11:41:16 -04:00
GitHub Actions 3d82cb26b0 chore: bump version to 6.1.0 2025-10-13 15:27:36 +00:00
Marcus Sanatan f2c57ca91e
Add testing and move menu items to resources (#316)
* deps: add tomli>=2.3.0 dependency to UnityMcpServer package

* feat: dynamically fetch package version from pyproject.toml for telemetry

* Add pydantic

* feat: add resource registry for MCP resource auto-discovery

* feat: add telemetry decorator for tracking MCP resource usage

* feat: add auto-discovery and registration system for MCP resources

* feat: add resource registration to MCP server initialization

* feat: add MCPResponse model class for standardized API responses

* refactor: replace Debug.Log calls with McpLog wrapper for consistent logging

* feat: add test discovery endpoints for Unity Test Framework integration

We haven't connected them as yet, still thinking about how to do this neatly

* Fix server setup

* refactor: reduce log verbosity by changing individual resource/tool registration logs to debug level

* chore: bump mcp[cli] dependency from 1.15.0 to 1.17.0

* refactor: remove Context parameter and add uri keyword argument in resource decorator

The Context parameter doesn't work on our version of FastMCP

* chore: upgrade Python base image to 3.13 and simplify Dockerfile setup

* fix: apply telemetry decorator before mcp.tool to ensure proper wrapping order

* fix: swap order of telemetry and resource decorators to properly wrap handlers

* fix: update log prefixes for consistency in logging methods

* Fix compile errors

* feat: extend command registry to support both tools and resources

* Run get tests as a coroutine because it doesn't return results immediately

This works but it spams logs like crazy, maybe there's a better/simpler way

* refactor: migrate from coroutines to async/await for test retrieval and command execution

* feat: add optional error field to MCPResponse model

* Increased timeout because loading tests can take some time

* Make message optional so error responses that only have success and error don't cause Pydantic errors

* Set max_retries to 5

This connection module needs a lookover. The retries should be an exponential backoff and we could structure why it's failing so much

* Use pydantic model to structure the error output

* fix: initialize data field in GetTestsResponse to avoid potential errors

* Don't return path parameter

* feat: add Unity test runner execution with structured results and Python bindings

* refactor: simplify GetTests by removing mode filtering and related parsing logic

* refactor: move test runner functionality into dedicated service interface

* feat: add resource retrieval telemetry tracking with new record type and helper function

* fix: convert tool functions to async and await ctx.info calls

* refactor: reorganize menu item functionality into separate execute and get commands

An MCP resource for retrieval, and a simple command to execute. Because it's a resource, it's easier for the user to see what's in the menu items

* refactor: rename manage_menu_item to execute_menu_item and update tool examples to use async/await

We'll eventually put a section for resources

* Revert "fix: convert tool functions to async and await ctx.info calls"

This reverts commit 012ea6b7439bd1f2593864d98d03d9d95d7bdd03.

* fix: replace tomllib with tomli for Python 3.10 compatibility in telemetry module

* Remove confusing comment

* refactor: improve error handling and simplify test retrieval logic in GetTests commands

* No cache by default

* docs: remove redundant comment for HandleCommand method in ExecuteMenuItem
2025-10-13 11:16:43 -04:00
Jos van der Westhuizen 5ad5b4a632
Update README.md 2025-10-11 16:30:02 -07:00
Marcus Sanatan 3a9ec4f1a6
docs: replace "Unity MCP" with "MCP for Unity" in all text strings (#314) 2025-10-11 04:01:51 -04:00
Marcus Sanatan 6b0ee30a86 fix: simplify zip command path traversal in version bump workflow 2025-10-11 03:25:43 -04:00
GitHub Actions 32cb8137cc chore: bump version to 6.0.0 2025-10-11 07:12:26 +00:00
Marcus Sanatan 1d6d8c67af
New UI and work without MCP server embedded (#313)
* First pass at new UI

* Point to new UI

* Refactor: New Service-Based MCP Editor Window Architecture

We separate the business logic from the UI rendering of the new editor window with new services.
I didn't go full Dependency Injection, not sure if I want to add those deps to the install as yet, but service location is fairly straightforward.

Some differences with the old window:

- No more Auto-Setup, users will manually decide what they want to do
- Removed Python detection warning, we have a setup wizard now
- Added explicit path overrides for `uv` and the MCP server itself

* style: add flex-shrink and overflow handling to improve UI element scaling

* fix: update UI configuration and visibility when client status changes

* feat: add menu item to open legacy MCP configuration window

* refactor: improve editor window lifecycle handling with proper update subscription

* feat: add auto-verification of bridge health when connected

* fix: update Claude Code MCP server registration to use lowercase unityMCP name and correct the manual installation instructions

* fix: add Claude CLI directory to PATH for node/nvm environments

* Clarify how users will see MCP tools

* Add a keyboard shortcut to open the window

* feat: add server download UI and improve installation status messaging

This is needed for the Unity Asset Store, which doesn't have the Python server embedded.

* feat: add dynamic asset path detection to support both Package Manager and Asset Store installations

* fix: replace unicode emojis with escaped characters in status messages

* feat: add server package creation and GitHub release publishing to version bump workflow

* fix: add v prefix to server package filename in release workflow

* Fix download location

* style: improve dropdown and settings layout responsiveness with flex-shrink and max-width

* feat: add package.json version detection and refactor path utilities

* refactor: simplify imports and use fully qualified names in ServerInstaller.cs

* refactor: replace Unity Debug.Log calls with custom McpLog class

* fix: extract server files to temp directory before moving to final location

* docs: add v6 UI documentation and screenshots with service architecture overview

* docs: add new UI Toolkit-based editor window with service architecture and path overrides

* feat: improve package path resolution to support Package Manager and Asset Store installations

* Change Claude Code's casing back to "UnityMCP"

There's no need to break anything as yet

* fix: update success dialog text to clarify manual bridge start requirement

* refactor: move RefreshDebounce and ManageScriptRefreshHelpers classes inside namespace

* feat: add Asset Store fallback path detection for package root lookup

* fix: update server installation success message to be more descriptive

* refactor: replace Unity Debug.Log calls with custom McpLog utility

* fix: add file existence check before opening configuration file

* refactor: simplify asset path handling and remove redundant helper namespace references

* docs: update code block syntax highlighting in UI changes doc

* docs: add code block syntax highlighting for file structure example

* feat: import UnityEditor.UIElements namespace for UI components for Unity 2021 compatibility

* refactor: rename Python server references to MCP server for consistency

* fix: reset client status label color after error state is cleared

* Replace the phrase "Python server" with "MCP server"

* MInor doc clarification

* docs: add path override methods for UV and Claude CLI executables

* docs: update service locator registration method name from SetCustomImplementation to Register
2025-10-11 03:08:16 -04:00
Jos van der Westhuizen 2c53943556
Update README.md 2025-10-10 16:02:43 -07:00
Jos van der Westhuizen 5bc51b6b1a
Update README.md (#310)
* Update README.md

* Update README.md
2025-10-09 09:02:21 -07:00
Marcus Sanatan 50844c20f4 docs: add Unity disclaimer and update package installation steps 2025-10-03 22:22:19 -04:00
GitHub Actions ba1e488f32 chore: bump version to 5.0.0 2025-10-04 01:01:06 +00:00
Marcus Sanatan 9d9652eb4d docs: add v5 migration guide with installation screenshots and steps 2025-10-03 20:56:02 -04:00
Marcus Sanatan e9b1ae44c5
Rename plugin folder to MCPForUnity (#303)
* Copy UnityMcpBridge into a new MCPForUnity folder

This is to close #284

* refactor: rename UnityMcpBridge directory to MCPForUnity in docs

* chore: rename UnityMcpBridge directory to MCPForUnity across workflow files

* chore: rename UnityMcpBridge directory to MCPForUnity across all files

* refactor: update import paths from UnityMcpBridge to MCPForUnity across test files

* fix: update module import paths to use MCPForUnity instead of UnityMcpBridge

* chore: update unity-mcp package path to MCPForUnity directory

* feat: add OneTimeSetUp to initialize CommandRegistry before tests run

Hopefully fix the CI failures

* Apply recent fix to new folder

* Temporarily trigger tests to see if CI works

* Revert "Temporarily trigger tests to see if CI works"

It works!

This reverts commit 8c6eaaad07545cef047769f2c52fe506545a8161.
2025-10-03 20:23:28 -04:00
dsarno ff736012fa
Fix read_console includeStacktrace parameter behavior (#304)
The includeStacktrace parameter was working backwards - when false,
it would return the full message with embedded stack traces, and when
true, it would extract the stack trace but the logic was inverted.

Changes:
- Always extract the first line as the message text
- Only populate stackTrace field when includeStacktrace is true
- Ensures clean, summary-only messages when includeStacktrace is false
- Properly separates stack traces into their own field when requested

This matches the expected Unity console behavior where the summary
is shown by default, and stack traces are only shown when expanded.
2025-10-03 17:08:39 -07:00
Marcus Sanatan 5488af2c99
Make it easier to add tools (#301)
* Add a decorate that wraps around the `mcp.tool` decorator.

This will allow us to more easily collect tools

* Register tools that's defined in the tools folder

* Update Python tools to use new decorator

* Convert script_apply_edits tool

* Convert last remaining tools with new decorator

* Create an attribute so we can identify tools via Reflection

* Add attribute to all C# tools

* Use reflection to load tools

* Initialize command registry to load tools at startup

* Update tests

* Move Dev docs to docs folder

* Add docs for adding custom tools

* Update function docs for Python decorator

* Add working example of adding a screenshot tool

* docs: update relative links in README files

Updated the relative links in both README-DEV.md and README-DEV-zh.md to use direct filenames instead of paths relative to the docs directory, improving link correctness when files are accessed from the root directory.

* docs: update telemetry documentation path reference

Updated the link to TELEMETRY.md in README.md to point to the new docs/ directory location to ensure users can access the telemetry documentation correctly. Also moved the TELEMETRY.md file to the docs/ directory as part of the documentation restructuring.

* rename CursorHelp.md to docs/CURSOR_HELP.md

Moved the CursorHelp.md file to the docs directory to better organize documentation files and improve project structure.

* docs: update CUSTOM_TOOLS.md with improved tool naming documentation and path corrections

- Clarified that the `name` argument in `@mcp_for_unity_tool` decorator is optional and defaults to the function name
- Added documentation about using all FastMCP `mcp.tool` function decorator options
- Updated class naming documentation to mention snake_case conversion by default
- Corrected Python file path from `tools/screenshot_tool.py` to `UnityMcpServer~/src/tools/screenshot_tool.py`
- Enhanced documentation for tool discovery and usage examples

* docs: restructure development documentation and add custom tools guide

Rearranged the development section in README.md to better organize the documentation flow. Added a dedicated section for "Adding Custom Tools" with a link to the new CUSTOM_TOOLS.md file, and renamed the previous "For Developers" section to "Contributing to the Project" to better reflect its content. This improves discoverability and organization of the development setup documentation.

* docs: update developer documentation and add README links

- Added links to developer READMEs in CUSTOM_TOOLS.md to guide users to the appropriate documentation
- Fixed typo in README-DEV.md ("roote" → "root") for improved clarity
- These changes improve the developer experience by providing better documentation navigation and correcting technical inaccuracies

* feat(tools): enhance tool registration with wrapped function assignment

Updated the tool registration process to properly chain the mcp.tool decorator and telemetry wrapper, ensuring the wrapped function is correctly assigned to tool_info['func'] for proper tool execution and telemetry tracking. This change improves the reliability of tool registration and monitoring.

* Remove AI generated code that was never used...

* feat: Rebuild MCP server installation with embedded source

Refactored the server repair logic to implement a full rebuild of the MCP server installation using the embedded source. The new RebuildMcpServer method now:
- Uses embedded server source instead of attempting repair of existing installation
- Deletes the entire existing server directory before re-copying
- Handles UV process cleanup for the target path
- Simplifies the installation flow by removing the complex Python environment repair logic
- Maintains the same installation behavior but with a cleaner, more reliable rebuild approach

This change improves reliability of server installations by ensuring a clean slate rebuild rather than attempting to repair potentially corrupted environments.

* Add the rebuild server step

* docs: clarify tool description field requirements and client compatibility

* fix: move initialization flag after tool discovery to prevent race conditions

* refactor: remove redundant TryParseVersion overrides in platform detectors

* refactor: remove duplicate UV validation code from platform detectors

* Update UnityMcpBridge/Editor/Tools/CommandRegistry.cs

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

* refactor: replace WriteToConfig reflection with direct McpConfigurationHelper call

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-10-03 18:53:09 -04:00
Justin Barnett 7c23f245ab
feat: Unity Asset Store compliance with post-installation dependency setup (#281)
* feat: implement Unity Asset Store compliance with post-installation dependency setup

- Remove bundled Python dependencies from Unity package
- Add comprehensive 6-step setup wizard with auto-trigger on first import
- Implement cross-platform dependency detection (Windows, macOS, Linux)
- Add integrated MCP client configuration within setup process
- Create production-ready menu structure with clean UI/UX
- Ensure complete end-to-end setup requiring no additional configuration
- Add comprehensive error handling and recovery mechanisms

This implementation ensures Asset Store compliance while maintaining full
functionality through guided user setup. Users are left 100% ready to use
MCP after completing the setup wizard.

* refactor: improve Asset Store compliance implementation with production-ready setup

- Remove automatic installation attempts on package import
- Always show setup wizard on package install/reinstall
- Integrate MCP client configuration as part of setup wizard process
- Ensure MCP client config window remains accessible via menu
- Remove testing components for production readiness
- Replace automatic installation with manual guidance only
- Add complete 4-step setup flow: Welcome → Dependencies → Installation Guide → Client Configuration → Complete
- Improve user experience with clear instructions and accessible client management

* feat: add comprehensive dependency requirement warnings

- Add critical warnings throughout setup wizard that package cannot function without dependencies
- Update package.json description to clearly state manual dependency installation requirement
- Prevent setup completion if dependencies are missing
- Enhance skip setup warning to emphasize package will be non-functional
- Add error messages explaining consequences of missing dependencies
- Update menu item to indicate setup wizard is required
- Ensure users understand package is completely non-functional without proper dependency installation

* refactor: simplify setup wizard for production

BREAKING: Reduced setup wizard from 5 steps to 3 streamlined steps:
- Step 1: Setup (welcome + dependency check + installation guide)
- Step 2: Configure (client configuration with direct access to full settings)
- Step 3: Complete (final status and quick access to resources)

Simplifications:
- Consolidated UI components with DRY helper methods (DrawSectionTitle, DrawSuccessStatus, DrawErrorStatus)
- Simplified dependency status display with clean icons and essential info
- Removed complex state management - using simple EditorPrefs instead
- Removed unused InstallationOrchestrator and SetupState classes
- Streamlined client configuration to direct users to full settings window
- Simplified navigation with back/skip/next buttons
- Reduced code complexity while maintaining solid principles

Results:
- 40% less code while maintaining all functionality
- Cleaner, more intuitive user flow
- Faster setup process with fewer clicks
- Production-ready simplicity
- Easier maintenance and debugging

* fix: add missing using statement for DependencyCheckResult

Add missing 'using MCPForUnity.Editor.Dependencies.Models;' to resolve
DependencyCheckResult type reference in SetupWizard.cs

* refactor: optimize dependency checks and remove dead code

* fix: remove unused DrawInstallationProgressStep method

Removes leftover method that references deleted _isInstalling and _installationStatus fields, fixing compilation errors.

* feat: improve setup wizard UX and add real client configuration

1. Remove dependency mentions from package.json description
2. Only show dependency warnings when dependencies are actually missing
3. Add actual MCP client configuration functionality within the wizard:
   - Client selection dropdown
   - Individual client configuration
   - Claude Code registration/unregistration
   - Batch configuration for all clients
   - Manual setup instructions
   - Real configuration file writing

Users can now complete full setup including client configuration without leaving the wizard.

* refactor: improve menu text and client restart tip

- Remove '(Required)' from Setup Wizard menu item for cleaner appearance
- Update tip to reflect that most AI clients auto-detect configuration changes

* refactor: simplify client restart tip message

* fix: add missing using statement for MCPForUnityEditorWindow

Add 'using MCPForUnity.Editor.Windows;' to resolve unresolved symbol error for MCPForUnityEditorWindow in SetupWizard.cs

* Format code

* Remove unused folders

* Same for validators

* Same for Setup...

* feat: add setup wizard persistence to avoid showing on subsequent imports

* fix: update Python version check to support Python 4+ across all platform detectors

* refactor: extract common platform detection logic into PlatformDetectorBase class

* feat: add configuration helpers for MCP client setup with sophisticated path resolution

* fix: add missing override keyword to DetectPython method in platform detectors

* fix: update menu item labels for consistent capitalization and naming

* fix: standardize "MCP For Unity" capitalization in window titles and dialogs

* refactor: update package ID from justinpbarnett to coplaydev across codebase

* refactor: remove unused validation and configuration helper methods

* refactor: remove unused warnOnLegacyPackageId parameter from TryFindEmbeddedServerSource

---------

Co-authored-by: Claude <claude@anthropic.com>
Co-authored-by: Marcus Sanatan <msanatan@gmail.com>
2025-10-03 16:43:40 -04:00
Marcus Sanatan f6796e61f7
Autoformat (#297) 2025-09-30 16:25:33 -04:00
GitHub Actions 47ec46ce93 chore: bump version to 4.1.1 2025-09-30 03:48:44 +00:00
dsarno 10d4e3bd4a
Merge pull request #296 from dsarno/managegameobject-fix
fix: add parameter validation to manage_gameobject tool
2025-09-29 20:48:02 -07:00