本指南将帮助你快速集成和使用 MCP 协议到你的 Unity 项目中,详细介绍安装配置、使用示例、通信协议等内容。
按照以下步骤,你可以轻松地在 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。npm install @model-context-protocol/mcp-typings @model-context-protocol/mcp-server
npm run start
在 Assets/Editor 文件夹下创建一个新的 C# 脚本,命名为 HelloWorldCommandHandler.cs:
using UnityEngine;
using ModelContextProtocol;
public class HelloWorldCommandHandler : CommandHandler {
protected override void Handle(string[] args) {
// 在此处实现你的业务逻辑
Debug.Log("Hello, World!");
}
}
在 Assets/Editor 文件夹下创建一个新的 C# 脚本,命名为 MyResourceHandler.cs:
using UnityEngine;
using ModelContextProtocol;
public class MyResourceHandler : ResourceHandler {
protected override async Task Handle(Request request) {
// 在此处实现你的业务逻辑
return await Response.Ok("Hello, World!");
}
}
在 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!";
}
}
{
"id": "123", # 请求唯一标识符
"type": "command", # 请求类型,可以是 command、resource 或者 prompt
"method": "GET", # HTTP 方法,如 GET, POST 等
"path": "/hello", # 请求路径
"body": { # 请求正文
"message": "Hello"
}
}
{
"id": "123",
"success": true, # 是否成功
"result": { # 响应结果
"greeting": "World"
}
}
McpServerSettings.csusing 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 错误 | 检查日志文件以获取更多错误信息 |