article
README
🚀 Unity MCP 入门指南
本指南将帮助你快速集成和使用 MCP 协议到你的 Unity 项目中,详细介绍安装配置、使用示例、通信协议等内容。
🚀 快速开始
按照以下步骤,你可以轻松地在 Unity 项目中集成和使用 MCP 协议。
📦 安装指南
Unity 端安装步骤
- 下载最新版本的 MCP 模块。
- 将模块文件(
.unitypackage)导入到你的 Unity 项目中。 - 在
Assets/Editor文件夹下创建一个新的空文件,命名为McpServerSettings.cs。 - 添加以下内容到该文件:
using UnityEngine;
using ModelContextProtocol;
public static class McpServerSettings {
public const bool StartOnLaunch = true; // 是否在Unity启动时自动启动服务器
public const bool RestartOnPlayModeChange = true; // 在切换Play模式时是否重启服务器
}
- 打开
Edit > Preferences > Projects > External Tools,勾选Enable MCP Server Support。
TypeScript 端安装步骤
- 克隆 MCP 示例项目仓库。
- 安装依赖项:
npm install @model-context-protocol/mcp-typings @model-context-protocol/mcp-server
- 启动 TypeScript 服务器:
npm run start
💻 使用示例
基本 Command Handler(C#)
在 Assets/Editor 文件夹下创建一个新的 C# 脚本,命名为 HelloWorldCommandHandler.cs:
using UnityEngine;
using ModelContextProtocol;
public class HelloWorldCommandHandler : CommandHandler {
protected override void Handle(string[] args) {
// 在此处实现你的业务逻辑
Debug.Log("Hello, World!");
}
}
基本 Resource Handler(C#)
在 Assets/Editor 文件夹下创建一个新的 C# 脚本,命名为 MyResourceHandler.cs:
using UnityEngine;
using ModelContextProtocol;
public class MyResourceHandler : ResourceHandler {
protected override async Task<HttpResponse> Handle(Request request) {
// 在此处实现你的业务逻辑
return await Response.Ok("Hello, World!");
}
}
基本 Command Handler(TypeScript)
在 handlers/commands 文件夹下创建一个新的 TypeScript 文件,命名为 hello-world.ts:
import { CommandHandler } from "@model-context-protocol/mcp-server";
export class HelloWorldCommand extends CommandHandler {
async execute(args: string[]): Promise<string> {
// 在此处实现你的业务逻辑
return "Hello, World!";
}
}
🔧 技术细节
通信协议
基本请求响应结构(JSON)
{
"id": "123", # 请求唯一标识符
"type": "command", # 请求类型,可以是 command、resource 或者 prompt
"method": "GET", # HTTP 方法,如 GET, POST 等
"path": "/hello", # 请求路径
"body": { # 请求正文
"message": "Hello"
}
}
响应结构(JSON)
{
"id": "123",
"success": true, # 是否成功
"result": { # 响应结果
"greeting": "World"
}
}
请求流程
- 客户端发送请求到 TypeScript 服务器。
- 服务器将请求转发到 Unity MCP Server。
- Unity 根据请求路径找到对应的 Handler。
- Handler 在 Unity 主线程处理请求。
- 响应结果返回给 TypeScript 服务器。
- 服务器将结果格式化为 JSON 返回给客户端。
配置参考
示例 McpServerSettings.cs
using UnityEngine;
using ModelContextProtocol;
public static class McpServerSettings {
public const bool StartOnLaunch = true; // 是否在Unity启动时自动启动服务器
public const bool RestartOnPlayModeChange = true; // 在切换Play模式时是否重启服务器
}
示例 mcp-config.json
{
"port": 5005, # MCP Server 监听端口
"workers": 4, # 工作进程数
"logging": {
"level": "debug", # 日志级别:debug、info、warning、error
"console": true # 是否启用控制台日志
}
}
📚 详细文档
故障排除
| 问题描述 | 解决方案 | |----------|----------| | MCP Server 没有启动 | 确保 Unity 启动时自动启动服务器功能已启用 | | 请求无响应 | 检查防火墙设置,确保端口开放 | | 500 错误 | 检查日志文件以获取更多错误信息 |
微信扫一扫