Go to file
Marcus Sanatan 664a43b76c
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely

* Remove calls to /plugin/sessions

The newer /api/instances covers that data, and we want to remove these "expose all" endpoints

* Disable CLI routes when running in remote hosted mode

* Update server README

* feat: add API key authentication support for remote-hosted HTTP transport

- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint

* feat: add environment variable support for HTTP remote hosted mode

- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option

* feat: add user isolation enforcement for remote-hosted mode session listing

- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering

* feat: add comprehensive integration tests for API key authentication

- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring

* test: add autouse fixture to restore config state after startup validation tests

Ensures test isolation for config-dependent integration tests

* feat: skip user_id resolution in non-remote-hosted mode

Prevents unnecessary API key validation when not in remote-hosted mode

* test: add missing mock attributes to instance routing tests

- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test

* Fix broken telemetry test

* Add comprehensive API key authentication documentation

- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows

* Add remote-hosted mode and API key authentication documentation to server README

* Update reference doc for Docker Hub

* Specify exception being caught

* Ensure caplog handler cleanup in telemetry queue worker test

* Use NoUnitySessionError instead of RuntimeError in session isolation test

* Remove unusued monkeypatch arg

* Use more obviously fake API keys

* Reject connections when ApiKeyService is not initialized in remote-hosted mode

- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures

* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var

Consistent with repo

* Invalidate cached login URL when HTTP base URL changes

* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues

* Cache API key in field instead of reading from EditorPrefs on each reconnection

* Align markdown table formatting in remote server auth documentation

* Minor fixes

* security: Sanitize API key values in shell commands and fix minor issues

Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).

Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request

* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class

Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.

* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases

Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.

* Fix imports

* Filter session listing by user_id in all code paths to prevent cross-user session access

Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.

* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter

Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.

* Add environment variable support for project-scoped-tools flag [skip ci]

Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.

* Fix Python tests

* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.

* Update Server/src/main.py

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

* Refactor HTTP transport configuration to support separate local and remote URLs

Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).

Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP

* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode

Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.

* Hide Manual Server Launch foldout when not in HTTP Local mode

* Fix failing test

* Improve error messaging and API key validation for HTTP Remote transport

Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection

* Add missing .meta file

* Store transport mode in ServerConfig instead of environment variable

* Add autouse fixture to restore global config state between tests

Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.

* Fix startup

* Replace _current_transport() calls with direct config.transport_mode access

* Minor cleanup

* Add integration tests for HTTP transport authentication behavior

Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.

* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes

Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-30 18:39:21 -04:00
.claude Large Cleanup and Refactor + Many new Tests added (#642) 2026-01-29 02:47:36 -08:00
.github Large Cleanup and Refactor + Many new Tests added (#642) 2026-01-29 02:47:36 -08:00
CustomTools/RoslynRuntimeCompilation [FEATURE] Custom Tool Fix and Add inspection window for all the tools (#414) 2025-12-07 19:38:32 -05:00
MCPForUnity Remote server auth (#644) 2026-01-30 18:39:21 -04:00
Server Remote server auth (#644) 2026-01-30 18:39:21 -04:00
TestProjects Fix CodexConfigHelperTests to account for --prerelease argument in uvx command (#652) 2026-01-29 15:54:44 -08:00
docs Remote server auth (#644) 2026-01-30 18:39:21 -04:00
scripts Improved ci prompt testing suite (#270) 2025-09-07 15:47:56 -07:00
tools Large Cleanup and Refactor + Many new Tests added (#642) 2026-01-29 02:47:36 -08:00
.dockerignore HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
.gitignore Large Cleanup and Refactor + Many new Tests added (#642) 2026-01-29 02:47:36 -08:00
.mcpbignore feat: Add MCPB bundle for Claude Desktop installation (#580) 2026-01-22 15:46:35 -04:00
CLAUDE.md Clarify resource handling guidelines in CLAUDE.md 2026-01-29 03:29:25 -08:00
LICENSE chore: update package metadata and license to CoplayDev organization 2025-08-08 15:54:43 -04:00
README.md Add GitHub Copilot CLI support to MCP client list and configurator (#641) 2026-01-30 12:55:57 -04:00
docker-compose.yml HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
manifest.json chore: bump version to 9.2.0 2026-01-23 05:34:19 +00:00
mcp_source.py Large Cleanup and Refactor + Many new Tests added (#642) 2026-01-29 02:47:36 -08:00

README.md

MCP for Unity
English 简体中文

Proudly sponsored and maintained by Coplay -- the best AI assistant for Unity.

Discord Unity Asset Store python

Create your Unity apps with LLMs! MCP for Unity bridges AI assistants (Claude, Cursor, VS Code, etc.) with your Unity Editor via the Model Context Protocol. Give your LLM the tools to manage assets, control scenes, edit scripts, and automate tasks.

MCP for Unity building a scene

Quick Start

Prerequisites

1. Install the Unity Package

In Unity: Window > Package Manager > + > Add package from git URL...

[!TIP]

https://github.com/CoplayDev/unity-mcp.git?path=/MCPForUnity#main

Want the latest beta? Use the beta branch:

https://github.com/CoplayDev/unity-mcp.git?path=/MCPForUnity#beta
Other install options (Asset Store, OpenUPM)

Unity Asset Store:

  1. Visit MCP for Unity on the Asset Store
  2. Click Add to My Assets, then import via Window > Package Manager

OpenUPM:

openupm add com.coplaydev.unity-mcp

2. Start the Server & Connect

  1. In Unity: Window > MCP for Unity
  2. Click Start Server (launches HTTP server on localhost:8080)
  3. Select your MCP Client from the dropdown and click Configure
  4. Look for 🟢 "Connected ✓"
  5. Connect your client: Some clients (Cursor, Windsurf, Antigravity) require enabling an MCP toggle in settings, while others (Claude Desktop, Claude Code) auto-connect after configuration.

That's it! Try a prompt like: "Create a red, blue and yellow cube" or "Build a simple player controller"


Features & Tools

Key Features

  • Natural Language Control — Instruct your LLM to perform Unity tasks
  • Powerful Tools — Manage assets, scenes, materials, scripts, and editor functions
  • Automation — Automate repetitive Unity workflows
  • Extensible — Works with various MCP Clients

Available Tools

manage_assetmanage_editormanage_gameobjectmanage_componentsmanage_materialmanage_prefabsmanage_scenemanage_scriptmanage_scriptable_objectmanage_shadermanage_vfxmanage_texturebatch_executefind_gameobjectsfind_in_fileread_consolerefresh_unityrun_testsget_test_jobexecute_menu_itemapply_text_editsscript_apply_editsvalidate_scriptcreate_scriptdelete_scriptget_sha

Available Resources

custom_toolsunity_instancesmenu_itemsget_testsgameobjectgameobject_componentsprefab_apiprefab_infoprefab_hierarchyeditor_stateeditor_selectioneditor_prefab_stageproject_infoproject_tagsproject_layers

Performance Tip: Use batch_execute for multiple operations — it's 10-100x faster than individual calls!

Manual Configuration

If auto-setup doesn't work, add this to your MCP client's config file:

HTTP (default — works with Claude Desktop, Cursor, Windsurf):

{
  "mcpServers": {
    "unityMCP": {
      "url": "http://localhost:8080/mcp"
    }
  }
}

VS Code:

{
  "servers": {
    "unityMCP": {
      "type": "http",
      "url": "http://localhost:8080/mcp"
    }
  }
}
Stdio configuration (uvx)

macOS/Linux:

{
  "mcpServers": {
    "unityMCP": {
      "command": "uvx",
      "args": ["--from", "mcpforunityserver", "mcp-for-unity", "--transport", "stdio"]
    }
  }
}

Windows:

{
  "mcpServers": {
    "unityMCP": {
      "command": "C:/Users/YOUR_USERNAME/AppData/Local/Microsoft/WinGet/Links/uvx.exe",
      "args": ["--from", "mcpforunityserver", "mcp-for-unity", "--transport", "stdio"]
    }
  }
}
Multiple Unity Instances

MCP for Unity supports multiple Unity Editor instances. To target a specific one:

  1. Ask your LLM to check the unity_instances resource
  2. Use set_active_instance with the Name@hash (e.g., MyProject@abc123)
  3. All subsequent tools route to that instance
Roslyn Script Validation (Advanced)

For Strict validation that catches undefined namespaces, types, and methods:

  1. Install NuGetForUnity
  2. Window > NuGet Package Manager → Install Microsoft.CodeAnalysis v5.0
  3. Also install SQLitePCLRaw.core and SQLitePCLRaw.bundle_e_sqlite3 v3.0.2
  4. Add USE_ROSLYN to Player Settings > Scripting Define Symbols
  5. Restart Unity
Manual DLL installation (if NuGetForUnity isn't available)
  1. Download Microsoft.CodeAnalysis.CSharp.dll and dependencies from NuGet
  2. Place DLLs in Assets/Plugins/ folder
  3. Ensure .NET compatibility settings are correct
  4. Add USE_ROSLYN to Scripting Define Symbols
  5. Restart Unity
Troubleshooting
  • Unity Bridge Not Connecting: Check Window > MCP for Unity status, restart Unity
  • Server Not Starting: Verify uv --version works, check the terminal for errors
  • Client Not Connecting: Ensure the HTTP server is running and the URL matches your config

Detailed setup guides:

Still stuck? Open an Issue or Join Discord

Contributing

See README-DEV.md for development setup. For custom tools, see CUSTOM_TOOLS.md.

  1. Fork → Create issue → Branch (feature/your-idea) → Make changes → PR
Telemetry & Privacy

Anonymous, privacy-focused telemetry (no code, no project names, no personal data). Opt out with DISABLE_TELEMETRY=true. See TELEMETRY.md.


License: MIT — See LICENSE | Need help? Discord | Issues


Star History

Star History Chart

Citation for Research If you are working on research that is related to Unity-MCP, please cite us!
@inproceedings{10.1145/3757376.3771417,
author = {Wu, Shutong and Barnett, Justin P.},
title = {MCP-Unity: Protocol-Driven Framework for Interactive 3D Authoring},
year = {2025},
isbn = {9798400721366},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
url = {https://doi.org/10.1145/3757376.3771417},
doi = {10.1145/3757376.3771417},
series = {SA Technical Communications '25}
}

Unity AI Tools by Coplay

Coplay offers 3 AI tools for Unity:

  • MCP for Unity is available freely under the MIT license.
  • Coplay is a premium Unity AI assistant that sits within Unity and is more than the MCP for Unity.
  • Coplay MCP a free-for-now MCP for Coplay tools.

(These tools have different tech stacks. See this blog post comparing Coplay to MCP for Unity.)

Coplay

Disclaimer

This project is a free and open-source tool for the Unity Editor, and is not affiliated with Unity Technologies.