Metadata-Version: 2.4
Name: ue5-editor-agent
Version: 0.2.2
Summary: Drive the Unreal Engine 5 editor from an LLM agent over the built-in Python Remote Execution channel - no C++ plugin, no project changes.
Author: rfioly
License: Apache-2.0
Project-URL: Homepage, https://github.com/rfioly/ue5-editor-agent
Project-URL: Repository, https://github.com/rfioly/ue5-editor-agent
Project-URL: Issues, https://github.com/rfioly/ue5-editor-agent/issues
Keywords: unreal-engine,ue5,mcp,llm-agent,python,editor-automation
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Code Generators
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# UE5 Editor Agent

[![ci](https://github.com/rfioly/ue5-editor-agent/actions/workflows/ci.yml/badge.svg)](https://github.com/rfioly/ue5-editor-agent/actions/workflows/ci.yml)
[![pypi](https://img.shields.io/pypi/v/ue5-editor-agent.svg)](https://pypi.org/project/ue5-editor-agent/)
[![python](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://github.com/rfioly/ue5-editor-agent/blob/main/pyproject.toml)
[![license](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/rfioly/ue5-editor-agent/blob/main/LICENSE)
[![dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)](https://github.com/rfioly/ue5-editor-agent/blob/main/pyproject.toml)

**Drive the Unreal Engine 5 editor from an LLM agent — no C++ plugin, no project
changes, nothing to install into your `.uproject`.**

Tell it *"add a point light at (500, 0, 300) and show me what it looks like"* and
it does it inside the running editor, then takes a screenshot so it can check the
result itself.

It speaks over Epic's built-in **Python Remote Execution** channel, which is why
there is no plugin to compile and no files dropped into your project. Works with
DeepSeek / OpenAI / any OpenAI-compatible model, and exposes the same 31 tools as
an **MCP server**, so Claude Code / Cursor / Codex can drive the editor too.

| | |
|---|---|
| ![viewport screenshot taken by the agent](https://raw.githubusercontent.com/rfioly/ue5-editor-agent/main/docs/screenshot.png) | **The agent can see its own work.**<br>`screenshot` spawns a temporary `SceneCapture2D` at your current viewport camera, renders into a transient `TextureRenderTarget2D` (never saved into the level), exports a PNG, then deletes the actor. No leftover actors, no dirty packages. Works without PIE and without the automation test framework. |

## Install

```bash
pip install ue5-editor-agent      # zero third-party dependencies
```

Or from source, to hack on it:

```bash
git clone https://github.com/rfioly/ue5-editor-agent
cd ue5-editor-agent && pip install -e .
```

## What it can do

Beyond spawning and moving actors, it can rename and duplicate them, read and
write properties through dot paths (`light_component.intensity`), search assets
with class filtering, save the level on demand, and move the viewport camera onto
an actor — always with an explicit `restore_viewport` to put it back.

It works on **assets**, not just level actors: rename, duplicate and delete
packages, inspect what an asset actually contains, and — critically — ask who
references it before touching it. It works on **material instances** the same way:
enumerate every parameter, write one instance and read every value back, or apply
a shared set of values across dozens at once.

And it can act on whatever you have **selected** in the viewport
(`get_selection` → `align_actors`), which is the shortest path between a human
pointing at something and an agent changing it: no label needs to be typed out.

Destructive operations default to a dry run. Full list in
**[docs/tools.md](https://github.com/rfioly/ue5-editor-agent/blob/main/docs/tools.md)**.

## Quick start

### 1. Turn on the two switches in the editor

`Edit → Plugins` — enable **Python Editor Script Plugin** and
**Editor Scripting Utilities**.

`Edit → Project Settings` (**Project Settings**, not Editor Preferences) → search
`Python` → under **Plugins → Python**, tick:

- ☑ **Enable Remote Execution?**
- ☑ **Develop Mode**

Then **restart the editor**. It does not take effect without a restart.

### 2. Check the connection

```bash
ue5-agent check
```

```
连接成功 [ok]
  engine_version: 5.8.2-56702186+++UE5+Release-5.8
  project_name: <your project>
  current_level: <level path>
  actor_count: <actors in level>
  is_mock: False
```

### 3. Give it a task

```bash
export LLM_API_KEY=sk-...        # DeepSeek / OpenAI / any compatible endpoint
ue5-agent once "在场景里 (500, 0, 300) 加一盏点光源，然后截图给我看"

python run_demo_live.py          # no API key needed — scripted model, real editor
python run_demo.py               # fully offline: fake engine, fake model
```

`run_demo_live.py` swaps in a `ScriptedLLM` (a canned script) but leaves
everything else real: real tools, real transport, real editor. It will genuinely
modify your current level, and it deliberately scripts one wrong class name so you
can watch the agent read the error and correct itself.

```bash
python tests/run_all.py            # 160 tests, zero dependencies
python eval/run_eval.py --self-test
ue5-agent --help                   # demo / check / once / chat
```

### As an MCP server

```json
{
  "mcpServers": {
    "ue5-agent": {
      "command": "python",
      "args": ["-m", "ue5_agent.mcp_server"],
      "cwd": "<absolute path to the install>"
    }
  }
}
```

Two implementation notes: tool failures are reported with `isError` rather than as
JSON-RPC errors (so the model can read the message and self-correct), and nothing
is ever written to stdout except JSON-RPC.

## Examples

Four short scripts in [`examples/`](https://github.com/rfioly/ue5-editor-agent/tree/main/examples) that do the things people actually ask
for, written as starting points rather than demos:

```bash
python examples/batch_rename_textures.py  --folder /Game/Textures --from "^T_" --to "TEX_"
python examples/audit_material_params.py  --folder /Game/Materials --param Roughness
python examples/align_selected_on_ground.py --mode min --apply
python examples/screenshot_after_change.py --actor DirectionalLight --intensity 12
```

They share one habit worth copying: the destructive ones default to a dry run, and
the one that moves the camera restores the previous camera position in a `finally`
block. `tests/test_examples.py` runs them so they cannot rot.

## Verified

Measured against a **live UE 5.8.2 editor on Windows 10**, not a mock:

| | |
|---|---|
| Tools exercised end to end | all 31 |
| Tests | 160, zero third-party dependencies |
| CI | Windows + Linux × Python 3.9 / 3.11 / 3.13 |
| Installed from the built wheel | asserted in CI, imported from a directory outside the checkout |
| Lines of Python | ~8,400 across `ue5_agent/` and `tests/` |

Each tool's confirmed behaviour is listed in [docs/tools.md](https://github.com/rfioly/ue5-editor-agent/blob/main/docs/tools.md); the 35
traps found along the way are in [docs/pitfalls.md](https://github.com/rfioly/ue5-editor-agent/blob/main/docs/pitfalls.md).

**Not yet verified:** more than one editor open at a time (the first discovered
node wins), operations running for tens of seconds (timeout edges), and screenshots
on levels other than the one test level (very large scenes may frame poorly on the
bounding-box fallback).

## How it works

The short version: the client pings over UDP multicast, the editor answers, and
then — the part that surprises everyone — **the editor connects out to the client's
TCP server**. Commands are self-contained Python snippets; results come back behind
a sentinel prefix in the log stream.

There is a fake `unreal` module in `tests/` so generated snippets can be executed
offline for real, which is the only thing that catches runtime errors without an
editor.

→ **[docs/architecture.md](https://github.com/rfioly/ue5-editor-agent/blob/main/docs/architecture.md)** for the full picture, including
why the templates use `string.Template` instead of `str.format`, and why output
trimming happens in one place.

## Five protocol traps, dug out of the engine source

The channel is documented almost entirely by example, and the examples are where it
goes wrong. Five of them, all visible in the 5.8 source once you know where to look:

**Epic ships a working client and the docs never mention it.**
`Engine/Plugins/Experimental/PythonScriptPlugin/Content/Python/remote_execution.py` is
649 lines of pure standard-library client for this exact protocol. `grep -i remote`
across the plugin's own `SphinxDocs/source/` returns zero hits.

**That client has a framing bug at 8192 bytes.** It decides a message is complete when
`recv()` returns fewer bytes than `DEFAULT_RECEIVE_BUFFER_SIZE` (8192). A result of
exactly 8192 bytes hangs it forever; a badly split one gives
`Unterminated string`; two queued results give `Extra data`. Parse by structure, not by
size.

**The TCP connection goes backwards.** The editor is the TCP *client* —
`PythonScriptRemoteExecution.cpp:465` calls `Connect`, not `Listen`. You listen, send
`open_connection` over UDP, and accept. Give it thirty seconds: the reference client
retries 6 × 5s and re-sends `open_connection` before every attempt.

**`MulticastBindAddress` is used as three things** — bind address, join interface, and
egress interface — all from one value, which defaults to `127.0.0.1`. And
`RemoteExecutionMulticastTtl` defaults to `0`, which means local host only. So "remote"
execution is machine-local on two independent settings out of the box. This project
matches the default by setting the outbound interface to loopback and trying it first
(see `build_strategies()` in `ue5_remote.py`).

**`ioctl(SIO_UDP_CONNRESET, 0)` is dead code.** CPython supports three ioctls and that
is not one of them — it raises `ValueError`, which most `except OSError` clauses let
escape. And the problem it claims to solve mostly does not exist here: ICMP
port-unreachable comes from *unicast* sends, and discovery only ever sends to the
multicast group. What actually keeps the loop alive is `except ConnectionResetError:
continue` on the receive side.

All five, with line numbers into the 5.8 source so you can check them instead of
trusting me: **[docs/remote-execution-traps.md](https://github.com/rfioly/ue-remote-exec/blob/main/docs/remote-execution-traps.md)**.

## How this compares

| Approach | Channel | Plugin required | Notes |
|---|---|---|---|
| Epic's official Unreal MCP (built into 5.8) | HTTP + SSE `127.0.0.1:8000/mcp` | yes (`ModelContextProtocol`) | Official, still early — 5.8.x has known editor crashes and silent data loss |
| Most community MCPs (`chongdashu/unreal-mcp`, `ChiR24/Unreal_mcp`) | C++ plugin + Python bridge | yes, compile it | Most capable; the cost is a compiled plugin in every project |
| **This project** | **Python Remote Execution (built in)** | **no** | Zero footprint: no `.uproject` edit, no files, no build |

"No plugin" is not "more powerful" — it buys near-zero setup cost and a project
that stays clean, at the price of the deep interfaces a plugin can offer (editing
Blueprint graph nodes directly, for instance). When you need those, `run_python` is
the escape hatch, or use a plugin-based project.

There was one earlier project on this channel, `runreal/unreal-mcp` (MIT), which
has not been updated since June 2025 and whose issues go unanswered. The point of
this project is to keep that channel maintained and to add the visual feedback loop
it never had.

## Repository layout

```
ue5-editor-agent/
├── ue5_agent/
│   ├── tools.py         31 tools + validation + result trimming
│   ├── agent.py         core loop, loop guards, trace recording
│   ├── llm.py           OpenAI-compatible client + ScriptedLLM (zero deps)
│   ├── mcp_server.py    MCP server over stdio, reuses the same tools
│   ├── cli.py           demo / check / once / chat
│   └── backends/        remote_exec (real engine) / mock (offline)
├── ue5_remote.py        Remote Execution client (also published as `ue-remote-exec`)
│                        — discovery + TCP command channel
├── eval/                eval cases + runner (judged by engine state, not an LLM)
├── examples/            small runnable scripts
├── docs/                architecture / tools / screenshot / pitfalls
└── tests/               run_all.py + fake_unreal.py + 160 tests
```

Zero third-party dependencies — not even `requests`, all standard library. `pytest
tests/` works if you have pytest installed.

---

## 中文说明

用自然语言操作 Unreal Engine 5 编辑器的 AI agent。输入「在场景里加一盏灯，放到
(500,0,300)」这类指令，agent 会在编辑器里真实执行，而不是给出操作说明；需要确认结果时
它会自己截一张图来看。

已在真实 UE 5.8.2 + Windows 上实测。走 Epic 官方内置的 Python Remote Execution 通道
—— 不需要写 C++ 插件，不需要往 UE 项目里放任何文件，`.uproject` 一行都不用改。

```bash
pip install ue5-editor-agent
ue5-agent check                                                    # 连上编辑器
ue5-agent once "在场景里 (500,0,300) 加一盏点光源，然后截图给我看"    # 需要 LLM_API_KEY
python run_demo_live.py                                            # 没有 API Key 也能跑
python tests/run_all.py                                            # 160 个测试，零依赖
```

编辑器侧只有两步：`编辑 → 插件` 勾上 **Python Editor Script Plugin** 与
**Editor Scripting Utilities**；`编辑 → 项目设置`（是项目设置，不是编辑器偏好设置）
搜 `Python`，勾上 **Enable Remote Execution?** 与 **Develop Mode**，然后**重启编辑器**。

- 工具全清单与每个工具的设计理由：[docs/tools.md](https://github.com/rfioly/ue5-editor-agent/blob/main/docs/tools.md)
- 架构、消息流、为什么模板不用 `str.format`：[docs/architecture.md](https://github.com/rfioly/ue5-editor-agent/blob/main/docs/architecture.md)
- 两个协议坑（带 5.8 源码行号）：[五个协议坑](https://github.com/rfioly/ue-remote-exec/blob/main/docs/remote-execution-traps.md)
- 截图是怎么拍出来的，以及为什么 `AutomationLibrary` 那条路是死路：[docs/screenshot.md](https://github.com/rfioly/ue5-editor-agent/blob/main/docs/screenshot.md)
- 开发中踩过的 35 个坑：[docs/pitfalls.md](https://github.com/rfioly/ue5-editor-agent/blob/main/docs/pitfalls.md)
- 版本历史：[CHANGELOG.md](https://github.com/rfioly/ue5-editor-agent/blob/main/CHANGELOG.md)

## License

Apache-2.0. See [LICENSE](https://github.com/rfioly/ue5-editor-agent/blob/main/LICENSE).
