---
catalog_id: "R-137"
kind: "repo"
domain: "tooling"
domain_label: "工程门禁 / Tooling & QA"
date: "2026-11-30"
title: "CoplayDev/unity-mcp"
verdict: "双通道桥接+10组分层按需暴露，Unity端主线程泵成熟"
summary: "面向 Unity Editor 的双进程生产级 MCP 桥接系统（Server v10.3.0 / UPM 包 v10.3.1-beta.11，MIT）：采用 Python FastMCP 服务层 + C# Editor 插件架构，支持 HTTP/WebSocket 与本地 TCP Stdio 双通道、多实例 `Name@hash` 路由、10 个工具组动态按需暴露、主线程防节流泵以及系统级密钥库与防 Zip-Slip 导入守卫。"
summary_en: "Dual-transport (WS + TCP stdio) Unity Editor MCP bridge with 10 lazy tool groups, main-thread pump, OS keychain store, and Roslyn eval."
canonical_url: "https://oumuatown.com/repos/CoplayDev__unity-mcp/"
markdown_url: "https://oumuatown.com/repos/CoplayDev__unity-mcp.md"
og_image_zh: "https://oumuatown.com/og/zh/R-137.png"
og_image_en: "https://oumuatown.com/og/en/R-137.png"
cite_count: 38
repo: "coplaydev/unity-mcp"
github_url: "https://github.com/coplaydev/unity-mcp"
commit: "19b66ec"
tags:
  - "unity"
  - "mcp"
  - "game-engine"
  - "fastmcp"
  - "csharp"
  - "editor-automation"
github_repos:
  - "https://github.com/coplaydev/unity-mcp/tree/19b66ec"
---

# R-137 · CoplayDev/unity-mcp

> **结论 / Verdict**: 双通道桥接+10组分层按需暴露，Unity端主线程泵成熟
> **EN Summary**: Dual-transport (WS + TCP stdio) Unity Editor MCP bridge with 10 lazy tool groups, main-thread pump, OS keychain store, and Roslyn eval.

## Provenance & Evidence

- Primary Repository: https://github.com/coplaydev/unity-mcp (@19b66ec)
- Verified Source Citations (#Lxx): 38
- Web Reader: https://oumuatown.com/repos/CoplayDev__unity-mcp/

# CoplayDev/unity-mcp

> 仓库地址：https://github.com/CoplayDev/unity-mcp · 审计版本：`CoplayDev/unity-mcp@19b66ec`（Server `v10.3.0` / UPM `v10.3.1-beta.11`） · 审计日期：2026-11-30
> 来源文章：[关联文章](../articles/2026-11-30-archiveexplorer-rea-reverse-anything.md)

## 定位与解决的真问题

- **核心定位与目标用户**：连接编码 Agent（内置 Claude Code、Cursor、Codex、Antigravity 2.0 等 24 个客户端自动配置器）与运行中 Unity Editor（`2021.3+`）的双向控制桥（`MCPForUnity/package.json#L1-L34`, `MCPForUnity/Editor/Clients/Configurators/AntigravityConfigurator.cs#L11-L31`）。
- **相比常规做法解决的关键痛点**：
  1. **跨越 Unity 主线程限制、失焦休眠与 Domain Reload 断连**：Unity Editor API 必须在主线程调用，且切到后台失焦或 C# 重新编译（Assembly Reload）时 `EditorApplication.update` 会被节流甚至中断 Socket；本仓在 C# 侧用常驻 `SynchronizationContext` + `QueuePlayerLoopUpdate` 唤醒泵与 `beforeAssemblyReload` 同步快拆重连，在 Python 侧对 `read_console`/`get_editor_state`/`ping` 设置 2.0s 快速失败提示重试而非拖死客户端 30s 超时（`MCPForUnity/Editor/Services/Transport/TransportCommandDispatcher.cs#L70-L195`, `Server/src/transport/plugin_hub.py#L128-L136`）。
  2. **抑制重型引擎 40+ 工具的上下文膨胀与幻觉调错 API**：默认仅开启 `core` 工具组，其余 9 个专业组（`vfx`、`probuilder`、`profiling`、`asset_gen`、`docs` 等）通过 `manage_tools` 动态启停并推送 `tools/list_changed`；同时提供 `unity_reflect` + `unity_docs` 让模型先反射当前工程真实程序集签名再写 C# 代码（`Server/src/services/registry/tool_registry.py#L18-L32`, `Server/src/main.py#L346-L350`）。
  3. **多开 Unity 工程时的精确会话隔离**：通过 `mcpforunity://instances` 暴露 `Name@hash` 列表，多实例并存未显式指定目标时主动报错拦截，支持会话级 `set_active_instance` 或单次调用传 `unity_instance` 路由（`Server/src/main.py#L306-L310`, `Server/src/transport/plugin_hub.py#L93-L115`）。

## 技术栈与核心目录结构

- **语言 / 运行时 / 关键依赖**：
  - **服务端（`Server/`）**：Python `>=3.10`，基于 `fastmcp>=3.0.2,<4`、`mcp>=1.16.0`、`starlette`/`fastapi`、`uvicorn`、`pydantic>=2.12.5`、`httpx`，打包暴露 `mcp-for-unity`（MCP Server）与 `unity-mcp`（独立 CLI）双入口（`Server/pyproject.toml#L30-L59`）。
  - **引擎插件端（`MCPForUnity/`）**：C# UPM 包（`com.coplaydev.unity-mcp`），依赖 `com.unity.nuget.newtonsoft-json`、`uielements`、`test-framework` 等官方模块，可选安装 Roslyn（`Microsoft.CodeAnalysis`）支持 C# 12+ 内存动态编译（`MCPForUnity/package.json#L9-L19`, `MCPForUnity/Editor/Setup/RoslynInstaller.cs`）。
  - **开源协议**：**MIT**（`LICENSE`, `Server/pyproject.toml#L6`）。
- **关键目录树与职责划分**：
  - `Server/src/main.py` & `Server/src/transport/{plugin_hub,plugin_registry,unity_transport,unity_instance_middleware}.py`：FastMCP 生命周期、WebSocket `PluginHub` 中心与传统本地 TCP（默认 6400 端口）连接池。
  - `Server/src/services/tools/`（43 个工具模块）& `Server/src/services/resources/`（19 个只读 `mcpforunity://` 资源模块）& `Server/src/cli/`：全套场景/Prefab/动画/VFX/Shader/UI Toolkit/ProBuilder/Profiler/测试/AI 资产工具与命令行直连子命令。
  - `MCPForUnity/Editor/Services/Transport/`：`TransportCommandDispatcher.cs`（主线程队列执行器）、`WebSocketTransportClient.cs`（指数退避重连客户端）与 `StdioBridgeHost.cs`（64MB 帧上限、5 分钟长超时 TCP 服务端）。
  - `MCPForUnity/Editor/Security/SecureKeyStore/` & `Services/AssetGen/Import/SafeZipExtractor.cs`：跨平台原生凭据库封装与资产解压安全守卫。
  - `MCPForUnity/Editor/Clients/Configurators/`：24 个宿主客户端配置生成器（其中 `AntigravityConfigurator.cs#L13-L25` 已跟进 Antigravity 2.0 迁移至 `~/.gemini/config/mcp_config.json` 并兼容 `AntigravityIdeConfigurator.cs`）。

## 核心实现源码级剖析（附文件路径与行号）

1. **双模传输层：WebSocket `PluginHub` 与防断连本地 TCP `StdioBridgeHost`**（`Server/src/transport/plugin_hub.py#L62-L83,L117-L350`, `MCPForUnity/Editor/Services/Transport/Transports/StdioBridgeHost.cs#L64-L93`）：
   - **HTTP/WebSocket 模式**：Unity 侧 `WebSocketTransportClient` 主动连向 Python `PluginHub`，附带 `[0, 1, 3, 5, 10, 30]s` 退避重连并在 `beforeAssemblyReload` 同步触发 `ForceStop` 避免域重载异步死锁（`WebSocketTransportClient.cs#L28-L37,L171-L180`）；Python 侧每 10s 主动发 Ping（20s 无 Pong 判死），断连瞬间遍历 `_pending` 字典向所有在途 `Future` 注入 `PluginDisconnectedError` 快速失败，绝不傻等超时（`plugin_hub.py#L125-L127,L260-L278`）。
   - **MCP 会话追踪补丁**：因 FastMCP 未公开活跃客户端会话集，`plugin_hub.py` 通过 `_install_session_tracking` 猴子补丁拦截 `MiddlewareServerSession.__aenter__` 写入 `WeakSet`，从而在 Unity 动态注册自定义工具或切换工具组时向所有活跃客户端广播 `tools/list_changed`（`plugin_hub.py#L58-L83`）。
   - **Stdio 模式**：Unity 内置 `StdioBridgeHost` 监听本地 TCP（默认 `6400`，单帧上限 `64MB`），并将帧 I/O 超时从旧版易腰斩重任务的 30s 提升至默认 `300,000ms`（支持 `UNITY_MCP_STDIO_COMMAND_TIMEOUT_MS` 覆盖，`StdioBridgeHost.cs#L64-L92`）。
2. **Unity 主线程无锁防重入调度与失焦唤醒泵**（`MCPForUnity/Editor/Services/Transport/TransportCommandDispatcher.cs#L70-L269`）：
   - 静态构造函数在 Editor 加载期捕获主线程 `SynchronizationContext` 与 `ManagedThreadId`，并永久挂载 `EditorApplication.update += ProcessQueue`（特意将 `UnhookUpdateIfIdle` 置为空操作，根治后台线程重订阅失效导致「必须切回点击 Unity 窗口才能恢复通信」的顽疾，`#L70-L85,L215-L220`）。
   - 后台线程收到指令入队后立即调用 `RequestMainThreadPump` 投递 `EditorApplication.QueuePlayerLoopUpdate` 强制踢醒失焦节流状态下的主循环；`ProcessQueue` 用 `Interlocked.Exchange(ref _processingFlag, 1)` 防重入，并在锁内判断空队列零分配直接返回以消除每帧 GC 抖动（`#L170-L194,L222-L240`）。
3. **10 组按需工具可见性与内存动态 C# 编译器缓存**（`Server/src/services/registry/tool_registry.py#L18-L110`, `MCPForUnity/Editor/Tools/ExecuteCode.cs#L16-L143`）：
   - `@mcp_for_unity_tool` 装饰器将 43 个工具模块归入 10 个 `group:<name>` 标签，默认仅开启 `DEFAULT_ENABLED_GROUPS = {"core"}`，显著压缩初始工具列表体积。
   - `ExecuteCode.cs`（归属默认关闭的 `scripting_ext` 组，标有 `destructiveHint=True`）支持在不落盘创建 `.cs` 脚本的前提下内存编译执行方法体（自动优先 Roslyn C# 12+，回退 CodeDom C# 6）；针对 Mono 运行时无法卸载动态程序集导致每次调用永久泄漏一个 `MCPDynamic` Assembly 的底层缺陷（Issue `#1351`），源码引入容量 64 的 `_compiledCache` 对相同代码片段复用已编译程序集，直到下次 Domain Reload 清空（`ExecuteCode.cs#L35-L62`）。
4. **纵深安全边界：网络绑定门禁、OS 原生密钥库与防 Zip-Slip 白名单解压**（`MCPForUnity/Editor/Helpers/HttpEndpointUtility.cs#L215-L351`, `SecureKeyStore.cs#L22-L64`, `SafeZipExtractor.cs#L20-L71`）：
   - **环回与传输加密门禁**：`HttpEndpointUtility` 默认拒绝本地 HTTP 绑定 `0.0.0.0`/`::`（需显式开启 `AllowLanHttpBind`），强制将本地 `"localhost"` 规范化为字面量 `"127.0.0.1"` 以规避 Windows `getaddrinfo` 优先返回 `::1` 导致无 Happy Eyeballs 客户端（如 Codex `reqwest`）握手失败（`#L339-L348`）；远程模式默认强制 `https://` 且在 `PluginHub.on_connect` 执行 Fail-Closed API Key + `user_id` 双重校验（`plugin_hub.py#L173-L216`）。
   - **密钥不出桥**：AI 资产生成（fal / Meshy / Tripo / OpenRouter / Sketchfab）的 API Key 经 `SecureKeyStore` 按平台存入 macOS Keychain、Windows Credential Manager 或 Linux `secret-tool`（回退加密文件），仅在 C# Editor 发起外部请求时本地读取，绝不流经 MCP 通道（`SecureKeyStore.cs#L6-L40`）。
   - **外部模型包防代码注入**：`SafeZipExtractor.ExtractTo` 不仅校验 `Path.GetFullPath` 前缀阻断 `..` Zip-Slip 目录穿越，还强制支持 `allowedExtensions` 惰性资产后缀白名单，防止不可信第三方模型压缩包夹带 `.cs`/`.dll`/`.asmdef` 落入 `Assets/` 被 Unity 自动编译执行（`SafeZipExtractor.cs#L14-L61`）。

## 亮点设计 vs 局限/坑点

- **值得借鉴的设计**：
  - **显式区分 Resources（读状态）与 Tools（做变更）**：在系统指令中强制要求先读 `mcpforunity://editor/state`（检查 `data.compilation.is_compiling` 与 `data.advice.ready_for_tools`）及 `unity_reflect`，再发修改指令（`Server/src/main.py#L313-L350`）。
  - **工程细节打磨极其扎实**：从 `WindowsSelectorEventLoopPolicy` 修复 IPv4 问题、Windows 日志轮转 `PermissionError` 吞错跳过（`Server/src/main.py#L26-L27,L68-L79`），到 `execute_code` 超时后刻意剥离传输层 `hint="retry"` 防止仍在 Unity 后台跑的副作用代码被 Agent 重复执行（`Server/src/services/tools/execute_code.py#L103`）。
- **局限、隐含假设与潜在坑点**：
  1. **默认开启匿名云端遥测**：Python 端（`Server/src/core/telemetry.py#L145-L197`）与 C# 端（`TelemetryHelper.cs`）默认向 `https://api-prod.coplay.dev/telemetry/events` 发送启动、连接耗时与工具执行记录并落盘 `customer_uuid.txt`；注重隐私的环境需显式设置环境变量 `UNITY_MCP_DISABLE_TELEMETRY=1`（或 `DISABLE_TELEMETRY=1`）。
  2. **`execute_code` 的 `safety_checks` 仅为大小写不敏感子串黑名单**：`ExecuteCode.cs#L64-L78` 仅拦截 `"System.IO.File.Delete"`、`"Process.Start"`、`"while(true)"` 等 12 个字面模式（如源码注释坦诚声明并非真沙箱），通过 `using System.IO; File.Delete(...)` 或反射即可绕过，不可向不受信任的外部输入开放 `scripting_ext` 组。
  3. **FastMCP 内部私有 API 耦合风险**：`plugin_hub.py#L72-L83` 与 `#L139-L141` 直接依赖 `fastmcp.server.low_level.MiddlewareServerSession.__aenter__` 及 `mcp._transforms` 内部结构，升级 FastMCP 次版本时需回归测试会话通知与工具可见性同步。

## 可复用的模块或设计模式

- **如何迁移到未来项目**：
  - **本机接入最佳实践**：在 Antigravity 2.0 中直接使用内置 `AntigravityConfigurator` 生成配置，同时在环境变量注入 `UNITY_MCP_DISABLE_TELEMETRY=1`；日常保持仅开启 `core` + `docs` 组，遇到 Shader/ProBuilder/Profiler 专项任务再由 Agent 通过 `manage_tools` 临时挂载对应组。
  - **单线程 GUI 宿主桥接模板**：开发 Blender、Unreal Editor、CAD 或音视频宿主插件时，可直接照搬 `TransportCommandDispatcher.cs`（加载期锚定主线程 `SynchronizationContext` + 常驻 `update` 空判零分配快退 + 后台入队主动踢醒主循环 + 在途 `Future` 断连快败）。
  - **不可信资产包安全落盘器**：任何自动下载外部 ZIP 素材导入引擎目录的管线（如 Sketchfab/itch 资产拉取），均应复用 `SafeZipExtractor.cs` 的「绝对路径前缀锁 + 纯数据后缀白名单剔除可执行脚本」双门禁。
- **关联 Pattern**：（由 `synthesizer` 补全）

## Cross-Referenced Specimens

- [A-031 · REA + Gemini 4 Neon 速配与「万物逆向重建」十赛道证据工程教程拆解](https://oumuatown.com/articles/2026-11-30-archiveexplorer-rea-reverse-anything.md) — 证据工作区加外部核验闭环可复用，但1M无分块宣传失实
- [P-029 · 跨领域逆向重建桥接与验证矩阵：Web UI、音视频/3D、游戏、硬件与增长策略（Multi-Domain Reconstruction Bridges）](https://oumuatown.com/patterns/multi-domain-reconstruction-bridges-ui-media-game-hw-growth.md) — 五大领域表征升级桥接选型与安全坑点总图
