hardcoded ports for now
parent
ec79442fd4
commit
8b67718734
|
|
@ -86,7 +86,8 @@ public class MCPEditorWindow : EditorWindow
|
||||||
private bool isPythonServerConnected = false;
|
private bool isPythonServerConnected = false;
|
||||||
private string pythonServerStatus = "Not Connected";
|
private string pythonServerStatus = "Not Connected";
|
||||||
private Color pythonServerStatusColor = Color.red;
|
private Color pythonServerStatusColor = Color.red;
|
||||||
private ServerConfig serverConfig;
|
private const int unityPort = 6400; // Hardcoded Unity port
|
||||||
|
private const int mcpPort = 6500; // Hardcoded MCP port
|
||||||
private const float CONNECTION_CHECK_INTERVAL = 2f; // Check every 2 seconds
|
private const float CONNECTION_CHECK_INTERVAL = 2f; // Check every 2 seconds
|
||||||
private float lastCheckTime = 0f;
|
private float lastCheckTime = 0f;
|
||||||
|
|
||||||
|
|
@ -98,41 +99,11 @@ public class MCPEditorWindow : EditorWindow
|
||||||
|
|
||||||
private void OnEnable()
|
private void OnEnable()
|
||||||
{
|
{
|
||||||
// Load server configuration
|
|
||||||
LoadServerConfig();
|
|
||||||
|
|
||||||
// Check initial states
|
// Check initial states
|
||||||
isUnityBridgeRunning = UnityMCPBridge.IsRunning;
|
isUnityBridgeRunning = UnityMCPBridge.IsRunning;
|
||||||
CheckPythonServerConnection();
|
CheckPythonServerConnection();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void LoadServerConfig()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// Get the directory of the current script
|
|
||||||
string scriptPath = Path.GetDirectoryName(typeof(MCPEditorWindow).Assembly.Location);
|
|
||||||
string configPath = Path.Combine(scriptPath, "..", "config.json");
|
|
||||||
|
|
||||||
if (File.Exists(configPath))
|
|
||||||
{
|
|
||||||
string jsonConfig = File.ReadAllText(configPath);
|
|
||||||
serverConfig = JsonConvert.DeserializeObject<ServerConfig>(jsonConfig);
|
|
||||||
UnityEngine.Debug.Log($"Loaded server config: Unity Port = {serverConfig.unityPort}, MCP Port = {serverConfig.mcpPort}");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
UnityEngine.Debug.LogError($"Server config file not found at: {configPath}");
|
|
||||||
serverConfig = new DefaultServerConfig();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
UnityEngine.Debug.LogError($"Error loading server config: {e.Message}");
|
|
||||||
serverConfig = new DefaultServerConfig();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void Update()
|
private void Update()
|
||||||
{
|
{
|
||||||
// Check Python server connection periodically
|
// Check Python server connection periodically
|
||||||
|
|
@ -145,24 +116,12 @@ public class MCPEditorWindow : EditorWindow
|
||||||
|
|
||||||
private async void CheckPythonServerConnection()
|
private async void CheckPythonServerConnection()
|
||||||
{
|
{
|
||||||
if (serverConfig == null)
|
|
||||||
{
|
|
||||||
LoadServerConfig(); // Reload config if not loaded
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate host is not null
|
|
||||||
if (string.IsNullOrEmpty(serverConfig.unityHost))
|
|
||||||
{
|
|
||||||
serverConfig.unityHost = "localhost"; // Fallback to localhost if null
|
|
||||||
UnityEngine.Debug.LogWarning("Unity host was null, defaulting to localhost");
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using (var client = new TcpClient())
|
using (var client = new TcpClient())
|
||||||
{
|
{
|
||||||
// Try to connect with a short timeout
|
// Try to connect with a short timeout
|
||||||
var connectTask = client.ConnectAsync(serverConfig.unityHost, serverConfig.unityPort);
|
var connectTask = client.ConnectAsync("localhost", unityPort);
|
||||||
if (await Task.WhenAny(connectTask, Task.Delay(1000)) == connectTask)
|
if (await Task.WhenAny(connectTask, Task.Delay(1000)) == connectTask)
|
||||||
{
|
{
|
||||||
// Try to send a ping message to verify connection is alive
|
// Try to send a ping message to verify connection is alive
|
||||||
|
|
@ -181,7 +140,7 @@ public class MCPEditorWindow : EditorWindow
|
||||||
isPythonServerConnected = true;
|
isPythonServerConnected = true;
|
||||||
pythonServerStatus = "Connected";
|
pythonServerStatus = "Connected";
|
||||||
pythonServerStatusColor = Color.green;
|
pythonServerStatusColor = Color.green;
|
||||||
UnityEngine.Debug.Log($"Python server connected successfully on port {serverConfig.unityPort}");
|
UnityEngine.Debug.Log($"Python server connected successfully on port {unityPort}");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|
@ -189,7 +148,7 @@ public class MCPEditorWindow : EditorWindow
|
||||||
isPythonServerConnected = false;
|
isPythonServerConnected = false;
|
||||||
pythonServerStatus = "No Response";
|
pythonServerStatus = "No Response";
|
||||||
pythonServerStatusColor = Color.yellow;
|
pythonServerStatusColor = Color.yellow;
|
||||||
UnityEngine.Debug.LogWarning($"Python server not responding on port {serverConfig.unityPort}");
|
UnityEngine.Debug.LogWarning($"Python server not responding on port {unityPort}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
|
|
@ -207,7 +166,7 @@ public class MCPEditorWindow : EditorWindow
|
||||||
isPythonServerConnected = false;
|
isPythonServerConnected = false;
|
||||||
pythonServerStatus = "Not Connected";
|
pythonServerStatus = "Not Connected";
|
||||||
pythonServerStatusColor = Color.red;
|
pythonServerStatusColor = Color.red;
|
||||||
UnityEngine.Debug.LogWarning($"Python server is not running or not accessible on port {serverConfig.unityPort}");
|
UnityEngine.Debug.LogWarning($"Python server is not running or not accessible on port {unityPort}");
|
||||||
}
|
}
|
||||||
client.Close();
|
client.Close();
|
||||||
}
|
}
|
||||||
|
|
@ -239,8 +198,8 @@ public class MCPEditorWindow : EditorWindow
|
||||||
EditorGUILayout.LabelField(pythonServerStatus);
|
EditorGUILayout.LabelField(pythonServerStatus);
|
||||||
EditorGUILayout.EndHorizontal();
|
EditorGUILayout.EndHorizontal();
|
||||||
|
|
||||||
EditorGUILayout.LabelField($"Unity Port: {serverConfig?.unityPort}");
|
EditorGUILayout.LabelField($"Unity Port: {unityPort}");
|
||||||
EditorGUILayout.LabelField($"MCP Port: {serverConfig?.mcpPort}");
|
EditorGUILayout.LabelField($"MCP Port: {mcpPort}");
|
||||||
EditorGUILayout.HelpBox("Start the Python server using command line: 'uv run server.py' in the Python directory", MessageType.Info);
|
EditorGUILayout.HelpBox("Start the Python server using command line: 'uv run server.py' in the Python directory", MessageType.Info);
|
||||||
EditorGUILayout.EndVertical();
|
EditorGUILayout.EndVertical();
|
||||||
|
|
||||||
|
|
@ -250,7 +209,7 @@ public class MCPEditorWindow : EditorWindow
|
||||||
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
|
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
|
||||||
EditorGUILayout.LabelField("Unity MCP Bridge", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Unity MCP Bridge", EditorStyles.boldLabel);
|
||||||
EditorGUILayout.LabelField($"Status: {(isUnityBridgeRunning ? "Running" : "Stopped")}");
|
EditorGUILayout.LabelField($"Status: {(isUnityBridgeRunning ? "Running" : "Stopped")}");
|
||||||
EditorGUILayout.LabelField($"Port: {serverConfig?.unityPort}");
|
EditorGUILayout.LabelField($"Port: {unityPort}");
|
||||||
|
|
||||||
if (GUILayout.Button(isUnityBridgeRunning ? "Stop Bridge" : "Start Bridge"))
|
if (GUILayout.Button(isUnityBridgeRunning ? "Stop Bridge" : "Start Bridge"))
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ public static partial class UnityMCPBridge
|
||||||
private static bool isRunning = false;
|
private static bool isRunning = false;
|
||||||
private static readonly object lockObj = new object();
|
private static readonly object lockObj = new object();
|
||||||
private static Dictionary<string, (string commandJson, TaskCompletionSource<string> tcs)> commandQueue = new();
|
private static Dictionary<string, (string commandJson, TaskCompletionSource<string> tcs)> commandQueue = new();
|
||||||
private static ServerConfig serverConfig;
|
private static readonly int unityPort = 6400; // Hardcoded port
|
||||||
|
|
||||||
// Add public property to expose running state
|
// Add public property to expose running state
|
||||||
public static bool IsRunning => isRunning;
|
public static bool IsRunning => isRunning;
|
||||||
|
|
@ -41,45 +41,17 @@ public static partial class UnityMCPBridge
|
||||||
|
|
||||||
static UnityMCPBridge()
|
static UnityMCPBridge()
|
||||||
{
|
{
|
||||||
LoadServerConfig();
|
|
||||||
Start();
|
Start();
|
||||||
EditorApplication.quitting += Stop;
|
EditorApplication.quitting += Stop;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void LoadServerConfig()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// Get the directory of the current script
|
|
||||||
string scriptPath = Path.GetDirectoryName(typeof(UnityMCPBridge).Assembly.Location);
|
|
||||||
string configPath = Path.Combine(scriptPath, "..", "config.json");
|
|
||||||
|
|
||||||
if (File.Exists(configPath))
|
|
||||||
{
|
|
||||||
string jsonConfig = File.ReadAllText(configPath);
|
|
||||||
serverConfig = JsonConvert.DeserializeObject<ServerConfig>(jsonConfig);
|
|
||||||
Debug.Log($"Loaded server config: Unity Port = {serverConfig.unityPort}, MCP Port = {serverConfig.mcpPort}");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Debug.LogError($"Server config file not found at: {configPath}");
|
|
||||||
serverConfig = new DefaultServerConfig();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Debug.LogError($"Error loading server config: {e.Message}");
|
|
||||||
serverConfig = new DefaultServerConfig();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void Start()
|
public static void Start()
|
||||||
{
|
{
|
||||||
if (isRunning) return;
|
if (isRunning) return;
|
||||||
isRunning = true;
|
isRunning = true;
|
||||||
listener = new TcpListener(IPAddress.Loopback, serverConfig.unityPort);
|
listener = new TcpListener(IPAddress.Loopback, unityPort);
|
||||||
listener.Start();
|
listener.Start();
|
||||||
Debug.Log($"UnityMCPBridge started on port {serverConfig.unityPort}.");
|
Debug.Log($"UnityMCPBridge started on port {unityPort}.");
|
||||||
Task.Run(ListenerLoop);
|
Task.Run(ListenerLoop);
|
||||||
EditorApplication.update += ProcessCommands;
|
EditorApplication.update += ProcessCommands;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,73 +4,27 @@ This file contains all configurable parameters for the server.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Dict, Any
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class ServerConfig:
|
class ServerConfig:
|
||||||
"""Main configuration class for the MCP server."""
|
"""Main configuration class for the MCP server."""
|
||||||
|
|
||||||
# Network settings
|
# Network settings
|
||||||
unity_host: str
|
unity_host: str = "localhost"
|
||||||
unity_port: int
|
unity_port: int = 6400
|
||||||
mcp_port: int
|
mcp_port: int = 6500
|
||||||
|
|
||||||
# Connection settings
|
# Connection settings
|
||||||
connection_timeout: float
|
connection_timeout: float = 15.0
|
||||||
buffer_size: int
|
buffer_size: int = 32768
|
||||||
|
|
||||||
# Logging settings
|
# Logging settings
|
||||||
log_level: str
|
log_level: str = "INFO"
|
||||||
log_format: str
|
log_format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||||
|
|
||||||
# Server settings
|
# Server settings
|
||||||
max_retries: int
|
max_retries: int = 3
|
||||||
retry_delay: float
|
retry_delay: float = 1.0
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_file(cls, config_path: str = None) -> "ServerConfig":
|
|
||||||
"""Load configuration from a JSON file."""
|
|
||||||
if config_path is None:
|
|
||||||
# Get the directory where this file is located
|
|
||||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
# Go up one directory to find config.json
|
|
||||||
config_path = os.path.join(os.path.dirname(current_dir), "config.json")
|
|
||||||
|
|
||||||
if not os.path.exists(config_path):
|
|
||||||
raise FileNotFoundError(f"Configuration file not found at {config_path}. Please ensure config.json exists.")
|
|
||||||
|
|
||||||
with open(config_path, 'r') as f:
|
|
||||||
config_dict = json.load(f)
|
|
||||||
return cls(**config_dict)
|
|
||||||
|
|
||||||
def to_file(self, config_path: str = None) -> None:
|
|
||||||
"""Save configuration to a JSON file."""
|
|
||||||
if config_path is None:
|
|
||||||
# Get the directory where this file is located
|
|
||||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
# Go up one directory to find config.json
|
|
||||||
config_path = os.path.join(os.path.dirname(current_dir), "config.json")
|
|
||||||
|
|
||||||
config_dict = {
|
|
||||||
"unity_host": self.unity_host,
|
|
||||||
"unity_port": self.unity_port,
|
|
||||||
"mcp_port": self.mcp_port,
|
|
||||||
"connection_timeout": self.connection_timeout,
|
|
||||||
"buffer_size": self.buffer_size,
|
|
||||||
"log_level": self.log_level,
|
|
||||||
"log_format": self.log_format,
|
|
||||||
"max_retries": self.max_retries,
|
|
||||||
"retry_delay": self.retry_delay
|
|
||||||
}
|
|
||||||
with open(config_path, 'w') as f:
|
|
||||||
json.dump(config_dict, f, indent=4)
|
|
||||||
|
|
||||||
# Create a global config instance
|
# Create a global config instance
|
||||||
try:
|
config = ServerConfig()
|
||||||
config = ServerConfig.from_file()
|
|
||||||
except FileNotFoundError as e:
|
|
||||||
print(f"Error: {e}")
|
|
||||||
print("Please ensure config.json exists in the Assets/MCPServer directory")
|
|
||||||
raise
|
|
||||||
11
config.json
11
config.json
|
|
@ -1,11 +0,0 @@
|
||||||
{
|
|
||||||
"unity_host": "localhost",
|
|
||||||
"unity_port": 6400,
|
|
||||||
"mcp_port": 6500,
|
|
||||||
"connection_timeout": 15.0,
|
|
||||||
"buffer_size": 32768,
|
|
||||||
"log_level": "INFO",
|
|
||||||
"log_format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
|
||||||
"max_retries": 3,
|
|
||||||
"retry_delay": 1.0
|
|
||||||
}
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
fileFormatVersion: 2
|
|
||||||
guid: 86c7cfcd92e19544abfbd1b410a0adf7
|
|
||||||
TextScriptImporter:
|
|
||||||
externalObjects: {}
|
|
||||||
userData:
|
|
||||||
assetBundleName:
|
|
||||||
assetBundleVariant:
|
|
||||||
Loading…
Reference in New Issue