一个完整的MCP (Model Context Protocol) 实现,允许AI助手(如Trae)通过自然语言控制Unity编辑器。本项目通过HTTP桥接MCP协议与Unity编辑器,实现了18个核心Unity操作工具。
Unity MCP Server是一个开源项目,旨在通过MCP协议将AI助手与Unity编辑器连接起来。它由两个主要组件组成:
- Node.js MCP Server - 实现MCP协议规范,处理来自AI助手的请求
- Unity HTTP Server - 在Unity编辑器中运行,接收HTTP请求并执行Unity操作
这种架构使得开发者可以通过自然语言与Unity编辑器交互,极大地提高了开发效率和可访问性。
- ✅ 18个核心Unity操作工具 - 涵盖对象创建、变换、材质、动画等
- ✅ 完整的MCP协议支持 - 标准化的AI助手集成
- ✅ 线程安全设计 - 所有Unity操作在主线程执行
- ✅ 实时响应 - 快速的请求-响应机制
- ✅ 易于扩展 - 清晰的代码结构,便于添加新功能
- ✅ 跨平台支持 - 支持Windows、macOS和Linux
| 工具名称 | 功能描述 |
|---|---|
ping |
检查Unity连接状态 |
create_primitive |
创建基础几何体(Cube, Sphere, Capsule等) |
create_light |
创建光源(Directional, Point, Spot等) |
create_camera |
创建相机 |
create_empty |
创建空物体 |
delete_object |
删除物体 |
find_object |
查找物体信息 |
list_objects |
列出场景中所有物体 |
set_transform |
设置物体的位置、旋转、缩放 |
get_transform |
获取物体的变换信息 |
add_component |
添加组件(如Rigidbody, Collider等) |
set_material |
设置材质颜色 |
play_animation |
播放动画 |
set_active |
启用/禁用物体 |
set_parent |
设置父子关系 |
get_scene_info |
获取场景信息 |
save_scene |
保存场景 |
load_scene |
加载场景 |
┌─────────────┐ MCP Protocol ┌──────────────┐ HTTP ┌─────────────┐
│ AI助手 │ ═══════════════════► │ Node.js MCP │ ═══════════► │ Unity HTTP │
│ (Trae等) │ │ Server │ │ Server │
└─────────────┘ └──────────────┘ └─────────────┘
│
▼
┌─────────────┐
│ Unity Editor│
└─────────────┘
Node.js MCP Server:
- Node.js 20+
- TypeScript 5.3+
- @modelcontextprotocol/sdk - MCP协议官方SDK
- axios - HTTP客户端
- zod - 数据验证
Unity HTTP Server:
- Unity 2020.3+
- C# .NET Standard 2.0
- System.Net.HttpListener - HTTP服务器
- AI助手通过MCP协议发送请求到Node.js MCP Server
- Node.js Server解析请求并转换为HTTP请求
- Unity HTTP Server接收HTTP请求并在主线程执行Unity操作
- Unity操作结果通过HTTP响应返回
- Node.js Server将结果转换为MCP响应格式
- AI助手接收并处理响应
- Node.js: 20.0.0 或更高版本
- npm: 9.0.0 或更高版本
- Unity: 2020.3 LTS 或更高版本
- TypeScript: 5.3.0 或更高版本(通过npm安装)
- Python: 3.7+(用于测试脚本)
- Git: 用于版本控制
- Windows 10/11
- macOS 10.15+
- Linux (Ubuntu 18.04+, Debian 10+, Fedora 33+)
git clone https://github.com/yourusername/unity-mcp-server.git
cd unity-mcp-servercd server
npm installnpm run build- 将
MCPServer.cs文件复制到你的Unity项目的Assets/Editor/目录 - 在Unity编辑器中打开项目
- 点击菜单
Tools > MCP > Start Server - 在Console中确认服务器已启动
在Trae或其他MCP客户端的配置文件中添加:
{
"mcpServers": {
"unity": {
"command": "node",
"args": ["./server/build/index.js"],
"env": {
"UNITY_URL": "http://localhost:5000"
}
}
}
}使用提供的测试脚本:
python test_unity_connection.py或在AI助手中输入:
检查Unity连接状态
默认端口为 5000。如需修改:
Node.js Server:
在 server/src/index.ts 中修改:
const UNITY_URL = process.env.UNITY_URL || "http://localhost:5000";Unity Server:
在 MCPServer.cs 中修改:
listener.Prefixes.Add("http://localhost:5000/");| 变量名 | 默认值 | 描述 |
|---|---|---|
UNITY_URL |
http://localhost:5000 |
Unity HTTP服务器地址 |
NODE_ENV |
production |
Node.js运行环境 |
确保Unity编辑器的以下设置:
- Scripting Runtime Version: .NET Standard 2.0 或更高
- Api Compatibility Level: .NET Standard 2.0 或更高
- Allow unsafe code: 不需要
所有工具遵循MCP协议规范,使用JSON格式进行数据交换。
检查Unity连接状态。
参数: 无
返回示例:
{
"success": true,
"message": "pong",
"unityVersion": "2021.3.0f1",
"sceneName": "SampleScene",
"objectCount": 5
}创建基础几何体。
参数:
{
"type": "Cube",
"name": "MyCube",
"x": 0,
"y": 1,
"z": 0
}类型选项: Cube, Sphere, Capsule, Cylinder, Plane, Quad
返回示例:
{
"success": true,
"objectName": "MyCube",
"position": {"x": 0, "y": 1, "z": 0}
}创建光源。
参数:
{
"type": "Point",
"name": "MyLight",
"x": 0,
"y": 2,
"z": 0,
"r": 1,
"g": 0.8,
"b": 0.6,
"intensity": 1.5
}类型选项: Directional, Point, Spot, Area
设置物体的变换属性。
参数:
{
"name": "MyCube",
"x": 1,
"y": 2,
"z": 3,
"rotX": 45,
"rotY": 90,
"rotZ": 0,
"scaleX": 2,
"scaleY": 2,
"scaleZ": 2
}设置材质颜色。
参数:
{
"name": "MyCube",
"r": 1,
"g": 0,
"b": 0,
"a": 1
}颜色范围: 0.0 - 1.0
Unity HTTP服务器提供以下端点:
| 方法 | 端点 | 描述 |
|---|---|---|
| GET | /ping |
健康检查 |
| POST | /create_primitive |
创建几何体 |
| POST | /create_light |
创建光源 |
| POST | /create_camera |
创建相机 |
| POST | /create_empty |
创建空物体 |
| POST | /delete_object |
删除物体 |
| POST | /find_object |
查找物体 |
| POST | /list_objects |
列出物体 |
| POST | /set_transform |
设置变换 |
| POST | /get_transform |
获取变换 |
| POST | /add_component |
添加组件 |
| POST | /set_material |
设置材质 |
| POST | /play_animation |
播放动画 |
| POST | /set_active |
设置活动状态 |
| POST | /set_parent |
设置父子关系 |
| GET | /get_scene_info |
获取场景信息 |
| POST | /save_scene |
保存场景 |
| POST | /load_scene |
加载场景 |
在AI助手中,你可以使用自然语言执行以下操作:
创建物体:
在场景中心创建一个红色的立方体
在(0, 5, 0)位置创建一个球体
创建一个名为"Player"的空物体
操作变换:
将立方体移动到(2, 3, 4)
将球体旋转45度
将立方体缩放为原来的2倍
材质操作:
将立方体的颜色改为蓝色
将球体设置为半透明的绿色
场景管理:
列出场景中的所有物体
保存当前场景
加载名为"Level1"的场景
动画控制:
播放角色上的跑步动画
播放"Jump"触发器
import requests
# 测试连接
response = requests.get("http://localhost:5000/ping")
print(response.json())
# 创建立方体
data = {
"type": "Cube",
"name": "TestCube",
"position": {"x": 0, "y": 1, "z": 0}
}
response = requests.post("http://localhost:5000/create_primitive", json=data)
print(response.json())
# 列出物体
data = {"rootOnly": True}
response = requests.post("http://localhost:5000/list_objects", json=data)
print(response.json())const axios = require('axios');
const UNITY_URL = 'http://localhost:5000';
// 测试连接
async function ping() {
const response = await axios.get(`${UNITY_URL}/ping`);
console.log(response.data);
}
// 创建立方体
async function createCube() {
const data = {
type: 'Cube',
name: 'TestCube',
position: { x: 0, y: 1, z: 0 }
};
const response = await axios.post(`${UNITY_URL}/create_primitive`, data);
console.log(response.data);
}
// 列出物体
async function listObjects() {
const data = { rootOnly: true };
const response = await axios.post(`${UNITY_URL}/list_objects`, data);
console.log(response.data);
}编辑 server/src/index.ts,在 TOOLS 数组中添加:
{
name: "your_new_tool",
description: "Description of your tool",
inputSchema: {
type: "object",
properties: {
param1: {
type: "string",
description: "Parameter description"
}
},
required: ["param1"]
}
}在 CallToolRequestSchema 处理器中添加:
case "your_new_tool":
result = await callUnity("/your_endpoint", {
param1: args?.param1
});
break;编辑 MCPServer.cs,添加端点处理:
static void HandleYourEndpoint(HttpListenerContext context)
{
var data = ReadJsonBody<YourDataType>(context);
mainThreadActions.Enqueue(() =>
{
try
{
// 你的Unity操作逻辑
var response = new YourResponse { success = true };
WriteJsonResponse(context, 200, response);
}
catch (Exception ex)
{
WriteJsonResponse(context, 500, new ErrorResponse { success = false, error = ex.Message });
}
});
}在 HandleRequest 方法中添加路由:
case "/your_endpoint":
HandleYourEndpoint(context);
break;cd server
npm run inspector在Unity编辑器中:
- 打开Console窗口
- 查看以
[MCP]开头的日志 - 使用Debug.Log输出调试信息
# 启用调试模式
DEBUG=* node build/index.js
# 或使用VSCode调试
# 配置launch.json
{
"type": "node",
"request": "launch",
"name": "Debug MCP Server",
"program": "${workspaceFolder}/server/build/index.js"
}- 使用4空格缩进
- 使用单引号
- 添加类型注解
- 遵循ESLint规则
- 使用4空格缩进
- 使用PascalCase命名类和方法
- 使用camelCase命名变量
- 添加XML文档注释
我们欢迎所有形式的贡献!
- Fork本仓库
- 创建特性分支 (
git checkout -b feature/AmazingFeature) - 提交更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 开启Pull Request
使用语义化提交信息:
feat:新功能fix:修复bugdocs:文档更新style:代码格式调整refactor:代码重构test:测试相关chore:构建/工具相关
示例:
feat: add support for creating particle systems
fix: resolve memory leak in object listing
docs: update API documentation
所有提交都需要通过代码审查。请确保:
- 代码符合项目规范
- 添加了必要的测试
- 更新了相关文档
- 没有引入新的警告
报告bug时,请提供:
- 详细的问题描述
- 复现步骤
- 预期行为
- 实际行为
- 环境信息(Unity版本、操作系统等)
- 相关日志或截图
A: 检查以下几点:
- 确保Unity编辑器正在运行
- 检查端口5000是否被占用
- 查看Unity Console中的错误信息
- 确保MCPServer.cs在正确的目录(Assets/Editor/)
A: 尝试以下步骤:
- 确认Unity服务器已启动
- 检查UNITY_URL环境变量配置
- 使用测试脚本验证连接
- 检查防火墙设置
A: 可能的原因:
- Unity编辑器未激活(失去焦点)
- 操作队列阻塞
- 网络连接问题
- 查看Console日志获取详细错误
A: 参见端口配置章节。
A: 支持2020.3 LTS及更高版本。建议使用最新的LTS版本。
A: 当前版本主要用于开发和测试。生产环境使用需要额外的安全措施和性能优化。
本项目采用MIT许可证。详见 LICENSE 文件。
MIT License
Copyright (c) 2024 Unity MCP Server Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
感谢以下开源项目:
- Model Context Protocol - MCP协议规范
- Anthropic - MCP协议的开发者
- Unity Technologies - Unity游戏引擎
- 问题反馈: GitHub Issues
- 功能建议: GitHub Discussions
- 邮件: your.email@example.com
当前版本: v1.0.0
最近更新: 2024-03-02
项目状态: ✅ 稳定发布
- 支持更多Unity组件类型
- 添加资源管理功能
- 支持多场景操作
- 添加撤销/重做功能
- 性能优化
- 添加单元测试
- 支持Unity 2022+新特性
注意: 本项目需要Unity编辑器保持运行状态。所有操作都在Unity编辑器中执行,不会影响构建后的游戏。