Skip to content

zimimwang/UnityMCP

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Unity MCP Server

License: MIT Node.js Unity

一个完整的MCP (Model Context Protocol) 实现,允许AI助手(如Trae)通过自然语言控制Unity编辑器。本项目通过HTTP桥接MCP协议与Unity编辑器,实现了18个核心Unity操作工具。

目录

项目概述

Unity MCP Server是一个开源项目,旨在通过MCP协议将AI助手与Unity编辑器连接起来。它由两个主要组件组成:

  1. Node.js MCP Server - 实现MCP协议规范,处理来自AI助手的请求
  2. Unity HTTP Server - 在Unity编辑器中运行,接收HTTP请求并执行Unity操作

这种架构使得开发者可以通过自然语言与Unity编辑器交互,极大地提高了开发效率和可访问性。

主要特性

  • 18个核心Unity操作工具 - 涵盖对象创建、变换、材质、动画等
  • 完整的MCP协议支持 - 标准化的AI助手集成
  • 线程安全设计 - 所有Unity操作在主线程执行
  • 实时响应 - 快速的请求-响应机制
  • 易于扩展 - 清晰的代码结构,便于添加新功能
  • 跨平台支持 - 支持Windows、macOS和Linux

核心功能

支持的MCP工具

工具名称 功能描述
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服务器

数据流

  1. AI助手通过MCP协议发送请求到Node.js MCP Server
  2. Node.js Server解析请求并转换为HTTP请求
  3. Unity HTTP Server接收HTTP请求并在主线程执行Unity操作
  4. Unity操作结果通过HTTP响应返回
  5. Node.js Server将结果转换为MCP响应格式
  6. 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+)

快速开始

1. 克隆项目

git clone https://github.com/yourusername/unity-mcp-server.git
cd unity-mcp-server

2. 安装Node.js依赖

cd server
npm install

3. 编译TypeScript

npm run build

4. 配置Unity项目

  1. MCPServer.cs 文件复制到你的Unity项目的 Assets/Editor/ 目录
  2. 在Unity编辑器中打开项目
  3. 点击菜单 Tools > MCP > Start Server
  4. 在Console中确认服务器已启动

5. 配置MCP客户端

在Trae或其他MCP客户端的配置文件中添加:

{
  "mcpServers": {
    "unity": {
      "command": "node",
      "args": ["./server/build/index.js"],
      "env": {
        "UNITY_URL": "http://localhost:5000"
      }
    }
  }
}

6. 测试连接

使用提供的测试脚本:

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编辑器设置

确保Unity编辑器的以下设置:

  1. Scripting Runtime Version: .NET Standard 2.0 或更高
  2. Api Compatibility Level: .NET Standard 2.0 或更高
  3. Allow unsafe code: 不需要

API文档

MCP工具API

所有工具遵循MCP协议规范,使用JSON格式进行数据交换。

ping

检查Unity连接状态。

参数:

返回示例:

{
  "success": true,
  "message": "pong",
  "unityVersion": "2021.3.0f1",
  "sceneName": "SampleScene",
  "objectCount": 5
}

create_primitive

创建基础几何体。

参数:

{
  "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}
}

create_light

创建光源。

参数:

{
  "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

set_transform

设置物体的变换属性。

参数:

{
  "name": "MyCube",
  "x": 1,
  "y": 2,
  "z": 3,
  "rotX": 45,
  "rotY": 90,
  "rotZ": 0,
  "scaleX": 2,
  "scaleY": 2,
  "scaleZ": 2
}

set_material

设置材质颜色。

参数:

{
  "name": "MyCube",
  "r": 1,
  "g": 0,
  "b": 0,
  "a": 1
}

颜色范围: 0.0 - 1.0

HTTP端点

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"触发器

代码示例

使用Python测试

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())

使用JavaScript/Node.js

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);
}

开发指南

添加新工具

1. 在Node.js Server中添加工具定义

编辑 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"]
  }
}

2. 添加工具处理逻辑

CallToolRequestSchema 处理器中添加:

case "your_new_tool":
  result = await callUnity("/your_endpoint", {
    param1: args?.param1
  });
  break;

3. 在Unity中添加HTTP端点

编辑 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;

调试

使用MCP Inspector

cd server
npm run inspector

Unity调试

在Unity编辑器中:

  1. 打开Console窗口
  2. 查看以 [MCP] 开头的日志
  3. 使用Debug.Log输出调试信息

Node.js调试

# 启用调试模式
DEBUG=* node build/index.js

# 或使用VSCode调试
# 配置launch.json
{
  "type": "node",
  "request": "launch",
  "name": "Debug MCP Server",
  "program": "${workspaceFolder}/server/build/index.js"
}

代码规范

TypeScript

  • 使用4空格缩进
  • 使用单引号
  • 添加类型注解
  • 遵循ESLint规则

C#

  • 使用4空格缩进
  • 使用PascalCase命名类和方法
  • 使用camelCase命名变量
  • 添加XML文档注释

贡献指南

我们欢迎所有形式的贡献!

如何贡献

  1. Fork本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 开启Pull Request

提交规范

使用语义化提交信息:

  • feat: 新功能
  • fix: 修复bug
  • docs: 文档更新
  • style: 代码格式调整
  • refactor: 代码重构
  • test: 测试相关
  • chore: 构建/工具相关

示例:

feat: add support for creating particle systems
fix: resolve memory leak in object listing
docs: update API documentation

代码审查

所有提交都需要通过代码审查。请确保:

  • 代码符合项目规范
  • 添加了必要的测试
  • 更新了相关文档
  • 没有引入新的警告

问题报告

报告bug时,请提供:

  • 详细的问题描述
  • 复现步骤
  • 预期行为
  • 实际行为
  • 环境信息(Unity版本、操作系统等)
  • 相关日志或截图

常见问题

Q: Unity服务器无法启动?

A: 检查以下几点:

  1. 确保Unity编辑器正在运行
  2. 检查端口5000是否被占用
  3. 查看Unity Console中的错误信息
  4. 确保MCPServer.cs在正确的目录(Assets/Editor/)

Q: MCP连接失败?

A: 尝试以下步骤:

  1. 确认Unity服务器已启动
  2. 检查UNITY_URL环境变量配置
  3. 使用测试脚本验证连接
  4. 检查防火墙设置

Q: 操作没有响应?

A: 可能的原因:

  1. Unity编辑器未激活(失去焦点)
  2. 操作队列阻塞
  3. 网络连接问题
  4. 查看Console日志获取详细错误

Q: 如何修改默认端口?

A: 参见端口配置章节。

Q: 支持哪些Unity版本?

A: 支持2020.3 LTS及更高版本。建议使用最新的LTS版本。

Q: 可以在生产环境使用吗?

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.

致谢

感谢以下开源项目:

联系方式

项目状态

当前版本: v1.0.0

最近更新: 2024-03-02

项目状态: ✅ 稳定发布

路线图

  • 支持更多Unity组件类型
  • 添加资源管理功能
  • 支持多场景操作
  • 添加撤销/重做功能
  • 性能优化
  • 添加单元测试
  • 支持Unity 2022+新特性

注意: 本项目需要Unity编辑器保持运行状态。所有操作都在Unity编辑器中执行,不会影响构建后的游戏。

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors