Unity Editor MCP

Cho phép các trợ lý AI tương tác trực tiếp với Unity Editor để hỗ trợ phát triển game và tự động hóa bằng AI.

GitHub
3
Dùng thử MCP nàyĐược tài trợ

Tài liệu

Unity Editor MCP

CI codecov License: MIT npm version

⚠️ This project is in beta and under heavy development. Features and APIs may change. Use at your own discretion.

Unity Editor MCP (Model Context Protocol) enables AI assistants like Claude and Cursor to interact directly with the Unity Editor, allowing for AI-assisted game development and automation.

🚀 Key Features

  • 🎮 GameObject Management: Create primitives, modify transforms, manage hierarchy, and delete objects
  • 🔧 Component System: Add, remove, modify, and list components on GameObjects with full property control
  • 🎭 Prefab Workflow: Complete prefab mode editing - open, modify, save, and exit with override management
  • 🔍 Smart Search: Find GameObjects by name, tag, layer, or component type with exact/partial matching
  • 📊 Scene Analysis: Analyze scene composition, component statistics, and prefab connections
  • 🎯 Component Inspection: Get component values, find objects by component, trace references between objects
  • 🎬 Scene Control: Create, load, save scenes, manage build settings, and work with multiple scenes
  • 🏃 Play Mode Testing: Start, pause, and stop play mode, check editor state and compilation status
  • 🖼️ Screenshot Capture: Take screenshots of Game View or Scene View with analysis capabilities
  • 🎨 Asset Management: Create and modify prefabs, materials, scripts with comprehensive property control
  • 🖱️ UI Automation: Interact with Unity UI elements programmatically for testing and automation
  • 📝 Console Integration: Read Unity console logs filtered by type with enhanced debugging features
  • 🔄 Editor Operations: Refresh assets, execute menu items, and trigger recompilation

📌 What's new

Unity package 0.16.0

Minor, not patch: this release changes a tool's contract and adds a package dependency, which is what the 0.x scheme here bumps the minor for (0.15.0 added the Test Runner tools the same way). The Node server package is versioned independently and is unchanged.

Breaking

  • run_tests now requires testMode. Pass "EditMode", "PlayMode" or "EditAndPlayMode" explicitly; there is no default, because PlayMode and EditAndPlayMode enter play mode and trigger a domain reload, and silently picking that for a caller who wanted EditMode was a foot-gun. An MCP server older than this package will fail every run_tests call against it, with testMode is required, because it does not send the field. Update the Node server (npx unity-editor-mcp@latest) together with the Unity package.
  • New package dependency: com.unity.ugui 2.0.0. The UI interaction tools reference uGUI types, so the dependency is now declared instead of assumed. Unity resolves it automatically; a project that had deliberately removed uGUI will see it come back.

Test runs are honest about their own state

  • get_test_results reports runStatus, runGuid, secondsSinceLastProgress and possiblyStale, and never mutates run state - polling can no longer abandon a run that was merely slow.
  • cancel_tests reports what actually happened. If the Test Runner API does not accept the cancellation, the run is left alone and told to you, instead of reporting a cancellation that never happened.
  • run_tests accepts force: true, which now genuinely cancels the in-progress run first and refuses to start a second one when cancellation is unavailable and the old run is not provably gone. Two concurrent runs reporting into one result set is no longer reachable.
  • Results survive the domain reload that a PlayMode run causes, and post-reload results are no longer discarded by a mid-run poll.

The bridge stays answerable while the editor main thread is busy

  • ping and get_editor_state are answered on the socket thread from cached state, and carry mainThreadResponsive, mainThreadLastTickSecondsAgo, mainThreadInFlightCommand and mainThreadInFlightSeconds - so a client can see what the editor is stuck on and for how long.
  • Commands that cannot be served that way fail with a MAIN_THREAD_STALLED error naming the in-flight command instead of hanging until an opaque timeout. A handler that holds the main thread past the 600s ceiling is reported once per handler, not once per second.

Instance registry

  • Registry entries whose Unity process is gone are pruned automatically, so crashed or force-quit editors stop slowing discovery down. Set UNITY_MCP_DISABLE_REGISTRY_PRUNE=true to opt out.
  • Entries are written atomically, and the listener port that Unity actually bound is republished immediately after a domain reload.

Troubleshooting

A modal dialog open in Unity, and a backgrounded Editor throttled by macOS App Nap, both stop the editor loop and look exactly like a hang. See Commands Hang or Return MAIN_THREAD_STALLED for how to tell them apart and what to do.

🚀 Quick Start

Prerequisites

  • ✅ Unity 2020.3 LTS or newer
  • ✅ Node.js 18.0.0 or newer
  • ✅ Claude Desktop or Cursor

Installation

📦 Step 1: Install Unity Package

In Unity:

  1. Open Window → Package Manager
  2. Click "+" → "Add package from git URL..."
  3. Paste: https://github.com/ozankasikci/unity-editor-mcp.git?path=unity-editor-mcp
  4. Click Add

✨ Unity will automatically start the MCP bridge. It uses port 6400 when available and falls back to a free local port when multiple Unity instances are open.

⚙️ Step 2: Configure Your MCP Client

For Claude Desktop:

Add to your config file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "unity-editor-mcp": {
      "command": "npx",
      "args": ["unity-editor-mcp@latest"]
    }
  }
}

For Cursor:

Add the same configuration to Cursor's MCP settings

✅ Step 3: Verify Connection

  1. Restart your MCP client (Claude Desktop or Cursor)
  2. Check Unity Console for: [Unity Editor MCP] Client connected
  3. You're ready to go! 🎮

Multiple Unity Instances

Unity Editor MCP now auto-discovers running Unity projects. Each Unity Editor instance writes an internal runtime registry entry under ~/.unity-editor-mcp/instances, including its project path, process ID, port, Unity version, package version, workspace ID, Git worktree metadata, and heartbeat timestamp. You do not edit this file.

When the Node MCP server starts, it selects the Unity instance in this order:

  1. UNITY_PORT or --port, if explicitly provided
  2. UNITY_MCP_INSTANCE_ID or --instance
  3. UNITY_PROJECT_PATH, UNITY_MCP_PROJECT_PATH, or --project
  4. UNITY_MCP_WORKSPACE_ID or --workspace-id
  5. the Unity project inferred from the current working directory
  6. the stable workspace ID inferred from the current working directory
  7. the only live Unity MCP instance, if exactly one exists

For Git worktrees, the workspace ID is stored in Git's private worktree metadata via git rev-parse --git-path unity-editor-mcp/workspace-id. For non-Git projects it is stored under Library/UnityEditorMCP/workspace-id. It is not written to tracked Unity project files.

If the server infers a local Unity project/workspace from the current working directory, it requires an exact project or workspace match and does not use the single-live-instance fallback. If related worktrees from the same Git repository are open but none match the current worktree, it fails closed with a WORKTREE_MISMATCH candidate list instead of connecting silently. To restore the old convenience fallback explicitly, set UNITY_MCP_ALLOW_SINGLE_INSTANCE_FALLBACK=true or pass --allow-single-instance-fallback.

To inspect discovery without starting an MCP session:

unity-editor-mcp doctor
unity-editor-mcp doctor --project /path/to/UnityProject
unity-editor-mcp doctor --workspace-id <workspace-id>
unity-editor-mcp doctor --instance <instance-id>
unity-editor-mcp doctor --allow-single-instance-fallback
unity-editor-mcp doctor --json

Available Tools

Unity Editor MCP provides 63 comprehensive tools across 11 categories for complete Unity Editor automation:

System & Core Tools (3 tools)

  • ping - Test connection to Unity Editor and verify server status
  • read_logs - Read Unity console logs with filtering by type (Log, Warning, Error, etc.)
  • refresh_assets - Refresh Unity assets and optionally wait for compilation to settle

GameObject Management (5 tools)

  • create_gameobject - Create GameObjects with primitives, transforms, tags, and layers
  • find_gameobject - Find GameObjects by name, tag, layer with pattern matching
  • modify_gameobject - Modify GameObject properties (transform, name, active state, parent, etc.)
  • delete_gameobject - Delete single or multiple GameObjects with optional child handling
  • get_hierarchy - Get complete scene hierarchy with components and depth control

Component System (5 tools)

  • add_component - Add Unity components to GameObjects with initial property values
  • remove_component - Remove components from GameObjects with safety checks (prevents Transform removal)
  • modify_component - Modify component properties with support for nested properties using dot notation
  • list_components - List all components on a GameObject with type information and removability status
  • get_component_types - Discover available component types with filtering by category and addability

Scene Management (5 tools)

  • create_scene - Create new scenes with build settings integration and auto-loading
  • load_scene - Load existing scenes in Single or Additive mode
  • save_scene - Save current scene with Save As functionality
  • list_scenes - List all scenes in project with filtering and build settings info
  • get_scene_info - Get detailed scene information including GameObject counts

Scene Analysis (5 tools)

  • get_gameobject_details - Deep inspection of GameObjects with component details and hierarchy
  • analyze_scene_contents - Comprehensive scene statistics, composition, and performance metrics
  • get_component_values - Get all properties and values of specific components with metadata
  • find_by_component - Find GameObjects by component type with scope filtering (scene/prefabs/all)
  • get_object_references - Analyze references between objects including hierarchy and asset connections

Asset Management (11 tools)

  • create_prefab - Create prefabs from GameObjects or empty templates with overwrite options
  • modify_prefab - Modify existing prefabs with property changes and instance updates
  • instantiate_prefab - Instantiate prefabs in scenes with transform and parenting options
  • open_prefab - Open prefabs in Unity's prefab mode for detailed editing with focus and isolation
  • exit_prefab_mode - Exit prefab mode with optional save/discard changes
  • save_prefab - Save prefab changes in prefab mode or apply instance overrides to prefab assets
  • create_material - Create new materials with shader assignment and property configuration
  • modify_material - Modify existing materials with shader changes and property updates
  • manage_asset_import_settings - Manage Unity asset import settings (get, modify, apply presets, reimport)
  • manage_asset_database - Manage Unity Asset Database operations (find, info, create folders, move, copy, delete, refresh)
  • analyze_asset_dependencies - Analyze Unity asset dependencies (get dependencies, dependents, circular deps, unused assets, size impact)

Script Management (6 tools)

  • create_script - Create new C# scripts with templates and namespace management
  • read_script - Read script file contents with syntax highlighting information
  • update_script - Modify existing scripts with content replacement and validation
  • delete_script - Delete script files with dependency checking and confirmation
  • list_scripts - List all scripts in project with filtering and metadata
  • validate_script - Validate script syntax and check for compilation errors

Play Mode Controls (4 tools)

  • play_game - Start Unity play mode for testing and interaction
  • pause_game - Pause or resume Unity play mode
  • stop_game - Stop Unity play mode and return to edit mode
  • get_editor_state - Get current Unity editor state (play mode, pause, compilation status)

UI Automation (5 tools)

  • find_ui_elements - Locate UI elements in scene hierarchy with filtering
  • click_ui_element - Simulate clicking on UI elements (buttons, toggles, etc.)
  • get_ui_element_state - Get detailed UI element state and interaction capabilities
  • set_ui_element_value - Set values for UI input elements (sliders, input fields, etc.)
  • simulate_ui_input - Execute complex UI interaction sequences

Editor Operations (5 tools)

  • execute_menu_item - Execute Unity menu items programmatically with safety checks
  • clear_console - Clear Unity console logs with optional filtering
  • enhanced_read_logs - Advanced log reading with search, filtering, and export capabilities
  • capture_screenshot - Take screenshots of Game View or Scene View with custom resolution and encoding
  • analyze_screenshot - Analyze screenshot content with basic image analysis capabilities

Editor Control & Automation (9 tools)

  • manage_tags - Manage Unity project tags (add, remove, list)
  • manage_layers - Manage Unity project layers (add, remove, list, convert index/name)
  • manage_selection - Manage Unity Editor selection (get, set, clear, get details)
  • manage_windows - Manage Unity Editor windows (list, focus, get state)
  • manage_tools - Manage Unity Editor tools and plugins (list, activate, deactivate, refresh)
  • start_compilation_monitoring - Start monitoring Unity compilation with real-time error detection
  • stop_compilation_monitoring - Stop compilation monitoring and get final status
  • get_compilation_state - Get current Unity compilation state and errors
  • wait_for_compilation - Wait for Unity compilation/domain reload to settle and return final messages

Troubleshooting

Unity TCP Listener Issues

If you see "Port 6400 is already in use":

  1. This is expected when another Unity instance already owns the default port
  2. The package will fall back to an available local port automatically
  3. The fallback port is kept for the rest of the session and is not silently moved back to 6400 later; the Node server follows the editor through the instance registry (process ID and project path), so the port number does not need to be stable
  4. Run unity-editor-mcp doctor to see which project and port will be selected

A fixed port only matters if you opt out of discovery with UNITY_PORT / --port. In that case make sure the port you pin is the one Unity actually bound, which unity-editor-mcp doctor reports.

Connection Failed

  1. Ensure Unity Editor is running with the package installed
  2. Check the Unity console for error messages
  3. Verify the Node.js server is running
  4. Check your MCP client configuration path is absolute

Commands Hang or Return MAIN_THREAD_STALLED

Almost every tool has to run on Unity's main thread, so it can only answer while the editor loop is pumping. When the loop stops, commands queue up instead of completing.

What the bridge does about it:

  • ping and get_editor_state are answered on the socket thread from cached state, so they keep working while the main thread is stuck. Both report mainThreadResponsive, mainThreadLastTickSecondsAgo, mainThreadInFlightCommand and mainThreadInFlightSeconds — use them to tell "Unity is frozen" apart from "the bridge is busy running the command you just sent" and from "the bridge is down".
  • Queued commands fail with MAIN_THREAD_STALLED rather than hanging until the client's timeout. The error names the command and how long the loop has been silent.
  • A long-running command of ours is not a stall. While the editor is inside one of our handlers (refresh_assets, a large import, entering play mode) the commands behind it keep waiting, and the error, if the 600s ceiling is eventually reached, names the command that is holding the main thread. That report happens once per stuck handler, not once per second, so commands queued behind it afterwards keep waiting rather than being failed on every watchdog tick.

Common causes, in order of likelihood:

  1. A modal dialog is open in Unity. Modal dialogs block the editor loop completely; nothing the bridge does can wake it. Bring Unity to the front and dismiss the dialog.
  2. The Editor window is hidden or fully occluded on macOS, so App Nap throttles it and the loop runs at a crawl. Un-occluding the window fixes it. If you need Unity to keep running while hidden, you can opt in to disabling App Nap yourself — this is a user-applied system setting, not something the package does:
    defaults write com.unity3d.UnityEditor5.x NSAppSleepDisabled -bool YES
    
    Restart Unity afterwards. (Verified against /Applications/Unity/Hub/Editor/<version>/Unity.app/Contents/Info.plist; older Unity installs may use a different bundle identifier, so check yours before running this.)
  3. A long import, script compile or play-mode transition is in progress. Wait it out; the command completes once the loop resumes.

Note that asking Unity to drain its queue from the socket thread only trims latency while the loop is already running — it cannot restart a loop that has stopped.

Node.js Server Won't Start

  1. Ensure you have Node.js 18+ installed: node --version
  2. Run npm install in the mcp-server directory
  3. Check for any error messages in the console

Contributing

See CONTRIBUTING.md for development guidelines.

License

MIT License - see LICENSE for details.