hardcoded ports for now
parent
ec79442fd4
commit
8b67718734
|
|
@ -86,7 +86,8 @@ public class MCPEditorWindow : EditorWindow
|
|||
private bool isPythonServerConnected = false;
|
||||
private string pythonServerStatus = "Not Connected";
|
||||
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 float lastCheckTime = 0f;
|
||||
|
||||
|
|
@ -98,41 +99,11 @@ public class MCPEditorWindow : EditorWindow
|
|||
|
||||
private void OnEnable()
|
||||
{
|
||||
// Load server configuration
|
||||
LoadServerConfig();
|
||||
|
||||
// Check initial states
|
||||
isUnityBridgeRunning = UnityMCPBridge.IsRunning;
|
||||
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()
|
||||
{
|
||||
// Check Python server connection periodically
|
||||
|
|
@ -145,24 +116,12 @@ public class MCPEditorWindow : EditorWindow
|
|||
|
||||
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
|
||||
{
|
||||
using (var client = new TcpClient())
|
||||
{
|
||||
// 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)
|
||||
{
|
||||
// Try to send a ping message to verify connection is alive
|
||||
|
|
@ -181,7 +140,7 @@ public class MCPEditorWindow : EditorWindow
|
|||
isPythonServerConnected = true;
|
||||
pythonServerStatus = "Connected";
|
||||
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
|
||||
{
|
||||
|
|
@ -189,7 +148,7 @@ public class MCPEditorWindow : EditorWindow
|
|||
isPythonServerConnected = false;
|
||||
pythonServerStatus = "No Response";
|
||||
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)
|
||||
|
|
@ -207,7 +166,7 @@ public class MCPEditorWindow : EditorWindow
|
|||
isPythonServerConnected = false;
|
||||
pythonServerStatus = "Not Connected";
|
||||
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();
|
||||
}
|
||||
|
|
@ -239,8 +198,8 @@ public class MCPEditorWindow : EditorWindow
|
|||
EditorGUILayout.LabelField(pythonServerStatus);
|
||||
EditorGUILayout.EndHorizontal();
|
||||
|
||||
EditorGUILayout.LabelField($"Unity Port: {serverConfig?.unityPort}");
|
||||
EditorGUILayout.LabelField($"MCP Port: {serverConfig?.mcpPort}");
|
||||
EditorGUILayout.LabelField($"Unity Port: {unityPort}");
|
||||
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.EndVertical();
|
||||
|
||||
|
|
@ -250,7 +209,7 @@ public class MCPEditorWindow : EditorWindow
|
|||
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
|
||||
EditorGUILayout.LabelField("Unity MCP Bridge", EditorStyles.boldLabel);
|
||||
EditorGUILayout.LabelField($"Status: {(isUnityBridgeRunning ? "Running" : "Stopped")}");
|
||||
EditorGUILayout.LabelField($"Port: {serverConfig?.unityPort}");
|
||||
EditorGUILayout.LabelField($"Port: {unityPort}");
|
||||
|
||||
if (GUILayout.Button(isUnityBridgeRunning ? "Stop Bridge" : "Start Bridge"))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ public static partial class UnityMCPBridge
|
|||
private static bool isRunning = false;
|
||||
private static readonly object lockObj = new object();
|
||||
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
|
||||
public static bool IsRunning => isRunning;
|
||||
|
|
@ -41,45 +41,17 @@ public static partial class UnityMCPBridge
|
|||
|
||||
static UnityMCPBridge()
|
||||
{
|
||||
LoadServerConfig();
|
||||
Start();
|
||||
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()
|
||||
{
|
||||
if (isRunning) return;
|
||||
isRunning = true;
|
||||
listener = new TcpListener(IPAddress.Loopback, serverConfig.unityPort);
|
||||
listener = new TcpListener(IPAddress.Loopback, unityPort);
|
||||
listener.Start();
|
||||
Debug.Log($"UnityMCPBridge started on port {serverConfig.unityPort}.");
|
||||
Debug.Log($"UnityMCPBridge started on port {unityPort}.");
|
||||
Task.Run(ListenerLoop);
|
||||
EditorApplication.update += ProcessCommands;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,73 +4,27 @@ This file contains all configurable parameters for the server.
|
|||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Any
|
||||
import json
|
||||
import os
|
||||
|
||||
@dataclass
|
||||
class ServerConfig:
|
||||
"""Main configuration class for the MCP server."""
|
||||
|
||||
# Network settings
|
||||
unity_host: str
|
||||
unity_port: int
|
||||
mcp_port: int
|
||||
unity_host: str = "localhost"
|
||||
unity_port: int = 6400
|
||||
mcp_port: int = 6500
|
||||
|
||||
# Connection settings
|
||||
connection_timeout: float
|
||||
buffer_size: int
|
||||
connection_timeout: float = 15.0
|
||||
buffer_size: int = 32768
|
||||
|
||||
# Logging settings
|
||||
log_level: str
|
||||
log_format: str
|
||||
log_level: str = "INFO"
|
||||
log_format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
# Server settings
|
||||
max_retries: int
|
||||
retry_delay: float
|
||||
|
||||
@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)
|
||||
max_retries: int = 3
|
||||
retry_delay: float = 1.0
|
||||
|
||||
# Create a global config instance
|
||||
try:
|
||||
config = ServerConfig.from_file()
|
||||
except FileNotFoundError as e:
|
||||
print(f"Error: {e}")
|
||||
print("Please ensure config.json exists in the Assets/MCPServer directory")
|
||||
raise
|
||||
config = ServerConfig()
|
||||
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