Skip to main content
Glama

unity-mcp-server

MCP server for Unity 6 Editor integration. Exposes scene, GameObject, component, console and play-mode tools to any MCP client (Claude Code, Cursor, Windsurf, VS Code Copilot) via stdio, forwarding to a small C# Editor bridge over HTTP on 127.0.0.1.

MCP client ←stdio→ unity-mcp-server (this repo) ←HTTP 127.0.0.1:6400→ Unity 6 Editor (UnityPackage/)

Requirements

  • Node.js 18+ (tested on 22)

  • Unity 6000.0+ (tested on 6000.6.0f1)

  • com.unity.nuget.newtonsoft-json 3.2.1 (declared as package dependency, auto-resolved by UPM)

Related MCP server: Agent Bridge for Unity

Install

1. Editor bridge — IMPORTANT: pick the nested package

  1. Window → Package Manager → + → Add package from disk

  2. Select Unity-MCP/UnityPackage/package.json (that exact file, not the repo root!)

The Package '@modelcontextprotocol/sdk' is invalid / zod Version '^3.23.8' is invalid error means the repo root was selected — it holds the npm package.json, which UPM cannot parse. The correct file is UnityPackage/package.json (com.local.unity-mcp).

Option B — copy folder:

  1. Copy UnityPackage/ into your project's Packages/com.local.unity-mcp/

Then open Window → Unity MCP → Start. Status must show Running on 127.0.0.1:6400.

2. MCP server

npm install
npm run build

Add to your MCP client config (Claude Code claude_desktop_config.json / Cursor mcp.json):

{
  "mcpServers": {
    "unity": {
      "command": "node",
      "args": ["C:/Users/Misha Krutoj/Documents/Unity-MCP/dist/index.js"],
      "env": { "UNITY_BRIDGE_PORT": "6400" }
    }
  }
}

Verify: ask the agent "Ping Unity and summarize the active scene".

Tools (34)

Scene / objects / editor (17, MVP)

Tool

Type

Description

unity_ping

read

Bridge reachability + versions

unity_get_project_info

read

Project, Unity version, scene, play-mode

unity_get_scene_info

read

Active scene details

unity_get_hierarchy

read

Root objects, paginated (limit/offset)

unity_save_scene

write (idempotent)

Save open scenes

unity_find_gameobjects

read

Search by name_contains/tag/with_component

unity_get_object_info

read

Transform + components of one object

unity_get_components

read

Component list of one object

unity_create_gameobject

write

Empty or primitive, optional parent

unity_delete_gameobject

write (destructive)

Delete by path

unity_set_transform

write (idempotent)

Partial pos/rot/scale update

unity_add_component

write

Add by type name

unity_set_component_property

write (idempotent)

One serialized field via JSON value

unity_get_console_logs

read

Recent logs, filter log/warning/error

unity_clear_console

write (idempotent)

Clear buffer

unity_get_play_mode

read

stopped/playing/paused

unity_set_play_mode

write

play/stop/pause/unpause

Scripts (5)

Tool

Type

Description

unity_list_scripts

read

.cs files under folder, paginated

unity_read_script

read

File content with line numbers, paginated — read before updating

unity_create_script

write

From template (monobehaviour/scriptableobject/editor/empty), AssetDatabase.Refresh

unity_update_script

write (idempotent)

Exact old_text → new_text block replace, occurrence-count guard

unity_attach_script

write

Attach compiled MonoBehaviour class to GameObject

Prefabs / assets (6)

Tool

Type

Description

unity_list_assets

read

Browse AssetDatabase by folder/name/type, paginated

unity_import_asset

write (idempotent)

Force reimport (picks up external changes)

unity_asset_dependencies

read

Direct + transitive deps of an asset

unity_folder_structure

read

Folder tree map, depth 1-5

unity_instantiate_prefab

write

Instantiate prefab, keeps prefab link

unity_apply_prefab

write

Apply instance overrides to prefab source

Sandboxed code execution (2)

Tool

Type

Description

unity_execute_code

write (destructive, async)

Compile + run bare C# statements via AssemblyBuilder, returns job_id

unity_get_code_result

read

Poll job: running / done {output, logs} / error

Code rules: bare statements in a static Run() (return sends JSON back); blocklist covers filesystem/network/process/reflection-load/Application.Quit/infinite-loop patterns. Requires mutations ON and Enable C# execution in Window > Unity MCP (off by default).

Game-specific extensions (custom methods)

The bridge package is game-agnostic by design (UPM packages cannot reference project code). Games expose their own methods at runtime:

UnityMCPBridge.RegisterHandler("game/state", _ => new Dictionary<string, object> {
    ["tanks"] = ...,
});

See UnityPackage/Samples~/SelfPlayGlue/MCPGameGlue.cs for a complete sample (input/set, input/clear, game/state for AI self-play). Copy it into your project's Assets/Editor/ and adapt to your game classes. The matching client tools are unity_set_player_input, unity_clear_player_input, unity_get_game_state (they report a clear error until the glue registers the methods).

AI self-play + background (4)

Tool

Type

Description

unity_set_player_input

write

Remote drive: throttle/steer/fire override for the player tank

unity_clear_player_input

write (idempotent)

Hand control back to the human

unity_get_game_state

read

Snapshot: every tank's team/HP/pose/turret/reload

unity_refresh_assets

write (idempotent)

AssetDatabase.Refresh on demand (background file drops)

All tools support response_format: markdown | json, return content + structuredContent, and use annotations (readOnlyHint, destructiveHint, idempotentHint).

All mutations go through Unity Undo — revert with Ctrl+Z in the Editor. Disable writes via the Enable mutations toggle in Window → Unity MCP.

Env vars

Var

Default

Description

UNITY_BRIDGE_HOST

127.0.0.1

Bridge host (keep loopback)

UNITY_BRIDGE_PORT

auto

Preferred port. If busy, the bridge scans upward (up to +100) and writes the actual port to %TEMP%/unity-mcp-bridge.port, which the server reads automatically. Set the env var explicitly to pin a port (required for multi-instance).

Development

npm run dev    # watch mode (tsx)
npm run build  # tsc → dist/

Test with MCP Inspector:

npx @modelcontextprotocol/inspector node dist/index.js

Security

  • Binds 127.0.0.1 only, 2 MB body cap, 25 s main-thread timeout.

  • Arbitrary C# execution exists but is sandboxed and off by default (blocklist + explicit opt-in toggle + job timeouts).

  • Bridge self-heals via watchdog (restarts listener if its thread dies).

  • No auth (local single-user). Do not expose the port.

Roadmap

  1. Scripts — ✅ done (list/read/create/update/attach).

  2. Prefabs/assets — ✅ done (list/import/dependencies/folders, instantiate/apply).

  3. Safe code exec — ✅ done (sandboxed execute_code + job_id polling, off by default).

  4. Visual QA: take_screenshot, scene-view control, undo/redo, batch_call.

  5. Pipeline: build_project, packages, run_tests.

  6. Scale: tool groups, multi-instance routing (port from project-path hash), Streamable HTTP variant, MCPB packaging.

License

MIT — see LICENSE.

Available Tools

34 tools
unity_add_componentAdd ComponentA

Add a component by type name to a GameObject. Uses Undo.

Example: {"path":"Player","component_type":"Rigidbody"}. Check unity_get_components first to avoid duplicates.

Inputs: path (required), component_type (required).

unity_apply_prefabApply Prefab OverridesA
Idempotent

Apply an instance's overrides back to its prefab source (Undo-able, but affects all instances once saved).

Args: object_path of the instance ('Level/Enemy_1'). Fails with hint if the object is not a prefab instance.

Inputs: object_path (required).

unity_asset_dependenciesGet Asset DependenciesA
Read-onlyIdempotent

List what an asset depends on (textures of a material, scripts of a prefab, ...). Recursive by default.

Args: path, recursive (default true). Use when: checking what will break if you move/delete an asset, or why a prefab pulls in half the project.

Inputs: path (required), recursive, response_format.

unity_attach_scriptAttach Script to GameObjectA

Attach a MonoBehaviour class to a GameObject (Undo-able). Script must be compiled — no compile errors in console.

Args: object_path ('Player'), script_class ('PlayerController'). Fails with hint if the class is not found (typo? not compiled yet?) — read the error.

Inputs: object_path (required), script_class (required).

unity_clear_consoleClear ConsoleA
Idempotent

Clear the Unity console buffer (log cache in the bridge + Editor log view).

Use when: you want a clean baseline before reproducing an error.

Inputs: no named parameters.

unity_clear_player_inputClear Player Input OverrideA
Idempotent

Hand control back to the human: disables the remote override, zeroes throttle/steer, drops queued shots.

Inputs: no named parameters.

unity_create_gameobjectCreate GameObjectA

Create an empty GameObject or a Unity primitive (cube/sphere/capsule/cylinder/plane/quad), optionally parented. Uses Undo so it can be reverted in Editor.

Args: name (required), primitive_type (default none), position/rotation/scale arrays, parent_path (optional). Returns { path, name }. Save with unity_save_scene when done.

Inputs: name (required), scale, position, rotation, +2 more.

unity_create_scriptCreate C# ScriptA

Create a script from a Unity 6 template. Refreshes AssetDatabase so Unity compiles it.

Args: path ('Assets/Scripts/PlayerController.cs'), template monobehaviour|scriptableobject|editor|empty, class_name (default = file name; must match file name), overwrite (default false). After creating, wait for compilation (console check) before attaching.

Inputs: path (required), template, overwrite, class_name.

unity_delete_gameobjectDelete GameObjectA
Destructive

Delete a GameObject by path (Undo-able in Editor, but file-wise destructive once scene is saved).

Provide exact path from unity_find_gameobjects. Double-check path before calling.

Inputs: path (required).

unity_execute_codeExecute C# in Editor (sandboxed)A
Destructive

Compile and run bare C# statements inside the Unity Editor via Roslyn/AssemblyBuilder. Returns a job_id immediately — poll unity_get_code_result for completion (compile takes ~2-10s).

Code rules: bare statements only (wrapped into static Run(); UnityEngine/UnityEditor/System/LINQ usings included); 'return ;' sends JSON back. Keep snippets short and side-effect aware (runs on main thread; infinite loops hang the Editor). Sandbox blocks: filesystem (System.IO/File./Directory.), processes, network, reflection-load (Assembly.Load/Activator/DllImport), Application.Quit, while(true)/for(;;). Requires: mutations ON + 'Enable C# execution' in Window > Unity MCP (off by default).

Inputs: code (required), timeout_s.

unity_find_gameobjectsFind GameObjectsA
Read-onlyIdempotent

Search GameObjects by name substring, tag, or component type. At least one filter required. Paginated.

Examples:

  • name_contains "Player" -> players, spawn points

  • tag "Enemy" -> all enemies

  • with_component "Rigidbody" -> physics objects Returns { total, count, offset, items[{name,path,active}], has_more, next_offset }.

Inputs: no named parameters.

unity_folder_structureGet Folder StructureA
Read-onlyIdempotent

Map the project folder tree up to a depth (default 3). Read-only overview of how the project is organized.

Args: folder (default 'Assets'), depth 1-5 (default 3). Large folders are truncated with a note — drill into subfolders for detail.

Inputs: depth, folder, response_format.

unity_get_code_resultGet C# Job ResultA
Read-onlyIdempotent

Poll a code-execution job: running | done {output, logs} | error {error, logs}.

Use when: after unity_execute_code returned a job_id. If still running, wait and poll again. Output is the JSON of your 'return' value; logs are Debug.Log lines captured during Run().

Inputs: job_id (required).

unity_get_componentsGet ComponentsA
Read-onlyIdempotent

List all components on a GameObject with enabled flags.

Use when: inspecting what behaviour/rendering an object has before modifying it.

Inputs: path (required), response_format.

unity_get_console_logsGet Console LogsA
Read-onlyIdempotent

Read buffered Unity console entries, most recent first. Filter by type.

Use when: 'summarize warnings/errors', 'check console after my change', verifying a fix. For full stacks use response_format json (stackTrace included). Default types: warning+error.

Inputs: max_logs, log_types, response_format.

unity_get_game_stateGet Game State SnapshotA
Read-onlyIdempotent

One-call snapshot for self-play: every tank's team, hp/maxHP, alive, position [x,y,z], hull yaw, turret yaw, reload fraction (1 = ready).

Use in the drive loop before each unity_set_player_input. JSON format recommended for parsing.

Inputs: no named parameters.

unity_get_hierarchyGet Scene HierarchyA
Read-onlyIdempotent

List root GameObjects of the active scene with components summary. Paginated.

Args:

  • root_only (bool, default true): only roots; false includes one level of children in 'children'

  • limit (1-100, default 20), offset (default 0)

  • response_format markdown|json

Use when: exploring what is in the scene. For search use unity_find_gameobjects. Returns markdown list + structured { total, count, offset, items, has_more, next_offset }.

Inputs: limit, offset, root_only, response_format.

unity_get_object_infoGet GameObject InfoA
Read-onlyIdempotent

Full details of one GameObject by hierarchy path: transform, tag/layer, components list.

Use path like 'Player' or 'Level/Enemies/Orc'. For search use unity_find_gameobjects first.

Inputs: path (required), response_format.

unity_get_play_modeGet Play Mode StateA
Read-onlyIdempotent

Report stopped|playing|paused. Use before set or before assuming edits apply (edits in play mode are discarded on stop).

Inputs: no named parameters.

unity_get_project_infoGet Unity Project InfoA
Read-onlyIdempotent

Get project name, path, Unity version, active scene and play-mode state.

Use when: starting a session to orient yourself in the project. Returns: { projectName, projectPath, unityVersion, activeScene{name,path,isDirty,rootCount}, playMode }.

Inputs: no named parameters.

unity_get_scene_infoGet Active Scene InfoA
Read-onlyIdempotent

Get the active scene: name, path, dirty flag, root object count, build index.

Use when: you need to know which scene is open before querying hierarchy.

Inputs: no named parameters.

unity_import_assetReimport AssetA
Idempotent

Force Unity to reimport an asset (picks up external file changes).

Args: path ('Assets/Textures/logo.png'). Idempotent — reimporting twice is harmless.

Inputs: path (required).

unity_instantiate_prefabInstantiate PrefabA

Instantiate a prefab from an asset path into the active scene (Undo-able). Keeps the prefab link so overrides can be applied later.

Args: prefab_path ('Assets/Prefabs/Enemy.prefab'), name override (optional), position/rotation, parent_path (optional). Find prefabs first with unity_list_assets type='Prefab'.

Inputs: prefab_path (required), name, position, rotation, +1 more.

unity_list_assetsList Project AssetsA
Read-onlyIdempotent

Browse AssetDatabase: find assets by folder, name substring and type. Paginated.

Args: folder (default 'Assets'), filter (name substring, optional), type (Prefab/Material/Texture2D/AudioClip/Scene/..., optional), limit/offset. Use when: locating prefabs, materials or textures before instantiating or assigning them.

Inputs: type, limit, filter, folder, +2 more.

unity_list_scriptsList C# ScriptsA
Read-onlyIdempotent

List .cs files under a project folder with sizes. Paginated.

Args: folder (default 'Assets'), filter substring (optional), limit/offset. Use when: finding where game code lives before reading or editing it.

Inputs: limit, filter, folder, offset, +1 more.

unity_pingPing Unity EditorA
Read-onlyIdempotent

Check whether the Unity Editor bridge is reachable and report Unity/editor versions.

Use when: before any other Unity tool, or when calls fail with connection errors. Don't use when: you already have a fresh successful response — skip re-pinging.

Inputs: no named parameters.

unity_read_scriptRead C# ScriptA
Read-onlyIdempotent

Read a script with line numbers, paginated. Always read before updating.

Args: path ('Assets/Scripts/X.cs'), start_line (1-based, default 1), max_lines (default 200). Returns { path, total_lines, start_line, content } — content lines prefixed 'line: code'.

Inputs: path (required), max_lines, start_line, response_format.

unity_refresh_assetsRefresh AssetDatabaseA
Idempotent

Trigger Unity asset reimport + script recompilation on demand (AssetDatabase.Refresh).

Use when: files were written to the project from outside the Editor (scripts, models, textures) and Unity hasn't picked them up yet — e.g. background work while the Editor is unfocused. Idempotent.

Inputs: no named parameters.

unity_save_sceneSave Active SceneA
Idempotent

Save the active scene to disk (AssetDatabase + EditorSceneManager.SaveOpenScenes).

Use when: after create/delete/transform batches so work is not lost. Idempotent: saving twice has no extra effect.

Inputs: no named parameters.

unity_set_component_propertySet Component PropertyA
Idempotent

Set one serialized property/field on a component. Value is parsed as JSON.

Examples:

  • {"path":"Player","component_type":"Rigidbody","property":"mass","value_json":"5.0"}

  • {"path":"Sun","component_type":"Light","property":"intensity","value_json":"2.5"} Fails with allowed-type hint if the property is not settable — read the error and retry.

Inputs: path (required), property (required), value_json (required), component_type (required).

unity_set_player_inputSet Player Input (AI self-play)A

Drive the player tank remotely: throttle/steer become the TankController input (physical keyboard ignored while override is on). Fire is edge-triggered — one call queues exactly one shot.

Loop: unity_get_game_state -> decide -> unity_set_player_input (repeat ~2-5x/sec) -> poll result. Call unity_clear_player_input to hand control back to the human.

Inputs: fire, steer, throttle.

unity_set_play_modeSet Play ModeA
Idempotent

Enter/exit play mode: play|stop|pause|unpause. Scene edits made while playing are lost on stop — prefer stopped for structural changes.

Inputs: action (required).

unity_set_transformSet TransformA
Idempotent

Partially update position (world), rotation euler degrees (world), scale (local). Provide only fields to change.

Example: {"path":"Player","position":[0,1,0]} moves player without touching rotation.

Inputs: no named parameters.

unity_update_scriptUpdate C# ScriptA
Idempotent

Replace an exact text block in a script (like a focused diff hunk). Fails unless old_text occurs exactly expected_occurrences times.

Workflow: unity_read_script first, copy old_text verbatim (whitespace matters), then call with new_text. Returns { path, replaced, total_lines }. Unity recompiles after the change — check console for errors.

Inputs: path (required), new_text (required), old_text (required), expected_occurrences.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 34 tools

    Disambiguation4/5

    Most tools target distinct resources and actions, and the descriptions actively cross-reference each other (e.g. find_gameobjects vs get_hierarchy). Minor overlap exists in the get_project_info / get_scene_info / get_play_mode cluster, since project_info already returns scene and play-mode state, and refresh_assets vs import_asset both trigger reimports.

    Naming Consistency5/5

    Every tool uses the unity_ prefix with a consistent verb_noun snake_case pattern (get_, set_, create_, delete_, list_, find_, read_, update_, clear_, apply_). No camelCase mixing or inconsistent verb styles; highly predictable.

    Tool Count3/5

    34 tools is heavy and sits above the comfortable 3-15 range, spanning scene, GameObject, component, script, asset, console, code-execution, and a game-drive loop. Each tool is individually justified, but the surface is broad enough that discoverability and context cost suffer.

    Completeness4/5

    Strong lifecycle coverage: GameObject create/delete/transform, components add/set, scripts create/read/update, assets list/deps, console, play mode, and code execution. Gaps include no scene open/create/load, no component removal, no script/asset deletion, and no prefab creation, though agents can often work around these.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      A native C# MCP server that gives AI agents real-time control and visual analysis of the Unity Editor, enabling dynamic code execution, scene manipulation, and debugging without external dependencies.
      8
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      An in-editor MCP server that exposes Unity convenience tools to AI assistants, allowing them to read console logs, execute menu items, dump scene hierarchies, and take screenshots.
      -