Skip to content

feat: add remote host configuration support for Unity WebSocket connection #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Editor/UnityBridge/McpUnityEditorWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,19 @@ private void DrawServerTab()

EditorGUILayout.Space();

// Allow remote connections toggle
bool allowRemoteConnections = EditorGUILayout.Toggle(new GUIContent("Allow Remote Connections", "Allow connections from remote MCP bridges. When disabled, only localhost connections are allowed (default)."), settings.AllowRemoteConnections);
if (allowRemoteConnections != settings.AllowRemoteConnections)
{
settings.AllowRemoteConnections = allowRemoteConnections;
settings.SaveSettings();
// Restart server to apply binding change
mcpUnityServer.StopServer();
mcpUnityServer.StartServer();
}

EditorGUILayout.Space();

// Enable info logs toggle
bool enableInfoLogs = EditorGUILayout.Toggle(new GUIContent("Enable Info Logs", "Show informational logs in the Unity console"), settings.EnableInfoLogs);
if (enableInfoLogs != settings.EnableInfoLogs)
Expand Down
5 changes: 3 additions & 2 deletions Editor/UnityBridge/McpUnityServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,11 @@ public void StartServer()

try
{
_webSocketServer = new WebSocketServer($"ws://localhost:{McpUnitySettings.Instance.Port}");
var host = McpUnitySettings.Instance.AllowRemoteConnections ? "0.0.0.0" : "localhost";
_webSocketServer = new WebSocketServer($"ws://{host}:{McpUnitySettings.Instance.Port}");
_webSocketServer.AddWebSocketService("/McpUnity", () => new McpUnitySocketHandler(this));
_webSocketServer.Start();
McpLogger.LogInfo($"WebSocket server started successfully on port {McpUnitySettings.Instance.Port}.");
McpLogger.LogInfo($"WebSocket server started successfully on {host}:{McpUnitySettings.Instance.Port}.");
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)
{
Expand Down
3 changes: 3 additions & 0 deletions Editor/UnityBridge/McpUnitySettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ public class McpUnitySettings

[Tooltip("Optional: Full path to the npm executable (e.g., /Users/user/.asdf/shims/npm or C:\\path\\to\\npm.cmd). If not set, 'npm' from the system PATH will be used.")]
public string NpmExecutablePath = string.Empty;

[Tooltip("Allow connections from remote MCP bridges. When disabled, only localhost connections are allowed (default).")]
public bool AllowRemoteConnections = false;

/// <summary>
/// Singleton instance of settings
Expand Down
12 changes: 12 additions & 0 deletions README-ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,18 @@ MCP Unityサーバーを起動するには2つの方法があります:
> [!TIP]
> AIコーディングIDE(Claude Desktop、Cursor IDE、Windsurf IDEなど)とMCPサーバー間のタイムアウトは、使用するIDEによって異なる場合があります。

## オプション:リモート MCP ブリッジ接続を許可する

デフォルトでは、WebSocket サーバーは 'localhost' にバインドされています。他のマシンから MCP ブリッジ接続を許可するには、以下の手順に従ってください:

1. Unity エディターを開く
2. メニューから「Tools > MCP Unity > Server Window」を選択
3. 「Allow Remote Connections(リモート接続を許可)」チェックボックスを有効にする
4. Unity は WebSocket サーバーを '0.0.0.0'(すべてのインターフェース)にバインドします
5. Node.js サーバーを再起動して新しいホスト設定を適用する
6. リモートで MCP ブリッジを実行する場合は、環境変数 UNITY_HOST を Unity 実行マシンの IP アドレスに設定して起動:
`UNITY_HOST=192.168.1.100 node server.js`

## サポート & フィードバック

ご質問やサポートが必要な場合は、このリポジトリの[Issue](https://github.com/CoderGamester/mcp-unity/issues)を開くか、以下までご連絡ください:
Expand Down
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,17 @@ You can change depending on the OS you are using:
> [!TIP]
> The timeout between your AI Coding IDE (e.g., Claude Desktop, Cursor IDE, Windsurf IDE) and the MCP Server depends on the IDE.

## Optional: Allow Remote MCP Bridge Connections

By default, the WebSocket server binds to 'localhost'. To allow MCP bridge connections from other machines:

1. Open the Unity Editor
2. Navigate to Tools > MCP Unity > Server Window
3. Enable the "Allow Remote Connections" checkbox
4. Unity will bind the WebSocket server to '0.0.0.0' (all interfaces)
5. Restart the Node.js server to apply the new host configuration
6. Set the environment variable UNITY_HOST to your Unity machine's IP address when running the MCP bridge remotely: `UNITY_HOST=192.168.1.100 node server.js`

## <a name="debug-server"></a>Debugging the Server

<details>
Expand Down
12 changes: 12 additions & 0 deletions README_zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,18 @@ MCP Unity 通过将 Unity `Library/PackedCache` 文件夹添加到您的工作
> [!TIP]
> 您的 AI 编码 IDE(例如 Claude Desktop、Cursor IDE、Windsurf IDE)与 MCP 服务器之间的超时时间取决于 IDE。

## 可选:允许远程 MCP Bridge 连接

默认情况下,WebSocket 服务器绑定到 'localhost'。要允许来自其他设备的 MCP Bridge 连接,请执行以下步骤:

1. 打开 Unity 编辑器
2. 依次点击菜单「Tools > MCP Unity > Server Window」
3. 勾选"Allow Remote Connections(允许远程连接)"复选框
4. Unity 将 WebSocket 服务器绑定到 '0.0.0.0'(所有网络接口)
5. 重新启动 Node.js 服务器以应用新的主机配置
6. 在远程运行 MCP Bridge 时,将环境变量 UNITY_HOST 设置为 Unity 所在机器的 IP 地址:
`UNITY_HOST=192.168.1.100 node server.js`

## <a name="debug-server"></a>调试服务器

<details>
Expand Down
7 changes: 6 additions & 1 deletion Server~/src/unity/mcpUnity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ interface UnityResponse {
export class McpUnity {
private logger: Logger;
private port: number | null = null;
private host: string = 'localhost';
private ws: WebSocket | null = null;
private pendingRequests: Map<string, PendingRequest> = new Map<string, PendingRequest>();
private requestTimeout = 10000;
Expand Down Expand Up @@ -80,6 +81,10 @@ export class McpUnity {
this.port = configPort ? parseInt(configPort, 10) : 8090;
this.logger.info(`Using port: ${this.port} for Unity WebSocket connection`);

// Check environment variable first, then config file, then default to localhost
const configHost = process.env.UNITY_HOST || config.Host;
this.host = configHost || 'localhost';

// Initialize timeout from environment variable (in seconds; it is the same as Cline) or use default (10 seconds)
const configTimeout = config.RequestTimeoutSeconds;
this.requestTimeout = configTimeout ? parseInt(configTimeout, 10) * 1000 : 10000;
Expand All @@ -100,7 +105,7 @@ export class McpUnity {
this.disconnect();

return new Promise<void>((resolve, reject) => {
const wsUrl = `ws://localhost:${this.port}/McpUnity`;
const wsUrl = `ws://${this.host}:${this.port}/McpUnity`;
this.logger.debug(`Connecting to ${wsUrl}...`);

// Create connection options with headers for client identification
Expand Down