Skip to main content
Glama
Unity UI Agent (MCP)

Unity UI Agent (MCP)

by maguera93
README.md
# Unity UI Agent (MCP)

Let AI agents such as **Claude Code** build, inspect and visually check **uGUI** layouts inside the Unity Editor, through the [Model Context Protocol](https://modelcontextprotocol.io).

The goal is a design-to-UI loop: the agent reads a mockup, builds the layout with real Unity components, renders it, compares the render with the design and fixes the differences until they match.

> **Status:** early prototype (v0.1). The tools for the core loop (inspect → build → capture → fix) are in place; design comparison and the evaluation suite are on the roadmap below.

<!-- Add a GIF here: Claude Code building a main menu from a mockup. -->

## How it works

```mermaid
flowchart LR
    A[Claude Code<br/>or any MCP client] -- MCP over stdio --> B[Python MCP server<br/>Server~/]
    B -- HTTP on 127.0.0.1:6400 --> C[Editor bridge<br/>Editor/UiAgentBridge.cs]
    C -- main-thread queue --> D[Unity Editor<br/>scene or prefab]
```

| Part | What it does |
|---|---|
| `Editor/` (C#, Unity package) | A local HTTP bridge inside the Editor. It queues each request and runs it on the main thread, because most of the Unity API is main-thread only. Commands create and edit uGUI elements, describe the hierarchy, render the UI to PNG and read the Console. |
| `Server~/` (Python) | The MCP server. It exposes typed tools to the agent, maps them to bridge commands and retries automatically while Unity recompiles scripts. |

### Design decisions

- **Main-thread queue.** HTTP requests arrive on background threads; they are queued and executed from `EditorApplication.update`, a few per frame so the Editor stays responsive.
- **Domain reloads.** The bridge stops before every script recompilation or Play Mode entry and restarts afterwards. The Python server retries for up to 20 s, so the agent never sees the gap.
- **Everything is undoable.** Every change goes through Unity's `Undo` system, so anything the agent does can be reverted with Ctrl+Z. A whole `build_ui_tree` call is one Undo step, and a call that fails leaves nothing half-built.
- **Edit-Mode screenshots.** Screen Space - Overlay canvases are not drawn by any camera. For the capture, they are switched temporarily to Screen Space - Camera with a hidden camera, rendered at the Canvas Scaler resolution, then restored. The agent can check its work without entering Play Mode.
- **Prefab Mode aware.** When a prefab is open in Prefab Mode, paths resolve inside that prefab, new elements go under the prefab root by default and captures render the prefab, so the agent can build UI prefabs as well as scene UI.
- **Local only.** The bridge listens on 127.0.0.1 and rejects requests that a web page could send (any request with an `Origin` header or without `Content-Type: application/json`). The MCP server only retries requests that never reached Unity, so a timeout cannot apply a change twice.
- **Agent-friendly errors.** Errors explain what to do next, for example "No GameObject found at path 'X'. Use get_hierarchy to see the available paths."

## Tools

| Tool | Purpose |
|---|---|
| `unity_status` | Check the connection, Unity version, Play Mode and open prefab. |
| `get_hierarchy` | Scene or prefab tree with paths, RectTransforms, colours, texts and components. |
| `create_ui_element` | Create a panel, image, text, button or empty container with anchors, size, colour, sprite, text and layout group. Creates the Canvas (with Canvas Scaler) and EventSystem if missing. |
| `build_ui_tree` | Create a whole screen in one call: a tree of elements with the same properties as `create_ui_element` plus `children`. Up to 500 elements, one Undo step, all-or-nothing. |
| `update_ui_element` | Change any of the above, rename, re-parent, reorder or enable/disable. |
| `delete_object` | Delete a GameObject (undoable). |
| `capture_game_view` | Render the UI to a PNG and return it to the agent as an image. |
| `read_console` | Recent Console messages, including compiler errors. |

Anchor presets: `center`, `top`, `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`, `stretch`, `stretch-top`, `stretch-bottom`, `stretch-left`, `stretch-right`, `stretch-horizontal`, `stretch-vertical`.

## Installation

Requirements: Unity 2021.3 or newer, [uv](https://docs.astral.sh/uv/) (it installs Python 3.10+ for you) and an MCP client such as Claude Code.

### 1. Add the Unity package

In Unity, open **Window > Package Manager > + > Add package from git URL…** and enter:

```
https://github.com/maguera93/unity-ui-agent-mcp.git
```

Then open **Window > UI Agent (MCP)**. The status should read *Running on http://127.0.0.1:6400/*.

### 2. Get the MCP server

Clone the same repository anywhere on your machine; the server lives in `Server~/`, a folder Unity ignores:

```bash
git clone https://github.com/maguera93/unity-ui-agent-mcp.git
```

### 3. Register it in Claude Code

From your Unity project folder:

```bash
claude mcp add unity-ui-agent -- uv run --directory "/path/to/unity-ui-agent-mcp/Server~" unity-ui-agent-mcp
```

If you changed the port in the Unity window, add `-e UNITY_UI_AGENT_PORT=<port>` after the server name. Other MCP clients can launch the same command over stdio.

**Tip:** in Unity, set **Preferences > General > Interaction Mode** to *No Throttling*, so commands run quickly while the Editor is in the background.

## Example prompt

```
Build a mobile main menu at 1080x1920: a dark background, the title "SKY RUNNER" at the top,
and three stacked buttons (Play, Shop, Settings) in a vertical layout group, centred with
40 px spacing. Use #FFB300 for the Play button. Capture the result, check that it looks
right and fix anything that doesn't.
```

## Roadmap

- [ ] **Design input:** read a Figma frame or a mockup image as the target.
- [ ] **Visual diff:** score each capture against the target (pixel and structural similarity) so the agent knows when to stop.
- [ ] **Evaluation suite:** about 10 reference designs with recorded scores, time and tool calls per run, to measure each change to prompts and tools.
- [ ] TextMeshPro support.
- [ ] Save the result as a prefab.
- [ ] Unit tests for the Editor commands (Unity Test Framework).

## Project layout

```
package.json                 Unity package manifest
Editor/
  UiAgentBridge.cs           HTTP bridge and main-thread queue
  CommandRegistry.cs         Command name -> handler
  SceneQuery.cs              Path lookup in scenes and Prefab Mode
  JsonParams.cs              Parameter parsing helpers
  UiAgentWindow.cs           Window > UI Agent (MCP)
  Commands/                  Hierarchy, UI, capture and console commands
Server~/                     Python MCP server (ignored by Unity)
```

## License

MIT © Marc Agüera Garcia