Go to file
dsarno c2a6b0ac7a
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus

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

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

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

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

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

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

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

* Fix Claude Code registration UI blocking and thread safety issues

This commit resolves three issues with Claude Code registration:

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

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

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

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

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

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

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

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

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

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

5. Removed unreachable else branch in async status check code

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

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

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

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

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

* Fix stop heuristics edge cases; remove dead pid capture

* Fix unity substring guard in stop heuristics

* Fix local server cleanup and connection checks

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

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

* Simplify PluginHub reload handling; honor run_tests timeout

* Fix Windows Claude CLI status check threading
2026-01-01 17:08:51 -08:00
.claude Fix/ci cleanup (#484) 2025-12-24 13:12:26 -08:00
.github Fix/ci cleanup (#484) 2025-12-24 13:12:26 -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 HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499) 2026-01-01 17:08:51 -08:00
Server HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499) 2026-01-01 17:08:51 -08:00
TestProjects/UnityMCPTests Optimise so startup is fast again (#494) 2025-12-29 18:39:03 -04:00
docs Payload-safe paging for hierarchy/components + safer asset search + docs (#490) 2025-12-28 20:57:57 -08:00
scripts Improved ci prompt testing suite (#270) 2025-09-07 15:47:56 -07:00
tools docs: replace "Unity MCP" with "MCP for Unity" in all text strings (#314) 2025-10-11 04:01:51 -04:00
.dockerignore HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
.gitignore feature/Add new manage_scriptable_object tool (#489) 2025-12-28 20:15:50 -08:00
LICENSE chore: update package metadata and license to CoplayDev organization 2025-08-08 15:54:43 -04:00
README-zh.md feat: Add `manage_material` tool for dedicated material manipulation (#440) 2025-12-07 19:39:52 -08:00
README.md feature/Add new manage_scriptable_object tool (#489) 2025-12-28 20:15:50 -08:00
claude_skill_unity.zip Claude Skill Example Upload (#380) 2025-12-02 00:43:22 -05:00
deploy-dev.bat [FEATURE] Camera Capture (#449) 2025-12-09 19:00:30 -05:00
docker-compose.yml HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
mcp_source.py HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
prune_tool_results.py Rename plugin folder to MCPForUnity (#303) 2025-10-03 20:23:28 -04:00
restore-dev.bat HTTP Server, uvx, C# only custom tools (#375) 2025-11-24 23:21:06 -04:00
test_unity_socket_framing.py Autoformat (#297) 2025-09-30 16:25:33 -04:00

README.md

MCP for Unity
English 简体中文

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

Discord python GitHub commit activity GitHub Issues or Pull Requests

Create your Unity apps with LLMs!

MCP for Unity acts as a bridge, allowing AI assistants (like Claude, Cursor) to interact directly with your Unity Editor via a local MCP (Model Context Protocol) Client. Give your LLM tools to manage assets, control scenes, edit scripts, and automate tasks within Unity.

MCP for Unity screenshot

💬 Join Our Discord

Get help, share ideas, and collaborate with other MCP for Unity developers!


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: Designed to work with various MCP Clients.
  • 🌐 HTTP-First Transport: Ships with HTTP connections enabled by default (stdio is still available as a fallback).
Tools

Your LLM can use functions like:

  • manage_asset: Performs asset operations (import, create, modify, delete, etc.).
  • manage_editor: Controls and queries the editor's state and settings.
  • manage_gameobject: Manages GameObjects: create, modify, delete, find, and component operations.
  • manage_material: Manages materials: create, set properties, colors, assign to renderers, and query material info.
  • manage_prefabs: Performs prefab operations (create, modify, delete, etc.).
  • manage_scene: Manages scenes (load, save, create, get hierarchy, etc.).
  • manage_script: Compatibility router for legacy script operations (create, read, delete). Prefer apply_text_edits or script_apply_edits for edits.
  • manage_scriptable_object: Creates and modifies ScriptableObject assets using Unity SerializedObject property paths.
  • manage_shader: Performs shader CRUD operations (create, read, modify, delete).
  • read_console: Gets messages from or clears the console.
  • run_tests: Runs tests in the Unity Editor.
  • execute_custom_tool: Execute a project-scoped custom tool registered by Unity.
  • execute_menu_item: Executes Unity Editor menu items (e.g., "File/Save Project").
  • set_active_instance: Routes subsequent tool calls to a specific Unity instance (when multiple are running). Requires the exact Name@hash from unity_instances.
  • apply_text_edits: Precise text edits with precondition hashes and atomic multi-edit batches.
  • script_apply_edits: Structured C# method/class edits (insert/replace/delete) with safer boundaries.
  • validate_script: Fast validation (basic/standard) to catch syntax/structure issues before/after writes.
  • create_script: Create a new C# script at the given project path.
  • delete_script: Delete a C# script by URI or Assets-relative path.
  • get_sha: Get SHA256 and basic metadata for a Unity C# script without returning file contents.
Resources

Your LLM can retrieve the following resources:

  • custom_tools: Lists custom tools available for the active Unity project.
  • unity_instances: Lists all running Unity Editor instances with their details (name, path, port, status).
  • menu_items: Retrieves all available menu items in the Unity Editor.
  • tests: Retrieves all available tests in the Unity Editor. Can select tests of a specific type (e.g., "EditMode", "PlayMode").
  • editor_active_tool: Currently active editor tool (Move, Rotate, Scale, etc.) and transform handle settings.
  • editor_prefab_stage: Current prefab editing context if a prefab is open in isolation mode.
  • editor_selection: Detailed information about currently selected objects in the editor.
  • editor_state: Current editor runtime state including play mode, compilation status, active scene, and selection summary.
  • editor_windows: All currently open editor windows with their titles, types, positions, and focus state.
  • project_info: Static project information including root path, Unity version, and platform.
  • project_layers: All layers defined in the project's TagManager with their indices (0-31).
  • project_tags: All tags defined in the project's TagManager.
---

How It Works

MCP for Unity connects your tools using two components:

  1. MCP for Unity Bridge: A Unity package running inside the Editor. (Installed via Package Manager).
  2. MCP for Unity Server: A Python server that runs locally (from a terminal window) and speaks HTTP/JSON-RPC to your MCP client. The Unity window launches it for you in HTTP mode by default; stdio is still available if you switch transports.
image

Installation ⚙️

Prerequisites

  • Python: Version 3.10 or newer. Download Python

  • Unity Hub & Editor: Version 2021.3 LTS or newer. Download Unity

  • uv (Python toolchain manager):

    # macOS / Linux
    curl -LsSf https://astral.sh/uv/install.sh | sh
    
    # Windows (PowerShell)
    winget install --id=astral-sh.uv  -e
    
    # Docs: https://docs.astral.sh/uv/getting-started/installation/
    
  • An MCP Client: : Claude Desktop | Claude Code | Cursor | Visual Studio Code Copilot | Windsurf | Others work with manual config

  • [Optional] Roslyn for Advanced Script Validation
    For **Strict** validation level that catches undefined namespaces, types, and methods: 
    
    **Method 1: NuGet for Unity (Recommended)**
    1. Install [NuGetForUnity](https://github.com/GlitchEnzo/NuGetForUnity)
    2. Go to `Window > NuGet Package Manager`
    3. Search for `Microsoft.CodeAnalysis`, select version 4.14.0, and install the package
    4. Also install package `SQLitePCLRaw.core` and `SQLitePCLRaw.bundle_e_sqlite3`.
    5. Go to `Player Settings > Scripting Define Symbols`
    6. Add `USE_ROSLYN`
    7. Restart Unity
    
    **Method 2: Manual DLL Installation**
    1. Download Microsoft.CodeAnalysis.CSharp.dll and dependencies from [NuGet](https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp/)
    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
    
    **Note:** Without Roslyn, script validation falls back to basic structural checks. Roslyn enables full C# compiler diagnostics with precise error reporting.</details>
    

🌟 Step 1: Install the Unity Package

To install via Git URL

  1. Open your Unity project.
  2. Go to Window > Package Manager.
  3. Click + -> Add package from git URL....
  4. Enter:
    https://github.com/CoplayDev/unity-mcp.git?path=/MCPForUnity
    
  5. Click Add.

Need a stable/fixed version? Use a tagged URL instead (updates require uninstalling and re-installing):

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

To install via OpenUPM

  1. Install the OpenUPM CLI
  2. Open a terminal (PowerShell, Terminal, etc.) and navigate to your Unity project directory
  3. Run openupm add com.coplaydev.unity-mcp

Note: If you installed the MCP Server before Coplay's maintenance, you will need to uninstall the old package before re-installing the new one.

Step 2: Start the Local HTTP Server (Default)

HTTP transport is enabled out of the box. The Unity window can launch the FastMCP server for you:

  1. Open Window > MCP for Unity.
  2. Make sure the Transport dropdown is set to HTTP (default) and the HTTP URL is what you want (defaults to http://localhost:8080).
  3. Click Start Local HTTP Server. Unity spawns a new operating-system terminal running uv ... server.py --transport http.
  4. Keep that terminal window open while you work; closing it stops the server. Use the Stop Session button in the Unity window if you need to tear it down cleanly.

Prefer stdio? Change the transport dropdown to Stdio and Unity will fall back to the embedded TCP bridge instead of launching the HTTP server.

Manual launch (optional)

You can also start the server yourself from a terminal—useful for CI or when you want to see raw logs:

uvx --from "git+https://github.com/CoplayDev/unity-mcp@v8.1.0#subdirectory=Server" mcp-for-unity --transport http --http-url http://localhost:8080

Keep the process running while clients are connected.

🛠️ Step 3: Configure Your MCP Client

Connect your MCP Client (Claude, Cursor, etc.) to the HTTP server from Step 2 (auto) or via Manual Configuration (below).

For Claude Desktop Users, try using our manually scrapped Unity_Skills by downloading and uploading the claude_skill_unity.zip following this link.

Option A: Configure Buttons (Recommended for Claude/Cursor/VSC Copilot)

  1. In Unity, go to Window > MCP for Unity.
  2. Select your Client/IDE from the dropdown.
  3. Click the Configure Button. (Or the Configure All Detected Clients button will try to configure every client it finds, but takes longer.)
  4. Look for a green status indicator 🟢 and "Connected ✓". (This writes the HTTP url pointing at the server you launched in Step 2.)
Client-specific troubleshooting
  • VSCode: uses Code/User/mcp.json with top-level servers.unityMCP, "type": "http", and the URL from Step 2. On Windows, MCP for Unity still prefers an absolute uv.exe path when you switch back to stdio.
  • Cursor / Windsurf (help link): if uv is missing, the MCP for Unity window shows "uv Not Found" with a quick [HELP] link and a "Choose uv Install Location" button.
  • Claude Code (help link): if claude isn't found, the window shows "Claude Not Found" with [HELP] and a "Choose Claude Location" button. Unregister now updates the UI immediately.

Option B: Manual Configuration

If Auto-Setup fails or you use a different client:

  1. Find your MCP Client's configuration file. (Check client documentation).
    • Claude Example (macOS): ~/Library/Application Support/Claude/claude_desktop_config.json
    • Claude Example (Windows): %APPDATA%\Claude\claude_desktop_config.json
  2. Edit the file to add/update the mcpServers section so it points at the HTTP endpoint from Step 2.
Click for Client-Specific JSON Configuration Snippets...

Claude Code

If you're using Claude Code, you can register the MCP server using the below commands:

macOS:

claude mcp add --scope user UnityMCP -- uv --directory /Users/USERNAME/Library/AppSupport/UnityMCP/UnityMcpServer/src run server.py

Windows:

claude mcp add --scope user UnityMCP -- "C:/Users/USERNAME/AppData/Local/Microsoft/WinGet/Links/uv.exe" --directory "C:/Users/USERNAME/AppData/Local/UnityMCP/UnityMcpServer/src" run server.py

VSCode (all OS HTTP default)

{
  "servers": {
    "unityMCP": {
      "type": "http",
      "url": "http://localhost:8080/mcp"
    }
  }
}

macOS / Windows / Linux (Claude Desktop, Cursor, Claude Code, Windsurf, etc. HTTP default)

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

Set the URL to match whatever you entered in the Unity window (include /mcp).

Stdio configuration examples (legacy / optional)

Switch the Unity transport dropdown to Stdio, then use one of the following command/args blocks.

VSCode (stdio)

{
  "servers": {
    "unityMCP": {
      "type": "stdio",
      "command": "uv",
      "args": [
        "--directory",
        "<ABSOLUTE_PATH_TO>/UnityMcpServer/src",
        "run",
        "server.py",
        "--transport",
        "stdio"
      ]
    }
  }
}

macOS / Linux (stdio)

{
  "mcpServers": {
    "unityMCP": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/Users/YOUR_USERNAME/Library/AppSupport/UnityMCP/UnityMcpServer/src",
        "server.py",
        "--transport",
        "stdio"
      ]
    }
  }
}

Windows (stdio)

{
  "mcpServers": {
    "unityMCP": {
      "command": "C:/Users/YOUR_USERNAME/AppData/Local/Microsoft/WinGet/Links/uv.exe",
      "args": [
        "run",
        "--directory",
        "C:/Users/YOUR_USERNAME/AppData/Local/UnityMCP/UnityMcpServer/src",
        "server.py",
        "--transport",
        "stdio"
      ]
    }
  }
}

Replace YOUR_USERNAME and AppSupport path segments as needed for your platform.


Usage ▶️

  1. Open your Unity Project and verify the HTTP server is running (Window > MCP for Unity > Start Local HTTP Server). The indicator should show "Session Active" once the server is up.

  2. Start your MCP Client (Claude, Cursor, etc.). It connects to the HTTP endpoint configured in Step 3—no extra terminals will be spawned by the client.

  3. Interact! Unity tools should now be available in your MCP Client.

    Example Prompt: Create a 3D player controller, Create a tic-tac-toe game in 3D, Create a cool shader and apply to a cube.

Working with Multiple Unity Instances

MCP for Unity supports multiple Unity Editor instances simultaneously. Each instance is isolated per MCP client session.

To direct tool calls to a specific instance:

  1. List available instances: Ask your LLM to check the unity_instances resource
  2. Set the active instance: Use set_active_instance with the exact Name@hash shown (e.g., MyProject@abc123)
  3. All subsequent tools route to that instance until changed. If multiple instances are running and no active instance is set, the server will error and instruct you to select one.

Example:

User: "List all Unity instances"
LLM: [Shows ProjectA@abc123 and ProjectB@def456]

User: "Set active instance to ProjectA@abc123"
LLM: [Calls set_active_instance("ProjectA@abc123")]

User: "Create a red cube"
LLM: [Creates cube in ProjectA]

Development & Contributing 🛠️

Development Setup and Guidelines

See README-DEV.md for complete development setup and workflow documentation.

Adding Custom Tools

MCP for Unity uses a Python MCP Server tied with Unity's C# scripts for tools. If you'd like to extend the functionality with your own tools, learn how to do so in CUSTOM_TOOLS.md.

How to Contribute

  1. Fork the main repository.
  2. Create an issue to discuss your idea or bug.
  3. Create a branch (feature/your-idea or bugfix/your-fix).
  4. Make changes.
  5. Commit (feat: Add cool new feature).
  6. Push your branch.
  7. Open a Pull Request against the main branch, referencing the issue you created earlier.

📊 Telemetry & Privacy

MCP for Unity includes privacy-focused, anonymous telemetry to help us improve the product. We collect usage analytics and performance data, but never your code, project names, or personal information.

  • 🔒 Anonymous: Random UUIDs only, no personal data
  • 🚫 Easy opt-out: Set DISABLE_TELEMETRY=true environment variable
  • 📖 Transparent: See TELEMETRY.md for full details

Your privacy matters to us. All telemetry is optional and designed to respect your workflow.


Troubleshooting

Click to view common issues and fixes...
  • Unity Bridge Not Running/Connecting:
    • Ensure Unity Editor is open.
    • Check the status window: Window > MCP for Unity.
    • Restart Unity.
  • MCP Client Not Connecting / Server Not Starting:
    • Make sure the local HTTP server is running (Window > MCP for Unity > Start Local HTTP Server). Keep the spawned terminal window open.
    • Verify Server Path: Double-check the --directory path in your MCP Client's JSON config. It must exactly match the installation location:
      • Windows: %USERPROFILE%\AppData\Local\UnityMCP\UnityMcpServer\src
      • macOS: ~/Library/AppSupport/UnityMCP/UnityMcpServer\src
      • Linux: ~/.local/share/UnityMCP/UnityMcpServer\src
    • Verify uv: Make sure uv is installed and working (uv --version).
    • Run Manually: Try running the server directly from the terminal to see errors:
      cd /path/to/your/UnityMCP/UnityMcpServer/src
      uv run server.py
      
  • Configuration Failed:
    • Use the Manual Configuration steps. The plugin may lack permissions to write to the MCP client's config file.

Still stuck? Open an Issue or Join the Discord!


License 📜

MIT License. See LICENSE file.


Star History

Star History Chart

Unity AI Tools by Coplay

Coplay offers 2 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.

(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.