using System;
using System.IO;
using UnityEngine;
namespace LocalMcp.UnityServer
{
/// <summary>
/// MCP Server configuration loaded from .unity-mcp-config.json
/// </summary>
[Serializable]
public class McpServerConfig
{
public string projectName = "UnityProject";
public PortConfig ports = new PortConfig();
public string description = "";
[Serializable]
public class PortConfig
{
public int websocket = 5050;
public int http = 5051;
}
/// <summary>
/// Loads configuration from .unity-mcp-config.json in the project root
/// </summary>
public static McpServerConfig Load()
{
string configPath = Path.Combine(Application.dataPath, "../.unity-mcp-config.json");
if (File.Exists(configPath))
{
try
{
string json = File.ReadAllText(configPath);
var config = JsonUtility.FromJson<McpServerConfig>(json);
Debug.Log($"[MCP Config] Loaded from {configPath}");
Debug.Log($"[MCP Config] Project: {config.projectName}, WS Port: {config.ports.websocket}, HTTP Port: {config.ports.http}");
return config;
}
catch (Exception e)
{
Debug.LogError($"[MCP Config] Failed to load config: {e.Message}");
}
}
else
{
Debug.LogWarning($"[MCP Config] Config file not found at {configPath}, using defaults");
}
// Return default config
return new McpServerConfig();
}
}
/// <summary>
/// Runtime configuration written after server starts
/// Used by mcp-bridge to discover actual ports
/// </summary>
[Serializable]
public class McpRuntimeConfig
{
public string projectName;
public int websocketPort;
public int httpPort;
public int processId;
public string startTime;
public string unityVersion;
/// <summary>
/// Saves runtime configuration to .unity-mcp-runtime.json
/// </summary>
public static void Save(McpRuntimeConfig config)
{
string runtimePath = Path.Combine(Application.dataPath, "../.unity-mcp-runtime.json");
try
{
string json = JsonUtility.ToJson(config, true);
File.WriteAllText(runtimePath, json);
Debug.Log($"[MCP Runtime] Saved runtime config to {runtimePath}");
}
catch (Exception e)
{
Debug.LogError($"[MCP Runtime] Failed to save runtime config: {e.Message}");
}
}
/// <summary>
/// Deletes runtime configuration file (called on shutdown)
/// </summary>
public static void Delete()
{
string runtimePath = Path.Combine(Application.dataPath, "../.unity-mcp-runtime.json");
try
{
if (File.Exists(runtimePath))
{
File.Delete(runtimePath);
Debug.Log($"[MCP Runtime] Deleted runtime config");
}
}
catch (Exception e)
{
Debug.LogError($"[MCP Runtime] Failed to delete runtime config: {e.Message}");
}
}
}
}