{"repo_name": "unity-mcp", "file_name": "/unity-mcp/UnityMcpBridge/Editor/UnityMcpBridge.cs", "inference_info": {"prefix_code": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\nusing UnityMcpBridge.Editor.Tools;\n\nnamespace UnityMcpBridge.Editor\n{\n [InitializeOnLoad]\n public static partial class UnityMcpBridge\n {\n private static TcpListener listener;\n private static bool isRunning = false;\n private static readonly object lockObj = new();\n private static Dictionary<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > commandQueue = new();\n private static readonly int unityPort = 6400; // Hardcoded port\n\n public static bool IsRunning => isRunning;\n\n ", "suffix_code": "\n\n static UnityMcpBridge()\n {\n Start();\n EditorApplication.quitting += Stop;\n }\n\n public static void Start()\n {\n Stop();\n\n try\n {\n ServerInstaller.EnsureServerInstalled();\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure UnityMcpServer is installed: {ex.Message}\");\n }\n\n if (isRunning)\n {\n return;\n }\n\n try\n {\n listener = new TcpListener(IPAddress.Loopback, unityPort);\n listener.Start();\n isRunning = true;\n Debug.Log($\"UnityMcpBridge started on port {unityPort}.\");\n // Assuming ListenerLoop and ProcessCommands are defined elsewhere\n Task.Run(ListenerLoop);\n EditorApplication.update += ProcessCommands;\n }\n catch (SocketException ex)\n {\n if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)\n {\n Debug.LogError(\n $\"Port {unityPort} is already in use. Ensure no other instances are running or change the port.\"\n );\n }\n else\n {\n Debug.LogError($\"Failed to start TCP listener: {ex.Message}\");\n }\n }\n }\n\n public static void Stop()\n {\n if (!isRunning)\n {\n return;\n }\n\n try\n {\n listener?.Stop();\n listener = null;\n isRunning = false;\n EditorApplication.update -= ProcessCommands;\n Debug.Log(\"UnityMcpBridge stopped.\");\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error stopping UnityMcpBridge: {ex.Message}\");\n }\n }\n\n private static async Task ListenerLoop()\n {\n while (isRunning)\n {\n try\n {\n TcpClient client = await listener.AcceptTcpClientAsync();\n // Enable basic socket keepalive\n client.Client.SetSocketOption(\n SocketOptionLevel.Socket,\n SocketOptionName.KeepAlive,\n true\n );\n\n // Set longer receive timeout to prevent quick disconnections\n client.ReceiveTimeout = 60000; // 60 seconds\n\n // Fire and forget each client connection\n _ = HandleClientAsync(client);\n }\n catch (Exception ex)\n {\n if (isRunning)\n {\n Debug.LogError($\"Listener error: {ex.Message}\");\n }\n }\n }\n }\n\n private static async Task HandleClientAsync(TcpClient client)\n {\n using (client)\n using (NetworkStream stream = client.GetStream())\n {\n byte[] buffer = new byte[8192];\n while (isRunning)\n {\n try\n {\n int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);\n if (bytesRead == 0)\n {\n break; // Client disconnected\n }\n\n string commandText = System.Text.Encoding.UTF8.GetString(\n buffer,\n 0,\n bytesRead\n );\n string commandId = Guid.NewGuid().ToString();\n TaskCompletionSource tcs = new();\n\n // Special handling for ping command to avoid JSON parsing\n if (commandText.Trim() == \"ping\")\n {\n // Direct response to ping without going through JSON parsing\n byte[] pingResponseBytes = System.Text.Encoding.UTF8.GetBytes(\n /*lang=json,strict*/\n \"{\\\"status\\\":\\\"success\\\",\\\"result\\\":{\\\"message\\\":\\\"pong\\\"}}\"\n );\n await stream.WriteAsync(pingResponseBytes, 0, pingResponseBytes.Length);\n continue;\n }\n\n lock (lockObj)\n {\n commandQueue[commandId] = (commandText, tcs);\n }\n\n string response = await tcs.Task;\n byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);\n await stream.WriteAsync(responseBytes, 0, responseBytes.Length);\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Client handler error: {ex.Message}\");\n break;\n }\n }\n }\n }\n\n private static void ProcessCommands()\n {\n List processedIds = new();\n lock (lockObj)\n {\n foreach (\n KeyValuePair<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > kvp in commandQueue.ToList()\n )\n {\n string id = kvp.Key;\n string commandText = kvp.Value.commandJson;\n TaskCompletionSource tcs = kvp.Value.tcs;\n\n try\n {\n // Special case handling\n if (string.IsNullOrEmpty(commandText))\n {\n var emptyResponse = new\n {\n status = \"error\",\n error = \"Empty command received\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(emptyResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Trim the command text to remove any whitespace\n commandText = commandText.Trim();\n\n // Non-JSON direct commands handling (like ping)\n if (commandText == \"ping\")\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n tcs.SetResult(JsonConvert.SerializeObject(pingResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Check if the command is valid JSON before attempting to deserialize\n if (!IsValidJson(commandText))\n {\n var invalidJsonResponse = new\n {\n status = \"error\",\n error = \"Invalid JSON format\",\n receivedText = commandText.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n tcs.SetResult(JsonConvert.SerializeObject(invalidJsonResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Normal JSON command processing\n Command command = JsonConvert.DeserializeObject(commandText);\n \n if (command == null)\n {\n var nullCommandResponse = new\n {\n status = \"error\",\n error = \"Command deserialized to null\",\n details = \"The command was valid JSON but could not be deserialized to a Command object\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(nullCommandResponse));\n }\n else\n {\n string responseJson = ExecuteCommand(command);\n tcs.SetResult(responseJson);\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error processing command: {ex.Message}\\n{ex.StackTrace}\");\n\n var response = new\n {\n status = \"error\",\n error = ex.Message,\n commandType = \"Unknown (error during processing)\",\n receivedText = commandText?.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n string responseJson = JsonConvert.SerializeObject(response);\n tcs.SetResult(responseJson);\n }\n\n processedIds.Add(id);\n }\n\n foreach (string id in processedIds)\n {\n commandQueue.Remove(id);\n }\n }\n }\n\n // Helper method to check if a string is valid JSON\n private static bool IsValidJson(string text)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n return false;\n }\n\n text = text.Trim();\n if (\n (text.StartsWith(\"{\") && text.EndsWith(\"}\"))\n || // Object\n (text.StartsWith(\"[\") && text.EndsWith(\"]\"))\n ) // Array\n {\n try\n {\n JToken.Parse(text);\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n return false;\n }\n\n private static string ExecuteCommand(Command command)\n {\n try\n {\n if (string.IsNullOrEmpty(command.type))\n {\n var errorResponse = new\n {\n status = \"error\",\n error = \"Command type cannot be empty\",\n details = \"A valid command type is required for processing\",\n };\n return JsonConvert.SerializeObject(errorResponse);\n }\n\n // Handle ping command for connection verification\n if (command.type.Equals(\"ping\", StringComparison.OrdinalIgnoreCase))\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n return JsonConvert.SerializeObject(pingResponse);\n }\n\n // Use JObject for parameters as the new handlers likely expect this\n JObject paramsObject = command.@params ?? new JObject();\n\n // Route command based on the new tool structure from the refactor plan\n object result = command.type switch\n {\n // Maps the command type (tool name) to the corresponding handler's static HandleCommand method\n // Assumes each handler class has a static method named 'HandleCommand' that takes JObject parameters\n \"manage_script\" => ManageScript.HandleCommand(paramsObject),\n \"manage_scene\" => ManageScene.HandleCommand(paramsObject),\n \"manage_editor\" => ManageEditor.HandleCommand(paramsObject),\n \"manage_gameobject\" => ManageGameObject.HandleCommand(paramsObject),\n \"manage_asset\" => ManageAsset.HandleCommand(paramsObject),\n \"manage_shader\" => ManageShader.HandleCommand(paramsObject),\n \"read_console\" => ReadConsole.HandleCommand(paramsObject),\n \"execute_menu_item\" => ExecuteMenuItem.HandleCommand(paramsObject),\n _ => throw new ArgumentException(\n $\"Unknown or unsupported command type: {command.type}\"\n ),\n };\n\n // Standard success response format\n var response = new { status = \"success\", result };\n return JsonConvert.SerializeObject(response);\n }\n catch (Exception ex)\n {\n // Log the detailed error in Unity for debugging\n Debug.LogError(\n $\"Error executing command '{command?.type ?? \"Unknown\"}': {ex.Message}\\n{ex.StackTrace}\"\n );\n\n // Standard error response format\n var response = new\n {\n status = \"error\",\n error = ex.Message, // Provide the specific error message\n command = command?.type ?? \"Unknown\", // Include the command type if available\n stackTrace = ex.StackTrace, // Include stack trace for detailed debugging\n paramsSummary = command?.@params != null\n ? GetParamsSummary(command.@params)\n : \"No parameters\", // Summarize parameters for context\n };\n return JsonConvert.SerializeObject(response);\n }\n }\n\n // Helper method to get a summary of parameters for error reporting\n private static string GetParamsSummary(JObject @params)\n {\n try\n {\n return @params == null || !@params.HasValues\n ? \"No parameters\"\n : string.Join(\n \", \",\n @params\n .Properties()\n .Select(static p =>\n $\"{p.Name}: {p.Value?.ToString()?[..Math.Min(20, p.Value?.ToString()?.Length ?? 0)]}\"\n )\n );\n }\n catch\n {\n return \"Could not summarize parameters\";\n }\n }\n }\n}\n", "middle_code": "public static bool FolderExists(string path)\n {\n if (string.IsNullOrEmpty(path))\n {\n return false;\n }\n if (path.Equals(\"Assets\", StringComparison.OrdinalIgnoreCase))\n {\n return true;\n }\n string fullPath = Path.Combine(\n Application.dataPath,\n path.StartsWith(\"Assets/\") ? path[7..] : path\n );\n return Directory.Exists(fullPath);\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/unity-mcp/UnityMcpBridge/Editor/Windows/UnityMcpEditorWindow.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing Newtonsoft.Json;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Data;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class UnityMcpEditorWindow : EditorWindow\n {\n private bool isUnityBridgeRunning = false;\n private Vector2 scrollPosition;\n private string pythonServerInstallationStatus = \"Not Installed\";\n private Color pythonServerInstallationStatusColor = Color.red;\n private const int unityPort = 6400; // Hardcoded Unity port\n private const int mcpPort = 6500; // Hardcoded MCP port\n private readonly McpClients mcpClients = new();\n \n // Script validation settings\n private int validationLevelIndex = 1; // Default to Standard\n private readonly string[] validationLevelOptions = new string[]\n {\n \"Basic - Only syntax checks\",\n \"Standard - Syntax + Unity practices\", \n \"Comprehensive - All checks + semantic analysis\",\n \"Strict - Full semantic validation (requires Roslyn)\"\n };\n \n // UI state\n private int selectedClientIndex = 0;\n\n [MenuItem(\"Window/Unity MCP\")]\n public static void ShowWindow()\n {\n GetWindow(\"MCP Editor\");\n }\n\n private void OnEnable()\n {\n UpdatePythonServerInstallationStatus();\n\n isUnityBridgeRunning = UnityMcpBridge.IsRunning;\n foreach (McpClient mcpClient in mcpClients.clients)\n {\n CheckMcpConfiguration(mcpClient);\n }\n \n // Load validation level setting\n LoadValidationLevelSetting();\n }\n\n private Color GetStatusColor(McpStatus status)\n {\n // Return appropriate color based on the status enum\n return status switch\n {\n McpStatus.Configured => Color.green,\n McpStatus.Running => Color.green,\n McpStatus.Connected => Color.green,\n McpStatus.IncorrectPath => Color.yellow,\n McpStatus.CommunicationError => Color.yellow,\n McpStatus.NoResponse => Color.yellow,\n _ => Color.red, // Default to red for error states or not configured\n };\n }\n\n private void UpdatePythonServerInstallationStatus()\n {\n string serverPath = ServerInstaller.GetServerPath();\n\n if (File.Exists(Path.Combine(serverPath, \"server.py\")))\n {\n string installedVersion = ServerInstaller.GetInstalledVersion();\n string latestVersion = ServerInstaller.GetLatestVersion();\n\n if (ServerInstaller.IsNewerVersion(latestVersion, installedVersion))\n {\n pythonServerInstallationStatus = \"Newer Version Available\";\n pythonServerInstallationStatusColor = Color.yellow;\n }\n else\n {\n pythonServerInstallationStatus = \"Up to Date\";\n pythonServerInstallationStatusColor = Color.green;\n }\n }\n else\n {\n pythonServerInstallationStatus = \"Not Installed\";\n pythonServerInstallationStatusColor = Color.red;\n }\n }\n\n\n private void DrawStatusDot(Rect statusRect, Color statusColor, float size = 12)\n {\n float offsetX = (statusRect.width - size) / 2;\n float offsetY = (statusRect.height - size) / 2;\n Rect dotRect = new(statusRect.x + offsetX, statusRect.y + offsetY, size, size);\n Vector3 center = new(\n dotRect.x + (dotRect.width / 2),\n dotRect.y + (dotRect.height / 2),\n 0\n );\n float radius = size / 2;\n\n // Draw the main dot\n Handles.color = statusColor;\n Handles.DrawSolidDisc(center, Vector3.forward, radius);\n\n // Draw the border\n Color borderColor = new(\n statusColor.r * 0.7f,\n statusColor.g * 0.7f,\n statusColor.b * 0.7f\n );\n Handles.color = borderColor;\n Handles.DrawWireDisc(center, Vector3.forward, radius);\n }\n\n private void OnGUI()\n {\n scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);\n\n // Header\n DrawHeader();\n \n // Main sections in a more compact layout\n EditorGUILayout.BeginHorizontal();\n \n // Left column - Status and Bridge\n EditorGUILayout.BeginVertical(GUILayout.Width(position.width * 0.5f));\n DrawServerStatusSection();\n EditorGUILayout.Space(5);\n DrawBridgeSection();\n EditorGUILayout.EndVertical();\n \n // Right column - Validation Settings\n EditorGUILayout.BeginVertical();\n DrawValidationSection();\n EditorGUILayout.EndVertical();\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Unified MCP Client Configuration\n DrawUnifiedClientConfiguration();\n\n EditorGUILayout.EndScrollView();\n }\n\n private void DrawHeader()\n {\n EditorGUILayout.Space(15);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 40);\n EditorGUI.DrawRect(titleRect, new Color(0.2f, 0.2f, 0.2f, 0.1f));\n \n GUIStyle titleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 16,\n alignment = TextAnchor.MiddleLeft\n };\n \n GUI.Label(\n new Rect(titleRect.x + 15, titleRect.y + 8, titleRect.width - 30, titleRect.height),\n \"Unity MCP Editor\",\n titleStyle\n );\n EditorGUILayout.Space(15);\n }\n\n private void DrawServerStatusSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Server Status\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(statusRect, pythonServerInstallationStatusColor, 16);\n \n GUIStyle statusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(pythonServerInstallationStatus, statusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(5);\n GUIStyle portStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 11\n };\n EditorGUILayout.LabelField($\"Ports: Unity {unityPort}, MCP {mcpPort}\", portStyle);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawBridgeSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Unity Bridge\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUILayout.BeginHorizontal();\n Color bridgeColor = isUnityBridgeRunning ? Color.green : Color.red;\n Rect bridgeStatusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(bridgeStatusRect, bridgeColor, 16);\n \n GUIStyle bridgeStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(isUnityBridgeRunning ? \"Running\" : \"Stopped\", bridgeStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(8);\n if (GUILayout.Button(isUnityBridgeRunning ? \"Stop Bridge\" : \"Start Bridge\", GUILayout.Height(32)))\n {\n ToggleUnityBridge();\n }\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawValidationSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Script Validation\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUI.BeginChangeCheck();\n validationLevelIndex = EditorGUILayout.Popup(\"Validation Level\", validationLevelIndex, validationLevelOptions, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n SaveValidationLevelSetting();\n }\n \n EditorGUILayout.Space(8);\n string description = GetValidationLevelDescription(validationLevelIndex);\n EditorGUILayout.HelpBox(description, MessageType.Info);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawUnifiedClientConfiguration()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"MCP Client Configuration\", sectionTitleStyle);\n EditorGUILayout.Space(10);\n \n // Client selector\n string[] clientNames = mcpClients.clients.Select(c => c.name).ToArray();\n EditorGUI.BeginChangeCheck();\n selectedClientIndex = EditorGUILayout.Popup(\"Select Client\", selectedClientIndex, clientNames, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n selectedClientIndex = Mathf.Clamp(selectedClientIndex, 0, mcpClients.clients.Count - 1);\n }\n \n EditorGUILayout.Space(10);\n \n if (mcpClients.clients.Count > 0 && selectedClientIndex < mcpClients.clients.Count)\n {\n McpClient selectedClient = mcpClients.clients[selectedClientIndex];\n DrawClientConfigurationCompact(selectedClient);\n }\n \n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawClientConfigurationCompact(McpClient mcpClient)\n {\n // Status display\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n Color statusColor = GetStatusColor(mcpClient.status);\n DrawStatusDot(statusRect, statusColor, 16);\n \n GUIStyle clientStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(mcpClient.configStatus, clientStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Action buttons in horizontal layout\n EditorGUILayout.BeginHorizontal();\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n if (GUILayout.Button(\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n else\n {\n if (GUILayout.Button($\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n \n if (GUILayout.Button(\"Manual Setup\", GUILayout.Height(32)))\n {\n string configPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)\n ? mcpClient.windowsConfigPath\n : mcpClient.linuxConfigPath;\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n string pythonDir = FindPackagePythonDirectory();\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n VSCodeManualSetupWindow.ShowWindow(configPath, manualConfigJson);\n }\n else\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n }\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(8);\n // Quick info\n GUIStyle configInfoStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 10\n };\n EditorGUILayout.LabelField($\"Config: {Path.GetFileName(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? mcpClient.windowsConfigPath : mcpClient.linuxConfigPath)}\", configInfoStyle);\n }\n\n private void ToggleUnityBridge()\n {\n if (isUnityBridgeRunning)\n {\n UnityMcpBridge.Stop();\n }\n else\n {\n UnityMcpBridge.Start();\n }\n\n isUnityBridgeRunning = !isUnityBridgeRunning;\n }\n\n private string WriteToConfig(string pythonDir, string configPath, McpClient mcpClient = null)\n {\n // Create configuration object for unityMCP\n McpConfigServer unityMCPConfig = new()\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n\n // Read existing config if it exists\n string existingJson = \"{}\";\n if (File.Exists(configPath))\n {\n try\n {\n existingJson = File.ReadAllText(configPath);\n }\n catch (Exception e)\n {\n Debug.LogWarning($\"Error reading existing config: {e.Message}.\");\n }\n }\n\n // Parse the existing JSON while preserving all properties\n dynamic existingConfig = JsonConvert.DeserializeObject(existingJson);\n existingConfig ??= new Newtonsoft.Json.Linq.JObject();\n\n // Handle different client types with a switch statement\n //Comments: Interestingly, VSCode has mcp.servers.unityMCP while others have mcpServers.unityMCP, which is why we need to prevent this\n switch (mcpClient?.mcpType)\n {\n case McpTypes.VSCode:\n // VSCode specific configuration\n // Ensure mcp object exists\n if (existingConfig.mcp == null)\n {\n existingConfig.mcp = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Ensure mcp.servers object exists\n if (existingConfig.mcp.servers == null)\n {\n existingConfig.mcp.servers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in VSCode settings\n existingConfig.mcp.servers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n\n default:\n // Standard MCP configuration (Claude Desktop, Cursor, etc.)\n // Ensure mcpServers object exists\n if (existingConfig.mcpServers == null)\n {\n existingConfig.mcpServers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in standard MCP settings\n existingConfig.mcpServers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n }\n\n // Write the merged configuration back to file\n string mergedJson = JsonConvert.SerializeObject(existingConfig, jsonSettings);\n File.WriteAllText(configPath, mergedJson);\n\n return \"Configured successfully\";\n }\n\n private void ShowManualConfigurationInstructions(string configPath, McpClient mcpClient)\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n\n // New method to show manual instructions without changing status\n private void ShowManualInstructionsWindow(string configPath, McpClient mcpClient)\n {\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n string manualConfigJson;\n \n // Create common JsonSerializerSettings\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n \n // Use switch statement to handle different client types\n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n // Create VSCode-specific configuration with proper format\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n break;\n \n default:\n // Create standard MCP configuration for other clients\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n break;\n }\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private string FindPackagePythonDirectory()\n {\n string pythonDir = ServerInstaller.GetServerPath();\n\n try\n {\n // Try to find the package using Package Manager API\n UnityEditor.PackageManager.Requests.ListRequest request =\n UnityEditor.PackageManager.Client.List();\n while (!request.IsCompleted) { } // Wait for the request to complete\n\n if (request.Status == UnityEditor.PackageManager.StatusCode.Success)\n {\n foreach (UnityEditor.PackageManager.PackageInfo package in request.Result)\n {\n if (package.name == \"com.justinpbarnett.unity-mcp\")\n {\n string packagePath = package.resolvedPath;\n string potentialPythonDir = Path.Combine(packagePath, \"Python\");\n\n if (\n Directory.Exists(potentialPythonDir)\n && File.Exists(Path.Combine(potentialPythonDir, \"server.py\"))\n )\n {\n return potentialPythonDir;\n }\n }\n }\n }\n else if (request.Error != null)\n {\n Debug.LogError(\"Failed to list packages: \" + request.Error.message);\n }\n\n // If not found via Package Manager, try manual approaches\n // First check for local installation\n string[] possibleDirs =\n {\n Path.GetFullPath(Path.Combine(Application.dataPath, \"unity-mcp\", \"Python\")),\n };\n\n foreach (string dir in possibleDirs)\n {\n if (Directory.Exists(dir) && File.Exists(Path.Combine(dir, \"server.py\")))\n {\n return dir;\n }\n }\n\n // If still not found, return the placeholder path\n Debug.LogWarning(\"Could not find Python directory, using placeholder path\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"Error finding package path: {e.Message}\");\n }\n\n return pythonDir;\n }\n\n private string ConfigureMcpClient(McpClient mcpClient)\n {\n try\n {\n // Determine the config file path based on OS\n string configPath;\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n return \"Unsupported OS\";\n }\n\n // Create directory if it doesn't exist\n Directory.CreateDirectory(Path.GetDirectoryName(configPath));\n\n // Find the server.py file location\n string pythonDir = ServerInstaller.GetServerPath();\n\n if (pythonDir == null || !File.Exists(Path.Combine(pythonDir, \"server.py\")))\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n return \"Manual Configuration Required\";\n }\n\n string result = WriteToConfig(pythonDir, configPath, mcpClient);\n\n // Update the client status after successful configuration\n if (result == \"Configured successfully\")\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n\n return result;\n }\n catch (Exception e)\n {\n // Determine the config file path based on OS for error message\n string configPath = \"\";\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n Debug.LogError(\n $\"Failed to configure {mcpClient.name}: {e.Message}\\n{e.StackTrace}\"\n );\n return $\"Failed to configure {mcpClient.name}\";\n }\n }\n\n private void ShowCursorManualConfigurationInstructions(\n string configPath,\n McpClient mcpClient\n )\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n\n // Create the manual configuration message\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private void LoadValidationLevelSetting()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n validationLevelIndex = savedLevel.ToLower() switch\n {\n \"basic\" => 0,\n \"standard\" => 1,\n \"comprehensive\" => 2,\n \"strict\" => 3,\n _ => 1 // Default to Standard\n };\n }\n\n private void SaveValidationLevelSetting()\n {\n string levelString = validationLevelIndex switch\n {\n 0 => \"basic\",\n 1 => \"standard\",\n 2 => \"comprehensive\",\n 3 => \"strict\",\n _ => \"standard\"\n };\n EditorPrefs.SetString(\"UnityMCP_ScriptValidationLevel\", levelString);\n }\n\n private string GetValidationLevelDescription(int index)\n {\n return index switch\n {\n 0 => \"Only basic syntax checks (braces, quotes, comments)\",\n 1 => \"Syntax checks + Unity best practices and warnings\",\n 2 => \"All checks + semantic analysis and performance warnings\",\n 3 => \"Full semantic validation with namespace/type resolution (requires Roslyn)\",\n _ => \"Standard validation\"\n };\n }\n\n public static string GetCurrentValidationLevel()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel;\n }\n\n private void CheckMcpConfiguration(McpClient mcpClient)\n {\n try\n {\n string configPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n mcpClient.SetStatus(McpStatus.UnsupportedOS);\n return;\n }\n\n if (!File.Exists(configPath))\n {\n mcpClient.SetStatus(McpStatus.NotConfigured);\n return;\n }\n\n string configJson = File.ReadAllText(configPath);\n string pythonDir = ServerInstaller.GetServerPath();\n \n // Use switch statement to handle different client types, extracting common logic\n string[] args = null;\n bool configExists = false;\n \n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n dynamic config = JsonConvert.DeserializeObject(configJson);\n \n if (config?.mcp?.servers?.unityMCP != null)\n {\n // Extract args from VSCode config format\n args = config.mcp.servers.unityMCP.args.ToObject();\n configExists = true;\n }\n break;\n \n default:\n // Standard MCP configuration check for Claude Desktop, Cursor, etc.\n McpConfig standardConfig = JsonConvert.DeserializeObject(configJson);\n \n if (standardConfig?.mcpServers?.unityMCP != null)\n {\n args = standardConfig.mcpServers.unityMCP.args;\n configExists = true;\n }\n break;\n }\n \n // Common logic for checking configuration status\n if (configExists)\n {\n if (pythonDir != null && \n Array.Exists(args, arg => arg.Contains(pythonDir, StringComparison.Ordinal)))\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n else\n {\n mcpClient.SetStatus(McpStatus.IncorrectPath);\n }\n }\n else\n {\n mcpClient.SetStatus(McpStatus.MissingConfig);\n }\n }\n catch (Exception e)\n {\n mcpClient.SetStatus(McpStatus.Error, e.Message);\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageGameObject.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json; // Added for JsonSerializationException\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\nusing UnityMcpBridge.Runtime.Serialization;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles GameObject manipulation within the current scene (CRUD, find, components).\n /// \n public static class ManageGameObject\n {\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Parameters used by various actions\n JToken targetToken = @params[\"target\"]; // Can be string (name/path) or int (instanceID)\n string searchMethod = @params[\"searchMethod\"]?.ToString().ToLower();\n\n // Get common parameters (consolidated)\n string name = @params[\"name\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString();\n string layer = @params[\"layer\"]?.ToString();\n JToken parentToken = @params[\"parent\"];\n\n // --- Add parameter for controlling non-public field inclusion ---\n bool includeNonPublicSerialized = @params[\"includeNonPublicSerialized\"]?.ToObject() ?? true; // Default to true\n // --- End add parameter ---\n\n // --- Prefab Redirection Check ---\n string targetPath =\n targetToken?.Type == JTokenType.String ? targetToken.ToString() : null;\n if (\n !string.IsNullOrEmpty(targetPath)\n && targetPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n // Allow 'create' (instantiate), 'find' (?), 'get_components' (?)\n if (action == \"modify\" || action == \"set_component_property\")\n {\n Debug.Log(\n $\"[ManageGameObject->ManageAsset] Redirecting action '{action}' for prefab '{targetPath}' to ManageAsset.\"\n );\n // Prepare params for ManageAsset.ModifyAsset\n JObject assetParams = new JObject();\n assetParams[\"action\"] = \"modify\"; // ManageAsset uses \"modify\"\n assetParams[\"path\"] = targetPath;\n\n // Extract properties.\n // For 'set_component_property', combine componentName and componentProperties.\n // For 'modify', directly use componentProperties.\n JObject properties = null;\n if (action == \"set_component_property\")\n {\n string compName = @params[\"componentName\"]?.ToString();\n JObject compProps = @params[\"componentProperties\"]?[compName] as JObject; // Handle potential nesting\n if (string.IsNullOrEmpty(compName))\n return Response.Error(\n \"Missing 'componentName' for 'set_component_property' on prefab.\"\n );\n if (compProps == null)\n return Response.Error(\n $\"Missing or invalid 'componentProperties' for component '{compName}' for 'set_component_property' on prefab.\"\n );\n\n properties = new JObject();\n properties[compName] = compProps;\n }\n else // action == \"modify\"\n {\n properties = @params[\"componentProperties\"] as JObject;\n if (properties == null)\n return Response.Error(\n \"Missing 'componentProperties' for 'modify' action on prefab.\"\n );\n }\n\n assetParams[\"properties\"] = properties;\n\n // Call ManageAsset handler\n return ManageAsset.HandleCommand(assetParams);\n }\n else if (\n action == \"delete\"\n || action == \"add_component\"\n || action == \"remove_component\"\n || action == \"get_components\"\n ) // Added get_components here too\n {\n // Explicitly block other modifications on the prefab asset itself via manage_gameobject\n return Response.Error(\n $\"Action '{action}' on a prefab asset ('{targetPath}') should be performed using the 'manage_asset' command.\"\n );\n }\n // Allow 'create' (instantiation) and 'find' to proceed, although finding a prefab asset by path might be less common via manage_gameobject.\n // No specific handling needed here, the code below will run.\n }\n // --- End Prefab Redirection Check ---\n\n try\n {\n switch (action)\n {\n case \"create\":\n return CreateGameObject(@params);\n case \"modify\":\n return ModifyGameObject(@params, targetToken, searchMethod);\n case \"delete\":\n return DeleteGameObject(targetToken, searchMethod);\n case \"find\":\n return FindGameObjects(@params, targetToken, searchMethod);\n case \"get_components\":\n string getCompTarget = targetToken?.ToString(); // Expect name, path, or ID string\n if (getCompTarget == null)\n return Response.Error(\n \"'target' parameter required for get_components.\"\n );\n // Pass the includeNonPublicSerialized flag here\n return GetComponentsFromTarget(getCompTarget, searchMethod, includeNonPublicSerialized);\n case \"add_component\":\n return AddComponentToTarget(@params, targetToken, searchMethod);\n case \"remove_component\":\n return RemoveComponentFromTarget(@params, targetToken, searchMethod);\n case \"set_component_property\":\n return SetComponentPropertyOnTarget(@params, targetToken, searchMethod);\n\n default:\n return Response.Error($\"Unknown action: '{action}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageGameObject] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object CreateGameObject(JObject @params)\n {\n string name = @params[\"name\"]?.ToString();\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"'name' parameter is required for 'create' action.\");\n }\n\n // Get prefab creation parameters\n bool saveAsPrefab = @params[\"saveAsPrefab\"]?.ToObject() ?? false;\n string prefabPath = @params[\"prefabPath\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString(); // Get tag for creation\n string primitiveType = @params[\"primitiveType\"]?.ToString(); // Keep primitiveType check\n GameObject newGo = null; // Initialize as null\n\n // --- Try Instantiating Prefab First ---\n string originalPrefabPath = prefabPath; // Keep original for messages\n if (!string.IsNullOrEmpty(prefabPath))\n {\n // If no extension, search for the prefab by name\n if (\n !prefabPath.Contains(\"/\")\n && !prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n string prefabNameOnly = prefabPath;\n Debug.Log(\n $\"[ManageGameObject.Create] Searching for prefab named: '{prefabNameOnly}'\"\n );\n string[] guids = AssetDatabase.FindAssets($\"t:Prefab {prefabNameOnly}\");\n if (guids.Length == 0)\n {\n return Response.Error(\n $\"Prefab named '{prefabNameOnly}' not found anywhere in the project.\"\n );\n }\n else if (guids.Length > 1)\n {\n string foundPaths = string.Join(\n \", \",\n guids.Select(g => AssetDatabase.GUIDToAssetPath(g))\n );\n return Response.Error(\n $\"Multiple prefabs found matching name '{prefabNameOnly}': {foundPaths}. Please provide a more specific path.\"\n );\n }\n else // Exactly one found\n {\n prefabPath = AssetDatabase.GUIDToAssetPath(guids[0]); // Update prefabPath with the full path\n Debug.Log(\n $\"[ManageGameObject.Create] Found unique prefab at path: '{prefabPath}'\"\n );\n }\n }\n else if (!prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n // If it looks like a path but doesn't end with .prefab, assume user forgot it and append it.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Provided prefabPath '{prefabPath}' does not end with .prefab. Assuming it's missing and appending.\"\n );\n prefabPath += \".prefab\";\n // Note: This path might still not exist, AssetDatabase.LoadAssetAtPath will handle that.\n }\n // The logic above now handles finding or assuming the .prefab extension.\n\n GameObject prefabAsset = AssetDatabase.LoadAssetAtPath(prefabPath);\n if (prefabAsset != null)\n {\n try\n {\n // Instantiate the prefab, initially place it at the root\n // Parent will be set later if specified\n newGo = PrefabUtility.InstantiatePrefab(prefabAsset) as GameObject;\n\n if (newGo == null)\n {\n // This might happen if the asset exists but isn't a valid GameObject prefab somehow\n Debug.LogError(\n $\"[ManageGameObject.Create] Failed to instantiate prefab at '{prefabPath}', asset might be corrupted or not a GameObject.\"\n );\n return Response.Error(\n $\"Failed to instantiate prefab at '{prefabPath}'.\"\n );\n }\n // Name the instance based on the 'name' parameter, not the prefab's default name\n if (!string.IsNullOrEmpty(name))\n {\n newGo.name = name;\n }\n // Register Undo for prefab instantiation\n Undo.RegisterCreatedObjectUndo(\n newGo,\n $\"Instantiate Prefab '{prefabAsset.name}' as '{newGo.name}'\"\n );\n Debug.Log(\n $\"[ManageGameObject.Create] Instantiated prefab '{prefabAsset.name}' from path '{prefabPath}' as '{newGo.name}'.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error instantiating prefab '{prefabPath}': {e.Message}\"\n );\n }\n }\n else\n {\n // Only return error if prefabPath was specified but not found.\n // If prefabPath was empty/null, we proceed to create primitive/empty.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Prefab asset not found at path: '{prefabPath}'. Will proceed to create new object if specified.\"\n );\n // Do not return error here, allow fallback to primitive/empty creation\n }\n }\n\n // --- Fallback: Create Primitive or Empty GameObject ---\n bool createdNewObject = false; // Flag to track if we created (not instantiated)\n if (newGo == null) // Only proceed if prefab instantiation didn't happen\n {\n if (!string.IsNullOrEmpty(primitiveType))\n {\n try\n {\n PrimitiveType type = (PrimitiveType)\n Enum.Parse(typeof(PrimitiveType), primitiveType, true);\n newGo = GameObject.CreatePrimitive(type);\n // Set name *after* creation for primitives\n if (!string.IsNullOrEmpty(name))\n newGo.name = name;\n else\n return Response.Error(\n \"'name' parameter is required when creating a primitive.\"\n ); // Name is essential\n createdNewObject = true;\n }\n catch (ArgumentException)\n {\n return Response.Error(\n $\"Invalid primitive type: '{primitiveType}'. Valid types: {string.Join(\", \", Enum.GetNames(typeof(PrimitiveType)))}\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Failed to create primitive '{primitiveType}': {e.Message}\"\n );\n }\n }\n else // Create empty GameObject\n {\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\n \"'name' parameter is required for 'create' action when not instantiating a prefab or creating a primitive.\"\n );\n }\n newGo = new GameObject(name);\n createdNewObject = true;\n }\n // Record creation for Undo *only* if we created a new object\n if (createdNewObject)\n {\n Undo.RegisterCreatedObjectUndo(newGo, $\"Create GameObject '{newGo.name}'\");\n }\n }\n // --- Common Setup (Parent, Transform, Tag, Components) - Applied AFTER object exists ---\n if (newGo == null)\n {\n // Should theoretically not happen if logic above is correct, but safety check.\n return Response.Error(\"Failed to create or instantiate the GameObject.\");\n }\n\n // Record potential changes to the existing prefab instance or the new GO\n // Record transform separately in case parent changes affect it\n Undo.RecordObject(newGo.transform, \"Set GameObject Transform\");\n Undo.RecordObject(newGo, \"Set GameObject Properties\");\n\n // Set Parent\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject parentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\"); // Flexible parent finding\n if (parentGo == null)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up created object\n return Response.Error($\"Parent specified ('{parentToken}') but not found.\");\n }\n newGo.transform.SetParent(parentGo.transform, true); // worldPositionStays = true\n }\n\n // Set Transform\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue)\n newGo.transform.localPosition = position.Value;\n if (rotation.HasValue)\n newGo.transform.localEulerAngles = rotation.Value;\n if (scale.HasValue)\n newGo.transform.localScale = scale.Value;\n\n // Set Tag (added for create action)\n if (!string.IsNullOrEmpty(tag))\n {\n // Similar logic as in ModifyGameObject for setting/creating tags\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n newGo.tag = tagToSet;\n }\n catch (UnityException ex)\n {\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n InternalEditorUtility.AddTag(tagToSet);\n newGo.tag = tagToSet; // Retry\n Debug.Log(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}' during creation: {innerEx.Message}.\"\n );\n }\n }\n else\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to set tag to '{tagToSet}' during creation: {ex.Message}.\"\n );\n }\n }\n }\n\n // Set Layer (new for create action)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId != -1)\n {\n newGo.layer = layerId;\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Layer '{layerName}' not found. Using default layer.\"\n );\n }\n }\n\n // Add Components\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArray)\n {\n foreach (var compToken in componentsToAddArray)\n {\n string typeName = null;\n JObject properties = null;\n\n if (compToken.Type == JTokenType.String)\n {\n typeName = compToken.ToString();\n }\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(newGo, typeName, properties);\n if (addResult != null) // Check if AddComponentInternal returned an error object\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return addResult; // Return the error response\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Invalid component format in componentsToAdd: {compToken}\"\n );\n }\n }\n }\n\n // Save as Prefab ONLY if we *created* a new object AND saveAsPrefab is true\n GameObject finalInstance = newGo; // Use this for selection and return data\n if (createdNewObject && saveAsPrefab)\n {\n string finalPrefabPath = prefabPath; // Use a separate variable for saving path\n // This check should now happen *before* attempting to save\n if (string.IsNullOrEmpty(finalPrefabPath))\n {\n // Clean up the created object before returning error\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n \"'prefabPath' is required when 'saveAsPrefab' is true and creating a new object.\"\n );\n }\n // Ensure the *saving* path ends with .prefab\n if (!finalPrefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n Debug.Log(\n $\"[ManageGameObject.Create] Appending .prefab extension to save path: '{finalPrefabPath}' -> '{finalPrefabPath}.prefab'\"\n );\n finalPrefabPath += \".prefab\";\n }\n\n try\n {\n // Ensure directory exists using the final saving path\n string directoryPath = System.IO.Path.GetDirectoryName(finalPrefabPath);\n if (\n !string.IsNullOrEmpty(directoryPath)\n && !System.IO.Directory.Exists(directoryPath)\n )\n {\n System.IO.Directory.CreateDirectory(directoryPath);\n AssetDatabase.Refresh(); // Refresh asset database to recognize the new folder\n Debug.Log(\n $\"[ManageGameObject.Create] Created directory for prefab: {directoryPath}\"\n );\n }\n // Use SaveAsPrefabAssetAndConnect with the final saving path\n finalInstance = PrefabUtility.SaveAsPrefabAssetAndConnect(\n newGo,\n finalPrefabPath,\n InteractionMode.UserAction\n );\n\n if (finalInstance == null)\n {\n // Destroy the original if saving failed somehow (shouldn't usually happen if path is valid)\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n $\"Failed to save GameObject '{name}' as prefab at '{finalPrefabPath}'. Check path and permissions.\"\n );\n }\n Debug.Log(\n $\"[ManageGameObject.Create] GameObject '{name}' saved as prefab to '{finalPrefabPath}' and instance connected.\"\n );\n // Mark the new prefab asset as dirty? Not usually necessary, SaveAsPrefabAsset handles it.\n // EditorUtility.SetDirty(finalInstance); // Instance is handled by SaveAsPrefabAssetAndConnect\n }\n catch (Exception e)\n {\n // Clean up the instance if prefab saving fails\n UnityEngine.Object.DestroyImmediate(newGo); // Destroy the original attempt\n return Response.Error($\"Error saving prefab '{finalPrefabPath}': {e.Message}\");\n }\n }\n\n // Select the instance in the scene (either prefab instance or newly created/saved one)\n Selection.activeGameObject = finalInstance;\n\n // Determine appropriate success message using the potentially updated or original path\n string messagePrefabPath =\n finalInstance == null\n ? originalPrefabPath\n : AssetDatabase.GetAssetPath(\n PrefabUtility.GetCorrespondingObjectFromSource(finalInstance)\n ?? (UnityEngine.Object)finalInstance\n );\n string successMessage;\n if (!createdNewObject && !string.IsNullOrEmpty(messagePrefabPath)) // Instantiated existing prefab\n {\n successMessage =\n $\"Prefab '{messagePrefabPath}' instantiated successfully as '{finalInstance.name}'.\";\n }\n else if (createdNewObject && saveAsPrefab && !string.IsNullOrEmpty(messagePrefabPath)) // Created new and saved as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created and saved as prefab to '{messagePrefabPath}'.\";\n }\n else // Created new primitive or empty GO, didn't save as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created successfully in scene.\";\n }\n\n // Use the new serializer helper\n //return Response.Success(successMessage, GetGameObjectData(finalInstance));\n return Response.Success(successMessage, Helpers.GameObjectSerializer.GetGameObjectData(finalInstance));\n }\n\n private static object ModifyGameObject(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n // Record state for Undo *before* modifications\n Undo.RecordObject(targetGo.transform, \"Modify GameObject Transform\");\n Undo.RecordObject(targetGo, \"Modify GameObject Properties\");\n\n bool modified = false;\n\n // Rename (using consolidated 'name' parameter)\n string name = @params[\"name\"]?.ToString();\n if (!string.IsNullOrEmpty(name) && targetGo.name != name)\n {\n targetGo.name = name;\n modified = true;\n }\n\n // Change Parent (using consolidated 'parent' parameter)\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject newParentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\");\n // Check for hierarchy loops\n if (\n newParentGo == null\n && !(\n parentToken.Type == JTokenType.Null\n || (\n parentToken.Type == JTokenType.String\n && string.IsNullOrEmpty(parentToken.ToString())\n )\n )\n )\n {\n return Response.Error($\"New parent ('{parentToken}') not found.\");\n }\n if (newParentGo != null && newParentGo.transform.IsChildOf(targetGo.transform))\n {\n return Response.Error(\n $\"Cannot parent '{targetGo.name}' to '{newParentGo.name}', as it would create a hierarchy loop.\"\n );\n }\n if (targetGo.transform.parent != (newParentGo?.transform))\n {\n targetGo.transform.SetParent(newParentGo?.transform, true); // worldPositionStays = true\n modified = true;\n }\n }\n\n // Set Active State\n bool? setActive = @params[\"setActive\"]?.ToObject();\n if (setActive.HasValue && targetGo.activeSelf != setActive.Value)\n {\n targetGo.SetActive(setActive.Value);\n modified = true;\n }\n\n // Change Tag (using consolidated 'tag' parameter)\n string tag = @params[\"tag\"]?.ToString();\n // Only attempt to change tag if a non-null tag is provided and it's different from the current one.\n // Allow setting an empty string to remove the tag (Unity uses \"Untagged\").\n if (tag != null && targetGo.tag != tag)\n {\n // Ensure the tag is not empty, if empty, it means \"Untagged\" implicitly\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n targetGo.tag = tagToSet;\n modified = true;\n }\n catch (UnityException ex)\n {\n // Check if the error is specifically because the tag doesn't exist\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n // Attempt to create the tag using internal utility\n InternalEditorUtility.AddTag(tagToSet);\n // Wait a frame maybe? Not strictly necessary but sometimes helps editor updates.\n // yield return null; // Cannot yield here, editor script limitation\n\n // Retry setting the tag immediately after creation\n targetGo.tag = tagToSet;\n modified = true;\n Debug.Log(\n $\"[ManageGameObject] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n // Handle failure during tag creation or the second assignment attempt\n Debug.LogError(\n $\"[ManageGameObject] Failed to create or assign tag '{tagToSet}' after attempting creation: {innerEx.Message}\"\n );\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}': {innerEx.Message}. Check Tag Manager and permissions.\"\n );\n }\n }\n else\n {\n // If the exception was for a different reason, return the original error\n return Response.Error($\"Failed to set tag to '{tagToSet}': {ex.Message}.\");\n }\n }\n }\n\n // Change Layer (using consolidated 'layer' parameter)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId == -1 && layerName != \"Default\")\n {\n return Response.Error(\n $\"Invalid layer specified: '{layerName}'. Use a valid layer name.\"\n );\n }\n if (layerId != -1 && targetGo.layer != layerId)\n {\n targetGo.layer = layerId;\n modified = true;\n }\n }\n\n // Transform Modifications\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue && targetGo.transform.localPosition != position.Value)\n {\n targetGo.transform.localPosition = position.Value;\n modified = true;\n }\n if (rotation.HasValue && targetGo.transform.localEulerAngles != rotation.Value)\n {\n targetGo.transform.localEulerAngles = rotation.Value;\n modified = true;\n }\n if (scale.HasValue && targetGo.transform.localScale != scale.Value)\n {\n targetGo.transform.localScale = scale.Value;\n modified = true;\n }\n\n // --- Component Modifications ---\n // Note: These might need more specific Undo recording per component\n\n // Remove Components\n if (@params[\"componentsToRemove\"] is JArray componentsToRemoveArray)\n {\n foreach (var compToken in componentsToRemoveArray)\n {\n // ... (parsing logic as in CreateGameObject) ...\n string typeName = compToken.ToString();\n if (!string.IsNullOrEmpty(typeName))\n {\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error if removal failed\n modified = true;\n }\n }\n }\n\n // Add Components (similar to create)\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArrayModify)\n {\n foreach (var compToken in componentsToAddArrayModify)\n {\n string typeName = null;\n JObject properties = null;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult;\n modified = true;\n }\n }\n }\n\n // Set Component Properties\n if (@params[\"componentProperties\"] is JObject componentPropertiesObj)\n {\n foreach (var prop in componentPropertiesObj.Properties())\n {\n string compName = prop.Name;\n JObject propertiesToSet = prop.Value as JObject;\n if (propertiesToSet != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n compName,\n propertiesToSet\n );\n if (setResult != null)\n return setResult;\n modified = true;\n }\n }\n }\n\n if (!modified)\n {\n // Use the new serializer helper\n // return Response.Success(\n // $\"No modifications applied to GameObject '{targetGo.name}'.\",\n // GetGameObjectData(targetGo));\n\n return Response.Success(\n $\"No modifications applied to GameObject '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n EditorUtility.SetDirty(targetGo); // Mark scene as dirty\n // Use the new serializer helper\n return Response.Success(\n $\"GameObject '{targetGo.name}' modified successfully.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n // return Response.Success(\n // $\"GameObject '{targetGo.name}' modified successfully.\",\n // GetGameObjectData(targetGo));\n \n }\n\n private static object DeleteGameObject(JToken targetToken, string searchMethod)\n {\n // Find potentially multiple objects if name/tag search is used without find_all=false implicitly\n List targets = FindObjectsInternal(targetToken, searchMethod, true); // find_all=true for delete safety\n\n if (targets.Count == 0)\n {\n return Response.Error(\n $\"Target GameObject(s) ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n List deletedObjects = new List();\n foreach (var targetGo in targets)\n {\n if (targetGo != null)\n {\n string goName = targetGo.name;\n int goId = targetGo.GetInstanceID();\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(targetGo);\n deletedObjects.Add(new { name = goName, instanceID = goId });\n }\n }\n\n if (deletedObjects.Count > 0)\n {\n string message =\n targets.Count == 1\n ? $\"GameObject '{deletedObjects[0].GetType().GetProperty(\"name\").GetValue(deletedObjects[0])}' deleted successfully.\"\n : $\"{deletedObjects.Count} GameObjects deleted successfully.\";\n return Response.Success(message, deletedObjects);\n }\n else\n {\n // Should not happen if targets.Count > 0 initially, but defensive check\n return Response.Error(\"Failed to delete target GameObject(s).\");\n }\n }\n\n private static object FindGameObjects(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n bool findAll = @params[\"findAll\"]?.ToObject() ?? false;\n List foundObjects = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n @params\n );\n\n if (foundObjects.Count == 0)\n {\n return Response.Success(\"No matching GameObjects found.\", new List());\n }\n\n // Use the new serializer helper\n //var results = foundObjects.Select(go => GetGameObjectData(go)).ToList();\n var results = foundObjects.Select(go => Helpers.GameObjectSerializer.GetGameObjectData(go)).ToList();\n return Response.Success($\"Found {results.Count} GameObject(s).\", results);\n }\n\n private static object GetComponentsFromTarget(string target, string searchMethod, bool includeNonPublicSerialized = true)\n {\n GameObject targetGo = FindObjectInternal(target, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{target}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n try\n {\n // --- Get components, immediately copy to list, and null original array --- \n Component[] originalComponents = targetGo.GetComponents();\n List componentsToIterate = new List(originalComponents ?? Array.Empty()); // Copy immediately, handle null case\n int componentCount = componentsToIterate.Count; \n originalComponents = null; // Null the original reference\n // Debug.Log($\"[GetComponentsFromTarget] Found {componentCount} components on {targetGo.name}. Copied to list, nulled original. Starting REVERSE for loop...\");\n // --- End Copy and Null --- \n \n var componentData = new List();\n \n for (int i = componentCount - 1; i >= 0; i--) // Iterate backwards over the COPY\n {\n Component c = componentsToIterate[i]; // Use the copy\n if (c == null) \n {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] Encountered a null component at index {i} on {targetGo.name}. Skipping.\");\n continue; // Safety check\n }\n // Debug.Log($\"[GetComponentsFromTarget REVERSE for] Processing component: {c.GetType()?.FullName ?? \"null\"} (ID: {c.GetInstanceID()}) at index {i} on {targetGo.name}\");\n try \n {\n var data = Helpers.GameObjectSerializer.GetComponentData(c, includeNonPublicSerialized);\n if (data != null) // Ensure GetComponentData didn't return null\n {\n componentData.Insert(0, data); // Insert at beginning to maintain original order in final list\n }\n // else\n // {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] GetComponentData returned null for component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}. Skipping addition.\");\n // }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"[GetComponentsFromTarget REVERSE for] Error processing component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}: {ex.Message}\\n{ex.StackTrace}\");\n // Optionally add placeholder data or just skip\n componentData.Insert(0, new JObject( // Insert error marker at beginning\n new JProperty(\"typeName\", c.GetType().FullName + \" (Serialization Error)\"),\n new JProperty(\"instanceID\", c.GetInstanceID()),\n new JProperty(\"error\", ex.Message)\n ));\n }\n }\n // Debug.Log($\"[GetComponentsFromTarget] Finished REVERSE for loop.\");\n \n // Cleanup the list we created\n componentsToIterate.Clear();\n componentsToIterate = null;\n\n return Response.Success(\n $\"Retrieved {componentData.Count} components from '{targetGo.name}'.\",\n componentData // List was built in original order\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error getting components from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n private static object AddComponentToTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n JObject properties = null;\n\n // Allow adding component specified directly or via componentsToAdd array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n properties = @params[\"componentProperties\"]?[typeName] as JObject; // Check if props are nested under name\n }\n else if (\n @params[\"componentsToAdd\"] is JArray componentsToAddArray\n && componentsToAddArray.Count > 0\n )\n {\n var compToken = componentsToAddArray.First;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToAdd') is required.\"\n );\n }\n\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' added to '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n ); // Return updated GO data\n }\n\n private static object RemoveComponentFromTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n // Allow removing component specified directly or via componentsToRemove array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n }\n else if (\n @params[\"componentsToRemove\"] is JArray componentsToRemoveArray\n && componentsToRemoveArray.Count > 0\n )\n {\n typeName = componentsToRemoveArray.First?.ToString();\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToRemove') is required.\"\n );\n }\n\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' removed from '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n private static object SetComponentPropertyOnTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string compName = @params[\"componentName\"]?.ToString();\n JObject propertiesToSet = null;\n\n if (!string.IsNullOrEmpty(compName))\n {\n // Properties might be directly under componentProperties or nested under the component name\n if (@params[\"componentProperties\"] is JObject compProps)\n {\n propertiesToSet = compProps[compName] as JObject ?? compProps; // Allow flat or nested structure\n }\n }\n else\n {\n return Response.Error(\"'componentName' parameter is required.\");\n }\n\n if (propertiesToSet == null || !propertiesToSet.HasValues)\n {\n return Response.Error(\n \"'componentProperties' dictionary for the specified component is required and cannot be empty.\"\n );\n }\n\n var setResult = SetComponentPropertiesInternal(targetGo, compName, propertiesToSet);\n if (setResult != null)\n return setResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Properties set for component '{compName}' on '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Finds a single GameObject based on token (ID, name, path) and search method.\n /// \n private static GameObject FindObjectInternal(\n JToken targetToken,\n string searchMethod,\n JObject findParams = null\n )\n {\n // If find_all is not explicitly false, we still want only one for most single-target operations.\n bool findAll = findParams?[\"findAll\"]?.ToObject() ?? false;\n // If a specific target ID is given, always find just that one.\n if (\n targetToken?.Type == JTokenType.Integer\n || (searchMethod == \"by_id\" && int.TryParse(targetToken?.ToString(), out _))\n )\n {\n findAll = false;\n }\n List results = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n findParams\n );\n return results.Count > 0 ? results[0] : null;\n }\n\n /// \n /// Core logic for finding GameObjects based on various criteria.\n /// \n private static List FindObjectsInternal(\n JToken targetToken,\n string searchMethod,\n bool findAll,\n JObject findParams = null\n )\n {\n List results = new List();\n string searchTerm = findParams?[\"searchTerm\"]?.ToString() ?? targetToken?.ToString(); // Use searchTerm if provided, else the target itself\n bool searchInChildren = findParams?[\"searchInChildren\"]?.ToObject() ?? false;\n bool searchInactive = findParams?[\"searchInactive\"]?.ToObject() ?? false;\n\n // Default search method if not specified\n if (string.IsNullOrEmpty(searchMethod))\n {\n if (targetToken?.Type == JTokenType.Integer)\n searchMethod = \"by_id\";\n else if (!string.IsNullOrEmpty(searchTerm) && searchTerm.Contains('/'))\n searchMethod = \"by_path\";\n else\n searchMethod = \"by_name\"; // Default fallback\n }\n\n GameObject rootSearchObject = null;\n // If searching in children, find the initial target first\n if (searchInChildren && targetToken != null)\n {\n rootSearchObject = FindObjectInternal(targetToken, \"by_id_or_name_or_path\"); // Find the root for child search\n if (rootSearchObject == null)\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Root object '{targetToken}' for child search not found.\"\n );\n return results; // Return empty if root not found\n }\n }\n\n switch (searchMethod)\n {\n case \"by_id\":\n if (int.TryParse(searchTerm, out int instanceId))\n {\n // EditorUtility.InstanceIDToObject is slow, iterate manually if possible\n // GameObject obj = EditorUtility.InstanceIDToObject(instanceId) as GameObject;\n var allObjects = GetAllSceneObjects(searchInactive); // More efficient\n GameObject obj = allObjects.FirstOrDefault(go =>\n go.GetInstanceID() == instanceId\n );\n if (obj != null)\n results.Add(obj);\n }\n break;\n case \"by_name\":\n var searchPoolName = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolName.Where(go => go.name == searchTerm));\n break;\n case \"by_path\":\n // Path is relative to scene root or rootSearchObject\n Transform foundTransform = rootSearchObject\n ? rootSearchObject.transform.Find(searchTerm)\n : GameObject.Find(searchTerm)?.transform;\n if (foundTransform != null)\n results.Add(foundTransform.gameObject);\n break;\n case \"by_tag\":\n var searchPoolTag = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolTag.Where(go => go.CompareTag(searchTerm)));\n break;\n case \"by_layer\":\n var searchPoolLayer = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n if (int.TryParse(searchTerm, out int layerIndex))\n {\n results.AddRange(searchPoolLayer.Where(go => go.layer == layerIndex));\n }\n else\n {\n int namedLayer = LayerMask.NameToLayer(searchTerm);\n if (namedLayer != -1)\n results.AddRange(searchPoolLayer.Where(go => go.layer == namedLayer));\n }\n break;\n case \"by_component\":\n Type componentType = FindType(searchTerm);\n if (componentType != null)\n {\n // Determine FindObjectsInactive based on the searchInactive flag\n FindObjectsInactive findInactive = searchInactive\n ? FindObjectsInactive.Include\n : FindObjectsInactive.Exclude;\n // Replace FindObjectsOfType with FindObjectsByType, specifying the sorting mode and inactive state\n var searchPoolComp = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(componentType, searchInactive)\n .Select(c => (c as Component).gameObject)\n : UnityEngine\n .Object.FindObjectsByType(\n componentType,\n findInactive,\n FindObjectsSortMode.None\n )\n .Select(c => (c as Component).gameObject);\n results.AddRange(searchPoolComp.Where(go => go != null)); // Ensure GO is valid\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Component type not found: {searchTerm}\"\n );\n }\n break;\n case \"by_id_or_name_or_path\": // Helper method used internally\n if (int.TryParse(searchTerm, out int id))\n {\n var allObjectsId = GetAllSceneObjects(true); // Search inactive for internal lookup\n GameObject objById = allObjectsId.FirstOrDefault(go =>\n go.GetInstanceID() == id\n );\n if (objById != null)\n {\n results.Add(objById);\n break;\n }\n }\n GameObject objByPath = GameObject.Find(searchTerm);\n if (objByPath != null)\n {\n results.Add(objByPath);\n break;\n }\n\n var allObjectsName = GetAllSceneObjects(true);\n results.AddRange(allObjectsName.Where(go => go.name == searchTerm));\n break;\n default:\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Unknown search method: {searchMethod}\"\n );\n break;\n }\n\n // If only one result is needed, return just the first one found.\n if (!findAll && results.Count > 1)\n {\n return new List { results[0] };\n }\n\n return results.Distinct().ToList(); // Ensure uniqueness\n }\n\n // Helper to get all scene objects efficiently\n private static IEnumerable GetAllSceneObjects(bool includeInactive)\n {\n // SceneManager.GetActiveScene().GetRootGameObjects() is faster than FindObjectsOfType()\n var rootObjects = SceneManager.GetActiveScene().GetRootGameObjects();\n var allObjects = new List();\n foreach (var root in rootObjects)\n {\n allObjects.AddRange(\n root.GetComponentsInChildren(includeInactive)\n .Select(t => t.gameObject)\n );\n }\n return allObjects;\n }\n\n /// \n /// Adds a component by type name and optionally sets properties.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object AddComponentInternal(\n GameObject targetGo,\n string typeName,\n JObject properties\n )\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error(\n $\"Component type '{typeName}' not found or is not a valid Component.\"\n );\n }\n if (!typeof(Component).IsAssignableFrom(componentType))\n {\n return Response.Error($\"Type '{typeName}' is not a Component.\");\n }\n\n // Prevent adding Transform again\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot add another Transform component.\");\n }\n\n // Check for 2D/3D physics component conflicts\n bool isAdding2DPhysics =\n typeof(Rigidbody2D).IsAssignableFrom(componentType)\n || typeof(Collider2D).IsAssignableFrom(componentType);\n bool isAdding3DPhysics =\n typeof(Rigidbody).IsAssignableFrom(componentType)\n || typeof(Collider).IsAssignableFrom(componentType);\n\n if (isAdding2DPhysics)\n {\n // Check if the GameObject already has any 3D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 2D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 3D Rigidbody or Collider.\"\n );\n }\n }\n else if (isAdding3DPhysics)\n {\n // Check if the GameObject already has any 2D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 3D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 2D Rigidbody or Collider.\"\n );\n }\n }\n\n try\n {\n // Use Undo.AddComponent for undo support\n Component newComponent = Undo.AddComponent(targetGo, componentType);\n if (newComponent == null)\n {\n return Response.Error(\n $\"Failed to add component '{typeName}' to '{targetGo.name}'. It might be disallowed (e.g., adding script twice).\"\n );\n }\n\n // Set default values for specific component types\n if (newComponent is Light light)\n {\n // Default newly added lights to directional\n light.type = LightType.Directional;\n }\n\n // Set properties if provided\n if (properties != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n typeName,\n properties,\n newComponent\n ); // Pass the new component instance\n if (setResult != null)\n {\n // If setting properties failed, maybe remove the added component?\n Undo.DestroyObjectImmediate(newComponent);\n return setResult; // Return the error from setting properties\n }\n }\n\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error adding component '{typeName}' to '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Removes a component by type name.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object RemoveComponentInternal(GameObject targetGo, string typeName)\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error($\"Component type '{typeName}' not found for removal.\");\n }\n\n // Prevent removing essential components\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot remove the Transform component.\");\n }\n\n Component componentToRemove = targetGo.GetComponent(componentType);\n if (componentToRemove == null)\n {\n return Response.Error(\n $\"Component '{typeName}' not found on '{targetGo.name}' to remove.\"\n );\n }\n\n try\n {\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(componentToRemove);\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error removing component '{typeName}' from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Sets properties on a component.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object SetComponentPropertiesInternal(\n GameObject targetGo,\n string compName,\n JObject propertiesToSet,\n Component targetComponentInstance = null\n )\n {\n Component targetComponent = targetComponentInstance ?? targetGo.GetComponent(compName);\n if (targetComponent == null)\n {\n return Response.Error(\n $\"Component '{compName}' not found on '{targetGo.name}' to set properties.\"\n );\n }\n\n Undo.RecordObject(targetComponent, \"Set Component Properties\");\n\n foreach (var prop in propertiesToSet.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n\n try\n {\n if (!SetProperty(targetComponent, propName, propValue))\n {\n // Log warning if property could not be set\n Debug.LogWarning(\n $\"[ManageGameObject] Could not set property '{propName}' on component '{compName}' ('{targetComponent.GetType().Name}'). Property might not exist, be read-only, or type mismatch.\"\n );\n // Optionally return an error here instead of just logging\n // return Response.Error($\"Could not set property '{propName}' on component '{compName}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageGameObject] Error setting property '{propName}' on '{compName}': {e.Message}\"\n );\n // Optionally return an error here\n // return Response.Error($\"Error setting property '{propName}' on '{compName}': {e.Message}\");\n }\n }\n EditorUtility.SetDirty(targetComponent);\n return null; // Success (or partial success if warnings were logged)\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types.\n /// \n private static bool SetProperty(object target, string memberName, JToken value)\n {\n Type type = target.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // --- Use a dedicated serializer for input conversion ---\n // Define this somewhere accessible, maybe static readonly field\n JsonSerializerSettings inputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n // Add specific converters needed for INPUT deserialization if different from output\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Crucial for finding references from instructions\n }\n // No ReferenceLoopHandling needed typically for input\n };\n JsonSerializer inputSerializer = JsonSerializer.Create(inputSerializerSettings);\n // --- End Serializer Setup ---\n\n try\n {\n // Handle special case for materials with dot notation (material.property)\n // Examples: material.color, sharedMaterial.color, materials[0].color\n if (memberName.Contains('.') || memberName.Contains('['))\n {\n // Pass the inputSerializer down for nested conversions\n return SetNestedProperty(target, memberName, value, inputSerializer);\n }\n\n PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for property '{memberName}' (Type: {propInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null) // Check if !IsLiteral?\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for field '{memberName}' (Type: {fieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetProperty] Failed to set '{memberName}' on {type.Name}: {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n return false;\n }\n\n /// \n /// Sets a nested property using dot notation (e.g., \"material.color\") or array access (e.g., \"materials[0]\")\n /// \n // Pass the input serializer for conversions\n //Using the serializer helper\n private static bool SetNestedProperty(object target, string path, JToken value, JsonSerializer inputSerializer)\n {\n try\n {\n // Split the path into parts (handling both dot notation and array indexing)\n string[] pathParts = SplitPropertyPath(path);\n if (pathParts.Length == 0)\n return false;\n\n object currentObject = target;\n Type currentType = currentObject.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // Traverse the path until we reach the final property\n for (int i = 0; i < pathParts.Length - 1; i++)\n {\n string part = pathParts[i];\n bool isArray = false;\n int arrayIndex = -1;\n\n // Check if this part contains array indexing\n if (part.Contains(\"[\"))\n {\n int startBracket = part.IndexOf('[');\n int endBracket = part.IndexOf(']');\n if (startBracket > 0 && endBracket > startBracket)\n {\n string indexStr = part.Substring(\n startBracket + 1,\n endBracket - startBracket - 1\n );\n if (int.TryParse(indexStr, out arrayIndex))\n {\n isArray = true;\n part = part.Substring(0, startBracket);\n }\n }\n }\n // Get the property/field\n PropertyInfo propInfo = currentType.GetProperty(part, flags);\n FieldInfo fieldInfo = null;\n if (propInfo == null)\n {\n fieldInfo = currentType.GetField(part, flags);\n if (fieldInfo == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find property or field '{part}' on type '{currentType.Name}'\"\n );\n return false;\n }\n }\n\n // Get the value\n currentObject =\n propInfo != null\n ? propInfo.GetValue(currentObject)\n : fieldInfo.GetValue(currentObject);\n //Need to stop if current property is null\n if (currentObject == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is null, cannot access nested properties.\"\n );\n return false;\n }\n // If this part was an array or list, access the specific index\n if (isArray)\n {\n if (currentObject is Material[])\n {\n var materials = currentObject as Material[];\n if (arrayIndex < 0 || arrayIndex >= materials.Length)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Material index {arrayIndex} out of range (0-{materials.Length - 1})\"\n );\n return false;\n }\n currentObject = materials[arrayIndex];\n }\n else if (currentObject is System.Collections.IList)\n {\n var list = currentObject as System.Collections.IList;\n if (arrayIndex < 0 || arrayIndex >= list.Count)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Index {arrayIndex} out of range (0-{list.Count - 1})\"\n );\n return false;\n }\n currentObject = list[arrayIndex];\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is not an array or list, cannot access by index.\"\n );\n return false;\n }\n }\n currentType = currentObject.GetType();\n }\n\n // Set the final property\n string finalPart = pathParts[pathParts.Length - 1];\n\n // Special handling for Material properties (shader properties)\n if (currentObject is Material material && finalPart.StartsWith(\"_\"))\n {\n // Use the serializer to convert the JToken value first\n if (value is JArray jArray)\n {\n // Try converting to known types that SetColor/SetVector accept\n if (jArray.Count == 4) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { }\n try { Vector4 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n } else if (jArray.Count == 3) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { } // ToObject handles conversion to Color\n } else if (jArray.Count == 2) {\n try { Vector2 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n }\n }\n else if (value.Type == JTokenType.Float || value.Type == JTokenType.Integer)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer)); return true; } catch { }\n }\n else if (value.Type == JTokenType.Boolean)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer) ? 1f : 0f); return true; } catch { }\n }\n else if (value.Type == JTokenType.String)\n {\n // Try converting to Texture using the serializer/converter\n try {\n Texture texture = value.ToObject(inputSerializer);\n if (texture != null) {\n material.SetTexture(finalPart, texture);\n return true;\n }\n } catch { }\n }\n\n Debug.LogWarning(\n $\"[SetNestedProperty] Unsupported or failed conversion for material property '{finalPart}' from value: {value.ToString(Formatting.None)}\"\n );\n return false;\n }\n\n // For standard properties (not shader specific)\n PropertyInfo finalPropInfo = currentType.GetProperty(finalPart, flags);\n if (finalPropInfo != null && finalPropInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalPropInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalPropInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for property '{finalPart}' (Type: {finalPropInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo finalFieldInfo = currentType.GetField(finalPart, flags);\n if (finalFieldInfo != null)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalFieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalFieldInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for field '{finalPart}' (Type: {finalFieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find final writable property or field '{finalPart}' on type '{currentType.Name}'\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetNestedProperty] Error setting nested property '{path}': {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n\n return false;\n }\n\n\n /// \n /// Split a property path into parts, handling both dot notation and array indexers\n /// \n private static string[] SplitPropertyPath(string path)\n {\n // Handle complex paths with both dots and array indexers\n List parts = new List();\n int startIndex = 0;\n bool inBrackets = false;\n\n for (int i = 0; i < path.Length; i++)\n {\n char c = path[i];\n\n if (c == '[')\n {\n inBrackets = true;\n }\n else if (c == ']')\n {\n inBrackets = false;\n }\n else if (c == '.' && !inBrackets)\n {\n // Found a dot separator outside of brackets\n parts.Add(path.Substring(startIndex, i - startIndex));\n startIndex = i + 1;\n }\n }\n if (startIndex < path.Length)\n {\n parts.Add(path.Substring(startIndex));\n }\n return parts.ToArray();\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types, using JsonSerializer.\n /// \n // Pass the input serializer\n private static object ConvertJTokenToType(JToken token, Type targetType, JsonSerializer inputSerializer)\n {\n if (token == null || token.Type == JTokenType.Null)\n {\n if (targetType.IsValueType && Nullable.GetUnderlyingType(targetType) == null)\n {\n Debug.LogWarning($\"Cannot assign null to non-nullable value type {targetType.Name}. Returning default value.\");\n return Activator.CreateInstance(targetType);\n }\n return null;\n }\n\n try\n {\n // Use the provided serializer instance which includes our custom converters\n return token.ToObject(targetType, inputSerializer);\n }\n catch (JsonSerializationException jsonEx)\n {\n Debug.LogError($\"JSON Deserialization Error converting token to {targetType.FullName}: {jsonEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n // Optionally re-throw or return null/default\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n throw; // Re-throw to indicate failure higher up\n }\n catch (ArgumentException argEx)\n {\n Debug.LogError($\"Argument Error converting token to {targetType.FullName}: {argEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Unexpected error converting token to {targetType.FullName}: {ex}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n // If ToObject succeeded, it would have returned. If it threw, we wouldn't reach here.\n // This fallback logic is likely unreachable if ToObject covers all cases or throws on failure.\n // Debug.LogWarning($\"Conversion failed for token to {targetType.FullName}. Token: {token.ToString(Formatting.None)}\");\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n }\n\n // --- ParseJTokenTo... helpers are likely redundant now with the serializer approach ---\n // Keep them temporarily for reference or if specific fallback logic is ever needed.\n\n private static Vector3 ParseJTokenToVector3(JToken token)\n {\n // ... (implementation - likely replaced by Vector3Converter) ...\n // Consider removing these if the serializer handles them reliably.\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\"))\n {\n return new Vector3(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 3)\n {\n return new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector3 using fallback. Returning Vector3.zero.\");\n return Vector3.zero;\n\n }\n private static Vector2 ParseJTokenToVector2(JToken token)\n {\n // ... (implementation - likely replaced by Vector2Converter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\"))\n {\n return new Vector2(obj[\"x\"].ToObject(), obj[\"y\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 2)\n {\n return new Vector2(arr[0].ToObject(), arr[1].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector2 using fallback. Returning Vector2.zero.\");\n return Vector2.zero;\n }\n private static Quaternion ParseJTokenToQuaternion(JToken token)\n {\n // ... (implementation - likely replaced by QuaternionConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\") && obj.ContainsKey(\"w\"))\n {\n return new Quaternion(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject(), obj[\"w\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Quaternion(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Quaternion using fallback. Returning Quaternion.identity.\");\n return Quaternion.identity;\n }\n private static Color ParseJTokenToColor(JToken token)\n {\n // ... (implementation - likely replaced by ColorConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"r\") && obj.ContainsKey(\"g\") && obj.ContainsKey(\"b\") && obj.ContainsKey(\"a\"))\n {\n return new Color(obj[\"r\"].ToObject(), obj[\"g\"].ToObject(), obj[\"b\"].ToObject(), obj[\"a\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Color(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Color using fallback. Returning Color.white.\");\n return Color.white;\n }\n private static Rect ParseJTokenToRect(JToken token)\n {\n // ... (implementation - likely replaced by RectConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"width\") && obj.ContainsKey(\"height\"))\n {\n return new Rect(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"width\"].ToObject(), obj[\"height\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Rect(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Rect using fallback. Returning Rect.zero.\");\n return Rect.zero;\n }\n private static Bounds ParseJTokenToBounds(JToken token)\n {\n // ... (implementation - likely replaced by BoundsConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"center\") && obj.ContainsKey(\"size\"))\n {\n // Requires Vector3 conversion, which should ideally use the serializer too\n Vector3 center = ParseJTokenToVector3(obj[\"center\"]); // Or use obj[\"center\"].ToObject(inputSerializer)\n Vector3 size = ParseJTokenToVector3(obj[\"size\"]); // Or use obj[\"size\"].ToObject(inputSerializer)\n return new Bounds(center, size);\n }\n // Array fallback for Bounds is less intuitive, maybe remove?\n // if (token is JArray arr && arr.Count >= 6)\n // {\n // return new Bounds(new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject()), new Vector3(arr[3].ToObject(), arr[4].ToObject(), arr[5].ToObject()));\n // }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Bounds using fallback. Returning new Bounds(Vector3.zero, Vector3.zero).\");\n return new Bounds(Vector3.zero, Vector3.zero);\n }\n // --- End Redundant Parse Helpers ---\n\n /// \n /// Finds a specific UnityEngine.Object based on a find instruction JObject.\n /// Primarily used by UnityEngineObjectConverter during deserialization.\n /// \n // Made public static so UnityEngineObjectConverter can call it. Moved from ConvertJTokenToType.\n public static UnityEngine.Object FindObjectByInstruction(JObject instruction, Type targetType)\n {\n string findTerm = instruction[\"find\"]?.ToString();\n string method = instruction[\"method\"]?.ToString()?.ToLower();\n string componentName = instruction[\"component\"]?.ToString(); // Specific component to get\n\n if (string.IsNullOrEmpty(findTerm))\n {\n Debug.LogWarning(\"Find instruction missing 'find' term.\");\n return null;\n }\n\n // Use a flexible default search method if none provided\n string searchMethodToUse = string.IsNullOrEmpty(method) ? \"by_id_or_name_or_path\" : method;\n\n // If the target is an asset (Material, Texture, ScriptableObject etc.) try AssetDatabase first\n if (typeof(Material).IsAssignableFrom(targetType) ||\n typeof(Texture).IsAssignableFrom(targetType) ||\n typeof(ScriptableObject).IsAssignableFrom(targetType) ||\n targetType.FullName.StartsWith(\"UnityEngine.U2D\") || // Sprites etc.\n typeof(AudioClip).IsAssignableFrom(targetType) ||\n typeof(AnimationClip).IsAssignableFrom(targetType) ||\n typeof(Font).IsAssignableFrom(targetType) ||\n typeof(Shader).IsAssignableFrom(targetType) ||\n typeof(ComputeShader).IsAssignableFrom(targetType) ||\n typeof(GameObject).IsAssignableFrom(targetType) && findTerm.StartsWith(\"Assets/\")) // Prefab check\n {\n // Try loading directly by path/GUID first\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(findTerm, targetType);\n if (asset != null) return asset;\n asset = AssetDatabase.LoadAssetAtPath(findTerm); // Try generic if type specific failed\n if (asset != null && targetType.IsAssignableFrom(asset.GetType())) return asset;\n\n\n // If direct path failed, try finding by name/type using FindAssets\n string searchFilter = $\"t:{targetType.Name} {System.IO.Path.GetFileNameWithoutExtension(findTerm)}\"; // Search by type and name\n string[] guids = AssetDatabase.FindAssets(searchFilter);\n\n if (guids.Length == 1)\n {\n asset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]), targetType);\n if (asset != null) return asset;\n }\n else if (guids.Length > 1)\n {\n Debug.LogWarning($\"[FindObjectByInstruction] Ambiguous asset find: Found {guids.Length} assets matching filter '{searchFilter}'. Provide a full path or unique name.\");\n // Optionally return the first one? Or null? Returning null is safer.\n return null;\n }\n // If still not found, fall through to scene search (though unlikely for assets)\n }\n\n\n // --- Scene Object Search ---\n // Find the GameObject using the internal finder\n GameObject foundGo = FindObjectInternal(new JValue(findTerm), searchMethodToUse);\n\n if (foundGo == null)\n {\n // Don't warn yet, could still be an asset not found above\n // Debug.LogWarning($\"Could not find GameObject using instruction: {instruction}\");\n return null;\n }\n\n // Now, get the target object/component from the found GameObject\n if (targetType == typeof(GameObject))\n {\n return foundGo; // We were looking for a GameObject\n }\n else if (typeof(Component).IsAssignableFrom(targetType))\n {\n Type componentToGetType = targetType;\n if (!string.IsNullOrEmpty(componentName))\n {\n Type specificCompType = FindType(componentName);\n if (specificCompType != null && typeof(Component).IsAssignableFrom(specificCompType))\n {\n componentToGetType = specificCompType;\n }\n else\n {\n Debug.LogWarning($\"Could not find component type '{componentName}' specified in find instruction. Falling back to target type '{targetType.Name}'.\");\n }\n }\n\n Component foundComp = foundGo.GetComponent(componentToGetType);\n if (foundComp == null)\n {\n Debug.LogWarning($\"Found GameObject '{foundGo.name}' but could not find component of type '{componentToGetType.Name}'.\");\n }\n return foundComp;\n }\n else\n {\n Debug.LogWarning($\"Find instruction handling not implemented for target type: {targetType.Name}\");\n return null;\n }\n }\n\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Handle fully qualified names first\n Type type = Type.GetType(typeName);\n if (type != null) return type;\n\n // Handle common namespaces implicitly (add more as needed)\n string[] namespaces = { \"UnityEngine\", \"UnityEngine.UI\", \"UnityEngine.AI\", \"UnityEngine.Animations\", \"UnityEngine.Audio\", \"UnityEngine.EventSystems\", \"UnityEngine.InputSystem\", \"UnityEngine.Networking\", \"UnityEngine.Rendering\", \"UnityEngine.SceneManagement\", \"UnityEngine.Tilemaps\", \"UnityEngine.U2D\", \"UnityEngine.Video\", \"UnityEditor\", \"UnityEditor.AI\", \"UnityEditor.Animations\", \"UnityEditor.Experimental.GraphView\", \"UnityEditor.IMGUI.Controls\", \"UnityEditor.PackageManager.UI\", \"UnityEditor.SceneManagement\", \"UnityEditor.UI\", \"UnityEditor.U2D\", \"UnityEditor.VersionControl\" }; // Add more relevant namespaces\n\n foreach (string ns in namespaces) {\n type = Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}.CoreModule\") ?? // Heuristic: Check CoreModule first for UnityEngine/UnityEditor\n Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}\"); // Try assembly matching namespace root\n if (type != null) return type;\n }\n\n\n // If not found, search all loaded assemblies (slower, last resort)\n // Prioritize assemblies likely to contain game/editor types\n Assembly[] priorityAssemblies = {\n Assembly.Load(\"Assembly-CSharp\"), // Main game scripts\n Assembly.Load(\"Assembly-CSharp-Editor\"), // Main editor scripts\n // Add other important project assemblies if known\n };\n foreach (var assembly in priorityAssemblies.Where(a => a != null))\n {\n type = assembly.GetType(typeName) ?? assembly.GetType(\"UnityEngine.\" + typeName) ?? assembly.GetType(\"UnityEditor.\" + typeName);\n if (type != null) return type;\n }\n\n // Search remaining assemblies\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Except(priorityAssemblies))\n {\n try { // Protect against assembly loading errors\n type = assembly.GetType(typeName);\n if (type != null) return type;\n // Also check with common namespaces if simple name given\n foreach (string ns in namespaces) {\n type = assembly.GetType($\"{ns}.{typeName}\");\n if (type != null) return type;\n }\n } catch (Exception ex) {\n Debug.LogWarning($\"[FindType] Error searching assembly {assembly.FullName}: {ex.Message}\");\n }\n }\n\n Debug.LogWarning($\"[FindType] Type not found after extensive search: '{typeName}'\");\n return null; // Not found\n }\n\n /// \n /// Parses a JArray like [x, y, z] into a Vector3.\n /// \n private static Vector3? ParseVector3(JArray array)\n {\n if (array != null && array.Count == 3)\n {\n try\n {\n // Use ToObject for potentially better handling than direct indexing\n return new Vector3(\n array[0].ToObject(),\n array[1].ToObject(),\n array[2].ToObject()\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Failed to parse JArray as Vector3: {array}. Error: {ex.Message}\");\n }\n }\n return null;\n }\n\n // Removed GetGameObjectData, GetComponentData, and related private helpers/caching/serializer setup.\n // They are now in Helpers.GameObjectSerializer\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScript.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\n#if USE_ROSLYN\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\n#endif\n\n#if UNITY_EDITOR\nusing UnityEditor.Compilation;\n#endif\n\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for C# scripts within the Unity project.\n /// \n /// ROSLYN INSTALLATION GUIDE:\n /// To enable advanced syntax validation with Roslyn compiler services:\n /// \n /// 1. Install Microsoft.CodeAnalysis.CSharp NuGet package:\n /// - Open Package Manager in Unity\n /// - Follow the instruction on https://github.com/GlitchEnzo/NuGetForUnity\n /// \n /// 2. Open NuGet Package Manager and Install Microsoft.CodeAnalysis.CSharp:\n /// \n /// 3. Alternative: Manual DLL installation:\n /// - Download Microsoft.CodeAnalysis.CSharp.dll and dependencies\n /// - Place in Assets/Plugins/ folder\n /// - Ensure .NET compatibility settings are correct\n /// \n /// 4. Define USE_ROSLYN symbol:\n /// - Go to Player Settings > Scripting Define Symbols\n /// - Add \"USE_ROSLYN\" to enable Roslyn-based validation\n /// \n /// 5. Restart Unity after installation\n /// \n /// Note: Without Roslyn, the system falls back to basic structural validation.\n /// Roslyn provides full C# compiler diagnostics with line numbers and detailed error messages.\n /// \n public static class ManageScript\n {\n /// \n /// Main handler for script management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode script contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n string scriptType = @params[\"scriptType\"]?.ToString(); // For templates/validation\n string namespaceName = @params[\"namespace\"]?.ToString(); // For organizing code\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid script name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Scripts\" if path is not provided\n string relativeDir = path ?? \"Scripts\"; // Default to \"Scripts\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Scripts\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string scriptFileName = $\"{name}.cs\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Application.dataPath ends in \"Assets\"\n string fullPath = Path.Combine(fullPathDir, scriptFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, scriptFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateScript(\n fullPath,\n relativePath,\n name,\n contents,\n scriptType,\n namespaceName\n );\n case \"read\":\n return ReadScript(fullPath, relativePath);\n case \"update\":\n return UpdateScript(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteScript(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents,\n string scriptType,\n string namespaceName\n )\n {\n // Check if script already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultScriptContent(name, scriptType, namespaceName);\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block creation\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new script\n return Response.Success(\n $\"Script '{name}.cs' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script not found at '{relativePath}'. Use 'create' action to add a new script.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block update\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath); // Re-import to reflect changes\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{name}.cs' updated successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'. Cannot delete.\");\n }\n\n try\n {\n // Use AssetDatabase.MoveAssetToTrash for safer deletion (allows undo)\n bool deleted = AssetDatabase.MoveAssetToTrash(relativePath);\n if (deleted)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' moved to trash successfully.\"\n );\n }\n else\n {\n // Fallback or error if MoveAssetToTrash fails\n return Response.Error(\n $\"Failed to move script '{relativePath}' to trash. It might be locked or in use.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting script '{relativePath}': {e.Message}\");\n }\n }\n\n /// \n /// Generates basic C# script content based on name and type.\n /// \n private static string GenerateDefaultScriptContent(\n string name,\n string scriptType,\n string namespaceName\n )\n {\n string usingStatements = \"using UnityEngine;\\nusing System.Collections;\\n\";\n string classDeclaration;\n string body =\n \"\\n // Use this for initialization\\n void Start() {\\n\\n }\\n\\n // Update is called once per frame\\n void Update() {\\n\\n }\\n\";\n\n string baseClass = \"\";\n if (!string.IsNullOrEmpty(scriptType))\n {\n if (scriptType.Equals(\"MonoBehaviour\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : MonoBehaviour\";\n else if (scriptType.Equals(\"ScriptableObject\", StringComparison.OrdinalIgnoreCase))\n {\n baseClass = \" : ScriptableObject\";\n body = \"\"; // ScriptableObjects don't usually need Start/Update\n }\n else if (\n scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase)\n || scriptType.Equals(\"EditorWindow\", StringComparison.OrdinalIgnoreCase)\n )\n {\n usingStatements += \"using UnityEditor;\\n\";\n if (scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : Editor\";\n else\n baseClass = \" : EditorWindow\";\n body = \"\"; // Editor scripts have different structures\n }\n // Add more types as needed\n }\n\n classDeclaration = $\"public class {name}{baseClass}\";\n\n string fullContent = $\"{usingStatements}\\n\";\n bool useNamespace = !string.IsNullOrEmpty(namespaceName);\n\n if (useNamespace)\n {\n fullContent += $\"namespace {namespaceName}\\n{{\\n\";\n // Indent class and body if using namespace\n classDeclaration = \" \" + classDeclaration;\n body = string.Join(\"\\n\", body.Split('\\n').Select(line => \" \" + line));\n }\n\n fullContent += $\"{classDeclaration}\\n{{\\n{body}\\n}}\";\n\n if (useNamespace)\n {\n fullContent += \"\\n}\"; // Close namespace\n }\n\n return fullContent.Trim() + \"\\n\"; // Ensure a trailing newline\n }\n\n /// \n /// Gets the validation level from the GUI settings\n /// \n private static ValidationLevel GetValidationLevelFromGUI()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel.ToLower() switch\n {\n \"basic\" => ValidationLevel.Basic,\n \"standard\" => ValidationLevel.Standard,\n \"comprehensive\" => ValidationLevel.Comprehensive,\n \"strict\" => ValidationLevel.Strict,\n _ => ValidationLevel.Standard // Default fallback\n };\n }\n\n /// \n /// Validates C# script syntax using multiple validation layers.\n /// \n private static bool ValidateScriptSyntax(string contents)\n {\n return ValidateScriptSyntax(contents, ValidationLevel.Standard, out _);\n }\n\n /// \n /// Advanced syntax validation with detailed diagnostics and configurable strictness.\n /// \n private static bool ValidateScriptSyntax(string contents, ValidationLevel level, out string[] errors)\n {\n var errorList = new System.Collections.Generic.List();\n errors = null;\n\n if (string.IsNullOrEmpty(contents))\n {\n return true; // Empty content is valid\n }\n\n // Basic structural validation\n if (!ValidateBasicStructure(contents, errorList))\n {\n errors = errorList.ToArray();\n return false;\n }\n\n#if USE_ROSLYN\n // Advanced Roslyn-based validation\n if (!ValidateScriptSyntaxRoslyn(contents, level, errorList))\n {\n errors = errorList.ToArray();\n return level != ValidationLevel.Standard; //TODO: Allow standard to run roslyn right now, might formalize it in the future\n }\n#endif\n\n // Unity-specific validation\n if (level >= ValidationLevel.Standard)\n {\n ValidateScriptSyntaxUnity(contents, errorList);\n }\n\n // Semantic analysis for common issues\n if (level >= ValidationLevel.Comprehensive)\n {\n ValidateSemanticRules(contents, errorList);\n }\n\n#if USE_ROSLYN\n // Full semantic compilation validation for Strict level\n if (level == ValidationLevel.Strict)\n {\n if (!ValidateScriptSemantics(contents, errorList))\n {\n errors = errorList.ToArray();\n return false; // Strict level fails on any semantic errors\n }\n }\n#endif\n\n errors = errorList.ToArray();\n return errorList.Count == 0 || (level != ValidationLevel.Strict && !errorList.Any(e => e.StartsWith(\"ERROR:\")));\n }\n\n /// \n /// Validation strictness levels\n /// \n private enum ValidationLevel\n {\n Basic, // Only syntax errors\n Standard, // Syntax + Unity best practices\n Comprehensive, // All checks + semantic analysis\n Strict // Treat all issues as errors\n }\n\n /// \n /// Validates basic code structure (braces, quotes, comments)\n /// \n private static bool ValidateBasicStructure(string contents, System.Collections.Generic.List errors)\n {\n bool isValid = true;\n int braceBalance = 0;\n int parenBalance = 0;\n int bracketBalance = 0;\n bool inStringLiteral = false;\n bool inCharLiteral = false;\n bool inSingleLineComment = false;\n bool inMultiLineComment = false;\n bool escaped = false;\n\n for (int i = 0; i < contents.Length; i++)\n {\n char c = contents[i];\n char next = i + 1 < contents.Length ? contents[i + 1] : '\\0';\n\n // Handle escape sequences\n if (escaped)\n {\n escaped = false;\n continue;\n }\n\n if (c == '\\\\' && (inStringLiteral || inCharLiteral))\n {\n escaped = true;\n continue;\n }\n\n // Handle comments\n if (!inStringLiteral && !inCharLiteral)\n {\n if (c == '/' && next == '/' && !inMultiLineComment)\n {\n inSingleLineComment = true;\n continue;\n }\n if (c == '/' && next == '*' && !inSingleLineComment)\n {\n inMultiLineComment = true;\n i++; // Skip next character\n continue;\n }\n if (c == '*' && next == '/' && inMultiLineComment)\n {\n inMultiLineComment = false;\n i++; // Skip next character\n continue;\n }\n }\n\n if (c == '\\n')\n {\n inSingleLineComment = false;\n continue;\n }\n\n if (inSingleLineComment || inMultiLineComment)\n continue;\n\n // Handle string and character literals\n if (c == '\"' && !inCharLiteral)\n {\n inStringLiteral = !inStringLiteral;\n continue;\n }\n if (c == '\\'' && !inStringLiteral)\n {\n inCharLiteral = !inCharLiteral;\n continue;\n }\n\n if (inStringLiteral || inCharLiteral)\n continue;\n\n // Count brackets and braces\n switch (c)\n {\n case '{': braceBalance++; break;\n case '}': braceBalance--; break;\n case '(': parenBalance++; break;\n case ')': parenBalance--; break;\n case '[': bracketBalance++; break;\n case ']': bracketBalance--; break;\n }\n\n // Check for negative balances (closing without opening)\n if (braceBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing brace '}'\");\n isValid = false;\n }\n if (parenBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing parenthesis ')'\");\n isValid = false;\n }\n if (bracketBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing bracket ']'\");\n isValid = false;\n }\n }\n\n // Check final balances\n if (braceBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced braces (difference: {braceBalance})\");\n isValid = false;\n }\n if (parenBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced parentheses (difference: {parenBalance})\");\n isValid = false;\n }\n if (bracketBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced brackets (difference: {bracketBalance})\");\n isValid = false;\n }\n if (inStringLiteral)\n {\n errors.Add(\"ERROR: Unterminated string literal\");\n isValid = false;\n }\n if (inCharLiteral)\n {\n errors.Add(\"ERROR: Unterminated character literal\");\n isValid = false;\n }\n if (inMultiLineComment)\n {\n errors.Add(\"WARNING: Unterminated multi-line comment\");\n }\n\n return isValid;\n }\n\n#if USE_ROSLYN\n /// \n /// Cached compilation references for performance\n /// \n private static System.Collections.Generic.List _cachedReferences = null;\n private static DateTime _cacheTime = DateTime.MinValue;\n private static readonly TimeSpan CacheExpiry = TimeSpan.FromMinutes(5);\n\n /// \n /// Validates syntax using Roslyn compiler services\n /// \n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n try\n {\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n var diagnostics = syntaxTree.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n string severity = diagnostic.Severity.ToString().ToUpper();\n string message = $\"{severity}: {diagnostic.GetMessage()}\";\n \n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n }\n \n // Include warnings in comprehensive mode\n if (level >= ValidationLevel.Standard || diagnostic.Severity == DiagnosticSeverity.Error) //Also use Standard for now\n {\n var location = diagnostic.Location.GetLineSpan();\n if (location.IsValid)\n {\n message += $\" (Line {location.StartLinePosition.Line + 1})\";\n }\n errors.Add(message);\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Roslyn validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Validates script semantics using full compilation context to catch namespace, type, and method resolution errors\n /// \n private static bool ValidateScriptSemantics(string contents, System.Collections.Generic.List errors)\n {\n try\n {\n // Get compilation references with caching\n var references = GetCompilationReferences();\n if (references == null || references.Count == 0)\n {\n errors.Add(\"WARNING: Could not load compilation references for semantic validation\");\n return true; // Don't fail if we can't get references\n }\n\n // Create syntax tree\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n\n // Create compilation with full context\n var compilation = CSharpCompilation.Create(\n \"TempValidation\",\n new[] { syntaxTree },\n references,\n new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)\n );\n\n // Get semantic diagnostics - this catches all the issues you mentioned!\n var diagnostics = compilation.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n // Include diagnostic ID for better error identification\n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"ERROR: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n else if (diagnostic.Severity == DiagnosticSeverity.Warning)\n {\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"WARNING: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Semantic validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets compilation references with caching for performance\n /// \n private static System.Collections.Generic.List GetCompilationReferences()\n {\n // Check cache validity\n if (_cachedReferences != null && DateTime.Now - _cacheTime < CacheExpiry)\n {\n return _cachedReferences;\n }\n\n try\n {\n var references = new System.Collections.Generic.List();\n\n // Core .NET assemblies\n references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); // mscorlib/System.Private.CoreLib\n references.Add(MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location)); // System.Linq\n references.Add(MetadataReference.CreateFromFile(typeof(System.Collections.Generic.List<>).Assembly.Location)); // System.Collections\n\n // Unity assemblies\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEngine.Debug).Assembly.Location)); // UnityEngine\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEngine assembly: {ex.Message}\");\n }\n\n#if UNITY_EDITOR\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEditor.Editor).Assembly.Location)); // UnityEditor\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEditor assembly: {ex.Message}\");\n }\n\n // Get Unity project assemblies\n try\n {\n var assemblies = CompilationPipeline.GetAssemblies();\n foreach (var assembly in assemblies)\n {\n if (File.Exists(assembly.outputPath))\n {\n references.Add(MetadataReference.CreateFromFile(assembly.outputPath));\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load Unity project assemblies: {ex.Message}\");\n }\n#endif\n\n // Cache the results\n _cachedReferences = references;\n _cacheTime = DateTime.Now;\n\n return references;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to get compilation references: {ex.Message}\");\n return new System.Collections.Generic.List();\n }\n }\n#else\n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n // Fallback when Roslyn is not available\n return true;\n }\n#endif\n\n /// \n /// Validates Unity-specific coding rules and best practices\n /// //TODO: Naive Unity Checks and not really yield any results, need to be improved\n /// \n private static void ValidateScriptSyntaxUnity(string contents, System.Collections.Generic.List errors)\n {\n // Check for common Unity anti-patterns\n if (contents.Contains(\"FindObjectOfType\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: FindObjectOfType in Update() can cause performance issues\");\n }\n\n if (contents.Contains(\"GameObject.Find\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: GameObject.Find in Update() can cause performance issues\");\n }\n\n // Check for proper MonoBehaviour usage\n if (contents.Contains(\": MonoBehaviour\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: MonoBehaviour requires 'using UnityEngine;'\");\n }\n\n // Check for SerializeField usage\n if (contents.Contains(\"[SerializeField]\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: SerializeField requires 'using UnityEngine;'\");\n }\n\n // Check for proper coroutine usage\n if (contents.Contains(\"StartCoroutine\") && !contents.Contains(\"IEnumerator\"))\n {\n errors.Add(\"WARNING: StartCoroutine typically requires IEnumerator methods\");\n }\n\n // Check for Update without FixedUpdate for physics\n if (contents.Contains(\"Rigidbody\") && contents.Contains(\"Update()\") && !contents.Contains(\"FixedUpdate()\"))\n {\n errors.Add(\"WARNING: Consider using FixedUpdate() for Rigidbody operations\");\n }\n\n // Check for missing null checks on Unity objects\n if (contents.Contains(\"GetComponent<\") && !contents.Contains(\"!= null\"))\n {\n errors.Add(\"WARNING: Consider null checking GetComponent results\");\n }\n\n // Check for proper event function signatures\n if (contents.Contains(\"void Start(\") && !contents.Contains(\"void Start()\"))\n {\n errors.Add(\"WARNING: Start() should not have parameters\");\n }\n\n if (contents.Contains(\"void Update(\") && !contents.Contains(\"void Update()\"))\n {\n errors.Add(\"WARNING: Update() should not have parameters\");\n }\n\n // Check for inefficient string operations\n if (contents.Contains(\"Update()\") && contents.Contains(\"\\\"\") && contents.Contains(\"+\"))\n {\n errors.Add(\"WARNING: String concatenation in Update() can cause garbage collection issues\");\n }\n }\n\n /// \n /// Validates semantic rules and common coding issues\n /// \n private static void ValidateSemanticRules(string contents, System.Collections.Generic.List errors)\n {\n // Check for potential memory leaks\n if (contents.Contains(\"new \") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: Creating objects in Update() may cause memory issues\");\n }\n\n // Check for magic numbers\n var magicNumberPattern = new Regex(@\"\\b\\d+\\.?\\d*f?\\b(?!\\s*[;})\\]])\");\n var matches = magicNumberPattern.Matches(contents);\n if (matches.Count > 5)\n {\n errors.Add(\"WARNING: Consider using named constants instead of magic numbers\");\n }\n\n // Check for long methods (simple line count check)\n var methodPattern = new Regex(@\"(public|private|protected|internal)?\\s*(static)?\\s*\\w+\\s+\\w+\\s*\\([^)]*\\)\\s*{\");\n var methodMatches = methodPattern.Matches(contents);\n foreach (Match match in methodMatches)\n {\n int startIndex = match.Index;\n int braceCount = 0;\n int lineCount = 0;\n bool inMethod = false;\n\n for (int i = startIndex; i < contents.Length; i++)\n {\n if (contents[i] == '{')\n {\n braceCount++;\n inMethod = true;\n }\n else if (contents[i] == '}')\n {\n braceCount--;\n if (braceCount == 0 && inMethod)\n break;\n }\n else if (contents[i] == '\\n' && inMethod)\n {\n lineCount++;\n }\n }\n\n if (lineCount > 50)\n {\n errors.Add(\"WARNING: Method is very long, consider breaking it into smaller methods\");\n break; // Only report once\n }\n }\n\n // Check for proper exception handling\n if (contents.Contains(\"catch\") && contents.Contains(\"catch()\"))\n {\n errors.Add(\"WARNING: Empty catch blocks should be avoided\");\n }\n\n // Check for proper async/await usage\n if (contents.Contains(\"async \") && !contents.Contains(\"await\"))\n {\n errors.Add(\"WARNING: Async method should contain await or return Task\");\n }\n\n // Check for hardcoded tags and layers\n if (contents.Contains(\"\\\"Player\\\"\") || contents.Contains(\"\\\"Enemy\\\"\"))\n {\n errors.Add(\"WARNING: Consider using constants for tags instead of hardcoded strings\");\n }\n }\n\n //TODO: A easier way for users to update incorrect scripts (now duplicated with the updateScript method and need to also update server side, put aside for now)\n /// \n /// Public method to validate script syntax with configurable validation level\n /// Returns detailed validation results including errors and warnings\n /// \n // public static object ValidateScript(JObject @params)\n // {\n // string contents = @params[\"contents\"]?.ToString();\n // string validationLevel = @params[\"validationLevel\"]?.ToString() ?? \"standard\";\n\n // if (string.IsNullOrEmpty(contents))\n // {\n // return Response.Error(\"Contents parameter is required for validation.\");\n // }\n\n // // Parse validation level\n // ValidationLevel level = ValidationLevel.Standard;\n // switch (validationLevel.ToLower())\n // {\n // case \"basic\": level = ValidationLevel.Basic; break;\n // case \"standard\": level = ValidationLevel.Standard; break;\n // case \"comprehensive\": level = ValidationLevel.Comprehensive; break;\n // case \"strict\": level = ValidationLevel.Strict; break;\n // default:\n // return Response.Error($\"Invalid validation level: '{validationLevel}'. Valid levels are: basic, standard, comprehensive, strict.\");\n // }\n\n // // Perform validation\n // bool isValid = ValidateScriptSyntax(contents, level, out string[] validationErrors);\n\n // var errors = validationErrors?.Where(e => e.StartsWith(\"ERROR:\")).ToArray() ?? new string[0];\n // var warnings = validationErrors?.Where(e => e.StartsWith(\"WARNING:\")).ToArray() ?? new string[0];\n\n // var result = new\n // {\n // isValid = isValid,\n // validationLevel = validationLevel,\n // errorCount = errors.Length,\n // warningCount = warnings.Length,\n // errors = errors,\n // warnings = warnings,\n // summary = isValid \n // ? (warnings.Length > 0 ? $\"Validation passed with {warnings.Length} warnings\" : \"Validation passed with no issues\")\n // : $\"Validation failed with {errors.Length} errors and {warnings.Length} warnings\"\n // };\n\n // if (isValid)\n // {\n // return Response.Success(\"Script validation completed successfully.\", result);\n // }\n // else\n // {\n // return Response.Error(\"Script validation failed.\", result);\n // }\n // }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageAsset.cs", "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\n#if UNITY_6000_0_OR_NEWER\nusing PhysicsMaterialType = UnityEngine.PhysicsMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicsMaterialCombine; \n#else\nusing PhysicsMaterialType = UnityEngine.PhysicMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicMaterialCombine;\n#endif\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles asset management operations within the Unity project.\n /// \n public static class ManageAsset\n {\n // --- Main Handler ---\n\n // Define the list of valid actions\n private static readonly List ValidActions = new List\n {\n \"import\",\n \"create\",\n \"modify\",\n \"delete\",\n \"duplicate\",\n \"move\",\n \"rename\",\n \"search\",\n \"get_info\",\n \"create_folder\",\n \"get_components\",\n };\n\n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Check if the action is valid before switching\n if (!ValidActions.Contains(action))\n {\n string validActionsList = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsList}\"\n );\n }\n\n // Common parameters\n string path = @params[\"path\"]?.ToString();\n\n try\n {\n switch (action)\n {\n case \"import\":\n // Note: Unity typically auto-imports. This might re-import or configure import settings.\n return ReimportAsset(path, @params[\"properties\"] as JObject);\n case \"create\":\n return CreateAsset(@params);\n case \"modify\":\n return ModifyAsset(path, @params[\"properties\"] as JObject);\n case \"delete\":\n return DeleteAsset(path);\n case \"duplicate\":\n return DuplicateAsset(path, @params[\"destination\"]?.ToString());\n case \"move\": // Often same as rename if within Assets/\n case \"rename\":\n return MoveOrRenameAsset(path, @params[\"destination\"]?.ToString());\n case \"search\":\n return SearchAssets(@params);\n case \"get_info\":\n return GetAssetInfo(\n path,\n @params[\"generatePreview\"]?.ToObject() ?? false\n );\n case \"create_folder\": // Added specific action for clarity\n return CreateFolder(path);\n case \"get_components\":\n return GetComponentsFromAsset(path);\n\n default:\n // This error message is less likely to be hit now, but kept here as a fallback or for potential future modifications.\n string validActionsListDefault = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsListDefault}\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageAsset] Action '{action}' failed for path '{path}': {e}\");\n return Response.Error(\n $\"Internal error processing action '{action}' on '{path}': {e.Message}\"\n );\n }\n }\n\n // --- Action Implementations ---\n\n private static object ReimportAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for reimport.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // TODO: Apply importer properties before reimporting?\n // This is complex as it requires getting the AssetImporter, casting it,\n // applying properties via reflection or specific methods, saving, then reimporting.\n if (properties != null && properties.HasValues)\n {\n Debug.LogWarning(\n \"[ManageAsset.Reimport] Modifying importer properties before reimport is not fully implemented yet.\"\n );\n // AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n // if (importer != null) { /* Apply properties */ AssetDatabase.WriteImportSettingsIfDirty(fullPath); }\n }\n\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate);\n // AssetDatabase.Refresh(); // Usually ImportAsset handles refresh\n return Response.Success($\"Asset '{fullPath}' reimported.\", GetAssetData(fullPath));\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to reimport asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateAsset(JObject @params)\n {\n string path = @params[\"path\"]?.ToString();\n string assetType = @params[\"assetType\"]?.ToString();\n JObject properties = @params[\"properties\"] as JObject;\n\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create.\");\n if (string.IsNullOrEmpty(assetType))\n return Response.Error(\"'assetType' is required for create.\");\n\n string fullPath = SanitizeAssetPath(path);\n string directory = Path.GetDirectoryName(fullPath);\n\n // Ensure directory exists\n if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), directory)))\n {\n Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), directory));\n AssetDatabase.Refresh(); // Make sure Unity knows about the new folder\n }\n\n if (AssetExists(fullPath))\n return Response.Error($\"Asset already exists at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object newAsset = null;\n string lowerAssetType = assetType.ToLowerInvariant();\n\n // Handle common asset types\n if (lowerAssetType == \"folder\")\n {\n return CreateFolder(path); // Use dedicated method\n }\n else if (lowerAssetType == \"material\")\n {\n Material mat = new Material(Shader.Find(\"Standard\")); // Default shader\n // TODO: Apply properties from JObject (e.g., shader name, color, texture assignments)\n if (properties != null)\n ApplyMaterialProperties(mat, properties);\n AssetDatabase.CreateAsset(mat, fullPath);\n newAsset = mat;\n }\n else if (lowerAssetType == \"physicsmaterial\")\n {\n PhysicsMaterialType pmat = new PhysicsMaterialType();\n if (properties != null)\n ApplyPhysicsMaterialProperties(pmat, properties);\n AssetDatabase.CreateAsset(pmat, fullPath);\n newAsset = pmat;\n }\n else if (lowerAssetType == \"scriptableobject\")\n {\n string scriptClassName = properties?[\"scriptClass\"]?.ToString();\n if (string.IsNullOrEmpty(scriptClassName))\n return Response.Error(\n \"'scriptClass' property required when creating ScriptableObject asset.\"\n );\n\n Type scriptType = FindType(scriptClassName);\n if (\n scriptType == null\n || !typeof(ScriptableObject).IsAssignableFrom(scriptType)\n )\n {\n return Response.Error(\n $\"Script class '{scriptClassName}' not found or does not inherit from ScriptableObject.\"\n );\n }\n\n ScriptableObject so = ScriptableObject.CreateInstance(scriptType);\n // TODO: Apply properties from JObject to the ScriptableObject instance?\n AssetDatabase.CreateAsset(so, fullPath);\n newAsset = so;\n }\n else if (lowerAssetType == \"prefab\")\n {\n // Creating prefabs usually involves saving an existing GameObject hierarchy.\n // A common pattern is to create an empty GameObject, configure it, and then save it.\n return Response.Error(\n \"Creating prefabs programmatically usually requires a source GameObject. Use manage_gameobject to create/configure, then save as prefab via a separate mechanism or future enhancement.\"\n );\n // Example (conceptual):\n // GameObject source = GameObject.Find(properties[\"sourceGameObject\"].ToString());\n // if(source != null) PrefabUtility.SaveAsPrefabAsset(source, fullPath);\n }\n // TODO: Add more asset types (Animation Controller, Scene, etc.)\n else\n {\n // Generic creation attempt (might fail or create empty files)\n // For some types, just creating the file might be enough if Unity imports it.\n // File.Create(Path.Combine(Directory.GetCurrentDirectory(), fullPath)).Close();\n // AssetDatabase.ImportAsset(fullPath); // Let Unity try to import it\n // newAsset = AssetDatabase.LoadAssetAtPath(fullPath);\n return Response.Error(\n $\"Creation for asset type '{assetType}' is not explicitly supported yet. Supported: Folder, Material, ScriptableObject.\"\n );\n }\n\n if (\n newAsset == null\n && !Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), fullPath))\n ) // Check if it wasn't a folder and asset wasn't created\n {\n return Response.Error(\n $\"Failed to create asset '{assetType}' at '{fullPath}'. See logs for details.\"\n );\n }\n\n AssetDatabase.SaveAssets();\n // AssetDatabase.Refresh(); // CreateAsset often handles refresh\n return Response.Success(\n $\"Asset '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create asset at '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateFolder(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create_folder.\");\n string fullPath = SanitizeAssetPath(path);\n string parentDir = Path.GetDirectoryName(fullPath);\n string folderName = Path.GetFileName(fullPath);\n\n if (AssetExists(fullPath))\n {\n // Check if it's actually a folder already\n if (AssetDatabase.IsValidFolder(fullPath))\n {\n return Response.Success(\n $\"Folder already exists at path: {fullPath}\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n return Response.Error(\n $\"An asset (not a folder) already exists at path: {fullPath}\"\n );\n }\n }\n\n try\n {\n // Ensure parent exists\n if (!string.IsNullOrEmpty(parentDir) && !AssetDatabase.IsValidFolder(parentDir))\n {\n // Recursively create parent folders if needed (AssetDatabase handles this internally)\n // Or we can do it manually: Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), parentDir)); AssetDatabase.Refresh();\n }\n\n string guid = AssetDatabase.CreateFolder(parentDir, folderName);\n if (string.IsNullOrEmpty(guid))\n {\n return Response.Error(\n $\"Failed to create folder '{fullPath}'. Check logs and permissions.\"\n );\n }\n\n // AssetDatabase.Refresh(); // CreateFolder usually handles refresh\n return Response.Success(\n $\"Folder '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create folder '{fullPath}': {e.Message}\");\n }\n }\n\n private static object ModifyAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for modify.\");\n if (properties == null || !properties.HasValues)\n return Response.Error(\"'properties' are required for modify.\");\n\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n bool modified = false; // Flag to track if any changes were made\n\n // --- NEW: Handle GameObject / Prefab Component Modification ---\n if (asset is GameObject gameObject)\n {\n // Iterate through the properties JSON: keys are component names, values are properties objects for that component\n foreach (var prop in properties.Properties())\n {\n string componentName = prop.Name; // e.g., \"Collectible\"\n // Check if the value associated with the component name is actually an object containing properties\n if (\n prop.Value is JObject componentProperties\n && componentProperties.HasValues\n ) // e.g., {\"bobSpeed\": 2.0}\n {\n // Find the component on the GameObject using the name from the JSON key\n // Using GetComponent(string) is convenient but might require exact type name or be ambiguous.\n // Consider using FindType helper if needed for more complex scenarios.\n Component targetComponent = gameObject.GetComponent(componentName);\n\n if (targetComponent != null)\n {\n // Apply the nested properties (e.g., bobSpeed) to the found component instance\n // Use |= to ensure 'modified' becomes true if any component is successfully modified\n modified |= ApplyObjectProperties(\n targetComponent,\n componentProperties\n );\n }\n else\n {\n // Log a warning if a specified component couldn't be found\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Component '{componentName}' not found on GameObject '{gameObject.name}' in asset '{fullPath}'. Skipping modification for this component.\"\n );\n }\n }\n else\n {\n // Log a warning if the structure isn't {\"ComponentName\": {\"prop\": value}}\n // We could potentially try to apply this property directly to the GameObject here if needed,\n // but the primary goal is component modification.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Property '{prop.Name}' for GameObject modification should have a JSON object value containing component properties. Value was: {prop.Value.Type}. Skipping.\"\n );\n }\n }\n // Note: 'modified' is now true if ANY component property was successfully changed.\n }\n // --- End NEW ---\n\n // --- Existing logic for other asset types (now as else-if) ---\n // Example: Modifying a Material\n else if (asset is Material material)\n {\n // Apply properties directly to the material. If this modifies, it sets modified=true.\n // Use |= in case the asset was already marked modified by previous logic (though unlikely here)\n modified |= ApplyMaterialProperties(material, properties);\n }\n // Example: Modifying a ScriptableObject\n else if (asset is ScriptableObject so)\n {\n // Apply properties directly to the ScriptableObject.\n modified |= ApplyObjectProperties(so, properties); // General helper\n }\n // Example: Modifying TextureImporter settings\n else if (asset is Texture)\n {\n AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n if (importer is TextureImporter textureImporter)\n {\n bool importerModified = ApplyObjectProperties(textureImporter, properties);\n if (importerModified)\n {\n // Importer settings need saving and reimporting\n AssetDatabase.WriteImportSettingsIfDirty(fullPath);\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate); // Reimport to apply changes\n modified = true; // Mark overall operation as modified\n }\n }\n else\n {\n Debug.LogWarning($\"Could not get TextureImporter for {fullPath}.\");\n }\n }\n // TODO: Add modification logic for other common asset types (Models, AudioClips importers, etc.)\n else // Fallback for other asset types OR direct properties on non-GameObject assets\n {\n // This block handles non-GameObject/Material/ScriptableObject/Texture assets.\n // Attempts to apply properties directly to the asset itself.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Asset type '{asset.GetType().Name}' at '{fullPath}' is not explicitly handled for component modification. Attempting generic property setting on the asset itself.\"\n );\n modified |= ApplyObjectProperties(asset, properties);\n }\n // --- End Existing Logic ---\n\n // Check if any modification happened (either component or direct asset modification)\n if (modified)\n {\n // Mark the asset as dirty (important for prefabs/SOs) so Unity knows to save it.\n EditorUtility.SetDirty(asset);\n // Save all modified assets to disk.\n AssetDatabase.SaveAssets();\n // Refresh might be needed in some edge cases, but SaveAssets usually covers it.\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{fullPath}' modified successfully.\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n // If no changes were made (e.g., component not found, property names incorrect, value unchanged), return a success message indicating nothing changed.\n return Response.Success(\n $\"No applicable or modifiable properties found for asset '{fullPath}'. Check component names, property names, and values.\",\n GetAssetData(fullPath)\n );\n // Previous message: return Response.Success($\"No applicable properties found to modify for asset '{fullPath}'.\", GetAssetData(fullPath));\n }\n }\n catch (Exception e)\n {\n // Log the detailed error internally\n Debug.LogError($\"[ManageAsset] Action 'modify' failed for path '{path}': {e}\");\n // Return a user-friendly error message\n return Response.Error($\"Failed to modify asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DeleteAsset(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for delete.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n bool success = AssetDatabase.DeleteAsset(fullPath);\n if (success)\n {\n // AssetDatabase.Refresh(); // DeleteAsset usually handles refresh\n return Response.Success($\"Asset '{fullPath}' deleted successfully.\");\n }\n else\n {\n // This might happen if the file couldn't be deleted (e.g., locked)\n return Response.Error(\n $\"Failed to delete asset '{fullPath}'. Check logs or if the file is locked.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DuplicateAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for duplicate.\");\n\n string sourcePath = SanitizeAssetPath(path);\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n\n string destPath;\n if (string.IsNullOrEmpty(destinationPath))\n {\n // Generate a unique path if destination is not provided\n destPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath);\n }\n else\n {\n destPath = SanitizeAssetPath(destinationPath);\n if (AssetExists(destPath))\n return Response.Error($\"Asset already exists at destination path: {destPath}\");\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n }\n\n try\n {\n bool success = AssetDatabase.CopyAsset(sourcePath, destPath);\n if (success)\n {\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{sourcePath}' duplicated to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n return Response.Error(\n $\"Failed to duplicate asset from '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error duplicating asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object MoveOrRenameAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for move/rename.\");\n if (string.IsNullOrEmpty(destinationPath))\n return Response.Error(\"'destination' path is required for move/rename.\");\n\n string sourcePath = SanitizeAssetPath(path);\n string destPath = SanitizeAssetPath(destinationPath);\n\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n if (AssetExists(destPath))\n return Response.Error(\n $\"An asset already exists at the destination path: {destPath}\"\n );\n\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n\n try\n {\n // Validate will return an error string if failed, null if successful\n string error = AssetDatabase.ValidateMoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(error))\n {\n return Response.Error(\n $\"Failed to move/rename asset from '{sourcePath}' to '{destPath}': {error}\"\n );\n }\n\n string guid = AssetDatabase.MoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(guid)) // MoveAsset returns the new GUID on success\n {\n // AssetDatabase.Refresh(); // MoveAsset usually handles refresh\n return Response.Success(\n $\"Asset moved/renamed from '{sourcePath}' to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n // This case might not be reachable if ValidateMoveAsset passes, but good to have\n return Response.Error(\n $\"MoveAsset call failed unexpectedly for '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error moving/renaming asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object SearchAssets(JObject @params)\n {\n string searchPattern = @params[\"searchPattern\"]?.ToString();\n string filterType = @params[\"filterType\"]?.ToString();\n string pathScope = @params[\"path\"]?.ToString(); // Use path as folder scope\n string filterDateAfterStr = @params[\"filterDateAfter\"]?.ToString();\n int pageSize = @params[\"pageSize\"]?.ToObject() ?? 50; // Default page size\n int pageNumber = @params[\"pageNumber\"]?.ToObject() ?? 1; // Default page number (1-based)\n bool generatePreview = @params[\"generatePreview\"]?.ToObject() ?? false;\n\n List searchFilters = new List();\n if (!string.IsNullOrEmpty(searchPattern))\n searchFilters.Add(searchPattern);\n if (!string.IsNullOrEmpty(filterType))\n searchFilters.Add($\"t:{filterType}\");\n\n string[] folderScope = null;\n if (!string.IsNullOrEmpty(pathScope))\n {\n folderScope = new string[] { SanitizeAssetPath(pathScope) };\n if (!AssetDatabase.IsValidFolder(folderScope[0]))\n {\n // Maybe the user provided a file path instead of a folder?\n // We could search in the containing folder, or return an error.\n Debug.LogWarning(\n $\"Search path '{folderScope[0]}' is not a valid folder. Searching entire project.\"\n );\n folderScope = null; // Search everywhere if path isn't a folder\n }\n }\n\n DateTime? filterDateAfter = null;\n if (!string.IsNullOrEmpty(filterDateAfterStr))\n {\n if (\n DateTime.TryParse(\n filterDateAfterStr,\n CultureInfo.InvariantCulture,\n DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,\n out DateTime parsedDate\n )\n )\n {\n filterDateAfter = parsedDate;\n }\n else\n {\n Debug.LogWarning(\n $\"Could not parse filterDateAfter: '{filterDateAfterStr}'. Expected ISO 8601 format.\"\n );\n }\n }\n\n try\n {\n string[] guids = AssetDatabase.FindAssets(\n string.Join(\" \", searchFilters),\n folderScope\n );\n List results = new List();\n int totalFound = 0;\n\n foreach (string guid in guids)\n {\n string assetPath = AssetDatabase.GUIDToAssetPath(guid);\n if (string.IsNullOrEmpty(assetPath))\n continue;\n\n // Apply date filter if present\n if (filterDateAfter.HasValue)\n {\n DateTime lastWriteTime = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), assetPath)\n );\n if (lastWriteTime <= filterDateAfter.Value)\n {\n continue; // Skip assets older than or equal to the filter date\n }\n }\n\n totalFound++; // Count matching assets before pagination\n results.Add(GetAssetData(assetPath, generatePreview));\n }\n\n // Apply pagination\n int startIndex = (pageNumber - 1) * pageSize;\n var pagedResults = results.Skip(startIndex).Take(pageSize).ToList();\n\n return Response.Success(\n $\"Found {totalFound} asset(s). Returning page {pageNumber} ({pagedResults.Count} assets).\",\n new\n {\n totalAssets = totalFound,\n pageSize = pageSize,\n pageNumber = pageNumber,\n assets = pagedResults,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error searching assets: {e.Message}\");\n }\n }\n\n private static object GetAssetInfo(string path, bool generatePreview)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_info.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n return Response.Success(\n \"Asset info retrieved.\",\n GetAssetData(fullPath, generatePreview)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting info for asset '{fullPath}': {e.Message}\");\n }\n }\n\n /// \n /// Retrieves components attached to a GameObject asset (like a Prefab).\n /// \n /// The asset path of the GameObject or Prefab.\n /// A response object containing a list of component type names or an error.\n private static object GetComponentsFromAsset(string path)\n {\n // 1. Validate input path\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_components.\");\n\n // 2. Sanitize and check existence\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // 3. Load the asset\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n // 4. Check if it's a GameObject (Prefabs load as GameObjects)\n GameObject gameObject = asset as GameObject;\n if (gameObject == null)\n {\n // Also check if it's *directly* a Component type (less common for primary assets)\n Component componentAsset = asset as Component;\n if (componentAsset != null)\n {\n // If the asset itself *is* a component, maybe return just its info?\n // This is an edge case. Let's stick to GameObjects for now.\n return Response.Error(\n $\"Asset at '{fullPath}' is a Component ({asset.GetType().FullName}), not a GameObject. Components are typically retrieved *from* a GameObject.\"\n );\n }\n return Response.Error(\n $\"Asset at '{fullPath}' is not a GameObject (Type: {asset.GetType().FullName}). Cannot get components from this asset type.\"\n );\n }\n\n // 5. Get components\n Component[] components = gameObject.GetComponents();\n\n // 6. Format component data\n List componentList = components\n .Select(comp => new\n {\n typeName = comp.GetType().FullName,\n instanceID = comp.GetInstanceID(),\n // TODO: Add more component-specific details here if needed in the future?\n // Requires reflection or specific handling per component type.\n })\n .ToList(); // Explicit cast for clarity if needed\n\n // 7. Return success response\n return Response.Success(\n $\"Found {componentList.Count} component(s) on asset '{fullPath}'.\",\n componentList\n );\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageAsset.GetComponentsFromAsset] Error getting components for '{fullPath}': {e}\"\n );\n return Response.Error(\n $\"Error getting components for asset '{fullPath}': {e.Message}\"\n );\n }\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Ensures the asset path starts with \"Assets/\".\n /// \n private static string SanitizeAssetPath(string path)\n {\n if (string.IsNullOrEmpty(path))\n return path;\n path = path.Replace('\\\\', '/'); // Normalize separators\n if (!path.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n return \"Assets/\" + path.TrimStart('/');\n }\n return path;\n }\n\n /// \n /// Checks if an asset exists at the given path (file or folder).\n /// \n private static bool AssetExists(string sanitizedPath)\n {\n // AssetDatabase APIs are generally preferred over raw File/Directory checks for assets.\n // Check if it's a known asset GUID.\n if (!string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath)))\n {\n return true;\n }\n // AssetPathToGUID might not work for newly created folders not yet refreshed.\n // Check directory explicitly for folders.\n if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n // Check if it's considered a *valid* folder by Unity\n return AssetDatabase.IsValidFolder(sanitizedPath);\n }\n // Check file existence for non-folder assets.\n if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n return true; // Assume if file exists, it's an asset or will be imported\n }\n\n return false;\n // Alternative: return !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath));\n }\n\n /// \n /// Ensures the directory for a given asset path exists, creating it if necessary.\n /// \n private static void EnsureDirectoryExists(string directoryPath)\n {\n if (string.IsNullOrEmpty(directoryPath))\n return;\n string fullDirPath = Path.Combine(Directory.GetCurrentDirectory(), directoryPath);\n if (!Directory.Exists(fullDirPath))\n {\n Directory.CreateDirectory(fullDirPath);\n AssetDatabase.Refresh(); // Let Unity know about the new folder\n }\n }\n\n /// \n /// Applies properties from JObject to a Material.\n /// \n private static bool ApplyMaterialProperties(Material mat, JObject properties)\n {\n if (mat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set shader\n if (properties[\"shader\"]?.Type == JTokenType.String)\n {\n Shader newShader = Shader.Find(properties[\"shader\"].ToString());\n if (newShader != null && mat.shader != newShader)\n {\n mat.shader = newShader;\n modified = true;\n }\n }\n // Example: Set color property\n if (properties[\"color\"] is JObject colorProps)\n {\n string propName = colorProps[\"name\"]?.ToString() ?? \"_Color\"; // Default main color\n if (colorProps[\"value\"] is JArray colArr && colArr.Count >= 3)\n {\n try\n {\n Color newColor = new Color(\n colArr[0].ToObject(),\n colArr[1].ToObject(),\n colArr[2].ToObject(),\n colArr.Count > 3 ? colArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n } else if (properties[\"color\"] is JArray colorArr) //Use color now with examples set in manage_asset.py\n {\n string propName = \"_Color\"; \n try {\n if (colorArr.Count >= 3)\n {\n Color newColor = new Color(\n colorArr[0].ToObject(),\n colorArr[1].ToObject(), \n colorArr[2].ToObject(), \n colorArr.Count > 3 ? colorArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n } \n catch (Exception ex) {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n // Example: Set float property\n if (properties[\"float\"] is JObject floatProps)\n {\n string propName = floatProps[\"name\"]?.ToString();\n if (\n !string.IsNullOrEmpty(propName) && floatProps[\"value\"]?.Type == JTokenType.Float\n || floatProps[\"value\"]?.Type == JTokenType.Integer\n )\n {\n try\n {\n float newVal = floatProps[\"value\"].ToObject();\n if (mat.HasProperty(propName) && mat.GetFloat(propName) != newVal)\n {\n mat.SetFloat(propName, newVal);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing float property '{propName}': {ex.Message}\"\n );\n }\n }\n }\n // Example: Set texture property\n if (properties[\"texture\"] is JObject texProps)\n {\n string propName = texProps[\"name\"]?.ToString() ?? \"_MainTex\"; // Default main texture\n string texPath = texProps[\"path\"]?.ToString();\n if (!string.IsNullOrEmpty(texPath))\n {\n Texture newTex = AssetDatabase.LoadAssetAtPath(\n SanitizeAssetPath(texPath)\n );\n if (\n newTex != null\n && mat.HasProperty(propName)\n && mat.GetTexture(propName) != newTex\n )\n {\n mat.SetTexture(propName, newTex);\n modified = true;\n }\n else if (newTex == null)\n {\n Debug.LogWarning($\"Texture not found at path: {texPath}\");\n }\n }\n }\n\n // TODO: Add handlers for other property types (Vectors, Ints, Keywords, RenderQueue, etc.)\n return modified;\n }\n\n /// \n /// Applies properties from JObject to a PhysicsMaterial.\n /// \n private static bool ApplyPhysicsMaterialProperties(PhysicsMaterialType pmat, JObject properties)\n {\n if (pmat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set dynamic friction\n if (properties[\"dynamicFriction\"]?.Type == JTokenType.Float)\n {\n float dynamicFriction = properties[\"dynamicFriction\"].ToObject();\n pmat.dynamicFriction = dynamicFriction;\n modified = true;\n }\n\n // Example: Set static friction\n if (properties[\"staticFriction\"]?.Type == JTokenType.Float)\n {\n float staticFriction = properties[\"staticFriction\"].ToObject();\n pmat.staticFriction = staticFriction;\n modified = true;\n }\n\n // Example: Set bounciness\n if (properties[\"bounciness\"]?.Type == JTokenType.Float)\n {\n float bounciness = properties[\"bounciness\"].ToObject();\n pmat.bounciness = bounciness;\n modified = true;\n }\n\n List averageList = new List { \"ave\", \"Ave\", \"average\", \"Average\" };\n List multiplyList = new List { \"mul\", \"Mul\", \"mult\", \"Mult\", \"multiply\", \"Multiply\" };\n List minimumList = new List { \"min\", \"Min\", \"minimum\", \"Minimum\" };\n List maximumList = new List { \"max\", \"Max\", \"maximum\", \"Maximum\" };\n\n // Example: Set friction combine\n if (properties[\"frictionCombine\"]?.Type == JTokenType.String)\n {\n string frictionCombine = properties[\"frictionCombine\"].ToString();\n if (averageList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n // Example: Set bounce combine\n if (properties[\"bounceCombine\"]?.Type == JTokenType.String)\n {\n string bounceCombine = properties[\"bounceCombine\"].ToString();\n if (averageList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n return modified;\n }\n\n /// \n /// Generic helper to set properties on any UnityEngine.Object using reflection.\n /// \n private static bool ApplyObjectProperties(UnityEngine.Object target, JObject properties)\n {\n if (target == null || properties == null)\n return false;\n bool modified = false;\n Type type = target.GetType();\n\n foreach (var prop in properties.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n if (SetPropertyOrField(target, propName, propValue, type))\n {\n modified = true;\n }\n }\n return modified;\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types and Unity objects.\n /// \n private static bool SetPropertyOrField(\n object target,\n string memberName,\n JToken value,\n Type type = null\n )\n {\n type = type ?? target.GetType();\n System.Reflection.BindingFlags flags =\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.Instance\n | System.Reflection.BindingFlags.IgnoreCase;\n\n try\n {\n System.Reflection.PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType);\n if (\n convertedValue != null\n && !object.Equals(propInfo.GetValue(target), convertedValue)\n )\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n else\n {\n System.Reflection.FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null)\n {\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType);\n if (\n convertedValue != null\n && !object.Equals(fieldInfo.GetValue(target), convertedValue)\n )\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[SetPropertyOrField] Failed to set '{memberName}' on {type.Name}: {ex.Message}\"\n );\n }\n return false;\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types and primitives.\n /// \n private static object ConvertJTokenToType(JToken token, Type targetType)\n {\n try\n {\n if (token == null || token.Type == JTokenType.Null)\n return null;\n\n if (targetType == typeof(string))\n return token.ToObject();\n if (targetType == typeof(int))\n return token.ToObject();\n if (targetType == typeof(float))\n return token.ToObject();\n if (targetType == typeof(bool))\n return token.ToObject();\n if (targetType == typeof(Vector2) && token is JArray arrV2 && arrV2.Count == 2)\n return new Vector2(arrV2[0].ToObject(), arrV2[1].ToObject());\n if (targetType == typeof(Vector3) && token is JArray arrV3 && arrV3.Count == 3)\n return new Vector3(\n arrV3[0].ToObject(),\n arrV3[1].ToObject(),\n arrV3[2].ToObject()\n );\n if (targetType == typeof(Vector4) && token is JArray arrV4 && arrV4.Count == 4)\n return new Vector4(\n arrV4[0].ToObject(),\n arrV4[1].ToObject(),\n arrV4[2].ToObject(),\n arrV4[3].ToObject()\n );\n if (targetType == typeof(Quaternion) && token is JArray arrQ && arrQ.Count == 4)\n return new Quaternion(\n arrQ[0].ToObject(),\n arrQ[1].ToObject(),\n arrQ[2].ToObject(),\n arrQ[3].ToObject()\n );\n if (targetType == typeof(Color) && token is JArray arrC && arrC.Count >= 3) // Allow RGB or RGBA\n return new Color(\n arrC[0].ToObject(),\n arrC[1].ToObject(),\n arrC[2].ToObject(),\n arrC.Count > 3 ? arrC[3].ToObject() : 1.0f\n );\n if (targetType.IsEnum)\n return Enum.Parse(targetType, token.ToString(), true); // Case-insensitive enum parsing\n\n // Handle loading Unity Objects (Materials, Textures, etc.) by path\n if (\n typeof(UnityEngine.Object).IsAssignableFrom(targetType)\n && token.Type == JTokenType.String\n )\n {\n string assetPath = SanitizeAssetPath(token.ToString());\n UnityEngine.Object loadedAsset = AssetDatabase.LoadAssetAtPath(\n assetPath,\n targetType\n );\n if (loadedAsset == null)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not load asset of type {targetType.Name} from path: {assetPath}\"\n );\n }\n return loadedAsset;\n }\n\n // Fallback: Try direct conversion (might work for other simple value types)\n return token.ToObject(targetType);\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not convert JToken '{token}' (type {token.Type}) to type '{targetType.Name}': {ex.Message}\"\n );\n return null;\n }\n }\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// Needed for creating ScriptableObjects or finding component types by name.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Try direct lookup first (common Unity types often don't need assembly qualified name)\n var type =\n Type.GetType(typeName)\n ?? Type.GetType($\"UnityEngine.{typeName}, UnityEngine.CoreModule\")\n ?? Type.GetType($\"UnityEngine.UI.{typeName}, UnityEngine.UI\")\n ?? Type.GetType($\"UnityEditor.{typeName}, UnityEditor.CoreModule\");\n\n if (type != null)\n return type;\n\n // If not found, search loaded assemblies (slower but more robust for user scripts)\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n {\n // Look for non-namespaced first\n type = assembly.GetType(typeName, false, true); // throwOnError=false, ignoreCase=true\n if (type != null)\n return type;\n\n // Check common namespaces if simple name given\n type = assembly.GetType(\"UnityEngine.\" + typeName, false, true);\n if (type != null)\n return type;\n type = assembly.GetType(\"UnityEditor.\" + typeName, false, true);\n if (type != null)\n return type;\n // Add other likely namespaces if needed (e.g., specific plugins)\n }\n\n Debug.LogWarning($\"[FindType] Type '{typeName}' not found in any loaded assembly.\");\n return null; // Not found\n }\n\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of an asset.\n /// \n private static object GetAssetData(string path, bool generatePreview = false)\n {\n if (string.IsNullOrEmpty(path) || !AssetExists(path))\n return null;\n\n string guid = AssetDatabase.AssetPathToGUID(path);\n Type assetType = AssetDatabase.GetMainAssetTypeAtPath(path);\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(path);\n string previewBase64 = null;\n int previewWidth = 0;\n int previewHeight = 0;\n\n if (generatePreview && asset != null)\n {\n Texture2D preview = AssetPreview.GetAssetPreview(asset);\n\n if (preview != null)\n {\n try\n {\n // Ensure texture is readable for EncodeToPNG\n // Creating a temporary readable copy is safer\n RenderTexture rt = RenderTexture.GetTemporary(\n preview.width,\n preview.height\n );\n Graphics.Blit(preview, rt);\n RenderTexture previous = RenderTexture.active;\n RenderTexture.active = rt;\n Texture2D readablePreview = new Texture2D(preview.width, preview.height);\n readablePreview.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);\n readablePreview.Apply();\n RenderTexture.active = previous;\n RenderTexture.ReleaseTemporary(rt);\n\n byte[] pngData = readablePreview.EncodeToPNG();\n previewBase64 = Convert.ToBase64String(pngData);\n previewWidth = readablePreview.width;\n previewHeight = readablePreview.height;\n UnityEngine.Object.DestroyImmediate(readablePreview); // Clean up temp texture\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Failed to generate readable preview for '{path}': {ex.Message}. Preview might not be readable.\"\n );\n // Fallback: Try getting static preview if available?\n // Texture2D staticPreview = AssetPreview.GetMiniThumbnail(asset);\n }\n }\n else\n {\n Debug.LogWarning(\n $\"Could not get asset preview for {path} (Type: {assetType?.Name}). Is it supported?\"\n );\n }\n }\n\n return new\n {\n path = path,\n guid = guid,\n assetType = assetType?.FullName ?? \"Unknown\",\n name = Path.GetFileNameWithoutExtension(path),\n fileName = Path.GetFileName(path),\n isFolder = AssetDatabase.IsValidFolder(path),\n instanceID = asset?.GetInstanceID() ?? 0,\n lastWriteTimeUtc = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), path)\n )\n .ToString(\"o\"), // ISO 8601\n // --- Preview Data ---\n previewBase64 = previewBase64, // PNG data as Base64 string\n previewWidth = previewWidth,\n previewHeight = previewHeight,\n // TODO: Add more metadata? Importer settings? Dependencies?\n };\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ReadConsole.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles reading and clearing Unity Editor console log entries.\n /// Uses reflection to access internal LogEntry methods/properties.\n /// \n public static class ReadConsole\n {\n // Reflection members for accessing internal LogEntry data\n // private static MethodInfo _getEntriesMethod; // Removed as it's unused and fails reflection\n private static MethodInfo _startGettingEntriesMethod;\n private static MethodInfo _endGettingEntriesMethod; // Renamed from _stopGettingEntriesMethod, trying End...\n private static MethodInfo _clearMethod;\n private static MethodInfo _getCountMethod;\n private static MethodInfo _getEntryMethod;\n private static FieldInfo _modeField;\n private static FieldInfo _messageField;\n private static FieldInfo _fileField;\n private static FieldInfo _lineField;\n private static FieldInfo _instanceIdField;\n\n // Note: Timestamp is not directly available in LogEntry; need to parse message or find alternative?\n\n // Static constructor for reflection setup\n static ReadConsole()\n {\n try\n {\n Type logEntriesType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntries\"\n );\n if (logEntriesType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntries\");\n\n // Include NonPublic binding flags as internal APIs might change accessibility\n BindingFlags staticFlags =\n BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;\n BindingFlags instanceFlags =\n BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\n\n _startGettingEntriesMethod = logEntriesType.GetMethod(\n \"StartGettingEntries\",\n staticFlags\n );\n if (_startGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.StartGettingEntries\");\n\n // Try reflecting EndGettingEntries based on warning message\n _endGettingEntriesMethod = logEntriesType.GetMethod(\n \"EndGettingEntries\",\n staticFlags\n );\n if (_endGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.EndGettingEntries\");\n\n _clearMethod = logEntriesType.GetMethod(\"Clear\", staticFlags);\n if (_clearMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.Clear\");\n\n _getCountMethod = logEntriesType.GetMethod(\"GetCount\", staticFlags);\n if (_getCountMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetCount\");\n\n _getEntryMethod = logEntriesType.GetMethod(\"GetEntryInternal\", staticFlags);\n if (_getEntryMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetEntryInternal\");\n\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntry\");\n\n _modeField = logEntryType.GetField(\"mode\", instanceFlags);\n if (_modeField == null)\n throw new Exception(\"Failed to reflect LogEntry.mode\");\n\n _messageField = logEntryType.GetField(\"message\", instanceFlags);\n if (_messageField == null)\n throw new Exception(\"Failed to reflect LogEntry.message\");\n\n _fileField = logEntryType.GetField(\"file\", instanceFlags);\n if (_fileField == null)\n throw new Exception(\"Failed to reflect LogEntry.file\");\n\n _lineField = logEntryType.GetField(\"line\", instanceFlags);\n if (_lineField == null)\n throw new Exception(\"Failed to reflect LogEntry.line\");\n\n _instanceIdField = logEntryType.GetField(\"instanceID\", instanceFlags);\n if (_instanceIdField == null)\n throw new Exception(\"Failed to reflect LogEntry.instanceID\");\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ReadConsole] Static Initialization Failed: Could not setup reflection for LogEntries/LogEntry. Console reading/clearing will likely fail. Specific Error: {e.Message}\"\n );\n // Set members to null to prevent NullReferenceExceptions later, HandleCommand should check this.\n _startGettingEntriesMethod =\n _endGettingEntriesMethod =\n _clearMethod =\n _getCountMethod =\n _getEntryMethod =\n null;\n _modeField = _messageField = _fileField = _lineField = _instanceIdField = null;\n }\n }\n\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n // Check if ALL required reflection members were successfully initialized.\n if (\n _startGettingEntriesMethod == null\n || _endGettingEntriesMethod == null\n || _clearMethod == null\n || _getCountMethod == null\n || _getEntryMethod == null\n || _modeField == null\n || _messageField == null\n || _fileField == null\n || _lineField == null\n || _instanceIdField == null\n )\n {\n // Log the error here as well for easier debugging in Unity Console\n Debug.LogError(\n \"[ReadConsole] HandleCommand called but reflection members are not initialized. Static constructor might have failed silently or there's an issue.\"\n );\n return Response.Error(\n \"ReadConsole handler failed to initialize due to reflection errors. Cannot access console logs.\"\n );\n }\n\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"get\";\n\n try\n {\n if (action == \"clear\")\n {\n return ClearConsole();\n }\n else if (action == \"get\")\n {\n // Extract parameters for 'get'\n var types =\n (@params[\"types\"] as JArray)?.Select(t => t.ToString().ToLower()).ToList()\n ?? new List { \"error\", \"warning\", \"log\" };\n int? count = @params[\"count\"]?.ToObject();\n string filterText = @params[\"filterText\"]?.ToString();\n string sinceTimestampStr = @params[\"sinceTimestamp\"]?.ToString(); // TODO: Implement timestamp filtering\n string format = (@params[\"format\"]?.ToString() ?? \"detailed\").ToLower();\n bool includeStacktrace =\n @params[\"includeStacktrace\"]?.ToObject() ?? true;\n\n if (types.Contains(\"all\"))\n {\n types = new List { \"error\", \"warning\", \"log\" }; // Expand 'all'\n }\n\n if (!string.IsNullOrEmpty(sinceTimestampStr))\n {\n Debug.LogWarning(\n \"[ReadConsole] Filtering by 'since_timestamp' is not currently implemented.\"\n );\n // Need a way to get timestamp per log entry.\n }\n\n return GetConsoleEntries(types, count, filterText, format, includeStacktrace);\n }\n else\n {\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'get' or 'clear'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object ClearConsole()\n {\n try\n {\n _clearMethod.Invoke(null, null); // Static method, no instance, no parameters\n return Response.Success(\"Console cleared successfully.\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to clear console: {e}\");\n return Response.Error($\"Failed to clear console: {e.Message}\");\n }\n }\n\n private static object GetConsoleEntries(\n List types,\n int? count,\n string filterText,\n string format,\n bool includeStacktrace\n )\n {\n List formattedEntries = new List();\n int retrievedCount = 0;\n\n try\n {\n // LogEntries requires calling Start/Stop around GetEntries/GetEntryInternal\n _startGettingEntriesMethod.Invoke(null, null);\n\n int totalEntries = (int)_getCountMethod.Invoke(null, null);\n // Create instance to pass to GetEntryInternal - Ensure the type is correct\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\n \"Could not find internal type UnityEditor.LogEntry during GetConsoleEntries.\"\n );\n object logEntryInstance = Activator.CreateInstance(logEntryType);\n\n for (int i = 0; i < totalEntries; i++)\n {\n // Get the entry data into our instance using reflection\n _getEntryMethod.Invoke(null, new object[] { i, logEntryInstance });\n\n // Extract data using reflection\n int mode = (int)_modeField.GetValue(logEntryInstance);\n string message = (string)_messageField.GetValue(logEntryInstance);\n string file = (string)_fileField.GetValue(logEntryInstance);\n\n int line = (int)_lineField.GetValue(logEntryInstance);\n // int instanceId = (int)_instanceIdField.GetValue(logEntryInstance);\n\n if (string.IsNullOrEmpty(message))\n continue; // Skip empty messages\n\n // --- Filtering ---\n // Filter by type\n LogType currentType = GetLogTypeFromMode(mode);\n if (!types.Contains(currentType.ToString().ToLowerInvariant()))\n {\n continue;\n }\n\n // Filter by text (case-insensitive)\n if (\n !string.IsNullOrEmpty(filterText)\n && message.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) < 0\n )\n {\n continue;\n }\n\n // TODO: Filter by timestamp (requires timestamp data)\n\n // --- Formatting ---\n string stackTrace = includeStacktrace ? ExtractStackTrace(message) : null;\n // Get first line if stack is present and requested, otherwise use full message\n string messageOnly =\n (includeStacktrace && !string.IsNullOrEmpty(stackTrace))\n ? message.Split(\n new[] { '\\n', '\\r' },\n StringSplitOptions.RemoveEmptyEntries\n )[0]\n : message;\n\n object formattedEntry = null;\n switch (format)\n {\n case \"plain\":\n formattedEntry = messageOnly;\n break;\n case \"json\":\n case \"detailed\": // Treat detailed as json for structured return\n default:\n formattedEntry = new\n {\n type = currentType.ToString(),\n message = messageOnly,\n file = file,\n line = line,\n // timestamp = \"\", // TODO\n stackTrace = stackTrace, // Will be null if includeStacktrace is false or no stack found\n };\n break;\n }\n\n formattedEntries.Add(formattedEntry);\n retrievedCount++;\n\n // Apply count limit (after filtering)\n if (count.HasValue && retrievedCount >= count.Value)\n {\n break;\n }\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Error while retrieving log entries: {e}\");\n // Ensure EndGettingEntries is called even if there's an error during iteration\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch\n { /* Ignore nested exception */\n }\n return Response.Error($\"Error retrieving log entries: {e.Message}\");\n }\n finally\n {\n // Ensure we always call EndGettingEntries\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to call EndGettingEntries: {e}\");\n // Don't return error here as we might have valid data, but log it.\n }\n }\n\n // Return the filtered and formatted list (might be empty)\n return Response.Success(\n $\"Retrieved {formattedEntries.Count} log entries.\",\n formattedEntries\n );\n }\n\n // --- Internal Helpers ---\n\n // Mapping from LogEntry.mode bits to LogType enum\n // Based on decompiled UnityEditor code or common patterns. Precise bits might change between Unity versions.\n // See comments below for LogEntry mode bits exploration.\n // Note: This mapping is simplified and might not cover all edge cases or future Unity versions perfectly.\n private const int ModeBitError = 1 << 0;\n private const int ModeBitAssert = 1 << 1;\n private const int ModeBitWarning = 1 << 2;\n private const int ModeBitLog = 1 << 3;\n private const int ModeBitException = 1 << 4; // Often combined with Error bits\n private const int ModeBitScriptingError = 1 << 9;\n private const int ModeBitScriptingWarning = 1 << 10;\n private const int ModeBitScriptingLog = 1 << 11;\n private const int ModeBitScriptingException = 1 << 18;\n private const int ModeBitScriptingAssertion = 1 << 22;\n\n private static LogType GetLogTypeFromMode(int mode)\n {\n // First, determine the type based on the original logic (most severe first)\n LogType initialType;\n if (\n (\n mode\n & (\n ModeBitError\n | ModeBitScriptingError\n | ModeBitException\n | ModeBitScriptingException\n )\n ) != 0\n )\n {\n initialType = LogType.Error;\n }\n else if ((mode & (ModeBitAssert | ModeBitScriptingAssertion)) != 0)\n {\n initialType = LogType.Assert;\n }\n else if ((mode & (ModeBitWarning | ModeBitScriptingWarning)) != 0)\n {\n initialType = LogType.Warning;\n }\n else\n {\n initialType = LogType.Log;\n }\n\n // Apply the observed \"one level lower\" correction\n switch (initialType)\n {\n case LogType.Error:\n return LogType.Warning; // Error becomes Warning\n case LogType.Warning:\n return LogType.Log; // Warning becomes Log\n case LogType.Assert:\n return LogType.Assert; // Assert remains Assert (no lower level defined)\n case LogType.Log:\n return LogType.Log; // Log remains Log\n default:\n return LogType.Log; // Default fallback\n }\n }\n\n /// \n /// Attempts to extract the stack trace part from a log message.\n /// Unity log messages often have the stack trace appended after the main message,\n /// starting on a new line and typically indented or beginning with \"at \".\n /// \n /// The complete log message including potential stack trace.\n /// The extracted stack trace string, or null if none is found.\n private static string ExtractStackTrace(string fullMessage)\n {\n if (string.IsNullOrEmpty(fullMessage))\n return null;\n\n // Split into lines, removing empty ones to handle different line endings gracefully.\n // Using StringSplitOptions.None might be better if empty lines matter within stack trace, but RemoveEmptyEntries is usually safer here.\n string[] lines = fullMessage.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n // If there's only one line or less, there's no separate stack trace.\n if (lines.Length <= 1)\n return null;\n\n int stackStartIndex = -1;\n\n // Start checking from the second line onwards.\n for (int i = 1; i < lines.Length; ++i)\n {\n // Performance: TrimStart creates a new string. Consider using IsWhiteSpace check if performance critical.\n string trimmedLine = lines[i].TrimStart();\n\n // Check for common stack trace patterns.\n if (\n trimmedLine.StartsWith(\"at \")\n || trimmedLine.StartsWith(\"UnityEngine.\")\n || trimmedLine.StartsWith(\"UnityEditor.\")\n || trimmedLine.Contains(\"(at \")\n || // Covers \"(at Assets/...\" pattern\n // Heuristic: Check if line starts with likely namespace/class pattern (Uppercase.Something)\n (\n trimmedLine.Length > 0\n && char.IsUpper(trimmedLine[0])\n && trimmedLine.Contains('.')\n )\n )\n {\n stackStartIndex = i;\n break; // Found the likely start of the stack trace\n }\n }\n\n // If a potential start index was found...\n if (stackStartIndex > 0)\n {\n // Join the lines from the stack start index onwards using standard newline characters.\n // This reconstructs the stack trace part of the message.\n return string.Join(\"\\n\", lines.Skip(stackStartIndex));\n }\n\n // No clear stack trace found based on the patterns.\n return null;\n }\n\n /* LogEntry.mode bits exploration (based on Unity decompilation/observation):\n May change between versions.\n\n Basic Types:\n kError = 1 << 0 (1)\n kAssert = 1 << 1 (2)\n kWarning = 1 << 2 (4)\n kLog = 1 << 3 (8)\n kFatal = 1 << 4 (16) - Often treated as Exception/Error\n\n Modifiers/Context:\n kAssetImportError = 1 << 7 (128)\n kAssetImportWarning = 1 << 8 (256)\n kScriptingError = 1 << 9 (512)\n kScriptingWarning = 1 << 10 (1024)\n kScriptingLog = 1 << 11 (2048)\n kScriptCompileError = 1 << 12 (4096)\n kScriptCompileWarning = 1 << 13 (8192)\n kStickyError = 1 << 14 (16384) - Stays visible even after Clear On Play\n kMayIgnoreLineNumber = 1 << 15 (32768)\n kReportBug = 1 << 16 (65536) - Shows the \"Report Bug\" button\n kDisplayPreviousErrorInStatusBar = 1 << 17 (131072)\n kScriptingException = 1 << 18 (262144)\n kDontExtractStacktrace = 1 << 19 (524288) - Hint to the console UI\n kShouldClearOnPlay = 1 << 20 (1048576) - Default behavior\n kGraphCompileError = 1 << 21 (2097152)\n kScriptingAssertion = 1 << 22 (4194304)\n kVisualScriptingError = 1 << 23 (8388608)\n\n Example observed values:\n Log: 2048 (ScriptingLog) or 8 (Log)\n Warning: 1028 (ScriptingWarning | Warning) or 4 (Warning)\n Error: 513 (ScriptingError | Error) or 1 (Error)\n Exception: 262161 (ScriptingException | Error | kFatal?) - Complex combination\n Assertion: 4194306 (ScriptingAssertion | Assert) or 2 (Assert)\n */\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageEditor.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal; // Required for tag management\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles operations related to controlling and querying the Unity Editor state,\n /// including managing Tags and Layers.\n /// \n public static class ManageEditor\n {\n // Constant for starting user layer index\n private const int FirstUserLayerIndex = 8;\n\n // Constant for total layer count\n private const int TotalLayerCount = 32;\n\n /// \n /// Main handler for editor management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n // Parameters for specific actions\n string tagName = @params[\"tagName\"]?.ToString();\n string layerName = @params[\"layerName\"]?.ToString();\n bool waitForCompletion = @params[\"waitForCompletion\"]?.ToObject() ?? false; // Example - not used everywhere\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Route action\n switch (action)\n {\n // Play Mode Control\n case \"play\":\n try\n {\n if (!EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = true;\n return Response.Success(\"Entered play mode.\");\n }\n return Response.Success(\"Already in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error entering play mode: {e.Message}\");\n }\n case \"pause\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPaused = !EditorApplication.isPaused;\n return Response.Success(\n EditorApplication.isPaused ? \"Game paused.\" : \"Game resumed.\"\n );\n }\n return Response.Error(\"Cannot pause/resume: Not in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error pausing/resuming game: {e.Message}\");\n }\n case \"stop\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = false;\n return Response.Success(\"Exited play mode.\");\n }\n return Response.Success(\"Already stopped (not in play mode).\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error stopping play mode: {e.Message}\");\n }\n\n // Editor State/Info\n case \"get_state\":\n return GetEditorState();\n case \"get_windows\":\n return GetEditorWindows();\n case \"get_active_tool\":\n return GetActiveTool();\n case \"get_selection\":\n return GetSelection();\n case \"set_active_tool\":\n string toolName = @params[\"toolName\"]?.ToString();\n if (string.IsNullOrEmpty(toolName))\n return Response.Error(\"'toolName' parameter required for set_active_tool.\");\n return SetActiveTool(toolName);\n\n // Tag Management\n case \"add_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for add_tag.\");\n return AddTag(tagName);\n case \"remove_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for remove_tag.\");\n return RemoveTag(tagName);\n case \"get_tags\":\n return GetTags(); // Helper to list current tags\n\n // Layer Management\n case \"add_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for add_layer.\");\n return AddLayer(layerName);\n case \"remove_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for remove_layer.\");\n return RemoveLayer(layerName);\n case \"get_layers\":\n return GetLayers(); // Helper to list current layers\n\n // --- Settings (Example) ---\n // case \"set_resolution\":\n // int? width = @params[\"width\"]?.ToObject();\n // int? height = @params[\"height\"]?.ToObject();\n // if (!width.HasValue || !height.HasValue) return Response.Error(\"'width' and 'height' parameters required.\");\n // return SetGameViewResolution(width.Value, height.Value);\n // case \"set_quality\":\n // // Handle string name or int index\n // return SetQualityLevel(@params[\"qualityLevel\"]);\n\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Supported actions include play, pause, stop, get_state, get_windows, get_active_tool, get_selection, set_active_tool, add_tag, remove_tag, get_tags, add_layer, remove_layer, get_layers.\"\n );\n }\n }\n\n // --- Editor State/Info Methods ---\n private static object GetEditorState()\n {\n try\n {\n var state = new\n {\n isPlaying = EditorApplication.isPlaying,\n isPaused = EditorApplication.isPaused,\n isCompiling = EditorApplication.isCompiling,\n isUpdating = EditorApplication.isUpdating,\n applicationPath = EditorApplication.applicationPath,\n applicationContentsPath = EditorApplication.applicationContentsPath,\n timeSinceStartup = EditorApplication.timeSinceStartup,\n };\n return Response.Success(\"Retrieved editor state.\", state);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor state: {e.Message}\");\n }\n }\n\n private static object GetEditorWindows()\n {\n try\n {\n // Get all types deriving from EditorWindow\n var windowTypes = AppDomain\n .CurrentDomain.GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => type.IsSubclassOf(typeof(EditorWindow)))\n .ToList();\n\n var openWindows = new List();\n\n // Find currently open instances\n // Resources.FindObjectsOfTypeAll seems more reliable than GetWindow for finding *all* open windows\n EditorWindow[] allWindows = Resources.FindObjectsOfTypeAll();\n\n foreach (EditorWindow window in allWindows)\n {\n if (window == null)\n continue; // Skip potentially destroyed windows\n\n try\n {\n openWindows.Add(\n new\n {\n title = window.titleContent.text,\n typeName = window.GetType().FullName,\n isFocused = EditorWindow.focusedWindow == window,\n position = new\n {\n x = window.position.x,\n y = window.position.y,\n width = window.position.width,\n height = window.position.height,\n },\n instanceID = window.GetInstanceID(),\n }\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Could not get info for window {window.GetType().Name}: {ex.Message}\"\n );\n }\n }\n\n return Response.Success(\"Retrieved list of open editor windows.\", openWindows);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor windows: {e.Message}\");\n }\n }\n\n private static object GetActiveTool()\n {\n try\n {\n Tool currentTool = UnityEditor.Tools.current;\n string toolName = currentTool.ToString(); // Enum to string\n bool customToolActive = UnityEditor.Tools.current == Tool.Custom; // Check if a custom tool is active\n string activeToolName = customToolActive\n ? EditorTools.GetActiveToolName()\n : toolName; // Get custom name if needed\n\n var toolInfo = new\n {\n activeTool = activeToolName,\n isCustom = customToolActive,\n pivotMode = UnityEditor.Tools.pivotMode.ToString(),\n pivotRotation = UnityEditor.Tools.pivotRotation.ToString(),\n handleRotation = UnityEditor.Tools.handleRotation.eulerAngles, // Euler for simplicity\n handlePosition = UnityEditor.Tools.handlePosition,\n };\n\n return Response.Success(\"Retrieved active tool information.\", toolInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active tool: {e.Message}\");\n }\n }\n\n private static object SetActiveTool(string toolName)\n {\n try\n {\n Tool targetTool;\n if (Enum.TryParse(toolName, true, out targetTool)) // Case-insensitive parse\n {\n // Check if it's a valid built-in tool\n if (targetTool != Tool.None && targetTool <= Tool.Custom) // Tool.Custom is the last standard tool\n {\n UnityEditor.Tools.current = targetTool;\n return Response.Success($\"Set active tool to '{targetTool}'.\");\n }\n else\n {\n return Response.Error(\n $\"Cannot directly set tool to '{toolName}'. It might be None, Custom, or invalid.\"\n );\n }\n }\n else\n {\n // Potentially try activating a custom tool by name here if needed\n // This often requires specific editor scripting knowledge for that tool.\n return Response.Error(\n $\"Could not parse '{toolName}' as a standard Unity Tool (View, Move, Rotate, Scale, Rect, Transform, Custom).\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error setting active tool: {e.Message}\");\n }\n }\n\n private static object GetSelection()\n {\n try\n {\n var selectionInfo = new\n {\n activeObject = Selection.activeObject?.name,\n activeGameObject = Selection.activeGameObject?.name,\n activeTransform = Selection.activeTransform?.name,\n activeInstanceID = Selection.activeInstanceID,\n count = Selection.count,\n objects = Selection\n .objects.Select(obj => new\n {\n name = obj?.name,\n type = obj?.GetType().FullName,\n instanceID = obj?.GetInstanceID(),\n })\n .ToList(),\n gameObjects = Selection\n .gameObjects.Select(go => new\n {\n name = go?.name,\n instanceID = go?.GetInstanceID(),\n })\n .ToList(),\n assetGUIDs = Selection.assetGUIDs, // GUIDs for selected assets in Project view\n };\n\n return Response.Success(\"Retrieved current selection details.\", selectionInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting selection: {e.Message}\");\n }\n }\n\n // --- Tag Management Methods ---\n\n private static object AddTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n\n // Check if tag already exists\n if (InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' already exists.\");\n }\n\n try\n {\n // Add the tag using the internal utility\n InternalEditorUtility.AddTag(tagName);\n // Force save assets to ensure the change persists in the TagManager asset\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' added successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object RemoveTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n if (tagName.Equals(\"Untagged\", StringComparison.OrdinalIgnoreCase))\n return Response.Error(\"Cannot remove the built-in 'Untagged' tag.\");\n\n // Check if tag exists before attempting removal\n if (!InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' does not exist.\");\n }\n\n try\n {\n // Remove the tag using the internal utility\n InternalEditorUtility.RemoveTag(tagName);\n // Force save assets\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' removed successfully.\");\n }\n catch (Exception e)\n {\n // Catch potential issues if the tag is somehow in use or removal fails\n return Response.Error($\"Failed to remove tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object GetTags()\n {\n try\n {\n string[] tags = InternalEditorUtility.tags;\n return Response.Success(\"Retrieved current tags.\", tags);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve tags: {e.Message}\");\n }\n }\n\n // --- Layer Management Methods ---\n\n private static object AddLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Check if layer name already exists (case-insensitive check recommended)\n for (int i = 0; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n return Response.Error($\"Layer '{layerName}' already exists at index {i}.\");\n }\n }\n\n // Find the first empty user layer slot (indices 8 to 31)\n int firstEmptyUserLayer = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (layerSP != null && string.IsNullOrEmpty(layerSP.stringValue))\n {\n firstEmptyUserLayer = i;\n break;\n }\n }\n\n if (firstEmptyUserLayer == -1)\n {\n return Response.Error(\"No empty User Layer slots available (8-31 are full).\");\n }\n\n // Assign the name to the found slot\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n firstEmptyUserLayer\n );\n targetLayerSP.stringValue = layerName;\n // Apply the changes to the TagManager asset\n tagManager.ApplyModifiedProperties();\n // Save assets to make sure it's written to disk\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' added successfully to slot {firstEmptyUserLayer}.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object RemoveLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Find the layer by name (must be user layer)\n int layerIndexToRemove = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++) // Start from user layers\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n // Case-insensitive comparison is safer\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n layerIndexToRemove = i;\n break;\n }\n }\n\n if (layerIndexToRemove == -1)\n {\n return Response.Error($\"User layer '{layerName}' not found.\");\n }\n\n // Clear the name for that index\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n layerIndexToRemove\n );\n targetLayerSP.stringValue = string.Empty; // Set to empty string to remove\n // Apply the changes\n tagManager.ApplyModifiedProperties();\n // Save assets\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' (slot {layerIndexToRemove}) removed successfully.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to remove layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object GetLayers()\n {\n try\n {\n var layers = new Dictionary();\n for (int i = 0; i < TotalLayerCount; i++)\n {\n string layerName = LayerMask.LayerToName(i);\n if (!string.IsNullOrEmpty(layerName)) // Only include layers that have names\n {\n layers.Add(i, layerName);\n }\n }\n return Response.Success(\"Retrieved current named layers.\", layers);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve layers: {e.Message}\");\n }\n }\n\n // --- Helper Methods ---\n\n /// \n /// Gets the SerializedObject for the TagManager asset.\n /// \n private static SerializedObject GetTagManager()\n {\n try\n {\n // Load the TagManager asset from the ProjectSettings folder\n UnityEngine.Object[] tagManagerAssets = AssetDatabase.LoadAllAssetsAtPath(\n \"ProjectSettings/TagManager.asset\"\n );\n if (tagManagerAssets == null || tagManagerAssets.Length == 0)\n {\n Debug.LogError(\"[ManageEditor] TagManager.asset not found in ProjectSettings.\");\n return null;\n }\n // The first object in the asset file should be the TagManager\n return new SerializedObject(tagManagerAssets[0]);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageEditor] Error accessing TagManager.asset: {e.Message}\");\n return null;\n }\n }\n\n // --- Example Implementations for Settings ---\n /*\n private static object SetGameViewResolution(int width, int height) { ... }\n private static object SetQualityLevel(JToken qualityLevelToken) { ... }\n */\n }\n\n // Helper class to get custom tool names (remains the same)\n internal static class EditorTools\n {\n public static string GetActiveToolName()\n {\n // This is a placeholder. Real implementation depends on how custom tools\n // are registered and tracked in the specific Unity project setup.\n // It might involve checking static variables, calling methods on specific tool managers, etc.\n if (UnityEditor.Tools.current == Tool.Custom)\n {\n // Example: Check a known custom tool manager\n // if (MyCustomToolManager.IsActive) return MyCustomToolManager.ActiveToolName;\n return \"Unknown Custom Tool\";\n }\n return UnityEditor.Tools.current.ToString();\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/GameObjectSerializer.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Runtime.Serialization; // For Converters\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Handles serialization of GameObjects and Components for MCP responses.\n /// Includes reflection helpers and caching for performance.\n /// \n public static class GameObjectSerializer\n {\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of a GameObject.\n /// \n public static object GetGameObjectData(GameObject go)\n {\n if (go == null)\n return null;\n return new\n {\n name = go.name,\n instanceID = go.GetInstanceID(),\n tag = go.tag,\n layer = go.layer,\n activeSelf = go.activeSelf,\n activeInHierarchy = go.activeInHierarchy,\n isStatic = go.isStatic,\n scenePath = go.scene.path, // Identify which scene it belongs to\n transform = new // Serialize transform components carefully to avoid JSON issues\n {\n // Serialize Vector3 components individually to prevent self-referencing loops.\n // The default serializer can struggle with properties like Vector3.normalized.\n position = new\n {\n x = go.transform.position.x,\n y = go.transform.position.y,\n z = go.transform.position.z,\n },\n localPosition = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.rotation.eulerAngles.x,\n y = go.transform.rotation.eulerAngles.y,\n z = go.transform.rotation.eulerAngles.z,\n },\n localRotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n },\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n forward = new\n {\n x = go.transform.forward.x,\n y = go.transform.forward.y,\n z = go.transform.forward.z,\n },\n up = new\n {\n x = go.transform.up.x,\n y = go.transform.up.y,\n z = go.transform.up.z,\n },\n right = new\n {\n x = go.transform.right.x,\n y = go.transform.right.y,\n z = go.transform.right.z,\n },\n },\n parentInstanceID = go.transform.parent?.gameObject.GetInstanceID() ?? 0, // 0 if no parent\n // Optionally include components, but can be large\n // components = go.GetComponents().Select(c => GetComponentData(c)).ToList()\n // Or just component names:\n componentNames = go.GetComponents()\n .Select(c => c.GetType().FullName)\n .ToList(),\n };\n }\n\n // --- Metadata Caching for Reflection ---\n private class CachedMetadata\n {\n public readonly List SerializableProperties;\n public readonly List SerializableFields;\n\n public CachedMetadata(List properties, List fields)\n {\n SerializableProperties = properties;\n SerializableFields = fields;\n }\n }\n // Key becomes Tuple\n private static readonly Dictionary, CachedMetadata> _metadataCache = new Dictionary, CachedMetadata>();\n // --- End Metadata Caching ---\n\n /// \n /// Creates a serializable representation of a Component, attempting to serialize\n /// public properties and fields using reflection, with caching and control over non-public fields.\n /// \n // Add the flag parameter here\n public static object GetComponentData(Component c, bool includeNonPublicSerializedFields = true)\n {\n // --- Add Early Logging --- \n // Debug.Log($\"[GetComponentData] Starting for component: {c?.GetType()?.FullName ?? \"null\"} (ID: {c?.GetInstanceID() ?? 0})\");\n // --- End Early Logging ---\n \n if (c == null) return null;\n Type componentType = c.GetType();\n\n // --- Special handling for Transform to avoid reflection crashes and problematic properties --- \n if (componentType == typeof(Transform))\n {\n Transform tr = c as Transform;\n // Debug.Log($\"[GetComponentData] Manually serializing Transform (ID: {tr.GetInstanceID()})\");\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", tr.GetInstanceID() },\n // Manually extract known-safe properties. Avoid Quaternion 'rotation' and 'lossyScale'.\n { \"position\", CreateTokenFromValue(tr.position, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localPosition\", CreateTokenFromValue(tr.localPosition, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"eulerAngles\", CreateTokenFromValue(tr.eulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() }, // Use Euler angles\n { \"localEulerAngles\", CreateTokenFromValue(tr.localEulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localScale\", CreateTokenFromValue(tr.localScale, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"right\", CreateTokenFromValue(tr.right, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"up\", CreateTokenFromValue(tr.up, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"forward\", CreateTokenFromValue(tr.forward, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"parentInstanceID\", tr.parent?.gameObject.GetInstanceID() ?? 0 },\n { \"rootInstanceID\", tr.root?.gameObject.GetInstanceID() ?? 0 },\n { \"childCount\", tr.childCount },\n // Include standard Object/Component properties\n { \"name\", tr.name }, \n { \"tag\", tr.tag }, \n { \"gameObjectInstanceID\", tr.gameObject?.GetInstanceID() ?? 0 }\n };\n }\n // --- End Special handling for Transform --- \n\n // --- Special handling for Camera to avoid matrix-related crashes ---\n if (componentType == typeof(Camera))\n {\n Camera cam = c as Camera;\n var cameraProperties = new Dictionary();\n\n // List of safe properties to serialize\n var safeProperties = new Dictionary>\n {\n { \"nearClipPlane\", () => cam.nearClipPlane },\n { \"farClipPlane\", () => cam.farClipPlane },\n { \"fieldOfView\", () => cam.fieldOfView },\n { \"renderingPath\", () => (int)cam.renderingPath },\n { \"actualRenderingPath\", () => (int)cam.actualRenderingPath },\n { \"allowHDR\", () => cam.allowHDR },\n { \"allowMSAA\", () => cam.allowMSAA },\n { \"allowDynamicResolution\", () => cam.allowDynamicResolution },\n { \"forceIntoRenderTexture\", () => cam.forceIntoRenderTexture },\n { \"orthographicSize\", () => cam.orthographicSize },\n { \"orthographic\", () => cam.orthographic },\n { \"opaqueSortMode\", () => (int)cam.opaqueSortMode },\n { \"transparencySortMode\", () => (int)cam.transparencySortMode },\n { \"depth\", () => cam.depth },\n { \"aspect\", () => cam.aspect },\n { \"cullingMask\", () => cam.cullingMask },\n { \"eventMask\", () => cam.eventMask },\n { \"backgroundColor\", () => cam.backgroundColor },\n { \"clearFlags\", () => (int)cam.clearFlags },\n { \"stereoEnabled\", () => cam.stereoEnabled },\n { \"stereoSeparation\", () => cam.stereoSeparation },\n { \"stereoConvergence\", () => cam.stereoConvergence },\n { \"enabled\", () => cam.enabled },\n { \"name\", () => cam.name },\n { \"tag\", () => cam.tag },\n { \"gameObject\", () => new { name = cam.gameObject.name, instanceID = cam.gameObject.GetInstanceID() } }\n };\n\n foreach (var prop in safeProperties)\n {\n try\n {\n var value = prop.Value();\n if (value != null)\n {\n AddSerializableValue(cameraProperties, prop.Key, value.GetType(), value);\n }\n }\n catch (Exception)\n {\n // Silently skip any property that fails\n continue;\n }\n }\n\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", cam.GetInstanceID() },\n { \"properties\", cameraProperties }\n };\n }\n // --- End Special handling for Camera ---\n\n var data = new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", c.GetInstanceID() }\n };\n\n // --- Get Cached or Generate Metadata (using new cache key) ---\n Tuple cacheKey = new Tuple(componentType, includeNonPublicSerializedFields);\n if (!_metadataCache.TryGetValue(cacheKey, out CachedMetadata cachedData))\n {\n var propertiesToCache = new List();\n var fieldsToCache = new List();\n\n // Traverse the hierarchy from the component type up to MonoBehaviour\n Type currentType = componentType;\n while (currentType != null && currentType != typeof(MonoBehaviour) && currentType != typeof(object))\n {\n // Get properties declared only at the current type level\n BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n foreach (var propInfo in currentType.GetProperties(propFlags))\n {\n // Basic filtering (readable, not indexer, not transform which is handled elsewhere)\n if (!propInfo.CanRead || propInfo.GetIndexParameters().Length > 0 || propInfo.Name == \"transform\") continue;\n // Add if not already added (handles overrides - keep the most derived version)\n if (!propertiesToCache.Any(p => p.Name == propInfo.Name)) {\n propertiesToCache.Add(propInfo);\n }\n }\n\n // Get fields declared only at the current type level (both public and non-public)\n BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n var declaredFields = currentType.GetFields(fieldFlags);\n\n // Process the declared Fields for caching\n foreach (var fieldInfo in declaredFields)\n {\n if (fieldInfo.Name.EndsWith(\"k__BackingField\")) continue; // Skip backing fields\n\n // Add if not already added (handles hiding - keep the most derived version)\n if (fieldsToCache.Any(f => f.Name == fieldInfo.Name)) continue;\n\n bool shouldInclude = false;\n if (includeNonPublicSerializedFields)\n {\n // If TRUE, include Public OR NonPublic with [SerializeField]\n shouldInclude = fieldInfo.IsPublic || (fieldInfo.IsPrivate && fieldInfo.IsDefined(typeof(SerializeField), inherit: false));\n }\n else // includeNonPublicSerializedFields is FALSE\n {\n // If FALSE, include ONLY if it is explicitly Public.\n shouldInclude = fieldInfo.IsPublic;\n }\n\n if (shouldInclude)\n {\n fieldsToCache.Add(fieldInfo);\n }\n }\n\n // Move to the base type\n currentType = currentType.BaseType;\n }\n // --- End Hierarchy Traversal ---\n\n cachedData = new CachedMetadata(propertiesToCache, fieldsToCache);\n _metadataCache[cacheKey] = cachedData; // Add to cache with combined key\n }\n // --- End Get Cached or Generate Metadata ---\n\n // --- Use cached metadata ---\n var serializablePropertiesOutput = new Dictionary();\n \n // --- Add Logging Before Property Loop ---\n // Debug.Log($\"[GetComponentData] Starting property loop for {componentType.Name}...\");\n // --- End Logging Before Property Loop ---\n\n // Use cached properties\n foreach (var propInfo in cachedData.SerializableProperties)\n {\n string propName = propInfo.Name;\n\n // --- Skip known obsolete/problematic Component shortcut properties ---\n bool skipProperty = false;\n if (propName == \"rigidbody\" || propName == \"rigidbody2D\" || propName == \"camera\" ||\n propName == \"light\" || propName == \"animation\" || propName == \"constantForce\" ||\n propName == \"renderer\" || propName == \"audio\" || propName == \"networkView\" ||\n propName == \"collider\" || propName == \"collider2D\" || propName == \"hingeJoint\" ||\n propName == \"particleSystem\" ||\n // Also skip potentially problematic Matrix properties prone to cycles/errors\n propName == \"worldToLocalMatrix\" || propName == \"localToWorldMatrix\")\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping generic property: {propName}\"); // Optional log\n skipProperty = true;\n }\n // --- End Skip Generic Properties ---\n\n // --- Skip specific potentially problematic Camera properties ---\n if (componentType == typeof(Camera) && \n (propName == \"pixelRect\" || \n propName == \"rect\" || \n propName == \"cullingMatrix\" ||\n propName == \"useOcclusionCulling\" ||\n propName == \"worldToCameraMatrix\" ||\n propName == \"projectionMatrix\" ||\n propName == \"nonJitteredProjectionMatrix\" ||\n propName == \"previousViewProjectionMatrix\" ||\n propName == \"cameraToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Camera property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Camera Properties ---\n\n // --- Skip specific potentially problematic Transform properties ---\n if (componentType == typeof(Transform) && \n (propName == \"lossyScale\" || \n propName == \"rotation\" ||\n propName == \"worldToLocalMatrix\" ||\n propName == \"localToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Transform property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Transform Properties ---\n\n // Skip if flagged\n if (skipProperty)\n {\n continue;\n }\n\n try\n {\n // --- Add detailed logging --- \n // Debug.Log($\"[GetComponentData] Accessing: {componentType.Name}.{propName}\");\n // --- End detailed logging ---\n object value = propInfo.GetValue(c);\n Type propType = propInfo.PropertyType;\n AddSerializableValue(serializablePropertiesOutput, propName, propType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read property {propName} on {componentType.Name}: {ex.Message}\");\n }\n }\n\n // --- Add Logging Before Field Loop ---\n // Debug.Log($\"[GetComponentData] Starting field loop for {componentType.Name}...\");\n // --- End Logging Before Field Loop ---\n\n // Use cached fields\n foreach (var fieldInfo in cachedData.SerializableFields)\n {\n try\n {\n // --- Add detailed logging for fields --- \n // Debug.Log($\"[GetComponentData] Accessing Field: {componentType.Name}.{fieldInfo.Name}\");\n // --- End detailed logging for fields ---\n object value = fieldInfo.GetValue(c);\n string fieldName = fieldInfo.Name;\n Type fieldType = fieldInfo.FieldType;\n AddSerializableValue(serializablePropertiesOutput, fieldName, fieldType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read field {fieldInfo.Name} on {componentType.Name}: {ex.Message}\");\n }\n }\n // --- End Use cached metadata ---\n\n if (serializablePropertiesOutput.Count > 0)\n {\n data[\"properties\"] = serializablePropertiesOutput;\n }\n\n return data;\n }\n\n // Helper function to decide how to serialize different types\n private static void AddSerializableValue(Dictionary dict, string name, Type type, object value)\n {\n // Simplified: Directly use CreateTokenFromValue which uses the serializer\n if (value == null)\n {\n dict[name] = null;\n return;\n }\n\n try\n {\n // Use the helper that employs our custom serializer settings\n JToken token = CreateTokenFromValue(value, type);\n if (token != null) // Check if serialization succeeded in the helper\n {\n // Convert JToken back to a basic object structure for the dictionary\n dict[name] = ConvertJTokenToPlainObject(token);\n }\n // If token is null, it means serialization failed and a warning was logged.\n }\n catch (Exception e)\n {\n // Catch potential errors during JToken conversion or addition to dictionary\n Debug.LogWarning($\"[AddSerializableValue] Error processing value for '{name}' (Type: {type.FullName}): {e.Message}. Skipping.\");\n }\n }\n\n // Helper to convert JToken back to basic object structure\n private static object ConvertJTokenToPlainObject(JToken token)\n {\n if (token == null) return null;\n\n switch (token.Type)\n {\n case JTokenType.Object:\n var objDict = new Dictionary();\n foreach (var prop in ((JObject)token).Properties())\n {\n objDict[prop.Name] = ConvertJTokenToPlainObject(prop.Value);\n }\n return objDict;\n\n case JTokenType.Array:\n var list = new List();\n foreach (var item in (JArray)token)\n {\n list.Add(ConvertJTokenToPlainObject(item));\n }\n return list;\n\n case JTokenType.Integer:\n return token.ToObject(); // Use long for safety\n case JTokenType.Float:\n return token.ToObject(); // Use double for safety\n case JTokenType.String:\n return token.ToObject();\n case JTokenType.Boolean:\n return token.ToObject();\n case JTokenType.Date:\n return token.ToObject();\n case JTokenType.Guid:\n return token.ToObject();\n case JTokenType.Uri:\n return token.ToObject();\n case JTokenType.TimeSpan:\n return token.ToObject();\n case JTokenType.Bytes:\n return token.ToObject();\n case JTokenType.Null:\n return null;\n case JTokenType.Undefined:\n return null; // Treat undefined as null\n\n default:\n // Fallback for simple value types not explicitly listed\n if (token is JValue jValue && jValue.Value != null)\n {\n return jValue.Value;\n }\n // Debug.LogWarning($\"Unsupported JTokenType encountered: {token.Type}. Returning null.\");\n return null;\n }\n }\n\n // --- Define custom JsonSerializerSettings for OUTPUT ---\n private static readonly JsonSerializerSettings _outputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Handles serialization of references\n },\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore,\n // ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } // Example if needed\n };\n private static readonly JsonSerializer _outputSerializer = JsonSerializer.Create(_outputSerializerSettings);\n // --- End Define custom JsonSerializerSettings ---\n\n // Helper to create JToken using the output serializer\n private static JToken CreateTokenFromValue(object value, Type type)\n {\n if (value == null) return JValue.CreateNull();\n\n try\n {\n // Use the pre-configured OUTPUT serializer instance\n return JToken.FromObject(value, _outputSerializer);\n }\n catch (JsonSerializationException e)\n {\n Debug.LogWarning($\"[GameObjectSerializer] Newtonsoft.Json Error serializing value of type {type.FullName}: {e.Message}. Skipping property/field.\");\n return null; // Indicate serialization failure\n }\n catch (Exception e) // Catch other unexpected errors\n {\n Debug.LogWarning($\"[GameObjectSerializer] Unexpected error serializing value of type {type.FullName}: {e}. Skipping property/field.\");\n return null; // Indicate serialization failure\n }\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScene.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles scene management operations like loading, saving, creating, and querying hierarchy.\n /// \n public static class ManageScene\n {\n /// \n /// Main handler for scene management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n int? buildIndex = @params[\"buildIndex\"]?.ToObject();\n // bool loadAdditive = @params[\"loadAdditive\"]?.ToObject() ?? false; // Example for future extension\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n string relativeDir = path ?? string.Empty;\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n\n // Apply default *after* sanitizing, using the original path variable for the check\n if (string.IsNullOrEmpty(path) && action == \"create\") // Check original path for emptiness\n {\n relativeDir = \"Scenes\"; // Default relative directory\n }\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n string sceneFileName = string.IsNullOrEmpty(name) ? null : $\"{name}.unity\";\n // Construct full system path correctly: ProjectRoot/Assets/relativeDir/sceneFileName\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Combine with Assets path (Application.dataPath ends in Assets)\n string fullPath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(fullPathDir, sceneFileName);\n // Ensure relativePath always starts with \"Assets/\" and uses forward slashes\n string relativePath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(\"Assets\", relativeDir, sceneFileName).Replace('\\\\', '/');\n\n // Ensure directory exists for 'create'\n if (action == \"create\" && !string.IsNullOrEmpty(fullPathDir))\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route action\n switch (action)\n {\n case \"create\":\n if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(relativePath))\n return Response.Error(\n \"'name' and 'path' parameters are required for 'create' action.\"\n );\n return CreateScene(fullPath, relativePath);\n case \"load\":\n // Loading can be done by path/name or build index\n if (!string.IsNullOrEmpty(relativePath))\n return LoadScene(relativePath);\n else if (buildIndex.HasValue)\n return LoadScene(buildIndex.Value);\n else\n return Response.Error(\n \"Either 'name'/'path' or 'buildIndex' must be provided for 'load' action.\"\n );\n case \"save\":\n // Save current scene, optionally to a new path\n return SaveScene(fullPath, relativePath);\n case \"get_hierarchy\":\n return GetSceneHierarchy();\n case \"get_active\":\n return GetActiveSceneInfo();\n case \"get_build_settings\":\n return GetBuildSettingsScenes();\n // Add cases for modifying build settings, additive loading, unloading etc.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions: create, load, save, get_hierarchy, get_active, get_build_settings.\"\n );\n }\n }\n\n private static object CreateScene(string fullPath, string relativePath)\n {\n if (File.Exists(fullPath))\n {\n return Response.Error($\"Scene already exists at '{relativePath}'.\");\n }\n\n try\n {\n // Create a new empty scene\n Scene newScene = EditorSceneManager.NewScene(\n NewSceneSetup.EmptyScene,\n NewSceneMode.Single\n );\n // Save it to the specified path\n bool saved = EditorSceneManager.SaveScene(newScene, relativePath);\n\n if (saved)\n {\n AssetDatabase.Refresh(); // Ensure Unity sees the new scene file\n return Response.Success(\n $\"Scene '{Path.GetFileName(relativePath)}' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n else\n {\n // If SaveScene fails, it might leave an untitled scene open.\n // Optionally try to close it, but be cautious.\n return Response.Error($\"Failed to save new scene to '{relativePath}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error creating scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(string relativePath)\n {\n if (\n !File.Exists(\n Path.Combine(\n Application.dataPath.Substring(\n 0,\n Application.dataPath.Length - \"Assets\".Length\n ),\n relativePath\n )\n )\n )\n {\n return Response.Error($\"Scene file not found at '{relativePath}'.\");\n }\n\n // Check for unsaved changes in the current scene\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n // Optionally prompt the user or save automatically before loading\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n // Example: bool saveOK = EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();\n // if (!saveOK) return Response.Error(\"Load cancelled by user.\");\n }\n\n try\n {\n EditorSceneManager.OpenScene(relativePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene '{relativePath}' loaded successfully.\",\n new\n {\n path = relativePath,\n name = Path.GetFileNameWithoutExtension(relativePath),\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error loading scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(int buildIndex)\n {\n if (buildIndex < 0 || buildIndex >= SceneManager.sceneCountInBuildSettings)\n {\n return Response.Error(\n $\"Invalid build index: {buildIndex}. Must be between 0 and {SceneManager.sceneCountInBuildSettings - 1}.\"\n );\n }\n\n // Check for unsaved changes\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n }\n\n try\n {\n string scenePath = SceneUtility.GetScenePathByBuildIndex(buildIndex);\n EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene at build index {buildIndex} ('{scenePath}') loaded successfully.\",\n new\n {\n path = scenePath,\n name = Path.GetFileNameWithoutExtension(scenePath),\n buildIndex = buildIndex,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error loading scene with build index {buildIndex}: {e.Message}\"\n );\n }\n }\n\n private static object SaveScene(string fullPath, string relativePath)\n {\n try\n {\n Scene currentScene = EditorSceneManager.GetActiveScene();\n if (!currentScene.IsValid())\n {\n return Response.Error(\"No valid scene is currently active to save.\");\n }\n\n bool saved;\n string finalPath = currentScene.path; // Path where it was last saved or will be saved\n\n if (!string.IsNullOrEmpty(relativePath) && currentScene.path != relativePath)\n {\n // Save As...\n // Ensure directory exists\n string dir = Path.GetDirectoryName(fullPath);\n if (!Directory.Exists(dir))\n Directory.CreateDirectory(dir);\n\n saved = EditorSceneManager.SaveScene(currentScene, relativePath);\n finalPath = relativePath;\n }\n else\n {\n // Save (overwrite existing or save untitled)\n if (string.IsNullOrEmpty(currentScene.path))\n {\n // Scene is untitled, needs a path\n return Response.Error(\n \"Cannot save an untitled scene without providing a 'name' and 'path'. Use Save As functionality.\"\n );\n }\n saved = EditorSceneManager.SaveScene(currentScene);\n }\n\n if (saved)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Scene '{currentScene.name}' saved successfully to '{finalPath}'.\",\n new { path = finalPath, name = currentScene.name }\n );\n }\n else\n {\n return Response.Error($\"Failed to save scene '{currentScene.name}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error saving scene: {e.Message}\");\n }\n }\n\n private static object GetActiveSceneInfo()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid())\n {\n return Response.Error(\"No active scene found.\");\n }\n\n var sceneInfo = new\n {\n name = activeScene.name,\n path = activeScene.path,\n buildIndex = activeScene.buildIndex, // -1 if not in build settings\n isDirty = activeScene.isDirty,\n isLoaded = activeScene.isLoaded,\n rootCount = activeScene.rootCount,\n };\n\n return Response.Success(\"Retrieved active scene information.\", sceneInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active scene info: {e.Message}\");\n }\n }\n\n private static object GetBuildSettingsScenes()\n {\n try\n {\n var scenes = new List();\n for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)\n {\n var scene = EditorBuildSettings.scenes[i];\n scenes.Add(\n new\n {\n path = scene.path,\n guid = scene.guid.ToString(),\n enabled = scene.enabled,\n buildIndex = i, // Actual build index considering only enabled scenes might differ\n }\n );\n }\n return Response.Success(\"Retrieved scenes from Build Settings.\", scenes);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scenes from Build Settings: {e.Message}\");\n }\n }\n\n private static object GetSceneHierarchy()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid() || !activeScene.isLoaded)\n {\n return Response.Error(\n \"No valid and loaded scene is active to get hierarchy from.\"\n );\n }\n\n GameObject[] rootObjects = activeScene.GetRootGameObjects();\n var hierarchy = rootObjects.Select(go => GetGameObjectDataRecursive(go)).ToList();\n\n return Response.Success(\n $\"Retrieved hierarchy for scene '{activeScene.name}'.\",\n hierarchy\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scene hierarchy: {e.Message}\");\n }\n }\n\n /// \n /// Recursively builds a data representation of a GameObject and its children.\n /// \n private static object GetGameObjectDataRecursive(GameObject go)\n {\n if (go == null)\n return null;\n\n var childrenData = new List();\n foreach (Transform child in go.transform)\n {\n childrenData.Add(GetGameObjectDataRecursive(child.gameObject));\n }\n\n var gameObjectData = new Dictionary\n {\n { \"name\", go.name },\n { \"activeSelf\", go.activeSelf },\n { \"activeInHierarchy\", go.activeInHierarchy },\n { \"tag\", go.tag },\n { \"layer\", go.layer },\n { \"isStatic\", go.isStatic },\n { \"instanceID\", go.GetInstanceID() }, // Useful unique identifier\n {\n \"transform\",\n new\n {\n position = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n }, // Euler for simplicity\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n }\n },\n { \"children\", childrenData },\n };\n\n return gameObjectData;\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ExecuteMenuItem.cs", "using System;\nusing System.Collections.Generic; // Added for HashSet\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles executing Unity Editor menu items by path.\n /// \n public static class ExecuteMenuItem\n {\n // Basic blacklist to prevent accidental execution of potentially disruptive menu items.\n // This can be expanded based on needs.\n private static readonly HashSet _menuPathBlacklist = new HashSet(\n StringComparer.OrdinalIgnoreCase\n )\n {\n \"File/Quit\",\n // Add other potentially dangerous items like \"Edit/Preferences...\", \"File/Build Settings...\" if needed\n };\n\n /// \n /// Main handler for executing menu items or getting available ones.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"execute\"; // Default action\n\n try\n {\n switch (action)\n {\n case \"execute\":\n return ExecuteItem(@params);\n case \"get_available_menus\":\n // Getting a comprehensive list of *all* menu items dynamically is very difficult\n // and often requires complex reflection or maintaining a manual list.\n // Returning a placeholder/acknowledgement for now.\n Debug.LogWarning(\n \"[ExecuteMenuItem] 'get_available_menus' action is not fully implemented. Dynamically listing all menu items is complex.\"\n );\n // Returning an empty list as per the refactor plan's requirements.\n return Response.Success(\n \"'get_available_menus' action is not fully implemented. Returning empty list.\",\n new List()\n );\n // TODO: Consider implementing a basic list of common/known menu items or exploring reflection techniques if this feature becomes critical.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'execute', 'get_available_menus'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ExecuteMenuItem] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n /// \n /// Executes a specific menu item.\n /// \n private static object ExecuteItem(JObject @params)\n {\n // Try both naming conventions: snake_case and camelCase\n string menuPath = @params[\"menu_path\"]?.ToString() ?? @params[\"menuPath\"]?.ToString();\n\n // string alias = @params[\"alias\"]?.ToString(); // TODO: Implement alias mapping based on refactor plan requirements.\n // JObject parameters = @params[\"parameters\"] as JObject; // TODO: Investigate parameter passing (often not directly supported by ExecuteMenuItem).\n\n if (string.IsNullOrWhiteSpace(menuPath))\n {\n return Response.Error(\"Required parameter 'menu_path' or 'menuPath' is missing or empty.\");\n }\n\n // Validate against blacklist\n if (_menuPathBlacklist.Contains(menuPath))\n {\n return Response.Error(\n $\"Execution of menu item '{menuPath}' is blocked for safety reasons.\"\n );\n }\n\n // TODO: Implement alias lookup here if needed (Map alias to actual menuPath).\n // if (!string.IsNullOrEmpty(alias)) { menuPath = LookupAlias(alias); if(menuPath == null) return Response.Error(...); }\n\n // TODO: Handle parameters ('parameters' object) if a viable method is found.\n // This is complex as EditorApplication.ExecuteMenuItem doesn't take arguments directly.\n // It might require finding the underlying EditorWindow or command if parameters are needed.\n\n try\n {\n // Attempt to execute the menu item on the main thread using delayCall for safety.\n EditorApplication.delayCall += () =>\n {\n try\n {\n bool executed = EditorApplication.ExecuteMenuItem(menuPath);\n // Log potential failure inside the delayed call.\n if (!executed)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to find or execute menu item via delayCall: '{menuPath}'. It might be invalid, disabled, or context-dependent.\"\n );\n }\n }\n catch (Exception delayEx)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Exception during delayed execution of '{menuPath}': {delayEx}\"\n );\n }\n };\n\n // Report attempt immediately, as execution is delayed.\n return Response.Success(\n $\"Attempted to execute menu item: '{menuPath}'. Check Unity logs for confirmation or errors.\"\n );\n }\n catch (Exception e)\n {\n // Catch errors during setup phase.\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to setup execution for '{menuPath}': {e}\"\n );\n return Response.Error(\n $\"Error setting up execution for menu item '{menuPath}': {e.Message}\"\n );\n }\n }\n\n // TODO: Add helper for alias lookup if implementing aliases.\n // private static string LookupAlias(string alias) { ... return actualMenuPath or null ... }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/ServerInstaller.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Runtime.InteropServices;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n public static class ServerInstaller\n {\n private const string RootFolder = \"UnityMCP\";\n private const string ServerFolder = \"UnityMcpServer\";\n private const string BranchName = \"master\";\n private const string GitUrl = \"https://github.com/justinpbarnett/unity-mcp.git\";\n private const string PyprojectUrl =\n \"https://raw.githubusercontent.com/justinpbarnett/unity-mcp/refs/heads/\"\n + BranchName\n + \"/UnityMcpServer/src/pyproject.toml\";\n\n /// \n /// Ensures the unity-mcp-server is installed and up to date.\n /// \n public static void EnsureServerInstalled()\n {\n try\n {\n string saveLocation = GetSaveLocation();\n\n if (!IsServerInstalled(saveLocation))\n {\n InstallServer(saveLocation);\n }\n else\n {\n string installedVersion = GetInstalledVersion();\n string latestVersion = GetLatestVersion();\n\n if (IsNewerVersion(latestVersion, installedVersion))\n {\n UpdateServer(saveLocation);\n }\n else { }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure server installation: {ex.Message}\");\n }\n }\n\n public static string GetServerPath()\n {\n return Path.Combine(GetSaveLocation(), ServerFolder, \"src\");\n }\n\n /// \n /// Gets the platform-specific save location for the server.\n /// \n private static string GetSaveLocation()\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"AppData\",\n \"Local\",\n \"Programs\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"bin\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n string path = \"/usr/local/bin\";\n return !Directory.Exists(path) || !IsDirectoryWritable(path)\n ? Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Applications\",\n RootFolder\n )\n : Path.Combine(path, RootFolder);\n }\n throw new Exception(\"Unsupported operating system.\");\n }\n\n private static bool IsDirectoryWritable(string path)\n {\n try\n {\n File.Create(Path.Combine(path, \"test.txt\")).Dispose();\n File.Delete(Path.Combine(path, \"test.txt\"));\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Checks if the server is installed at the specified location.\n /// \n private static bool IsServerInstalled(string location)\n {\n return Directory.Exists(location)\n && File.Exists(Path.Combine(location, ServerFolder, \"src\", \"pyproject.toml\"));\n }\n\n /// \n /// Installs the server by cloning only the UnityMcpServer folder from the repository and setting up dependencies.\n /// \n private static void InstallServer(string location)\n {\n // Create the src directory where the server code will reside\n Directory.CreateDirectory(location);\n\n // Initialize git repo in the src directory\n RunCommand(\"git\", $\"init\", workingDirectory: location);\n\n // Add remote\n RunCommand(\"git\", $\"remote add origin {GitUrl}\", workingDirectory: location);\n\n // Configure sparse checkout\n RunCommand(\"git\", \"config core.sparseCheckout true\", workingDirectory: location);\n\n // Set sparse checkout path to only include UnityMcpServer folder\n string sparseCheckoutPath = Path.Combine(location, \".git\", \"info\", \"sparse-checkout\");\n File.WriteAllText(sparseCheckoutPath, $\"{ServerFolder}/\");\n\n // Fetch and checkout the branch\n RunCommand(\"git\", $\"fetch --depth=1 origin {BranchName}\", workingDirectory: location);\n RunCommand(\"git\", $\"checkout {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Fetches the currently installed version from the local pyproject.toml file.\n /// \n public static string GetInstalledVersion()\n {\n string pyprojectPath = Path.Combine(\n GetSaveLocation(),\n ServerFolder,\n \"src\",\n \"pyproject.toml\"\n );\n return ParseVersionFromPyproject(File.ReadAllText(pyprojectPath));\n }\n\n /// \n /// Fetches the latest version from the GitHub pyproject.toml file.\n /// \n public static string GetLatestVersion()\n {\n using WebClient webClient = new();\n string pyprojectContent = webClient.DownloadString(PyprojectUrl);\n return ParseVersionFromPyproject(pyprojectContent);\n }\n\n /// \n /// Updates the server by pulling the latest changes for the UnityMcpServer folder only.\n /// \n private static void UpdateServer(string location)\n {\n RunCommand(\"git\", $\"pull origin {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Parses the version number from pyproject.toml content.\n /// \n private static string ParseVersionFromPyproject(string content)\n {\n foreach (string line in content.Split('\\n'))\n {\n if (line.Trim().StartsWith(\"version =\"))\n {\n string[] parts = line.Split('=');\n if (parts.Length == 2)\n {\n return parts[1].Trim().Trim('\"');\n }\n }\n }\n throw new Exception(\"Version not found in pyproject.toml\");\n }\n\n /// \n /// Compares two version strings to determine if the latest is newer.\n /// \n public static bool IsNewerVersion(string latest, string installed)\n {\n int[] latestParts = latest.Split('.').Select(int.Parse).ToArray();\n int[] installedParts = installed.Split('.').Select(int.Parse).ToArray();\n for (int i = 0; i < Math.Min(latestParts.Length, installedParts.Length); i++)\n {\n if (latestParts[i] > installedParts[i])\n {\n return true;\n }\n\n if (latestParts[i] < installedParts[i])\n {\n return false;\n }\n }\n return latestParts.Length > installedParts.Length;\n }\n\n /// \n /// Runs a command-line process and handles output/errors.\n /// \n private static void RunCommand(\n string command,\n string arguments,\n string workingDirectory = null\n )\n {\n System.Diagnostics.Process process = new()\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = command,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n WorkingDirectory = workingDirectory ?? string.Empty,\n },\n };\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n if (process.ExitCode != 0)\n {\n throw new Exception(\n $\"Command failed: {command} {arguments}\\nOutput: {output}\\nError: {error}\"\n );\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageShader.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for shader files within the Unity project.\n /// \n public static class ManageShader\n {\n /// \n /// Main handler for shader management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode shader contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid shader name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Shaders\" if path is not provided\n string relativeDir = path ?? \"Shaders\"; // Default to \"Shaders\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Shaders\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string shaderFileName = $\"{name}.shader\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir);\n string fullPath = Path.Combine(fullPathDir, shaderFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, shaderFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n if (!Directory.Exists(fullPathDir))\n {\n Directory.CreateDirectory(fullPathDir);\n // Refresh AssetDatabase to recognize new folders\n AssetDatabase.Refresh();\n }\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateShader(fullPath, relativePath, name, contents);\n case \"read\":\n return ReadShader(fullPath, relativePath);\n case \"update\":\n return UpdateShader(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteShader(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n // Check if shader already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Add validation for shader name conflicts in Unity\n if (Shader.Find(name) != null)\n {\n return Response.Error(\n $\"A shader with name '{name}' already exists in the project. Choose a different name.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultShaderContent(name);\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new shader\n return Response.Success(\n $\"Shader '{name}.shader' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n //TODO: Consider a threshold for large files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader not found at '{relativePath}'. Use 'create' action to add a new shader.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' updated successfully.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n // Delete the asset through Unity's AssetDatabase first\n bool success = AssetDatabase.DeleteAsset(relativePath);\n if (!success)\n {\n return Response.Error($\"Failed to delete shader through Unity's AssetDatabase: '{relativePath}'\");\n }\n\n // If the file still exists (rare case), try direct deletion\n if (File.Exists(fullPath))\n {\n File.Delete(fullPath);\n }\n\n return Response.Success($\"Shader '{Path.GetFileName(relativePath)}' deleted successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to delete shader '{relativePath}': {e.Message}\");\n }\n }\n\n //This is a CGProgram template\n //TODO: making a HLSL template as well?\n private static string GenerateDefaultShaderContent(string name)\n {\n return @\"Shader \"\"\" + name + @\"\"\"\n {\n Properties\n {\n _MainTex (\"\"Texture\"\", 2D) = \"\"white\"\" {}\n }\n SubShader\n {\n Tags { \"\"RenderType\"\"=\"\"Opaque\"\" }\n LOD 100\n\n Pass\n {\n CGPROGRAM\n #pragma vertex vert\n #pragma fragment frag\n #include \"\"UnityCG.cginc\"\"\n\n struct appdata\n {\n float4 vertex : POSITION;\n float2 uv : TEXCOORD0;\n };\n\n struct v2f\n {\n float2 uv : TEXCOORD0;\n float4 vertex : SV_POSITION;\n };\n\n sampler2D _MainTex;\n float4 _MainTex_ST;\n\n v2f vert (appdata v)\n {\n v2f o;\n o.vertex = UnityObjectToClipPos(v.vertex);\n o.uv = TRANSFORM_TEX(v.uv, _MainTex);\n return o;\n }\n\n fixed4 frag (v2f i) : SV_Target\n {\n fixed4 col = tex2D(_MainTex, i.uv);\n return col;\n }\n ENDCG\n }\n }\n }\";\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Windows/ManualConfigEditorWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n // Editor window to display manual configuration instructions\n public class ManualConfigEditorWindow : EditorWindow\n {\n protected string configPath;\n protected string configJson;\n protected Vector2 scrollPos;\n protected bool pathCopied = false;\n protected bool jsonCopied = false;\n protected float copyFeedbackTimer = 0;\n protected McpClient mcpClient;\n\n public static void ShowWindow(string configPath, string configJson, McpClient mcpClient)\n {\n var window = GetWindow(\"Manual Configuration\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.mcpClient = mcpClient;\n window.minSize = new Vector2(500, 400);\n window.Show();\n }\n\n protected virtual void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n mcpClient.name + \" Manual Configuration\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"The automatic configuration failed. Please follow these steps:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Open \" + mcpClient.name + \" config file by either:\",\n instructionStyle\n );\n if (mcpClient.mcpType == McpTypes.ClaudeDesktop)\n {\n EditorGUILayout.LabelField(\n \" a) Going to Settings > Developer > Edit Config\",\n instructionStyle\n );\n }\n else if (mcpClient.mcpType == McpTypes.Cursor)\n {\n EditorGUILayout.LabelField(\n \" a) Going to File > Preferences > Cursor Settings > MCP > Add new global MCP server\",\n instructionStyle\n );\n }\n EditorGUILayout.LabelField(\" OR\", instructionStyle);\n EditorGUILayout.LabelField(\n \" b) Opening the configuration file at:\",\n instructionStyle\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n displayPath = mcpClient.linuxConfigPath;\n }\n else\n {\n displayPath = configPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"2. Paste the following JSON configuration:\",\n instructionStyle\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"3. Save the file and restart \" + mcpClient.name,\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected virtual void Update()\n {\n // Handle the feedback message timer\n if (copyFeedbackTimer > 0)\n {\n copyFeedbackTimer -= Time.deltaTime;\n if (copyFeedbackTimer <= 0)\n {\n pathCopied = false;\n jsonCopied = false;\n Repaint();\n }\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Windows/VSCodeManualSetupWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class VSCodeManualSetupWindow : ManualConfigEditorWindow\n {\n public static new void ShowWindow(string configPath, string configJson)\n {\n var window = GetWindow(\"VSCode GitHub Copilot Setup\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.minSize = new Vector2(550, 500);\n \n // Create a McpClient for VSCode\n window.mcpClient = new McpClient\n {\n name = \"VSCode GitHub Copilot\",\n mcpType = McpTypes.VSCode\n };\n \n window.Show();\n }\n\n protected override void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n \"VSCode GitHub Copilot MCP Setup\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"Setting up GitHub Copilot in VSCode with Unity MCP\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Prerequisites\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have VSCode installed\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have GitHub Copilot extension installed in VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have a valid GitHub Copilot subscription\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"2. Steps to Configure\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"a) Open VSCode Settings (File > Preferences > Settings)\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"b) Click on the 'Open Settings (JSON)' button in the top right\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"c) Add the MCP configuration shown below to your settings.json file\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"d) Save the file and restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"3. VSCode settings.json location:\",\n EditorStyles.boldLabel\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n else \n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n\n // Store the path in the base class config path\n if (string.IsNullOrEmpty(configPath))\n {\n configPath = displayPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"4. Add this configuration to your settings.json:\",\n EditorStyles.boldLabel\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"5. After configuration:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• GitHub Copilot will now be able to interact with your Unity project through the MCP protocol\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Remember to have the Unity MCP Bridge running in Unity Editor\",\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected override void Update()\n {\n // Call the base implementation which handles the copy feedback timer\n base.Update();\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Runtime/Serialization/UnityTypeConverters.cs", "using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing UnityEngine;\n#if UNITY_EDITOR\nusing UnityEditor; // Required for AssetDatabase and EditorUtility\n#endif\n\nnamespace UnityMcpBridge.Runtime.Serialization\n{\n public class Vector3Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector3 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WriteEndObject();\n }\n\n public override Vector3 ReadJson(JsonReader reader, Type objectType, Vector3 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector3(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"]\n );\n }\n }\n\n public class Vector2Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WriteEndObject();\n }\n\n public override Vector2 ReadJson(JsonReader reader, Type objectType, Vector2 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector2(\n (float)jo[\"x\"],\n (float)jo[\"y\"]\n );\n }\n }\n\n public class QuaternionConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Quaternion value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WritePropertyName(\"w\");\n writer.WriteValue(value.w);\n writer.WriteEndObject();\n }\n\n public override Quaternion ReadJson(JsonReader reader, Type objectType, Quaternion existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Quaternion(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"],\n (float)jo[\"w\"]\n );\n }\n }\n\n public class ColorConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Color value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"r\");\n writer.WriteValue(value.r);\n writer.WritePropertyName(\"g\");\n writer.WriteValue(value.g);\n writer.WritePropertyName(\"b\");\n writer.WriteValue(value.b);\n writer.WritePropertyName(\"a\");\n writer.WriteValue(value.a);\n writer.WriteEndObject();\n }\n\n public override Color ReadJson(JsonReader reader, Type objectType, Color existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Color(\n (float)jo[\"r\"],\n (float)jo[\"g\"],\n (float)jo[\"b\"],\n (float)jo[\"a\"]\n );\n }\n }\n \n public class RectConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Rect value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"width\");\n writer.WriteValue(value.width);\n writer.WritePropertyName(\"height\");\n writer.WriteValue(value.height);\n writer.WriteEndObject();\n }\n\n public override Rect ReadJson(JsonReader reader, Type objectType, Rect existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Rect(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"width\"],\n (float)jo[\"height\"]\n );\n }\n }\n \n public class BoundsConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Bounds value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"center\");\n serializer.Serialize(writer, value.center); // Use serializer to handle nested Vector3\n writer.WritePropertyName(\"size\");\n serializer.Serialize(writer, value.size); // Use serializer to handle nested Vector3\n writer.WriteEndObject();\n }\n\n public override Bounds ReadJson(JsonReader reader, Type objectType, Bounds existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n Vector3 center = jo[\"center\"].ToObject(serializer); // Use serializer to handle nested Vector3\n Vector3 size = jo[\"size\"].ToObject(serializer); // Use serializer to handle nested Vector3\n return new Bounds(center, size);\n }\n }\n\n // Converter for UnityEngine.Object references (GameObjects, Components, Materials, Textures, etc.)\n public class UnityEngineObjectConverter : JsonConverter\n {\n public override bool CanRead => true; // We need to implement ReadJson\n public override bool CanWrite => true;\n\n public override void WriteJson(JsonWriter writer, UnityEngine.Object value, JsonSerializer serializer)\n {\n if (value == null)\n {\n writer.WriteNull();\n return;\n }\n\n#if UNITY_EDITOR // AssetDatabase and EditorUtility are Editor-only\n if (UnityEditor.AssetDatabase.Contains(value))\n {\n // It's an asset (Material, Texture, Prefab, etc.)\n string path = UnityEditor.AssetDatabase.GetAssetPath(value);\n if (!string.IsNullOrEmpty(path))\n {\n writer.WriteValue(path);\n }\n else\n {\n // Asset exists but path couldn't be found? Write minimal info.\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"isAssetWithoutPath\");\n writer.WriteValue(true);\n writer.WriteEndObject();\n }\n }\n else\n {\n // It's a scene object (GameObject, Component, etc.)\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WriteEndObject();\n }\n#else\n // Runtime fallback: Write basic info without AssetDatabase\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"warning\");\n writer.WriteValue(\"UnityEngineObjectConverter running in non-Editor mode, asset path unavailable.\");\n writer.WriteEndObject();\n#endif\n }\n\n public override UnityEngine.Object ReadJson(JsonReader reader, Type objectType, UnityEngine.Object existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n if (reader.TokenType == JsonToken.Null)\n {\n return null;\n }\n\n#if UNITY_EDITOR\n if (reader.TokenType == JsonToken.String)\n {\n // Assume it's an asset path\n string path = reader.Value.ToString();\n return UnityEditor.AssetDatabase.LoadAssetAtPath(path, objectType);\n }\n\n if (reader.TokenType == JsonToken.StartObject)\n {\n JObject jo = JObject.Load(reader);\n if (jo.TryGetValue(\"instanceID\", out JToken idToken) && idToken.Type == JTokenType.Integer)\n {\n int instanceId = idToken.ToObject();\n UnityEngine.Object obj = UnityEditor.EditorUtility.InstanceIDToObject(instanceId);\n if (obj != null && objectType.IsAssignableFrom(obj.GetType()))\n {\n return obj;\n }\n }\n // Could potentially try finding by name as a fallback if ID lookup fails/isn't present\n // but that's less reliable.\n }\n#else\n // Runtime deserialization is tricky without AssetDatabase/EditorUtility\n // Maybe log a warning and return null or existingValue?\n Debug.LogWarning(\"UnityEngineObjectConverter cannot deserialize complex objects in non-Editor mode.\");\n // Skip the token to avoid breaking the reader\n if (reader.TokenType == JsonToken.StartObject) JObject.Load(reader);\n else if (reader.TokenType == JsonToken.String) reader.ReadAsString(); \n // Return null or existing value, depending on desired behavior\n return existingValue; \n#endif\n\n throw new JsonSerializationException($\"Unexpected token type '{reader.TokenType}' when deserializing UnityEngine.Object\");\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Tools/CommandRegistry.cs", "using System;\nusing System.Collections.Generic;\nusing Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Registry for all MCP command handlers (Refactored Version)\n /// \n public static class CommandRegistry\n {\n // Maps command names (matching those called from Python via ctx.bridge.unity_editor.HandlerName)\n // to the corresponding static HandleCommand method in the appropriate tool class.\n private static readonly Dictionary> _handlers = new()\n {\n { \"HandleManageScript\", ManageScript.HandleCommand },\n { \"HandleManageScene\", ManageScene.HandleCommand },\n { \"HandleManageEditor\", ManageEditor.HandleCommand },\n { \"HandleManageGameObject\", ManageGameObject.HandleCommand },\n { \"HandleManageAsset\", ManageAsset.HandleCommand },\n { \"HandleReadConsole\", ReadConsole.HandleCommand },\n { \"HandleExecuteMenuItem\", ExecuteMenuItem.HandleCommand },\n { \"HandleManageShader\", ManageShader.HandleCommand},\n };\n\n /// \n /// Gets a command handler by name.\n /// \n /// Name of the command handler (e.g., \"HandleManageAsset\").\n /// The command handler function if found, null otherwise.\n public static Func GetHandler(string commandName)\n {\n // Use case-insensitive comparison for flexibility, although Python side should be consistent\n return _handlers.TryGetValue(commandName, out var handler) ? handler : null;\n // Consider adding logging here if a handler is not found\n /*\n if (_handlers.TryGetValue(commandName, out var handler)) {\n return handler;\n } else {\n UnityEngine.Debug.LogError($\\\"[CommandRegistry] No handler found for command: {commandName}\\\");\n return null;\n }\n */\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpClient.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public class McpClient\n {\n public string name;\n public string windowsConfigPath;\n public string linuxConfigPath;\n public McpTypes mcpType;\n public string configStatus;\n public McpStatus status = McpStatus.NotConfigured;\n\n // Helper method to convert the enum to a display string\n public string GetStatusDisplayString()\n {\n return status switch\n {\n McpStatus.NotConfigured => \"Not Configured\",\n McpStatus.Configured => \"Configured\",\n McpStatus.Running => \"Running\",\n McpStatus.Connected => \"Connected\",\n McpStatus.IncorrectPath => \"Incorrect Path\",\n McpStatus.CommunicationError => \"Communication Error\",\n McpStatus.NoResponse => \"No Response\",\n McpStatus.UnsupportedOS => \"Unsupported OS\",\n McpStatus.MissingConfig => \"Missing UnityMCP Config\",\n McpStatus.Error => configStatus.StartsWith(\"Error:\") ? configStatus : \"Error\",\n _ => \"Unknown\",\n };\n }\n\n // Helper method to set both status enum and string for backward compatibility\n public void SetStatus(McpStatus newStatus, string errorDetails = null)\n {\n status = newStatus;\n\n if (newStatus == McpStatus.Error && !string.IsNullOrEmpty(errorDetails))\n {\n configStatus = $\"Error: {errorDetails}\";\n }\n else\n {\n configStatus = GetStatusDisplayString();\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Response.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Provides static methods for creating standardized success and error response objects.\n /// Ensures consistent JSON structure for communication back to the Python server.\n /// \n public static class Response\n {\n /// \n /// Creates a standardized success response object.\n /// \n /// A message describing the successful operation.\n /// Optional additional data to include in the response.\n /// An object representing the success response.\n public static object Success(string message, object data = null)\n {\n if (data != null)\n {\n return new\n {\n success = true,\n message = message,\n data = data,\n };\n }\n else\n {\n return new { success = true, message = message };\n }\n }\n\n /// \n /// Creates a standardized error response object.\n /// \n /// A message describing the error.\n /// Optional additional data (e.g., error details) to include.\n /// An object representing the error response.\n public static object Error(string errorMessage, object data = null)\n {\n if (data != null)\n {\n // Note: The key is \"error\" for error messages, not \"message\"\n return new\n {\n success = false,\n error = errorMessage,\n data = data,\n };\n }\n else\n {\n return new { success = false, error = errorMessage };\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Data/McpClients.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class McpClients\n {\n public List clients = new()\n {\n new()\n {\n name = \"Claude Desktop\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n mcpType = McpTypes.ClaudeDesktop,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"Cursor\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n mcpType = McpTypes.Cursor,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"VSCode GitHub Copilot\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n mcpType = McpTypes.VSCode,\n configStatus = \"Not Configured\",\n },\n };\n\n // Initialize status enums after construction\n public McpClients()\n {\n foreach (var client in clients)\n {\n if (client.configStatus == \"Not Configured\")\n {\n client.status = McpStatus.NotConfigured;\n }\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Vector3Helper.cs", "using Newtonsoft.Json.Linq;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Helper class for Vector3 operations\n /// \n public static class Vector3Helper\n {\n /// \n /// Parses a JArray into a Vector3\n /// \n /// The array containing x, y, z coordinates\n /// A Vector3 with the parsed coordinates\n /// Thrown when array is invalid\n public static Vector3 ParseVector3(JArray array)\n {\n if (array == null || array.Count != 3)\n throw new System.Exception(\"Vector3 must be an array of 3 floats [x, y, z].\");\n return new Vector3((float)array[0], (float)array[1], (float)array[2]);\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/Command.cs", "using Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n /// \n /// Represents a command received from the MCP client\n /// \n public class Command\n {\n /// \n /// The type of command to execute\n /// \n public string type { get; set; }\n\n /// \n /// The parameters for the command\n /// \n public JObject @params { get; set; }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Data/DefaultServerConfig.cs", "using UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class DefaultServerConfig : ServerConfig\n {\n public new string unityHost = \"localhost\";\n public new int unityPort = 6400;\n public new int mcpPort = 6500;\n public new float connectionTimeout = 15.0f;\n public new int bufferSize = 32768;\n public new string logLevel = \"INFO\";\n public new string logFormat = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\";\n public new int maxRetries = 3;\n public new float retryDelay = 1.0f;\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpStatus.cs", "namespace UnityMcpBridge.Editor.Models\n{\n // Enum representing the various status states for MCP clients\n public enum McpStatus\n {\n NotConfigured, // Not set up yet\n Configured, // Successfully configured\n Running, // Service is running\n Connected, // Successfully connected\n IncorrectPath, // Configuration has incorrect paths\n CommunicationError, // Connected but communication issues\n NoResponse, // Connected but not responding\n MissingConfig, // Config file exists but missing required elements\n UnsupportedOS, // OS is not supported\n Error, // General error state\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServer.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServer\n {\n [JsonProperty(\"command\")]\n public string command;\n\n [JsonProperty(\"args\")]\n public string[] args;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/ServerConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class ServerConfig\n {\n [JsonProperty(\"unity_host\")]\n public string unityHost = \"localhost\";\n\n [JsonProperty(\"unity_port\")]\n public int unityPort;\n\n [JsonProperty(\"mcp_port\")]\n public int mcpPort;\n\n [JsonProperty(\"connection_timeout\")]\n public float connectionTimeout;\n\n [JsonProperty(\"buffer_size\")]\n public int bufferSize;\n\n [JsonProperty(\"log_level\")]\n public string logLevel;\n\n [JsonProperty(\"log_format\")]\n public string logFormat;\n\n [JsonProperty(\"max_retries\")]\n public int maxRetries;\n\n [JsonProperty(\"retry_delay\")]\n public float retryDelay;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServers.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServers\n {\n [JsonProperty(\"unityMCP\")]\n public McpConfigServer unityMCP;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfig\n {\n [JsonProperty(\"mcpServers\")]\n public McpConfigServers mcpServers;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpTypes.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public enum McpTypes\n {\n ClaudeDesktop,\n Cursor,\n VSCode,\n }\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-20 19:14:43", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static bool FolderExists (string path) {}", "code_description": "This code segment functions to: Verify if a specified directory exists within the application's data structure by resolving relative paths and validating input parameters before checking the filesystem."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public static bool FolderExists(string path)\n {\n return Directory.Exists(path);\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-15-00"}, "editdistance_info": {"edit_distance": 20.7317, "calculate_time": "2025-08-20 19:15:00", "true_code_clean": "public static bool FolderExists(string path)\n {\n if (string.IsNullOrEmpty(path))\n {\n return false;\n }\n if (path.Equals(\"Assets\", StringComparison.OrdinalIgnoreCase))\n {\n return true;\n }\n string fullPath = Path.Combine(\n Application.dataPath,\n path.StartsWith(\"Assets/\") ? path[7..] : path\n );\n return Directory.Exists(fullPath);\n }", "predict_code_clean": "public static bool FolderExists(string path)\n {\n return Directory.Exists(path);\n }"}} {"repo_name": "unity-mcp", "file_name": "/unity-mcp/UnityMcpBridge/Editor/Helpers/GameObjectSerializer.cs", "inference_info": {"prefix_code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Runtime.Serialization; // For Converters\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Handles serialization of GameObjects and Components for MCP responses.\n /// Includes reflection helpers and caching for performance.\n /// \n public static class GameObjectSerializer\n {\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of a GameObject.\n /// \n public static object GetGameObjectData(GameObject go)\n {\n if (go == null)\n return null;\n return new\n {\n name = go.name,\n instanceID = go.GetInstanceID(),\n tag = go.tag,\n layer = go.layer,\n activeSelf = go.activeSelf,\n activeInHierarchy = go.activeInHierarchy,\n isStatic = go.isStatic,\n scenePath = go.scene.path, // Identify which scene it belongs to\n transform = new // Serialize transform components carefully to avoid JSON issues\n {\n // Serialize Vector3 components individually to prevent self-referencing loops.\n // The default serializer can struggle with properties like Vector3.normalized.\n position = new\n {\n x = go.transform.position.x,\n y = go.transform.position.y,\n z = go.transform.position.z,\n },\n localPosition = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.rotation.eulerAngles.x,\n y = go.transform.rotation.eulerAngles.y,\n z = go.transform.rotation.eulerAngles.z,\n },\n localRotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n },\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n forward = new\n {\n x = go.transform.forward.x,\n y = go.transform.forward.y,\n z = go.transform.forward.z,\n },\n up = new\n {\n x = go.transform.up.x,\n y = go.transform.up.y,\n z = go.transform.up.z,\n },\n right = new\n {\n x = go.transform.right.x,\n y = go.transform.right.y,\n z = go.transform.right.z,\n },\n },\n parentInstanceID = go.transform.parent?.gameObject.GetInstanceID() ?? 0, // 0 if no parent\n // Optionally include components, but can be large\n // components = go.GetComponents().Select(c => GetComponentData(c)).ToList()\n // Or just component names:\n componentNames = go.GetComponents()\n .Select(c => c.GetType().FullName)\n .ToList(),\n };\n }\n\n // --- Metadata Caching for Reflection ---\n private class CachedMetadata\n {\n public readonly List SerializableProperties;\n public readonly List SerializableFields;\n\n public CachedMetadata(List properties, List fields)\n {\n SerializableProperties = properties;\n SerializableFields = fields;\n }\n }\n // Key becomes Tuple\n private static readonly Dictionary, CachedMetadata> _metadataCache = new Dictionary, CachedMetadata>();\n // --- End Metadata Caching ---\n\n /// \n /// Creates a serializable representation of a Component, attempting to serialize\n /// public properties and fields using reflection, with caching and control over non-public fields.\n /// \n // Add the flag parameter here\n public static object GetComponentData(Component c, bool includeNonPublicSerializedFields = true)\n {\n // --- Add Early Logging --- \n // Debug.Log($\"[GetComponentData] Starting for component: {c?.GetType()?.FullName ?? \"null\"} (ID: {c?.GetInstanceID() ?? 0})\");\n // --- End Early Logging ---\n \n if (c == null) return null;\n Type componentType = c.GetType();\n\n // --- Special handling for Transform to avoid reflection crashes and problematic properties --- \n if (componentType == typeof(Transform))\n {\n Transform tr = c as Transform;\n // Debug.Log($\"[GetComponentData] Manually serializing Transform (ID: {tr.GetInstanceID()})\");\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", tr.GetInstanceID() },\n // Manually extract known-safe properties. Avoid Quaternion 'rotation' and 'lossyScale'.\n { \"position\", CreateTokenFromValue(tr.position, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localPosition\", CreateTokenFromValue(tr.localPosition, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"eulerAngles\", CreateTokenFromValue(tr.eulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() }, // Use Euler angles\n { \"localEulerAngles\", CreateTokenFromValue(tr.localEulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localScale\", CreateTokenFromValue(tr.localScale, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"right\", CreateTokenFromValue(tr.right, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"up\", CreateTokenFromValue(tr.up, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"forward\", CreateTokenFromValue(tr.forward, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"parentInstanceID\", tr.parent?.gameObject.GetInstanceID() ?? 0 },\n { \"rootInstanceID\", tr.root?.gameObject.GetInstanceID() ?? 0 },\n { \"childCount\", tr.childCount },\n // Include standard Object/Component properties\n { \"name\", tr.name }, \n { \"tag\", tr.tag }, \n { \"gameObjectInstanceID\", tr.gameObject?.GetInstanceID() ?? 0 }\n };\n }\n // --- End Special handling for Transform --- \n\n // --- Special handling for Camera to avoid matrix-related crashes ---\n if (componentType == typeof(Camera))\n {\n Camera cam = c as Camera;\n var cameraProperties = new Dictionary();\n\n // List of safe properties to serialize\n var safeProperties = new Dictionary>\n {\n { \"nearClipPlane\", () => cam.nearClipPlane },\n { \"farClipPlane\", () => cam.farClipPlane },\n { \"fieldOfView\", () => cam.fieldOfView },\n { \"renderingPath\", () => (int)cam.renderingPath },\n { \"actualRenderingPath\", () => (int)cam.actualRenderingPath },\n { \"allowHDR\", () => cam.allowHDR },\n { \"allowMSAA\", () => cam.allowMSAA },\n { \"allowDynamicResolution\", () => cam.allowDynamicResolution },\n { \"forceIntoRenderTexture\", () => cam.forceIntoRenderTexture },\n { \"orthographicSize\", () => cam.orthographicSize },\n { \"orthographic\", () => cam.orthographic },\n { \"opaqueSortMode\", () => (int)cam.opaqueSortMode },\n { \"transparencySortMode\", () => (int)cam.transparencySortMode },\n { \"depth\", () => cam.depth },\n { \"aspect\", () => cam.aspect },\n { \"cullingMask\", () => cam.cullingMask },\n { \"eventMask\", () => cam.eventMask },\n { \"backgroundColor\", () => cam.backgroundColor },\n { \"clearFlags\", () => (int)cam.clearFlags },\n { \"stereoEnabled\", () => cam.stereoEnabled },\n { \"stereoSeparation\", () => cam.stereoSeparation },\n { \"stereoConvergence\", () => cam.stereoConvergence },\n { \"enabled\", () => cam.enabled },\n { \"name\", () => cam.name },\n { \"tag\", () => cam.tag },\n { \"gameObject\", () => new { name = cam.gameObject.name, instanceID = cam.gameObject.GetInstanceID() } }\n };\n\n foreach (var prop in safeProperties)\n {\n try\n {\n var value = prop.Value();\n if (value != null)\n {\n AddSerializableValue(cameraProperties, prop.Key, value.GetType(), value);\n }\n }\n catch (Exception)\n {\n // Silently skip any property that fails\n continue;\n }\n }\n\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", cam.GetInstanceID() },\n { \"properties\", cameraProperties }\n };\n }\n // --- End Special handling for Camera ---\n\n var data = new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", c.GetInstanceID() }\n };\n\n // --- Get Cached or Generate Metadata (using new cache key) ---\n Tuple cacheKey = new Tuple(componentType, includeNonPublicSerializedFields);\n if (!_metadataCache.TryGetValue(cacheKey, out CachedMetadata cachedData))\n {\n var propertiesToCache = new List();\n var fieldsToCache = new List();\n\n // Traverse the hierarchy from the component type up to MonoBehaviour\n Type currentType = componentType;\n while (currentType != null && currentType != typeof(MonoBehaviour) && currentType != typeof(object))\n {\n // Get properties declared only at the current type level\n BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n foreach (var propInfo in currentType.GetProperties(propFlags))\n {\n // Basic filtering (readable, not indexer, not transform which is handled elsewhere)\n if (!propInfo.CanRead || propInfo.GetIndexParameters().Length > 0 || propInfo.Name == \"transform\") continue;\n // Add if not already added (handles overrides - keep the most derived version)\n if (!propertiesToCache.Any(p => p.Name == propInfo.Name)) {\n propertiesToCache.Add(propInfo);\n }\n }\n\n // Get fields declared only at the current type level (both public and non-public)\n BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n var declaredFields = currentType.GetFields(fieldFlags);\n\n // Process the declared Fields for caching\n foreach (var fieldInfo in declaredFields)\n {\n if (fieldInfo.Name.EndsWith(\"k__BackingField\")) continue; // Skip backing fields\n\n // Add if not already added (handles hiding - keep the most derived version)\n if (fieldsToCache.Any(f => f.Name == fieldInfo.Name)) continue;\n\n bool shouldInclude = false;\n if (includeNonPublicSerializedFields)\n {\n // If TRUE, include Public OR NonPublic with [SerializeField]\n shouldInclude = fieldInfo.IsPublic || (fieldInfo.IsPrivate && fieldInfo.IsDefined(typeof(SerializeField), inherit: false));\n }\n else // includeNonPublicSerializedFields is FALSE\n {\n // If FALSE, include ONLY if it is explicitly Public.\n shouldInclude = fieldInfo.IsPublic;\n }\n\n if (shouldInclude)\n {\n fieldsToCache.Add(fieldInfo);\n }\n }\n\n // Move to the base type\n currentType = currentType.BaseType;\n }\n // --- End Hierarchy Traversal ---\n\n cachedData = new CachedMetadata(propertiesToCache, fieldsToCache);\n _metadataCache[cacheKey] = cachedData; // Add to cache with combined key\n }\n // --- End Get Cached or Generate Metadata ---\n\n // --- Use cached metadata ---\n var serializablePropertiesOutput = new Dictionary();\n \n // --- Add Logging Before Property Loop ---\n // Debug.Log($\"[GetComponentData] Starting property loop for {componentType.Name}...\");\n // --- End Logging Before Property Loop ---\n\n // Use cached properties\n foreach (var propInfo in cachedData.SerializableProperties)\n {\n string propName = propInfo.Name;\n\n // --- Skip known obsolete/problematic Component shortcut properties ---\n bool skipProperty = false;\n if (propName == \"rigidbody\" || propName == \"rigidbody2D\" || propName == \"camera\" ||\n propName == \"light\" || propName == \"animation\" || propName == \"constantForce\" ||\n propName == \"renderer\" || propName == \"audio\" || propName == \"networkView\" ||\n propName == \"collider\" || propName == \"collider2D\" || propName == \"hingeJoint\" ||\n propName == \"particleSystem\" ||\n // Also skip potentially problematic Matrix properties prone to cycles/errors\n propName == \"worldToLocalMatrix\" || propName == \"localToWorldMatrix\")\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping generic property: {propName}\"); // Optional log\n skipProperty = true;\n }\n // --- End Skip Generic Properties ---\n\n // --- Skip specific potentially problematic Camera properties ---\n if (componentType == typeof(Camera) && \n (propName == \"pixelRect\" || \n propName == \"rect\" || \n propName == \"cullingMatrix\" ||\n propName == \"useOcclusionCulling\" ||\n propName == \"worldToCameraMatrix\" ||\n propName == \"projectionMatrix\" ||\n propName == \"nonJitteredProjectionMatrix\" ||\n propName == \"previousViewProjectionMatrix\" ||\n propName == \"cameraToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Camera property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Camera Properties ---\n\n // --- Skip specific potentially problematic Transform properties ---\n if (componentType == typeof(Transform) && \n (propName == \"lossyScale\" || \n propName == \"rotation\" ||\n propName == \"worldToLocalMatrix\" ||\n propName == \"localToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Transform property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Transform Properties ---\n\n // Skip if flagged\n if (skipProperty)\n {\n continue;\n }\n\n try\n {\n // --- Add detailed logging --- \n // Debug.Log($\"[GetComponentData] Accessing: {componentType.Name}.{propName}\");\n // --- End detailed logging ---\n object value = propInfo.GetValue(c);\n Type propType = propInfo.PropertyType;\n AddSerializableValue(serializablePropertiesOutput, propName, propType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read property {propName} on {componentType.Name}: {ex.Message}\");\n }\n }\n\n // --- Add Logging Before Field Loop ---\n // Debug.Log($\"[GetComponentData] Starting field loop for {componentType.Name}...\");\n // --- End Logging Before Field Loop ---\n\n // Use cached fields\n foreach (var fieldInfo in cachedData.SerializableFields)\n {\n try\n {\n // --- Add detailed logging for fields --- \n // Debug.Log($\"[GetComponentData] Accessing Field: {componentType.Name}.{fieldInfo.Name}\");\n // --- End detailed logging for fields ---\n object value = fieldInfo.GetValue(c);\n string fieldName = fieldInfo.Name;\n Type fieldType = fieldInfo.FieldType;\n AddSerializableValue(serializablePropertiesOutput, fieldName, fieldType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read field {fieldInfo.Name} on {componentType.Name}: {ex.Message}\");\n }\n }\n // --- End Use cached metadata ---\n\n if (serializablePropertiesOutput.Count > 0)\n {\n data[\"properties\"] = serializablePropertiesOutput;\n }\n\n return data;\n }\n\n // Helper function to decide how to serialize different types\n private static void AddSerializableValue(Dictionary dict, string name, Type type, object value)\n {\n // Simplified: Directly use CreateTokenFromValue which uses the serializer\n if (value == null)\n {\n dict[name] = null;\n return;\n }\n\n try\n {\n // Use the helper that employs our custom serializer settings\n JToken token = CreateTokenFromValue(value, type);\n if (token != null) // Check if serialization succeeded in the helper\n {\n // Convert JToken back to a basic object structure for the dictionary\n dict[name] = ConvertJTokenToPlainObject(token);\n }\n // If token is null, it means serialization failed and a warning was logged.\n }\n catch (Exception e)\n {\n // Catch potential errors during JToken conversion or addition to dictionary\n Debug.LogWarning($\"[AddSerializableValue] Error processing value for '{name}' (Type: {type.FullName}): {e.Message}. Skipping.\");\n }\n }\n\n // Helper to convert JToken back to basic object structure\n private static object ConvertJTokenToPlainObject(JToken token)\n {\n if (token == null) return null;\n\n switch (token.Type)\n {\n case JTokenType.Object:\n var objDict = new Dictionary();\n foreach (var prop in ((JObject)token).Properties())\n {\n objDict[prop.Name] = ConvertJTokenToPlainObject(prop.Value);\n }\n return objDict;\n\n case JTokenType.Array:\n var list = new List();\n foreach (var item in (JArray)token)\n {\n list.Add(ConvertJTokenToPlainObject(item));\n }\n return list;\n\n case JTokenType.Integer:\n return token.ToObject(); // Use long for safety\n case JTokenType.Float:\n return token.ToObject(); // Use double for safety\n case JTokenType.String:\n return token.ToObject();\n case JTokenType.Boolean:\n return token.ToObject();\n case JTokenType.Date:\n return token.ToObject();\n case JTokenType.Guid:\n return token.ToObject();\n case JTokenType.Uri:\n return token.ToObject();\n case JTokenType.TimeSpan:\n return token.ToObject();\n case JTokenType.Bytes:\n return token.ToObject();\n case JTokenType.Null:\n return null;\n case JTokenType.Undefined:\n return null; // Treat undefined as null\n\n default:\n // Fallback for simple value types not explicitly listed\n if (token is JValue jValue && jValue.Value != null)\n {\n return jValue.Value;\n }\n // Debug.LogWarning($\"Unsupported JTokenType encountered: {token.Type}. Returning null.\");\n return null;\n }\n }\n\n // --- Define custom JsonSerializerSettings for OUTPUT ---\n private static readonly JsonSerializerSettings _outputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Handles serialization of references\n },\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore,\n // ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } // Example if needed\n };\n private static readonly JsonSerializer _outputSerializer = JsonSerializer.Create(_outputSerializerSettings);\n // --- End Define custom JsonSerializerSettings ---\n\n // Helper to create JToken using the output serializer\n ", "suffix_code": "\n }\n} ", "middle_code": "private static JToken CreateTokenFromValue(object value, Type type)\n {\n if (value == null) return JValue.CreateNull();\n try\n {\n return JToken.FromObject(value, _outputSerializer);\n }\n catch (JsonSerializationException e)\n {\n Debug.LogWarning($\"[GameObjectSerializer] Newtonsoft.Json Error serializing value of type {type.FullName}: {e.Message}. Skipping property/field.\");\n return null; \n }\n catch (Exception e) \n {\n Debug.LogWarning($\"[GameObjectSerializer] Unexpected error serializing value of type {type.FullName}: {e}. Skipping property/field.\");\n return null; \n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageGameObject.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json; // Added for JsonSerializationException\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\nusing UnityMcpBridge.Runtime.Serialization;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles GameObject manipulation within the current scene (CRUD, find, components).\n /// \n public static class ManageGameObject\n {\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Parameters used by various actions\n JToken targetToken = @params[\"target\"]; // Can be string (name/path) or int (instanceID)\n string searchMethod = @params[\"searchMethod\"]?.ToString().ToLower();\n\n // Get common parameters (consolidated)\n string name = @params[\"name\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString();\n string layer = @params[\"layer\"]?.ToString();\n JToken parentToken = @params[\"parent\"];\n\n // --- Add parameter for controlling non-public field inclusion ---\n bool includeNonPublicSerialized = @params[\"includeNonPublicSerialized\"]?.ToObject() ?? true; // Default to true\n // --- End add parameter ---\n\n // --- Prefab Redirection Check ---\n string targetPath =\n targetToken?.Type == JTokenType.String ? targetToken.ToString() : null;\n if (\n !string.IsNullOrEmpty(targetPath)\n && targetPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n // Allow 'create' (instantiate), 'find' (?), 'get_components' (?)\n if (action == \"modify\" || action == \"set_component_property\")\n {\n Debug.Log(\n $\"[ManageGameObject->ManageAsset] Redirecting action '{action}' for prefab '{targetPath}' to ManageAsset.\"\n );\n // Prepare params for ManageAsset.ModifyAsset\n JObject assetParams = new JObject();\n assetParams[\"action\"] = \"modify\"; // ManageAsset uses \"modify\"\n assetParams[\"path\"] = targetPath;\n\n // Extract properties.\n // For 'set_component_property', combine componentName and componentProperties.\n // For 'modify', directly use componentProperties.\n JObject properties = null;\n if (action == \"set_component_property\")\n {\n string compName = @params[\"componentName\"]?.ToString();\n JObject compProps = @params[\"componentProperties\"]?[compName] as JObject; // Handle potential nesting\n if (string.IsNullOrEmpty(compName))\n return Response.Error(\n \"Missing 'componentName' for 'set_component_property' on prefab.\"\n );\n if (compProps == null)\n return Response.Error(\n $\"Missing or invalid 'componentProperties' for component '{compName}' for 'set_component_property' on prefab.\"\n );\n\n properties = new JObject();\n properties[compName] = compProps;\n }\n else // action == \"modify\"\n {\n properties = @params[\"componentProperties\"] as JObject;\n if (properties == null)\n return Response.Error(\n \"Missing 'componentProperties' for 'modify' action on prefab.\"\n );\n }\n\n assetParams[\"properties\"] = properties;\n\n // Call ManageAsset handler\n return ManageAsset.HandleCommand(assetParams);\n }\n else if (\n action == \"delete\"\n || action == \"add_component\"\n || action == \"remove_component\"\n || action == \"get_components\"\n ) // Added get_components here too\n {\n // Explicitly block other modifications on the prefab asset itself via manage_gameobject\n return Response.Error(\n $\"Action '{action}' on a prefab asset ('{targetPath}') should be performed using the 'manage_asset' command.\"\n );\n }\n // Allow 'create' (instantiation) and 'find' to proceed, although finding a prefab asset by path might be less common via manage_gameobject.\n // No specific handling needed here, the code below will run.\n }\n // --- End Prefab Redirection Check ---\n\n try\n {\n switch (action)\n {\n case \"create\":\n return CreateGameObject(@params);\n case \"modify\":\n return ModifyGameObject(@params, targetToken, searchMethod);\n case \"delete\":\n return DeleteGameObject(targetToken, searchMethod);\n case \"find\":\n return FindGameObjects(@params, targetToken, searchMethod);\n case \"get_components\":\n string getCompTarget = targetToken?.ToString(); // Expect name, path, or ID string\n if (getCompTarget == null)\n return Response.Error(\n \"'target' parameter required for get_components.\"\n );\n // Pass the includeNonPublicSerialized flag here\n return GetComponentsFromTarget(getCompTarget, searchMethod, includeNonPublicSerialized);\n case \"add_component\":\n return AddComponentToTarget(@params, targetToken, searchMethod);\n case \"remove_component\":\n return RemoveComponentFromTarget(@params, targetToken, searchMethod);\n case \"set_component_property\":\n return SetComponentPropertyOnTarget(@params, targetToken, searchMethod);\n\n default:\n return Response.Error($\"Unknown action: '{action}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageGameObject] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object CreateGameObject(JObject @params)\n {\n string name = @params[\"name\"]?.ToString();\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"'name' parameter is required for 'create' action.\");\n }\n\n // Get prefab creation parameters\n bool saveAsPrefab = @params[\"saveAsPrefab\"]?.ToObject() ?? false;\n string prefabPath = @params[\"prefabPath\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString(); // Get tag for creation\n string primitiveType = @params[\"primitiveType\"]?.ToString(); // Keep primitiveType check\n GameObject newGo = null; // Initialize as null\n\n // --- Try Instantiating Prefab First ---\n string originalPrefabPath = prefabPath; // Keep original for messages\n if (!string.IsNullOrEmpty(prefabPath))\n {\n // If no extension, search for the prefab by name\n if (\n !prefabPath.Contains(\"/\")\n && !prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n string prefabNameOnly = prefabPath;\n Debug.Log(\n $\"[ManageGameObject.Create] Searching for prefab named: '{prefabNameOnly}'\"\n );\n string[] guids = AssetDatabase.FindAssets($\"t:Prefab {prefabNameOnly}\");\n if (guids.Length == 0)\n {\n return Response.Error(\n $\"Prefab named '{prefabNameOnly}' not found anywhere in the project.\"\n );\n }\n else if (guids.Length > 1)\n {\n string foundPaths = string.Join(\n \", \",\n guids.Select(g => AssetDatabase.GUIDToAssetPath(g))\n );\n return Response.Error(\n $\"Multiple prefabs found matching name '{prefabNameOnly}': {foundPaths}. Please provide a more specific path.\"\n );\n }\n else // Exactly one found\n {\n prefabPath = AssetDatabase.GUIDToAssetPath(guids[0]); // Update prefabPath with the full path\n Debug.Log(\n $\"[ManageGameObject.Create] Found unique prefab at path: '{prefabPath}'\"\n );\n }\n }\n else if (!prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n // If it looks like a path but doesn't end with .prefab, assume user forgot it and append it.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Provided prefabPath '{prefabPath}' does not end with .prefab. Assuming it's missing and appending.\"\n );\n prefabPath += \".prefab\";\n // Note: This path might still not exist, AssetDatabase.LoadAssetAtPath will handle that.\n }\n // The logic above now handles finding or assuming the .prefab extension.\n\n GameObject prefabAsset = AssetDatabase.LoadAssetAtPath(prefabPath);\n if (prefabAsset != null)\n {\n try\n {\n // Instantiate the prefab, initially place it at the root\n // Parent will be set later if specified\n newGo = PrefabUtility.InstantiatePrefab(prefabAsset) as GameObject;\n\n if (newGo == null)\n {\n // This might happen if the asset exists but isn't a valid GameObject prefab somehow\n Debug.LogError(\n $\"[ManageGameObject.Create] Failed to instantiate prefab at '{prefabPath}', asset might be corrupted or not a GameObject.\"\n );\n return Response.Error(\n $\"Failed to instantiate prefab at '{prefabPath}'.\"\n );\n }\n // Name the instance based on the 'name' parameter, not the prefab's default name\n if (!string.IsNullOrEmpty(name))\n {\n newGo.name = name;\n }\n // Register Undo for prefab instantiation\n Undo.RegisterCreatedObjectUndo(\n newGo,\n $\"Instantiate Prefab '{prefabAsset.name}' as '{newGo.name}'\"\n );\n Debug.Log(\n $\"[ManageGameObject.Create] Instantiated prefab '{prefabAsset.name}' from path '{prefabPath}' as '{newGo.name}'.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error instantiating prefab '{prefabPath}': {e.Message}\"\n );\n }\n }\n else\n {\n // Only return error if prefabPath was specified but not found.\n // If prefabPath was empty/null, we proceed to create primitive/empty.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Prefab asset not found at path: '{prefabPath}'. Will proceed to create new object if specified.\"\n );\n // Do not return error here, allow fallback to primitive/empty creation\n }\n }\n\n // --- Fallback: Create Primitive or Empty GameObject ---\n bool createdNewObject = false; // Flag to track if we created (not instantiated)\n if (newGo == null) // Only proceed if prefab instantiation didn't happen\n {\n if (!string.IsNullOrEmpty(primitiveType))\n {\n try\n {\n PrimitiveType type = (PrimitiveType)\n Enum.Parse(typeof(PrimitiveType), primitiveType, true);\n newGo = GameObject.CreatePrimitive(type);\n // Set name *after* creation for primitives\n if (!string.IsNullOrEmpty(name))\n newGo.name = name;\n else\n return Response.Error(\n \"'name' parameter is required when creating a primitive.\"\n ); // Name is essential\n createdNewObject = true;\n }\n catch (ArgumentException)\n {\n return Response.Error(\n $\"Invalid primitive type: '{primitiveType}'. Valid types: {string.Join(\", \", Enum.GetNames(typeof(PrimitiveType)))}\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Failed to create primitive '{primitiveType}': {e.Message}\"\n );\n }\n }\n else // Create empty GameObject\n {\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\n \"'name' parameter is required for 'create' action when not instantiating a prefab or creating a primitive.\"\n );\n }\n newGo = new GameObject(name);\n createdNewObject = true;\n }\n // Record creation for Undo *only* if we created a new object\n if (createdNewObject)\n {\n Undo.RegisterCreatedObjectUndo(newGo, $\"Create GameObject '{newGo.name}'\");\n }\n }\n // --- Common Setup (Parent, Transform, Tag, Components) - Applied AFTER object exists ---\n if (newGo == null)\n {\n // Should theoretically not happen if logic above is correct, but safety check.\n return Response.Error(\"Failed to create or instantiate the GameObject.\");\n }\n\n // Record potential changes to the existing prefab instance or the new GO\n // Record transform separately in case parent changes affect it\n Undo.RecordObject(newGo.transform, \"Set GameObject Transform\");\n Undo.RecordObject(newGo, \"Set GameObject Properties\");\n\n // Set Parent\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject parentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\"); // Flexible parent finding\n if (parentGo == null)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up created object\n return Response.Error($\"Parent specified ('{parentToken}') but not found.\");\n }\n newGo.transform.SetParent(parentGo.transform, true); // worldPositionStays = true\n }\n\n // Set Transform\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue)\n newGo.transform.localPosition = position.Value;\n if (rotation.HasValue)\n newGo.transform.localEulerAngles = rotation.Value;\n if (scale.HasValue)\n newGo.transform.localScale = scale.Value;\n\n // Set Tag (added for create action)\n if (!string.IsNullOrEmpty(tag))\n {\n // Similar logic as in ModifyGameObject for setting/creating tags\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n newGo.tag = tagToSet;\n }\n catch (UnityException ex)\n {\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n InternalEditorUtility.AddTag(tagToSet);\n newGo.tag = tagToSet; // Retry\n Debug.Log(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}' during creation: {innerEx.Message}.\"\n );\n }\n }\n else\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to set tag to '{tagToSet}' during creation: {ex.Message}.\"\n );\n }\n }\n }\n\n // Set Layer (new for create action)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId != -1)\n {\n newGo.layer = layerId;\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Layer '{layerName}' not found. Using default layer.\"\n );\n }\n }\n\n // Add Components\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArray)\n {\n foreach (var compToken in componentsToAddArray)\n {\n string typeName = null;\n JObject properties = null;\n\n if (compToken.Type == JTokenType.String)\n {\n typeName = compToken.ToString();\n }\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(newGo, typeName, properties);\n if (addResult != null) // Check if AddComponentInternal returned an error object\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return addResult; // Return the error response\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Invalid component format in componentsToAdd: {compToken}\"\n );\n }\n }\n }\n\n // Save as Prefab ONLY if we *created* a new object AND saveAsPrefab is true\n GameObject finalInstance = newGo; // Use this for selection and return data\n if (createdNewObject && saveAsPrefab)\n {\n string finalPrefabPath = prefabPath; // Use a separate variable for saving path\n // This check should now happen *before* attempting to save\n if (string.IsNullOrEmpty(finalPrefabPath))\n {\n // Clean up the created object before returning error\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n \"'prefabPath' is required when 'saveAsPrefab' is true and creating a new object.\"\n );\n }\n // Ensure the *saving* path ends with .prefab\n if (!finalPrefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n Debug.Log(\n $\"[ManageGameObject.Create] Appending .prefab extension to save path: '{finalPrefabPath}' -> '{finalPrefabPath}.prefab'\"\n );\n finalPrefabPath += \".prefab\";\n }\n\n try\n {\n // Ensure directory exists using the final saving path\n string directoryPath = System.IO.Path.GetDirectoryName(finalPrefabPath);\n if (\n !string.IsNullOrEmpty(directoryPath)\n && !System.IO.Directory.Exists(directoryPath)\n )\n {\n System.IO.Directory.CreateDirectory(directoryPath);\n AssetDatabase.Refresh(); // Refresh asset database to recognize the new folder\n Debug.Log(\n $\"[ManageGameObject.Create] Created directory for prefab: {directoryPath}\"\n );\n }\n // Use SaveAsPrefabAssetAndConnect with the final saving path\n finalInstance = PrefabUtility.SaveAsPrefabAssetAndConnect(\n newGo,\n finalPrefabPath,\n InteractionMode.UserAction\n );\n\n if (finalInstance == null)\n {\n // Destroy the original if saving failed somehow (shouldn't usually happen if path is valid)\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n $\"Failed to save GameObject '{name}' as prefab at '{finalPrefabPath}'. Check path and permissions.\"\n );\n }\n Debug.Log(\n $\"[ManageGameObject.Create] GameObject '{name}' saved as prefab to '{finalPrefabPath}' and instance connected.\"\n );\n // Mark the new prefab asset as dirty? Not usually necessary, SaveAsPrefabAsset handles it.\n // EditorUtility.SetDirty(finalInstance); // Instance is handled by SaveAsPrefabAssetAndConnect\n }\n catch (Exception e)\n {\n // Clean up the instance if prefab saving fails\n UnityEngine.Object.DestroyImmediate(newGo); // Destroy the original attempt\n return Response.Error($\"Error saving prefab '{finalPrefabPath}': {e.Message}\");\n }\n }\n\n // Select the instance in the scene (either prefab instance or newly created/saved one)\n Selection.activeGameObject = finalInstance;\n\n // Determine appropriate success message using the potentially updated or original path\n string messagePrefabPath =\n finalInstance == null\n ? originalPrefabPath\n : AssetDatabase.GetAssetPath(\n PrefabUtility.GetCorrespondingObjectFromSource(finalInstance)\n ?? (UnityEngine.Object)finalInstance\n );\n string successMessage;\n if (!createdNewObject && !string.IsNullOrEmpty(messagePrefabPath)) // Instantiated existing prefab\n {\n successMessage =\n $\"Prefab '{messagePrefabPath}' instantiated successfully as '{finalInstance.name}'.\";\n }\n else if (createdNewObject && saveAsPrefab && !string.IsNullOrEmpty(messagePrefabPath)) // Created new and saved as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created and saved as prefab to '{messagePrefabPath}'.\";\n }\n else // Created new primitive or empty GO, didn't save as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created successfully in scene.\";\n }\n\n // Use the new serializer helper\n //return Response.Success(successMessage, GetGameObjectData(finalInstance));\n return Response.Success(successMessage, Helpers.GameObjectSerializer.GetGameObjectData(finalInstance));\n }\n\n private static object ModifyGameObject(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n // Record state for Undo *before* modifications\n Undo.RecordObject(targetGo.transform, \"Modify GameObject Transform\");\n Undo.RecordObject(targetGo, \"Modify GameObject Properties\");\n\n bool modified = false;\n\n // Rename (using consolidated 'name' parameter)\n string name = @params[\"name\"]?.ToString();\n if (!string.IsNullOrEmpty(name) && targetGo.name != name)\n {\n targetGo.name = name;\n modified = true;\n }\n\n // Change Parent (using consolidated 'parent' parameter)\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject newParentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\");\n // Check for hierarchy loops\n if (\n newParentGo == null\n && !(\n parentToken.Type == JTokenType.Null\n || (\n parentToken.Type == JTokenType.String\n && string.IsNullOrEmpty(parentToken.ToString())\n )\n )\n )\n {\n return Response.Error($\"New parent ('{parentToken}') not found.\");\n }\n if (newParentGo != null && newParentGo.transform.IsChildOf(targetGo.transform))\n {\n return Response.Error(\n $\"Cannot parent '{targetGo.name}' to '{newParentGo.name}', as it would create a hierarchy loop.\"\n );\n }\n if (targetGo.transform.parent != (newParentGo?.transform))\n {\n targetGo.transform.SetParent(newParentGo?.transform, true); // worldPositionStays = true\n modified = true;\n }\n }\n\n // Set Active State\n bool? setActive = @params[\"setActive\"]?.ToObject();\n if (setActive.HasValue && targetGo.activeSelf != setActive.Value)\n {\n targetGo.SetActive(setActive.Value);\n modified = true;\n }\n\n // Change Tag (using consolidated 'tag' parameter)\n string tag = @params[\"tag\"]?.ToString();\n // Only attempt to change tag if a non-null tag is provided and it's different from the current one.\n // Allow setting an empty string to remove the tag (Unity uses \"Untagged\").\n if (tag != null && targetGo.tag != tag)\n {\n // Ensure the tag is not empty, if empty, it means \"Untagged\" implicitly\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n targetGo.tag = tagToSet;\n modified = true;\n }\n catch (UnityException ex)\n {\n // Check if the error is specifically because the tag doesn't exist\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n // Attempt to create the tag using internal utility\n InternalEditorUtility.AddTag(tagToSet);\n // Wait a frame maybe? Not strictly necessary but sometimes helps editor updates.\n // yield return null; // Cannot yield here, editor script limitation\n\n // Retry setting the tag immediately after creation\n targetGo.tag = tagToSet;\n modified = true;\n Debug.Log(\n $\"[ManageGameObject] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n // Handle failure during tag creation or the second assignment attempt\n Debug.LogError(\n $\"[ManageGameObject] Failed to create or assign tag '{tagToSet}' after attempting creation: {innerEx.Message}\"\n );\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}': {innerEx.Message}. Check Tag Manager and permissions.\"\n );\n }\n }\n else\n {\n // If the exception was for a different reason, return the original error\n return Response.Error($\"Failed to set tag to '{tagToSet}': {ex.Message}.\");\n }\n }\n }\n\n // Change Layer (using consolidated 'layer' parameter)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId == -1 && layerName != \"Default\")\n {\n return Response.Error(\n $\"Invalid layer specified: '{layerName}'. Use a valid layer name.\"\n );\n }\n if (layerId != -1 && targetGo.layer != layerId)\n {\n targetGo.layer = layerId;\n modified = true;\n }\n }\n\n // Transform Modifications\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue && targetGo.transform.localPosition != position.Value)\n {\n targetGo.transform.localPosition = position.Value;\n modified = true;\n }\n if (rotation.HasValue && targetGo.transform.localEulerAngles != rotation.Value)\n {\n targetGo.transform.localEulerAngles = rotation.Value;\n modified = true;\n }\n if (scale.HasValue && targetGo.transform.localScale != scale.Value)\n {\n targetGo.transform.localScale = scale.Value;\n modified = true;\n }\n\n // --- Component Modifications ---\n // Note: These might need more specific Undo recording per component\n\n // Remove Components\n if (@params[\"componentsToRemove\"] is JArray componentsToRemoveArray)\n {\n foreach (var compToken in componentsToRemoveArray)\n {\n // ... (parsing logic as in CreateGameObject) ...\n string typeName = compToken.ToString();\n if (!string.IsNullOrEmpty(typeName))\n {\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error if removal failed\n modified = true;\n }\n }\n }\n\n // Add Components (similar to create)\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArrayModify)\n {\n foreach (var compToken in componentsToAddArrayModify)\n {\n string typeName = null;\n JObject properties = null;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult;\n modified = true;\n }\n }\n }\n\n // Set Component Properties\n if (@params[\"componentProperties\"] is JObject componentPropertiesObj)\n {\n foreach (var prop in componentPropertiesObj.Properties())\n {\n string compName = prop.Name;\n JObject propertiesToSet = prop.Value as JObject;\n if (propertiesToSet != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n compName,\n propertiesToSet\n );\n if (setResult != null)\n return setResult;\n modified = true;\n }\n }\n }\n\n if (!modified)\n {\n // Use the new serializer helper\n // return Response.Success(\n // $\"No modifications applied to GameObject '{targetGo.name}'.\",\n // GetGameObjectData(targetGo));\n\n return Response.Success(\n $\"No modifications applied to GameObject '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n EditorUtility.SetDirty(targetGo); // Mark scene as dirty\n // Use the new serializer helper\n return Response.Success(\n $\"GameObject '{targetGo.name}' modified successfully.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n // return Response.Success(\n // $\"GameObject '{targetGo.name}' modified successfully.\",\n // GetGameObjectData(targetGo));\n \n }\n\n private static object DeleteGameObject(JToken targetToken, string searchMethod)\n {\n // Find potentially multiple objects if name/tag search is used without find_all=false implicitly\n List targets = FindObjectsInternal(targetToken, searchMethod, true); // find_all=true for delete safety\n\n if (targets.Count == 0)\n {\n return Response.Error(\n $\"Target GameObject(s) ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n List deletedObjects = new List();\n foreach (var targetGo in targets)\n {\n if (targetGo != null)\n {\n string goName = targetGo.name;\n int goId = targetGo.GetInstanceID();\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(targetGo);\n deletedObjects.Add(new { name = goName, instanceID = goId });\n }\n }\n\n if (deletedObjects.Count > 0)\n {\n string message =\n targets.Count == 1\n ? $\"GameObject '{deletedObjects[0].GetType().GetProperty(\"name\").GetValue(deletedObjects[0])}' deleted successfully.\"\n : $\"{deletedObjects.Count} GameObjects deleted successfully.\";\n return Response.Success(message, deletedObjects);\n }\n else\n {\n // Should not happen if targets.Count > 0 initially, but defensive check\n return Response.Error(\"Failed to delete target GameObject(s).\");\n }\n }\n\n private static object FindGameObjects(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n bool findAll = @params[\"findAll\"]?.ToObject() ?? false;\n List foundObjects = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n @params\n );\n\n if (foundObjects.Count == 0)\n {\n return Response.Success(\"No matching GameObjects found.\", new List());\n }\n\n // Use the new serializer helper\n //var results = foundObjects.Select(go => GetGameObjectData(go)).ToList();\n var results = foundObjects.Select(go => Helpers.GameObjectSerializer.GetGameObjectData(go)).ToList();\n return Response.Success($\"Found {results.Count} GameObject(s).\", results);\n }\n\n private static object GetComponentsFromTarget(string target, string searchMethod, bool includeNonPublicSerialized = true)\n {\n GameObject targetGo = FindObjectInternal(target, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{target}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n try\n {\n // --- Get components, immediately copy to list, and null original array --- \n Component[] originalComponents = targetGo.GetComponents();\n List componentsToIterate = new List(originalComponents ?? Array.Empty()); // Copy immediately, handle null case\n int componentCount = componentsToIterate.Count; \n originalComponents = null; // Null the original reference\n // Debug.Log($\"[GetComponentsFromTarget] Found {componentCount} components on {targetGo.name}. Copied to list, nulled original. Starting REVERSE for loop...\");\n // --- End Copy and Null --- \n \n var componentData = new List();\n \n for (int i = componentCount - 1; i >= 0; i--) // Iterate backwards over the COPY\n {\n Component c = componentsToIterate[i]; // Use the copy\n if (c == null) \n {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] Encountered a null component at index {i} on {targetGo.name}. Skipping.\");\n continue; // Safety check\n }\n // Debug.Log($\"[GetComponentsFromTarget REVERSE for] Processing component: {c.GetType()?.FullName ?? \"null\"} (ID: {c.GetInstanceID()}) at index {i} on {targetGo.name}\");\n try \n {\n var data = Helpers.GameObjectSerializer.GetComponentData(c, includeNonPublicSerialized);\n if (data != null) // Ensure GetComponentData didn't return null\n {\n componentData.Insert(0, data); // Insert at beginning to maintain original order in final list\n }\n // else\n // {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] GetComponentData returned null for component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}. Skipping addition.\");\n // }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"[GetComponentsFromTarget REVERSE for] Error processing component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}: {ex.Message}\\n{ex.StackTrace}\");\n // Optionally add placeholder data or just skip\n componentData.Insert(0, new JObject( // Insert error marker at beginning\n new JProperty(\"typeName\", c.GetType().FullName + \" (Serialization Error)\"),\n new JProperty(\"instanceID\", c.GetInstanceID()),\n new JProperty(\"error\", ex.Message)\n ));\n }\n }\n // Debug.Log($\"[GetComponentsFromTarget] Finished REVERSE for loop.\");\n \n // Cleanup the list we created\n componentsToIterate.Clear();\n componentsToIterate = null;\n\n return Response.Success(\n $\"Retrieved {componentData.Count} components from '{targetGo.name}'.\",\n componentData // List was built in original order\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error getting components from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n private static object AddComponentToTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n JObject properties = null;\n\n // Allow adding component specified directly or via componentsToAdd array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n properties = @params[\"componentProperties\"]?[typeName] as JObject; // Check if props are nested under name\n }\n else if (\n @params[\"componentsToAdd\"] is JArray componentsToAddArray\n && componentsToAddArray.Count > 0\n )\n {\n var compToken = componentsToAddArray.First;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToAdd') is required.\"\n );\n }\n\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' added to '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n ); // Return updated GO data\n }\n\n private static object RemoveComponentFromTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n // Allow removing component specified directly or via componentsToRemove array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n }\n else if (\n @params[\"componentsToRemove\"] is JArray componentsToRemoveArray\n && componentsToRemoveArray.Count > 0\n )\n {\n typeName = componentsToRemoveArray.First?.ToString();\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToRemove') is required.\"\n );\n }\n\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' removed from '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n private static object SetComponentPropertyOnTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string compName = @params[\"componentName\"]?.ToString();\n JObject propertiesToSet = null;\n\n if (!string.IsNullOrEmpty(compName))\n {\n // Properties might be directly under componentProperties or nested under the component name\n if (@params[\"componentProperties\"] is JObject compProps)\n {\n propertiesToSet = compProps[compName] as JObject ?? compProps; // Allow flat or nested structure\n }\n }\n else\n {\n return Response.Error(\"'componentName' parameter is required.\");\n }\n\n if (propertiesToSet == null || !propertiesToSet.HasValues)\n {\n return Response.Error(\n \"'componentProperties' dictionary for the specified component is required and cannot be empty.\"\n );\n }\n\n var setResult = SetComponentPropertiesInternal(targetGo, compName, propertiesToSet);\n if (setResult != null)\n return setResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Properties set for component '{compName}' on '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Finds a single GameObject based on token (ID, name, path) and search method.\n /// \n private static GameObject FindObjectInternal(\n JToken targetToken,\n string searchMethod,\n JObject findParams = null\n )\n {\n // If find_all is not explicitly false, we still want only one for most single-target operations.\n bool findAll = findParams?[\"findAll\"]?.ToObject() ?? false;\n // If a specific target ID is given, always find just that one.\n if (\n targetToken?.Type == JTokenType.Integer\n || (searchMethod == \"by_id\" && int.TryParse(targetToken?.ToString(), out _))\n )\n {\n findAll = false;\n }\n List results = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n findParams\n );\n return results.Count > 0 ? results[0] : null;\n }\n\n /// \n /// Core logic for finding GameObjects based on various criteria.\n /// \n private static List FindObjectsInternal(\n JToken targetToken,\n string searchMethod,\n bool findAll,\n JObject findParams = null\n )\n {\n List results = new List();\n string searchTerm = findParams?[\"searchTerm\"]?.ToString() ?? targetToken?.ToString(); // Use searchTerm if provided, else the target itself\n bool searchInChildren = findParams?[\"searchInChildren\"]?.ToObject() ?? false;\n bool searchInactive = findParams?[\"searchInactive\"]?.ToObject() ?? false;\n\n // Default search method if not specified\n if (string.IsNullOrEmpty(searchMethod))\n {\n if (targetToken?.Type == JTokenType.Integer)\n searchMethod = \"by_id\";\n else if (!string.IsNullOrEmpty(searchTerm) && searchTerm.Contains('/'))\n searchMethod = \"by_path\";\n else\n searchMethod = \"by_name\"; // Default fallback\n }\n\n GameObject rootSearchObject = null;\n // If searching in children, find the initial target first\n if (searchInChildren && targetToken != null)\n {\n rootSearchObject = FindObjectInternal(targetToken, \"by_id_or_name_or_path\"); // Find the root for child search\n if (rootSearchObject == null)\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Root object '{targetToken}' for child search not found.\"\n );\n return results; // Return empty if root not found\n }\n }\n\n switch (searchMethod)\n {\n case \"by_id\":\n if (int.TryParse(searchTerm, out int instanceId))\n {\n // EditorUtility.InstanceIDToObject is slow, iterate manually if possible\n // GameObject obj = EditorUtility.InstanceIDToObject(instanceId) as GameObject;\n var allObjects = GetAllSceneObjects(searchInactive); // More efficient\n GameObject obj = allObjects.FirstOrDefault(go =>\n go.GetInstanceID() == instanceId\n );\n if (obj != null)\n results.Add(obj);\n }\n break;\n case \"by_name\":\n var searchPoolName = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolName.Where(go => go.name == searchTerm));\n break;\n case \"by_path\":\n // Path is relative to scene root or rootSearchObject\n Transform foundTransform = rootSearchObject\n ? rootSearchObject.transform.Find(searchTerm)\n : GameObject.Find(searchTerm)?.transform;\n if (foundTransform != null)\n results.Add(foundTransform.gameObject);\n break;\n case \"by_tag\":\n var searchPoolTag = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolTag.Where(go => go.CompareTag(searchTerm)));\n break;\n case \"by_layer\":\n var searchPoolLayer = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n if (int.TryParse(searchTerm, out int layerIndex))\n {\n results.AddRange(searchPoolLayer.Where(go => go.layer == layerIndex));\n }\n else\n {\n int namedLayer = LayerMask.NameToLayer(searchTerm);\n if (namedLayer != -1)\n results.AddRange(searchPoolLayer.Where(go => go.layer == namedLayer));\n }\n break;\n case \"by_component\":\n Type componentType = FindType(searchTerm);\n if (componentType != null)\n {\n // Determine FindObjectsInactive based on the searchInactive flag\n FindObjectsInactive findInactive = searchInactive\n ? FindObjectsInactive.Include\n : FindObjectsInactive.Exclude;\n // Replace FindObjectsOfType with FindObjectsByType, specifying the sorting mode and inactive state\n var searchPoolComp = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(componentType, searchInactive)\n .Select(c => (c as Component).gameObject)\n : UnityEngine\n .Object.FindObjectsByType(\n componentType,\n findInactive,\n FindObjectsSortMode.None\n )\n .Select(c => (c as Component).gameObject);\n results.AddRange(searchPoolComp.Where(go => go != null)); // Ensure GO is valid\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Component type not found: {searchTerm}\"\n );\n }\n break;\n case \"by_id_or_name_or_path\": // Helper method used internally\n if (int.TryParse(searchTerm, out int id))\n {\n var allObjectsId = GetAllSceneObjects(true); // Search inactive for internal lookup\n GameObject objById = allObjectsId.FirstOrDefault(go =>\n go.GetInstanceID() == id\n );\n if (objById != null)\n {\n results.Add(objById);\n break;\n }\n }\n GameObject objByPath = GameObject.Find(searchTerm);\n if (objByPath != null)\n {\n results.Add(objByPath);\n break;\n }\n\n var allObjectsName = GetAllSceneObjects(true);\n results.AddRange(allObjectsName.Where(go => go.name == searchTerm));\n break;\n default:\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Unknown search method: {searchMethod}\"\n );\n break;\n }\n\n // If only one result is needed, return just the first one found.\n if (!findAll && results.Count > 1)\n {\n return new List { results[0] };\n }\n\n return results.Distinct().ToList(); // Ensure uniqueness\n }\n\n // Helper to get all scene objects efficiently\n private static IEnumerable GetAllSceneObjects(bool includeInactive)\n {\n // SceneManager.GetActiveScene().GetRootGameObjects() is faster than FindObjectsOfType()\n var rootObjects = SceneManager.GetActiveScene().GetRootGameObjects();\n var allObjects = new List();\n foreach (var root in rootObjects)\n {\n allObjects.AddRange(\n root.GetComponentsInChildren(includeInactive)\n .Select(t => t.gameObject)\n );\n }\n return allObjects;\n }\n\n /// \n /// Adds a component by type name and optionally sets properties.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object AddComponentInternal(\n GameObject targetGo,\n string typeName,\n JObject properties\n )\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error(\n $\"Component type '{typeName}' not found or is not a valid Component.\"\n );\n }\n if (!typeof(Component).IsAssignableFrom(componentType))\n {\n return Response.Error($\"Type '{typeName}' is not a Component.\");\n }\n\n // Prevent adding Transform again\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot add another Transform component.\");\n }\n\n // Check for 2D/3D physics component conflicts\n bool isAdding2DPhysics =\n typeof(Rigidbody2D).IsAssignableFrom(componentType)\n || typeof(Collider2D).IsAssignableFrom(componentType);\n bool isAdding3DPhysics =\n typeof(Rigidbody).IsAssignableFrom(componentType)\n || typeof(Collider).IsAssignableFrom(componentType);\n\n if (isAdding2DPhysics)\n {\n // Check if the GameObject already has any 3D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 2D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 3D Rigidbody or Collider.\"\n );\n }\n }\n else if (isAdding3DPhysics)\n {\n // Check if the GameObject already has any 2D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 3D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 2D Rigidbody or Collider.\"\n );\n }\n }\n\n try\n {\n // Use Undo.AddComponent for undo support\n Component newComponent = Undo.AddComponent(targetGo, componentType);\n if (newComponent == null)\n {\n return Response.Error(\n $\"Failed to add component '{typeName}' to '{targetGo.name}'. It might be disallowed (e.g., adding script twice).\"\n );\n }\n\n // Set default values for specific component types\n if (newComponent is Light light)\n {\n // Default newly added lights to directional\n light.type = LightType.Directional;\n }\n\n // Set properties if provided\n if (properties != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n typeName,\n properties,\n newComponent\n ); // Pass the new component instance\n if (setResult != null)\n {\n // If setting properties failed, maybe remove the added component?\n Undo.DestroyObjectImmediate(newComponent);\n return setResult; // Return the error from setting properties\n }\n }\n\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error adding component '{typeName}' to '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Removes a component by type name.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object RemoveComponentInternal(GameObject targetGo, string typeName)\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error($\"Component type '{typeName}' not found for removal.\");\n }\n\n // Prevent removing essential components\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot remove the Transform component.\");\n }\n\n Component componentToRemove = targetGo.GetComponent(componentType);\n if (componentToRemove == null)\n {\n return Response.Error(\n $\"Component '{typeName}' not found on '{targetGo.name}' to remove.\"\n );\n }\n\n try\n {\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(componentToRemove);\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error removing component '{typeName}' from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Sets properties on a component.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object SetComponentPropertiesInternal(\n GameObject targetGo,\n string compName,\n JObject propertiesToSet,\n Component targetComponentInstance = null\n )\n {\n Component targetComponent = targetComponentInstance ?? targetGo.GetComponent(compName);\n if (targetComponent == null)\n {\n return Response.Error(\n $\"Component '{compName}' not found on '{targetGo.name}' to set properties.\"\n );\n }\n\n Undo.RecordObject(targetComponent, \"Set Component Properties\");\n\n foreach (var prop in propertiesToSet.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n\n try\n {\n if (!SetProperty(targetComponent, propName, propValue))\n {\n // Log warning if property could not be set\n Debug.LogWarning(\n $\"[ManageGameObject] Could not set property '{propName}' on component '{compName}' ('{targetComponent.GetType().Name}'). Property might not exist, be read-only, or type mismatch.\"\n );\n // Optionally return an error here instead of just logging\n // return Response.Error($\"Could not set property '{propName}' on component '{compName}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageGameObject] Error setting property '{propName}' on '{compName}': {e.Message}\"\n );\n // Optionally return an error here\n // return Response.Error($\"Error setting property '{propName}' on '{compName}': {e.Message}\");\n }\n }\n EditorUtility.SetDirty(targetComponent);\n return null; // Success (or partial success if warnings were logged)\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types.\n /// \n private static bool SetProperty(object target, string memberName, JToken value)\n {\n Type type = target.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // --- Use a dedicated serializer for input conversion ---\n // Define this somewhere accessible, maybe static readonly field\n JsonSerializerSettings inputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n // Add specific converters needed for INPUT deserialization if different from output\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Crucial for finding references from instructions\n }\n // No ReferenceLoopHandling needed typically for input\n };\n JsonSerializer inputSerializer = JsonSerializer.Create(inputSerializerSettings);\n // --- End Serializer Setup ---\n\n try\n {\n // Handle special case for materials with dot notation (material.property)\n // Examples: material.color, sharedMaterial.color, materials[0].color\n if (memberName.Contains('.') || memberName.Contains('['))\n {\n // Pass the inputSerializer down for nested conversions\n return SetNestedProperty(target, memberName, value, inputSerializer);\n }\n\n PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for property '{memberName}' (Type: {propInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null) // Check if !IsLiteral?\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for field '{memberName}' (Type: {fieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetProperty] Failed to set '{memberName}' on {type.Name}: {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n return false;\n }\n\n /// \n /// Sets a nested property using dot notation (e.g., \"material.color\") or array access (e.g., \"materials[0]\")\n /// \n // Pass the input serializer for conversions\n //Using the serializer helper\n private static bool SetNestedProperty(object target, string path, JToken value, JsonSerializer inputSerializer)\n {\n try\n {\n // Split the path into parts (handling both dot notation and array indexing)\n string[] pathParts = SplitPropertyPath(path);\n if (pathParts.Length == 0)\n return false;\n\n object currentObject = target;\n Type currentType = currentObject.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // Traverse the path until we reach the final property\n for (int i = 0; i < pathParts.Length - 1; i++)\n {\n string part = pathParts[i];\n bool isArray = false;\n int arrayIndex = -1;\n\n // Check if this part contains array indexing\n if (part.Contains(\"[\"))\n {\n int startBracket = part.IndexOf('[');\n int endBracket = part.IndexOf(']');\n if (startBracket > 0 && endBracket > startBracket)\n {\n string indexStr = part.Substring(\n startBracket + 1,\n endBracket - startBracket - 1\n );\n if (int.TryParse(indexStr, out arrayIndex))\n {\n isArray = true;\n part = part.Substring(0, startBracket);\n }\n }\n }\n // Get the property/field\n PropertyInfo propInfo = currentType.GetProperty(part, flags);\n FieldInfo fieldInfo = null;\n if (propInfo == null)\n {\n fieldInfo = currentType.GetField(part, flags);\n if (fieldInfo == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find property or field '{part}' on type '{currentType.Name}'\"\n );\n return false;\n }\n }\n\n // Get the value\n currentObject =\n propInfo != null\n ? propInfo.GetValue(currentObject)\n : fieldInfo.GetValue(currentObject);\n //Need to stop if current property is null\n if (currentObject == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is null, cannot access nested properties.\"\n );\n return false;\n }\n // If this part was an array or list, access the specific index\n if (isArray)\n {\n if (currentObject is Material[])\n {\n var materials = currentObject as Material[];\n if (arrayIndex < 0 || arrayIndex >= materials.Length)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Material index {arrayIndex} out of range (0-{materials.Length - 1})\"\n );\n return false;\n }\n currentObject = materials[arrayIndex];\n }\n else if (currentObject is System.Collections.IList)\n {\n var list = currentObject as System.Collections.IList;\n if (arrayIndex < 0 || arrayIndex >= list.Count)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Index {arrayIndex} out of range (0-{list.Count - 1})\"\n );\n return false;\n }\n currentObject = list[arrayIndex];\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is not an array or list, cannot access by index.\"\n );\n return false;\n }\n }\n currentType = currentObject.GetType();\n }\n\n // Set the final property\n string finalPart = pathParts[pathParts.Length - 1];\n\n // Special handling for Material properties (shader properties)\n if (currentObject is Material material && finalPart.StartsWith(\"_\"))\n {\n // Use the serializer to convert the JToken value first\n if (value is JArray jArray)\n {\n // Try converting to known types that SetColor/SetVector accept\n if (jArray.Count == 4) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { }\n try { Vector4 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n } else if (jArray.Count == 3) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { } // ToObject handles conversion to Color\n } else if (jArray.Count == 2) {\n try { Vector2 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n }\n }\n else if (value.Type == JTokenType.Float || value.Type == JTokenType.Integer)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer)); return true; } catch { }\n }\n else if (value.Type == JTokenType.Boolean)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer) ? 1f : 0f); return true; } catch { }\n }\n else if (value.Type == JTokenType.String)\n {\n // Try converting to Texture using the serializer/converter\n try {\n Texture texture = value.ToObject(inputSerializer);\n if (texture != null) {\n material.SetTexture(finalPart, texture);\n return true;\n }\n } catch { }\n }\n\n Debug.LogWarning(\n $\"[SetNestedProperty] Unsupported or failed conversion for material property '{finalPart}' from value: {value.ToString(Formatting.None)}\"\n );\n return false;\n }\n\n // For standard properties (not shader specific)\n PropertyInfo finalPropInfo = currentType.GetProperty(finalPart, flags);\n if (finalPropInfo != null && finalPropInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalPropInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalPropInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for property '{finalPart}' (Type: {finalPropInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo finalFieldInfo = currentType.GetField(finalPart, flags);\n if (finalFieldInfo != null)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalFieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalFieldInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for field '{finalPart}' (Type: {finalFieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find final writable property or field '{finalPart}' on type '{currentType.Name}'\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetNestedProperty] Error setting nested property '{path}': {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n\n return false;\n }\n\n\n /// \n /// Split a property path into parts, handling both dot notation and array indexers\n /// \n private static string[] SplitPropertyPath(string path)\n {\n // Handle complex paths with both dots and array indexers\n List parts = new List();\n int startIndex = 0;\n bool inBrackets = false;\n\n for (int i = 0; i < path.Length; i++)\n {\n char c = path[i];\n\n if (c == '[')\n {\n inBrackets = true;\n }\n else if (c == ']')\n {\n inBrackets = false;\n }\n else if (c == '.' && !inBrackets)\n {\n // Found a dot separator outside of brackets\n parts.Add(path.Substring(startIndex, i - startIndex));\n startIndex = i + 1;\n }\n }\n if (startIndex < path.Length)\n {\n parts.Add(path.Substring(startIndex));\n }\n return parts.ToArray();\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types, using JsonSerializer.\n /// \n // Pass the input serializer\n private static object ConvertJTokenToType(JToken token, Type targetType, JsonSerializer inputSerializer)\n {\n if (token == null || token.Type == JTokenType.Null)\n {\n if (targetType.IsValueType && Nullable.GetUnderlyingType(targetType) == null)\n {\n Debug.LogWarning($\"Cannot assign null to non-nullable value type {targetType.Name}. Returning default value.\");\n return Activator.CreateInstance(targetType);\n }\n return null;\n }\n\n try\n {\n // Use the provided serializer instance which includes our custom converters\n return token.ToObject(targetType, inputSerializer);\n }\n catch (JsonSerializationException jsonEx)\n {\n Debug.LogError($\"JSON Deserialization Error converting token to {targetType.FullName}: {jsonEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n // Optionally re-throw or return null/default\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n throw; // Re-throw to indicate failure higher up\n }\n catch (ArgumentException argEx)\n {\n Debug.LogError($\"Argument Error converting token to {targetType.FullName}: {argEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Unexpected error converting token to {targetType.FullName}: {ex}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n // If ToObject succeeded, it would have returned. If it threw, we wouldn't reach here.\n // This fallback logic is likely unreachable if ToObject covers all cases or throws on failure.\n // Debug.LogWarning($\"Conversion failed for token to {targetType.FullName}. Token: {token.ToString(Formatting.None)}\");\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n }\n\n // --- ParseJTokenTo... helpers are likely redundant now with the serializer approach ---\n // Keep them temporarily for reference or if specific fallback logic is ever needed.\n\n private static Vector3 ParseJTokenToVector3(JToken token)\n {\n // ... (implementation - likely replaced by Vector3Converter) ...\n // Consider removing these if the serializer handles them reliably.\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\"))\n {\n return new Vector3(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 3)\n {\n return new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector3 using fallback. Returning Vector3.zero.\");\n return Vector3.zero;\n\n }\n private static Vector2 ParseJTokenToVector2(JToken token)\n {\n // ... (implementation - likely replaced by Vector2Converter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\"))\n {\n return new Vector2(obj[\"x\"].ToObject(), obj[\"y\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 2)\n {\n return new Vector2(arr[0].ToObject(), arr[1].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector2 using fallback. Returning Vector2.zero.\");\n return Vector2.zero;\n }\n private static Quaternion ParseJTokenToQuaternion(JToken token)\n {\n // ... (implementation - likely replaced by QuaternionConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\") && obj.ContainsKey(\"w\"))\n {\n return new Quaternion(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject(), obj[\"w\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Quaternion(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Quaternion using fallback. Returning Quaternion.identity.\");\n return Quaternion.identity;\n }\n private static Color ParseJTokenToColor(JToken token)\n {\n // ... (implementation - likely replaced by ColorConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"r\") && obj.ContainsKey(\"g\") && obj.ContainsKey(\"b\") && obj.ContainsKey(\"a\"))\n {\n return new Color(obj[\"r\"].ToObject(), obj[\"g\"].ToObject(), obj[\"b\"].ToObject(), obj[\"a\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Color(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Color using fallback. Returning Color.white.\");\n return Color.white;\n }\n private static Rect ParseJTokenToRect(JToken token)\n {\n // ... (implementation - likely replaced by RectConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"width\") && obj.ContainsKey(\"height\"))\n {\n return new Rect(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"width\"].ToObject(), obj[\"height\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Rect(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Rect using fallback. Returning Rect.zero.\");\n return Rect.zero;\n }\n private static Bounds ParseJTokenToBounds(JToken token)\n {\n // ... (implementation - likely replaced by BoundsConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"center\") && obj.ContainsKey(\"size\"))\n {\n // Requires Vector3 conversion, which should ideally use the serializer too\n Vector3 center = ParseJTokenToVector3(obj[\"center\"]); // Or use obj[\"center\"].ToObject(inputSerializer)\n Vector3 size = ParseJTokenToVector3(obj[\"size\"]); // Or use obj[\"size\"].ToObject(inputSerializer)\n return new Bounds(center, size);\n }\n // Array fallback for Bounds is less intuitive, maybe remove?\n // if (token is JArray arr && arr.Count >= 6)\n // {\n // return new Bounds(new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject()), new Vector3(arr[3].ToObject(), arr[4].ToObject(), arr[5].ToObject()));\n // }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Bounds using fallback. Returning new Bounds(Vector3.zero, Vector3.zero).\");\n return new Bounds(Vector3.zero, Vector3.zero);\n }\n // --- End Redundant Parse Helpers ---\n\n /// \n /// Finds a specific UnityEngine.Object based on a find instruction JObject.\n /// Primarily used by UnityEngineObjectConverter during deserialization.\n /// \n // Made public static so UnityEngineObjectConverter can call it. Moved from ConvertJTokenToType.\n public static UnityEngine.Object FindObjectByInstruction(JObject instruction, Type targetType)\n {\n string findTerm = instruction[\"find\"]?.ToString();\n string method = instruction[\"method\"]?.ToString()?.ToLower();\n string componentName = instruction[\"component\"]?.ToString(); // Specific component to get\n\n if (string.IsNullOrEmpty(findTerm))\n {\n Debug.LogWarning(\"Find instruction missing 'find' term.\");\n return null;\n }\n\n // Use a flexible default search method if none provided\n string searchMethodToUse = string.IsNullOrEmpty(method) ? \"by_id_or_name_or_path\" : method;\n\n // If the target is an asset (Material, Texture, ScriptableObject etc.) try AssetDatabase first\n if (typeof(Material).IsAssignableFrom(targetType) ||\n typeof(Texture).IsAssignableFrom(targetType) ||\n typeof(ScriptableObject).IsAssignableFrom(targetType) ||\n targetType.FullName.StartsWith(\"UnityEngine.U2D\") || // Sprites etc.\n typeof(AudioClip).IsAssignableFrom(targetType) ||\n typeof(AnimationClip).IsAssignableFrom(targetType) ||\n typeof(Font).IsAssignableFrom(targetType) ||\n typeof(Shader).IsAssignableFrom(targetType) ||\n typeof(ComputeShader).IsAssignableFrom(targetType) ||\n typeof(GameObject).IsAssignableFrom(targetType) && findTerm.StartsWith(\"Assets/\")) // Prefab check\n {\n // Try loading directly by path/GUID first\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(findTerm, targetType);\n if (asset != null) return asset;\n asset = AssetDatabase.LoadAssetAtPath(findTerm); // Try generic if type specific failed\n if (asset != null && targetType.IsAssignableFrom(asset.GetType())) return asset;\n\n\n // If direct path failed, try finding by name/type using FindAssets\n string searchFilter = $\"t:{targetType.Name} {System.IO.Path.GetFileNameWithoutExtension(findTerm)}\"; // Search by type and name\n string[] guids = AssetDatabase.FindAssets(searchFilter);\n\n if (guids.Length == 1)\n {\n asset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]), targetType);\n if (asset != null) return asset;\n }\n else if (guids.Length > 1)\n {\n Debug.LogWarning($\"[FindObjectByInstruction] Ambiguous asset find: Found {guids.Length} assets matching filter '{searchFilter}'. Provide a full path or unique name.\");\n // Optionally return the first one? Or null? Returning null is safer.\n return null;\n }\n // If still not found, fall through to scene search (though unlikely for assets)\n }\n\n\n // --- Scene Object Search ---\n // Find the GameObject using the internal finder\n GameObject foundGo = FindObjectInternal(new JValue(findTerm), searchMethodToUse);\n\n if (foundGo == null)\n {\n // Don't warn yet, could still be an asset not found above\n // Debug.LogWarning($\"Could not find GameObject using instruction: {instruction}\");\n return null;\n }\n\n // Now, get the target object/component from the found GameObject\n if (targetType == typeof(GameObject))\n {\n return foundGo; // We were looking for a GameObject\n }\n else if (typeof(Component).IsAssignableFrom(targetType))\n {\n Type componentToGetType = targetType;\n if (!string.IsNullOrEmpty(componentName))\n {\n Type specificCompType = FindType(componentName);\n if (specificCompType != null && typeof(Component).IsAssignableFrom(specificCompType))\n {\n componentToGetType = specificCompType;\n }\n else\n {\n Debug.LogWarning($\"Could not find component type '{componentName}' specified in find instruction. Falling back to target type '{targetType.Name}'.\");\n }\n }\n\n Component foundComp = foundGo.GetComponent(componentToGetType);\n if (foundComp == null)\n {\n Debug.LogWarning($\"Found GameObject '{foundGo.name}' but could not find component of type '{componentToGetType.Name}'.\");\n }\n return foundComp;\n }\n else\n {\n Debug.LogWarning($\"Find instruction handling not implemented for target type: {targetType.Name}\");\n return null;\n }\n }\n\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Handle fully qualified names first\n Type type = Type.GetType(typeName);\n if (type != null) return type;\n\n // Handle common namespaces implicitly (add more as needed)\n string[] namespaces = { \"UnityEngine\", \"UnityEngine.UI\", \"UnityEngine.AI\", \"UnityEngine.Animations\", \"UnityEngine.Audio\", \"UnityEngine.EventSystems\", \"UnityEngine.InputSystem\", \"UnityEngine.Networking\", \"UnityEngine.Rendering\", \"UnityEngine.SceneManagement\", \"UnityEngine.Tilemaps\", \"UnityEngine.U2D\", \"UnityEngine.Video\", \"UnityEditor\", \"UnityEditor.AI\", \"UnityEditor.Animations\", \"UnityEditor.Experimental.GraphView\", \"UnityEditor.IMGUI.Controls\", \"UnityEditor.PackageManager.UI\", \"UnityEditor.SceneManagement\", \"UnityEditor.UI\", \"UnityEditor.U2D\", \"UnityEditor.VersionControl\" }; // Add more relevant namespaces\n\n foreach (string ns in namespaces) {\n type = Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}.CoreModule\") ?? // Heuristic: Check CoreModule first for UnityEngine/UnityEditor\n Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}\"); // Try assembly matching namespace root\n if (type != null) return type;\n }\n\n\n // If not found, search all loaded assemblies (slower, last resort)\n // Prioritize assemblies likely to contain game/editor types\n Assembly[] priorityAssemblies = {\n Assembly.Load(\"Assembly-CSharp\"), // Main game scripts\n Assembly.Load(\"Assembly-CSharp-Editor\"), // Main editor scripts\n // Add other important project assemblies if known\n };\n foreach (var assembly in priorityAssemblies.Where(a => a != null))\n {\n type = assembly.GetType(typeName) ?? assembly.GetType(\"UnityEngine.\" + typeName) ?? assembly.GetType(\"UnityEditor.\" + typeName);\n if (type != null) return type;\n }\n\n // Search remaining assemblies\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Except(priorityAssemblies))\n {\n try { // Protect against assembly loading errors\n type = assembly.GetType(typeName);\n if (type != null) return type;\n // Also check with common namespaces if simple name given\n foreach (string ns in namespaces) {\n type = assembly.GetType($\"{ns}.{typeName}\");\n if (type != null) return type;\n }\n } catch (Exception ex) {\n Debug.LogWarning($\"[FindType] Error searching assembly {assembly.FullName}: {ex.Message}\");\n }\n }\n\n Debug.LogWarning($\"[FindType] Type not found after extensive search: '{typeName}'\");\n return null; // Not found\n }\n\n /// \n /// Parses a JArray like [x, y, z] into a Vector3.\n /// \n private static Vector3? ParseVector3(JArray array)\n {\n if (array != null && array.Count == 3)\n {\n try\n {\n // Use ToObject for potentially better handling than direct indexing\n return new Vector3(\n array[0].ToObject(),\n array[1].ToObject(),\n array[2].ToObject()\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Failed to parse JArray as Vector3: {array}. Error: {ex.Message}\");\n }\n }\n return null;\n }\n\n // Removed GetGameObjectData, GetComponentData, and related private helpers/caching/serializer setup.\n // They are now in Helpers.GameObjectSerializer\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageAsset.cs", "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\n#if UNITY_6000_0_OR_NEWER\nusing PhysicsMaterialType = UnityEngine.PhysicsMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicsMaterialCombine; \n#else\nusing PhysicsMaterialType = UnityEngine.PhysicMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicMaterialCombine;\n#endif\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles asset management operations within the Unity project.\n /// \n public static class ManageAsset\n {\n // --- Main Handler ---\n\n // Define the list of valid actions\n private static readonly List ValidActions = new List\n {\n \"import\",\n \"create\",\n \"modify\",\n \"delete\",\n \"duplicate\",\n \"move\",\n \"rename\",\n \"search\",\n \"get_info\",\n \"create_folder\",\n \"get_components\",\n };\n\n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Check if the action is valid before switching\n if (!ValidActions.Contains(action))\n {\n string validActionsList = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsList}\"\n );\n }\n\n // Common parameters\n string path = @params[\"path\"]?.ToString();\n\n try\n {\n switch (action)\n {\n case \"import\":\n // Note: Unity typically auto-imports. This might re-import or configure import settings.\n return ReimportAsset(path, @params[\"properties\"] as JObject);\n case \"create\":\n return CreateAsset(@params);\n case \"modify\":\n return ModifyAsset(path, @params[\"properties\"] as JObject);\n case \"delete\":\n return DeleteAsset(path);\n case \"duplicate\":\n return DuplicateAsset(path, @params[\"destination\"]?.ToString());\n case \"move\": // Often same as rename if within Assets/\n case \"rename\":\n return MoveOrRenameAsset(path, @params[\"destination\"]?.ToString());\n case \"search\":\n return SearchAssets(@params);\n case \"get_info\":\n return GetAssetInfo(\n path,\n @params[\"generatePreview\"]?.ToObject() ?? false\n );\n case \"create_folder\": // Added specific action for clarity\n return CreateFolder(path);\n case \"get_components\":\n return GetComponentsFromAsset(path);\n\n default:\n // This error message is less likely to be hit now, but kept here as a fallback or for potential future modifications.\n string validActionsListDefault = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsListDefault}\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageAsset] Action '{action}' failed for path '{path}': {e}\");\n return Response.Error(\n $\"Internal error processing action '{action}' on '{path}': {e.Message}\"\n );\n }\n }\n\n // --- Action Implementations ---\n\n private static object ReimportAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for reimport.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // TODO: Apply importer properties before reimporting?\n // This is complex as it requires getting the AssetImporter, casting it,\n // applying properties via reflection or specific methods, saving, then reimporting.\n if (properties != null && properties.HasValues)\n {\n Debug.LogWarning(\n \"[ManageAsset.Reimport] Modifying importer properties before reimport is not fully implemented yet.\"\n );\n // AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n // if (importer != null) { /* Apply properties */ AssetDatabase.WriteImportSettingsIfDirty(fullPath); }\n }\n\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate);\n // AssetDatabase.Refresh(); // Usually ImportAsset handles refresh\n return Response.Success($\"Asset '{fullPath}' reimported.\", GetAssetData(fullPath));\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to reimport asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateAsset(JObject @params)\n {\n string path = @params[\"path\"]?.ToString();\n string assetType = @params[\"assetType\"]?.ToString();\n JObject properties = @params[\"properties\"] as JObject;\n\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create.\");\n if (string.IsNullOrEmpty(assetType))\n return Response.Error(\"'assetType' is required for create.\");\n\n string fullPath = SanitizeAssetPath(path);\n string directory = Path.GetDirectoryName(fullPath);\n\n // Ensure directory exists\n if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), directory)))\n {\n Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), directory));\n AssetDatabase.Refresh(); // Make sure Unity knows about the new folder\n }\n\n if (AssetExists(fullPath))\n return Response.Error($\"Asset already exists at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object newAsset = null;\n string lowerAssetType = assetType.ToLowerInvariant();\n\n // Handle common asset types\n if (lowerAssetType == \"folder\")\n {\n return CreateFolder(path); // Use dedicated method\n }\n else if (lowerAssetType == \"material\")\n {\n Material mat = new Material(Shader.Find(\"Standard\")); // Default shader\n // TODO: Apply properties from JObject (e.g., shader name, color, texture assignments)\n if (properties != null)\n ApplyMaterialProperties(mat, properties);\n AssetDatabase.CreateAsset(mat, fullPath);\n newAsset = mat;\n }\n else if (lowerAssetType == \"physicsmaterial\")\n {\n PhysicsMaterialType pmat = new PhysicsMaterialType();\n if (properties != null)\n ApplyPhysicsMaterialProperties(pmat, properties);\n AssetDatabase.CreateAsset(pmat, fullPath);\n newAsset = pmat;\n }\n else if (lowerAssetType == \"scriptableobject\")\n {\n string scriptClassName = properties?[\"scriptClass\"]?.ToString();\n if (string.IsNullOrEmpty(scriptClassName))\n return Response.Error(\n \"'scriptClass' property required when creating ScriptableObject asset.\"\n );\n\n Type scriptType = FindType(scriptClassName);\n if (\n scriptType == null\n || !typeof(ScriptableObject).IsAssignableFrom(scriptType)\n )\n {\n return Response.Error(\n $\"Script class '{scriptClassName}' not found or does not inherit from ScriptableObject.\"\n );\n }\n\n ScriptableObject so = ScriptableObject.CreateInstance(scriptType);\n // TODO: Apply properties from JObject to the ScriptableObject instance?\n AssetDatabase.CreateAsset(so, fullPath);\n newAsset = so;\n }\n else if (lowerAssetType == \"prefab\")\n {\n // Creating prefabs usually involves saving an existing GameObject hierarchy.\n // A common pattern is to create an empty GameObject, configure it, and then save it.\n return Response.Error(\n \"Creating prefabs programmatically usually requires a source GameObject. Use manage_gameobject to create/configure, then save as prefab via a separate mechanism or future enhancement.\"\n );\n // Example (conceptual):\n // GameObject source = GameObject.Find(properties[\"sourceGameObject\"].ToString());\n // if(source != null) PrefabUtility.SaveAsPrefabAsset(source, fullPath);\n }\n // TODO: Add more asset types (Animation Controller, Scene, etc.)\n else\n {\n // Generic creation attempt (might fail or create empty files)\n // For some types, just creating the file might be enough if Unity imports it.\n // File.Create(Path.Combine(Directory.GetCurrentDirectory(), fullPath)).Close();\n // AssetDatabase.ImportAsset(fullPath); // Let Unity try to import it\n // newAsset = AssetDatabase.LoadAssetAtPath(fullPath);\n return Response.Error(\n $\"Creation for asset type '{assetType}' is not explicitly supported yet. Supported: Folder, Material, ScriptableObject.\"\n );\n }\n\n if (\n newAsset == null\n && !Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), fullPath))\n ) // Check if it wasn't a folder and asset wasn't created\n {\n return Response.Error(\n $\"Failed to create asset '{assetType}' at '{fullPath}'. See logs for details.\"\n );\n }\n\n AssetDatabase.SaveAssets();\n // AssetDatabase.Refresh(); // CreateAsset often handles refresh\n return Response.Success(\n $\"Asset '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create asset at '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateFolder(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create_folder.\");\n string fullPath = SanitizeAssetPath(path);\n string parentDir = Path.GetDirectoryName(fullPath);\n string folderName = Path.GetFileName(fullPath);\n\n if (AssetExists(fullPath))\n {\n // Check if it's actually a folder already\n if (AssetDatabase.IsValidFolder(fullPath))\n {\n return Response.Success(\n $\"Folder already exists at path: {fullPath}\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n return Response.Error(\n $\"An asset (not a folder) already exists at path: {fullPath}\"\n );\n }\n }\n\n try\n {\n // Ensure parent exists\n if (!string.IsNullOrEmpty(parentDir) && !AssetDatabase.IsValidFolder(parentDir))\n {\n // Recursively create parent folders if needed (AssetDatabase handles this internally)\n // Or we can do it manually: Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), parentDir)); AssetDatabase.Refresh();\n }\n\n string guid = AssetDatabase.CreateFolder(parentDir, folderName);\n if (string.IsNullOrEmpty(guid))\n {\n return Response.Error(\n $\"Failed to create folder '{fullPath}'. Check logs and permissions.\"\n );\n }\n\n // AssetDatabase.Refresh(); // CreateFolder usually handles refresh\n return Response.Success(\n $\"Folder '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create folder '{fullPath}': {e.Message}\");\n }\n }\n\n private static object ModifyAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for modify.\");\n if (properties == null || !properties.HasValues)\n return Response.Error(\"'properties' are required for modify.\");\n\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n bool modified = false; // Flag to track if any changes were made\n\n // --- NEW: Handle GameObject / Prefab Component Modification ---\n if (asset is GameObject gameObject)\n {\n // Iterate through the properties JSON: keys are component names, values are properties objects for that component\n foreach (var prop in properties.Properties())\n {\n string componentName = prop.Name; // e.g., \"Collectible\"\n // Check if the value associated with the component name is actually an object containing properties\n if (\n prop.Value is JObject componentProperties\n && componentProperties.HasValues\n ) // e.g., {\"bobSpeed\": 2.0}\n {\n // Find the component on the GameObject using the name from the JSON key\n // Using GetComponent(string) is convenient but might require exact type name or be ambiguous.\n // Consider using FindType helper if needed for more complex scenarios.\n Component targetComponent = gameObject.GetComponent(componentName);\n\n if (targetComponent != null)\n {\n // Apply the nested properties (e.g., bobSpeed) to the found component instance\n // Use |= to ensure 'modified' becomes true if any component is successfully modified\n modified |= ApplyObjectProperties(\n targetComponent,\n componentProperties\n );\n }\n else\n {\n // Log a warning if a specified component couldn't be found\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Component '{componentName}' not found on GameObject '{gameObject.name}' in asset '{fullPath}'. Skipping modification for this component.\"\n );\n }\n }\n else\n {\n // Log a warning if the structure isn't {\"ComponentName\": {\"prop\": value}}\n // We could potentially try to apply this property directly to the GameObject here if needed,\n // but the primary goal is component modification.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Property '{prop.Name}' for GameObject modification should have a JSON object value containing component properties. Value was: {prop.Value.Type}. Skipping.\"\n );\n }\n }\n // Note: 'modified' is now true if ANY component property was successfully changed.\n }\n // --- End NEW ---\n\n // --- Existing logic for other asset types (now as else-if) ---\n // Example: Modifying a Material\n else if (asset is Material material)\n {\n // Apply properties directly to the material. If this modifies, it sets modified=true.\n // Use |= in case the asset was already marked modified by previous logic (though unlikely here)\n modified |= ApplyMaterialProperties(material, properties);\n }\n // Example: Modifying a ScriptableObject\n else if (asset is ScriptableObject so)\n {\n // Apply properties directly to the ScriptableObject.\n modified |= ApplyObjectProperties(so, properties); // General helper\n }\n // Example: Modifying TextureImporter settings\n else if (asset is Texture)\n {\n AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n if (importer is TextureImporter textureImporter)\n {\n bool importerModified = ApplyObjectProperties(textureImporter, properties);\n if (importerModified)\n {\n // Importer settings need saving and reimporting\n AssetDatabase.WriteImportSettingsIfDirty(fullPath);\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate); // Reimport to apply changes\n modified = true; // Mark overall operation as modified\n }\n }\n else\n {\n Debug.LogWarning($\"Could not get TextureImporter for {fullPath}.\");\n }\n }\n // TODO: Add modification logic for other common asset types (Models, AudioClips importers, etc.)\n else // Fallback for other asset types OR direct properties on non-GameObject assets\n {\n // This block handles non-GameObject/Material/ScriptableObject/Texture assets.\n // Attempts to apply properties directly to the asset itself.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Asset type '{asset.GetType().Name}' at '{fullPath}' is not explicitly handled for component modification. Attempting generic property setting on the asset itself.\"\n );\n modified |= ApplyObjectProperties(asset, properties);\n }\n // --- End Existing Logic ---\n\n // Check if any modification happened (either component or direct asset modification)\n if (modified)\n {\n // Mark the asset as dirty (important for prefabs/SOs) so Unity knows to save it.\n EditorUtility.SetDirty(asset);\n // Save all modified assets to disk.\n AssetDatabase.SaveAssets();\n // Refresh might be needed in some edge cases, but SaveAssets usually covers it.\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{fullPath}' modified successfully.\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n // If no changes were made (e.g., component not found, property names incorrect, value unchanged), return a success message indicating nothing changed.\n return Response.Success(\n $\"No applicable or modifiable properties found for asset '{fullPath}'. Check component names, property names, and values.\",\n GetAssetData(fullPath)\n );\n // Previous message: return Response.Success($\"No applicable properties found to modify for asset '{fullPath}'.\", GetAssetData(fullPath));\n }\n }\n catch (Exception e)\n {\n // Log the detailed error internally\n Debug.LogError($\"[ManageAsset] Action 'modify' failed for path '{path}': {e}\");\n // Return a user-friendly error message\n return Response.Error($\"Failed to modify asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DeleteAsset(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for delete.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n bool success = AssetDatabase.DeleteAsset(fullPath);\n if (success)\n {\n // AssetDatabase.Refresh(); // DeleteAsset usually handles refresh\n return Response.Success($\"Asset '{fullPath}' deleted successfully.\");\n }\n else\n {\n // This might happen if the file couldn't be deleted (e.g., locked)\n return Response.Error(\n $\"Failed to delete asset '{fullPath}'. Check logs or if the file is locked.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DuplicateAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for duplicate.\");\n\n string sourcePath = SanitizeAssetPath(path);\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n\n string destPath;\n if (string.IsNullOrEmpty(destinationPath))\n {\n // Generate a unique path if destination is not provided\n destPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath);\n }\n else\n {\n destPath = SanitizeAssetPath(destinationPath);\n if (AssetExists(destPath))\n return Response.Error($\"Asset already exists at destination path: {destPath}\");\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n }\n\n try\n {\n bool success = AssetDatabase.CopyAsset(sourcePath, destPath);\n if (success)\n {\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{sourcePath}' duplicated to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n return Response.Error(\n $\"Failed to duplicate asset from '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error duplicating asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object MoveOrRenameAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for move/rename.\");\n if (string.IsNullOrEmpty(destinationPath))\n return Response.Error(\"'destination' path is required for move/rename.\");\n\n string sourcePath = SanitizeAssetPath(path);\n string destPath = SanitizeAssetPath(destinationPath);\n\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n if (AssetExists(destPath))\n return Response.Error(\n $\"An asset already exists at the destination path: {destPath}\"\n );\n\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n\n try\n {\n // Validate will return an error string if failed, null if successful\n string error = AssetDatabase.ValidateMoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(error))\n {\n return Response.Error(\n $\"Failed to move/rename asset from '{sourcePath}' to '{destPath}': {error}\"\n );\n }\n\n string guid = AssetDatabase.MoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(guid)) // MoveAsset returns the new GUID on success\n {\n // AssetDatabase.Refresh(); // MoveAsset usually handles refresh\n return Response.Success(\n $\"Asset moved/renamed from '{sourcePath}' to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n // This case might not be reachable if ValidateMoveAsset passes, but good to have\n return Response.Error(\n $\"MoveAsset call failed unexpectedly for '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error moving/renaming asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object SearchAssets(JObject @params)\n {\n string searchPattern = @params[\"searchPattern\"]?.ToString();\n string filterType = @params[\"filterType\"]?.ToString();\n string pathScope = @params[\"path\"]?.ToString(); // Use path as folder scope\n string filterDateAfterStr = @params[\"filterDateAfter\"]?.ToString();\n int pageSize = @params[\"pageSize\"]?.ToObject() ?? 50; // Default page size\n int pageNumber = @params[\"pageNumber\"]?.ToObject() ?? 1; // Default page number (1-based)\n bool generatePreview = @params[\"generatePreview\"]?.ToObject() ?? false;\n\n List searchFilters = new List();\n if (!string.IsNullOrEmpty(searchPattern))\n searchFilters.Add(searchPattern);\n if (!string.IsNullOrEmpty(filterType))\n searchFilters.Add($\"t:{filterType}\");\n\n string[] folderScope = null;\n if (!string.IsNullOrEmpty(pathScope))\n {\n folderScope = new string[] { SanitizeAssetPath(pathScope) };\n if (!AssetDatabase.IsValidFolder(folderScope[0]))\n {\n // Maybe the user provided a file path instead of a folder?\n // We could search in the containing folder, or return an error.\n Debug.LogWarning(\n $\"Search path '{folderScope[0]}' is not a valid folder. Searching entire project.\"\n );\n folderScope = null; // Search everywhere if path isn't a folder\n }\n }\n\n DateTime? filterDateAfter = null;\n if (!string.IsNullOrEmpty(filterDateAfterStr))\n {\n if (\n DateTime.TryParse(\n filterDateAfterStr,\n CultureInfo.InvariantCulture,\n DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,\n out DateTime parsedDate\n )\n )\n {\n filterDateAfter = parsedDate;\n }\n else\n {\n Debug.LogWarning(\n $\"Could not parse filterDateAfter: '{filterDateAfterStr}'. Expected ISO 8601 format.\"\n );\n }\n }\n\n try\n {\n string[] guids = AssetDatabase.FindAssets(\n string.Join(\" \", searchFilters),\n folderScope\n );\n List results = new List();\n int totalFound = 0;\n\n foreach (string guid in guids)\n {\n string assetPath = AssetDatabase.GUIDToAssetPath(guid);\n if (string.IsNullOrEmpty(assetPath))\n continue;\n\n // Apply date filter if present\n if (filterDateAfter.HasValue)\n {\n DateTime lastWriteTime = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), assetPath)\n );\n if (lastWriteTime <= filterDateAfter.Value)\n {\n continue; // Skip assets older than or equal to the filter date\n }\n }\n\n totalFound++; // Count matching assets before pagination\n results.Add(GetAssetData(assetPath, generatePreview));\n }\n\n // Apply pagination\n int startIndex = (pageNumber - 1) * pageSize;\n var pagedResults = results.Skip(startIndex).Take(pageSize).ToList();\n\n return Response.Success(\n $\"Found {totalFound} asset(s). Returning page {pageNumber} ({pagedResults.Count} assets).\",\n new\n {\n totalAssets = totalFound,\n pageSize = pageSize,\n pageNumber = pageNumber,\n assets = pagedResults,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error searching assets: {e.Message}\");\n }\n }\n\n private static object GetAssetInfo(string path, bool generatePreview)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_info.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n return Response.Success(\n \"Asset info retrieved.\",\n GetAssetData(fullPath, generatePreview)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting info for asset '{fullPath}': {e.Message}\");\n }\n }\n\n /// \n /// Retrieves components attached to a GameObject asset (like a Prefab).\n /// \n /// The asset path of the GameObject or Prefab.\n /// A response object containing a list of component type names or an error.\n private static object GetComponentsFromAsset(string path)\n {\n // 1. Validate input path\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_components.\");\n\n // 2. Sanitize and check existence\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // 3. Load the asset\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n // 4. Check if it's a GameObject (Prefabs load as GameObjects)\n GameObject gameObject = asset as GameObject;\n if (gameObject == null)\n {\n // Also check if it's *directly* a Component type (less common for primary assets)\n Component componentAsset = asset as Component;\n if (componentAsset != null)\n {\n // If the asset itself *is* a component, maybe return just its info?\n // This is an edge case. Let's stick to GameObjects for now.\n return Response.Error(\n $\"Asset at '{fullPath}' is a Component ({asset.GetType().FullName}), not a GameObject. Components are typically retrieved *from* a GameObject.\"\n );\n }\n return Response.Error(\n $\"Asset at '{fullPath}' is not a GameObject (Type: {asset.GetType().FullName}). Cannot get components from this asset type.\"\n );\n }\n\n // 5. Get components\n Component[] components = gameObject.GetComponents();\n\n // 6. Format component data\n List componentList = components\n .Select(comp => new\n {\n typeName = comp.GetType().FullName,\n instanceID = comp.GetInstanceID(),\n // TODO: Add more component-specific details here if needed in the future?\n // Requires reflection or specific handling per component type.\n })\n .ToList(); // Explicit cast for clarity if needed\n\n // 7. Return success response\n return Response.Success(\n $\"Found {componentList.Count} component(s) on asset '{fullPath}'.\",\n componentList\n );\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageAsset.GetComponentsFromAsset] Error getting components for '{fullPath}': {e}\"\n );\n return Response.Error(\n $\"Error getting components for asset '{fullPath}': {e.Message}\"\n );\n }\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Ensures the asset path starts with \"Assets/\".\n /// \n private static string SanitizeAssetPath(string path)\n {\n if (string.IsNullOrEmpty(path))\n return path;\n path = path.Replace('\\\\', '/'); // Normalize separators\n if (!path.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n return \"Assets/\" + path.TrimStart('/');\n }\n return path;\n }\n\n /// \n /// Checks if an asset exists at the given path (file or folder).\n /// \n private static bool AssetExists(string sanitizedPath)\n {\n // AssetDatabase APIs are generally preferred over raw File/Directory checks for assets.\n // Check if it's a known asset GUID.\n if (!string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath)))\n {\n return true;\n }\n // AssetPathToGUID might not work for newly created folders not yet refreshed.\n // Check directory explicitly for folders.\n if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n // Check if it's considered a *valid* folder by Unity\n return AssetDatabase.IsValidFolder(sanitizedPath);\n }\n // Check file existence for non-folder assets.\n if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n return true; // Assume if file exists, it's an asset or will be imported\n }\n\n return false;\n // Alternative: return !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath));\n }\n\n /// \n /// Ensures the directory for a given asset path exists, creating it if necessary.\n /// \n private static void EnsureDirectoryExists(string directoryPath)\n {\n if (string.IsNullOrEmpty(directoryPath))\n return;\n string fullDirPath = Path.Combine(Directory.GetCurrentDirectory(), directoryPath);\n if (!Directory.Exists(fullDirPath))\n {\n Directory.CreateDirectory(fullDirPath);\n AssetDatabase.Refresh(); // Let Unity know about the new folder\n }\n }\n\n /// \n /// Applies properties from JObject to a Material.\n /// \n private static bool ApplyMaterialProperties(Material mat, JObject properties)\n {\n if (mat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set shader\n if (properties[\"shader\"]?.Type == JTokenType.String)\n {\n Shader newShader = Shader.Find(properties[\"shader\"].ToString());\n if (newShader != null && mat.shader != newShader)\n {\n mat.shader = newShader;\n modified = true;\n }\n }\n // Example: Set color property\n if (properties[\"color\"] is JObject colorProps)\n {\n string propName = colorProps[\"name\"]?.ToString() ?? \"_Color\"; // Default main color\n if (colorProps[\"value\"] is JArray colArr && colArr.Count >= 3)\n {\n try\n {\n Color newColor = new Color(\n colArr[0].ToObject(),\n colArr[1].ToObject(),\n colArr[2].ToObject(),\n colArr.Count > 3 ? colArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n } else if (properties[\"color\"] is JArray colorArr) //Use color now with examples set in manage_asset.py\n {\n string propName = \"_Color\"; \n try {\n if (colorArr.Count >= 3)\n {\n Color newColor = new Color(\n colorArr[0].ToObject(),\n colorArr[1].ToObject(), \n colorArr[2].ToObject(), \n colorArr.Count > 3 ? colorArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n } \n catch (Exception ex) {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n // Example: Set float property\n if (properties[\"float\"] is JObject floatProps)\n {\n string propName = floatProps[\"name\"]?.ToString();\n if (\n !string.IsNullOrEmpty(propName) && floatProps[\"value\"]?.Type == JTokenType.Float\n || floatProps[\"value\"]?.Type == JTokenType.Integer\n )\n {\n try\n {\n float newVal = floatProps[\"value\"].ToObject();\n if (mat.HasProperty(propName) && mat.GetFloat(propName) != newVal)\n {\n mat.SetFloat(propName, newVal);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing float property '{propName}': {ex.Message}\"\n );\n }\n }\n }\n // Example: Set texture property\n if (properties[\"texture\"] is JObject texProps)\n {\n string propName = texProps[\"name\"]?.ToString() ?? \"_MainTex\"; // Default main texture\n string texPath = texProps[\"path\"]?.ToString();\n if (!string.IsNullOrEmpty(texPath))\n {\n Texture newTex = AssetDatabase.LoadAssetAtPath(\n SanitizeAssetPath(texPath)\n );\n if (\n newTex != null\n && mat.HasProperty(propName)\n && mat.GetTexture(propName) != newTex\n )\n {\n mat.SetTexture(propName, newTex);\n modified = true;\n }\n else if (newTex == null)\n {\n Debug.LogWarning($\"Texture not found at path: {texPath}\");\n }\n }\n }\n\n // TODO: Add handlers for other property types (Vectors, Ints, Keywords, RenderQueue, etc.)\n return modified;\n }\n\n /// \n /// Applies properties from JObject to a PhysicsMaterial.\n /// \n private static bool ApplyPhysicsMaterialProperties(PhysicsMaterialType pmat, JObject properties)\n {\n if (pmat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set dynamic friction\n if (properties[\"dynamicFriction\"]?.Type == JTokenType.Float)\n {\n float dynamicFriction = properties[\"dynamicFriction\"].ToObject();\n pmat.dynamicFriction = dynamicFriction;\n modified = true;\n }\n\n // Example: Set static friction\n if (properties[\"staticFriction\"]?.Type == JTokenType.Float)\n {\n float staticFriction = properties[\"staticFriction\"].ToObject();\n pmat.staticFriction = staticFriction;\n modified = true;\n }\n\n // Example: Set bounciness\n if (properties[\"bounciness\"]?.Type == JTokenType.Float)\n {\n float bounciness = properties[\"bounciness\"].ToObject();\n pmat.bounciness = bounciness;\n modified = true;\n }\n\n List averageList = new List { \"ave\", \"Ave\", \"average\", \"Average\" };\n List multiplyList = new List { \"mul\", \"Mul\", \"mult\", \"Mult\", \"multiply\", \"Multiply\" };\n List minimumList = new List { \"min\", \"Min\", \"minimum\", \"Minimum\" };\n List maximumList = new List { \"max\", \"Max\", \"maximum\", \"Maximum\" };\n\n // Example: Set friction combine\n if (properties[\"frictionCombine\"]?.Type == JTokenType.String)\n {\n string frictionCombine = properties[\"frictionCombine\"].ToString();\n if (averageList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n // Example: Set bounce combine\n if (properties[\"bounceCombine\"]?.Type == JTokenType.String)\n {\n string bounceCombine = properties[\"bounceCombine\"].ToString();\n if (averageList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n return modified;\n }\n\n /// \n /// Generic helper to set properties on any UnityEngine.Object using reflection.\n /// \n private static bool ApplyObjectProperties(UnityEngine.Object target, JObject properties)\n {\n if (target == null || properties == null)\n return false;\n bool modified = false;\n Type type = target.GetType();\n\n foreach (var prop in properties.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n if (SetPropertyOrField(target, propName, propValue, type))\n {\n modified = true;\n }\n }\n return modified;\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types and Unity objects.\n /// \n private static bool SetPropertyOrField(\n object target,\n string memberName,\n JToken value,\n Type type = null\n )\n {\n type = type ?? target.GetType();\n System.Reflection.BindingFlags flags =\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.Instance\n | System.Reflection.BindingFlags.IgnoreCase;\n\n try\n {\n System.Reflection.PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType);\n if (\n convertedValue != null\n && !object.Equals(propInfo.GetValue(target), convertedValue)\n )\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n else\n {\n System.Reflection.FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null)\n {\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType);\n if (\n convertedValue != null\n && !object.Equals(fieldInfo.GetValue(target), convertedValue)\n )\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[SetPropertyOrField] Failed to set '{memberName}' on {type.Name}: {ex.Message}\"\n );\n }\n return false;\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types and primitives.\n /// \n private static object ConvertJTokenToType(JToken token, Type targetType)\n {\n try\n {\n if (token == null || token.Type == JTokenType.Null)\n return null;\n\n if (targetType == typeof(string))\n return token.ToObject();\n if (targetType == typeof(int))\n return token.ToObject();\n if (targetType == typeof(float))\n return token.ToObject();\n if (targetType == typeof(bool))\n return token.ToObject();\n if (targetType == typeof(Vector2) && token is JArray arrV2 && arrV2.Count == 2)\n return new Vector2(arrV2[0].ToObject(), arrV2[1].ToObject());\n if (targetType == typeof(Vector3) && token is JArray arrV3 && arrV3.Count == 3)\n return new Vector3(\n arrV3[0].ToObject(),\n arrV3[1].ToObject(),\n arrV3[2].ToObject()\n );\n if (targetType == typeof(Vector4) && token is JArray arrV4 && arrV4.Count == 4)\n return new Vector4(\n arrV4[0].ToObject(),\n arrV4[1].ToObject(),\n arrV4[2].ToObject(),\n arrV4[3].ToObject()\n );\n if (targetType == typeof(Quaternion) && token is JArray arrQ && arrQ.Count == 4)\n return new Quaternion(\n arrQ[0].ToObject(),\n arrQ[1].ToObject(),\n arrQ[2].ToObject(),\n arrQ[3].ToObject()\n );\n if (targetType == typeof(Color) && token is JArray arrC && arrC.Count >= 3) // Allow RGB or RGBA\n return new Color(\n arrC[0].ToObject(),\n arrC[1].ToObject(),\n arrC[2].ToObject(),\n arrC.Count > 3 ? arrC[3].ToObject() : 1.0f\n );\n if (targetType.IsEnum)\n return Enum.Parse(targetType, token.ToString(), true); // Case-insensitive enum parsing\n\n // Handle loading Unity Objects (Materials, Textures, etc.) by path\n if (\n typeof(UnityEngine.Object).IsAssignableFrom(targetType)\n && token.Type == JTokenType.String\n )\n {\n string assetPath = SanitizeAssetPath(token.ToString());\n UnityEngine.Object loadedAsset = AssetDatabase.LoadAssetAtPath(\n assetPath,\n targetType\n );\n if (loadedAsset == null)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not load asset of type {targetType.Name} from path: {assetPath}\"\n );\n }\n return loadedAsset;\n }\n\n // Fallback: Try direct conversion (might work for other simple value types)\n return token.ToObject(targetType);\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not convert JToken '{token}' (type {token.Type}) to type '{targetType.Name}': {ex.Message}\"\n );\n return null;\n }\n }\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// Needed for creating ScriptableObjects or finding component types by name.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Try direct lookup first (common Unity types often don't need assembly qualified name)\n var type =\n Type.GetType(typeName)\n ?? Type.GetType($\"UnityEngine.{typeName}, UnityEngine.CoreModule\")\n ?? Type.GetType($\"UnityEngine.UI.{typeName}, UnityEngine.UI\")\n ?? Type.GetType($\"UnityEditor.{typeName}, UnityEditor.CoreModule\");\n\n if (type != null)\n return type;\n\n // If not found, search loaded assemblies (slower but more robust for user scripts)\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n {\n // Look for non-namespaced first\n type = assembly.GetType(typeName, false, true); // throwOnError=false, ignoreCase=true\n if (type != null)\n return type;\n\n // Check common namespaces if simple name given\n type = assembly.GetType(\"UnityEngine.\" + typeName, false, true);\n if (type != null)\n return type;\n type = assembly.GetType(\"UnityEditor.\" + typeName, false, true);\n if (type != null)\n return type;\n // Add other likely namespaces if needed (e.g., specific plugins)\n }\n\n Debug.LogWarning($\"[FindType] Type '{typeName}' not found in any loaded assembly.\");\n return null; // Not found\n }\n\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of an asset.\n /// \n private static object GetAssetData(string path, bool generatePreview = false)\n {\n if (string.IsNullOrEmpty(path) || !AssetExists(path))\n return null;\n\n string guid = AssetDatabase.AssetPathToGUID(path);\n Type assetType = AssetDatabase.GetMainAssetTypeAtPath(path);\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(path);\n string previewBase64 = null;\n int previewWidth = 0;\n int previewHeight = 0;\n\n if (generatePreview && asset != null)\n {\n Texture2D preview = AssetPreview.GetAssetPreview(asset);\n\n if (preview != null)\n {\n try\n {\n // Ensure texture is readable for EncodeToPNG\n // Creating a temporary readable copy is safer\n RenderTexture rt = RenderTexture.GetTemporary(\n preview.width,\n preview.height\n );\n Graphics.Blit(preview, rt);\n RenderTexture previous = RenderTexture.active;\n RenderTexture.active = rt;\n Texture2D readablePreview = new Texture2D(preview.width, preview.height);\n readablePreview.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);\n readablePreview.Apply();\n RenderTexture.active = previous;\n RenderTexture.ReleaseTemporary(rt);\n\n byte[] pngData = readablePreview.EncodeToPNG();\n previewBase64 = Convert.ToBase64String(pngData);\n previewWidth = readablePreview.width;\n previewHeight = readablePreview.height;\n UnityEngine.Object.DestroyImmediate(readablePreview); // Clean up temp texture\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Failed to generate readable preview for '{path}': {ex.Message}. Preview might not be readable.\"\n );\n // Fallback: Try getting static preview if available?\n // Texture2D staticPreview = AssetPreview.GetMiniThumbnail(asset);\n }\n }\n else\n {\n Debug.LogWarning(\n $\"Could not get asset preview for {path} (Type: {assetType?.Name}). Is it supported?\"\n );\n }\n }\n\n return new\n {\n path = path,\n guid = guid,\n assetType = assetType?.FullName ?? \"Unknown\",\n name = Path.GetFileNameWithoutExtension(path),\n fileName = Path.GetFileName(path),\n isFolder = AssetDatabase.IsValidFolder(path),\n instanceID = asset?.GetInstanceID() ?? 0,\n lastWriteTimeUtc = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), path)\n )\n .ToString(\"o\"), // ISO 8601\n // --- Preview Data ---\n previewBase64 = previewBase64, // PNG data as Base64 string\n previewWidth = previewWidth,\n previewHeight = previewHeight,\n // TODO: Add more metadata? Importer settings? Dependencies?\n };\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ReadConsole.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles reading and clearing Unity Editor console log entries.\n /// Uses reflection to access internal LogEntry methods/properties.\n /// \n public static class ReadConsole\n {\n // Reflection members for accessing internal LogEntry data\n // private static MethodInfo _getEntriesMethod; // Removed as it's unused and fails reflection\n private static MethodInfo _startGettingEntriesMethod;\n private static MethodInfo _endGettingEntriesMethod; // Renamed from _stopGettingEntriesMethod, trying End...\n private static MethodInfo _clearMethod;\n private static MethodInfo _getCountMethod;\n private static MethodInfo _getEntryMethod;\n private static FieldInfo _modeField;\n private static FieldInfo _messageField;\n private static FieldInfo _fileField;\n private static FieldInfo _lineField;\n private static FieldInfo _instanceIdField;\n\n // Note: Timestamp is not directly available in LogEntry; need to parse message or find alternative?\n\n // Static constructor for reflection setup\n static ReadConsole()\n {\n try\n {\n Type logEntriesType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntries\"\n );\n if (logEntriesType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntries\");\n\n // Include NonPublic binding flags as internal APIs might change accessibility\n BindingFlags staticFlags =\n BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;\n BindingFlags instanceFlags =\n BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\n\n _startGettingEntriesMethod = logEntriesType.GetMethod(\n \"StartGettingEntries\",\n staticFlags\n );\n if (_startGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.StartGettingEntries\");\n\n // Try reflecting EndGettingEntries based on warning message\n _endGettingEntriesMethod = logEntriesType.GetMethod(\n \"EndGettingEntries\",\n staticFlags\n );\n if (_endGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.EndGettingEntries\");\n\n _clearMethod = logEntriesType.GetMethod(\"Clear\", staticFlags);\n if (_clearMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.Clear\");\n\n _getCountMethod = logEntriesType.GetMethod(\"GetCount\", staticFlags);\n if (_getCountMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetCount\");\n\n _getEntryMethod = logEntriesType.GetMethod(\"GetEntryInternal\", staticFlags);\n if (_getEntryMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetEntryInternal\");\n\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntry\");\n\n _modeField = logEntryType.GetField(\"mode\", instanceFlags);\n if (_modeField == null)\n throw new Exception(\"Failed to reflect LogEntry.mode\");\n\n _messageField = logEntryType.GetField(\"message\", instanceFlags);\n if (_messageField == null)\n throw new Exception(\"Failed to reflect LogEntry.message\");\n\n _fileField = logEntryType.GetField(\"file\", instanceFlags);\n if (_fileField == null)\n throw new Exception(\"Failed to reflect LogEntry.file\");\n\n _lineField = logEntryType.GetField(\"line\", instanceFlags);\n if (_lineField == null)\n throw new Exception(\"Failed to reflect LogEntry.line\");\n\n _instanceIdField = logEntryType.GetField(\"instanceID\", instanceFlags);\n if (_instanceIdField == null)\n throw new Exception(\"Failed to reflect LogEntry.instanceID\");\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ReadConsole] Static Initialization Failed: Could not setup reflection for LogEntries/LogEntry. Console reading/clearing will likely fail. Specific Error: {e.Message}\"\n );\n // Set members to null to prevent NullReferenceExceptions later, HandleCommand should check this.\n _startGettingEntriesMethod =\n _endGettingEntriesMethod =\n _clearMethod =\n _getCountMethod =\n _getEntryMethod =\n null;\n _modeField = _messageField = _fileField = _lineField = _instanceIdField = null;\n }\n }\n\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n // Check if ALL required reflection members were successfully initialized.\n if (\n _startGettingEntriesMethod == null\n || _endGettingEntriesMethod == null\n || _clearMethod == null\n || _getCountMethod == null\n || _getEntryMethod == null\n || _modeField == null\n || _messageField == null\n || _fileField == null\n || _lineField == null\n || _instanceIdField == null\n )\n {\n // Log the error here as well for easier debugging in Unity Console\n Debug.LogError(\n \"[ReadConsole] HandleCommand called but reflection members are not initialized. Static constructor might have failed silently or there's an issue.\"\n );\n return Response.Error(\n \"ReadConsole handler failed to initialize due to reflection errors. Cannot access console logs.\"\n );\n }\n\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"get\";\n\n try\n {\n if (action == \"clear\")\n {\n return ClearConsole();\n }\n else if (action == \"get\")\n {\n // Extract parameters for 'get'\n var types =\n (@params[\"types\"] as JArray)?.Select(t => t.ToString().ToLower()).ToList()\n ?? new List { \"error\", \"warning\", \"log\" };\n int? count = @params[\"count\"]?.ToObject();\n string filterText = @params[\"filterText\"]?.ToString();\n string sinceTimestampStr = @params[\"sinceTimestamp\"]?.ToString(); // TODO: Implement timestamp filtering\n string format = (@params[\"format\"]?.ToString() ?? \"detailed\").ToLower();\n bool includeStacktrace =\n @params[\"includeStacktrace\"]?.ToObject() ?? true;\n\n if (types.Contains(\"all\"))\n {\n types = new List { \"error\", \"warning\", \"log\" }; // Expand 'all'\n }\n\n if (!string.IsNullOrEmpty(sinceTimestampStr))\n {\n Debug.LogWarning(\n \"[ReadConsole] Filtering by 'since_timestamp' is not currently implemented.\"\n );\n // Need a way to get timestamp per log entry.\n }\n\n return GetConsoleEntries(types, count, filterText, format, includeStacktrace);\n }\n else\n {\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'get' or 'clear'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object ClearConsole()\n {\n try\n {\n _clearMethod.Invoke(null, null); // Static method, no instance, no parameters\n return Response.Success(\"Console cleared successfully.\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to clear console: {e}\");\n return Response.Error($\"Failed to clear console: {e.Message}\");\n }\n }\n\n private static object GetConsoleEntries(\n List types,\n int? count,\n string filterText,\n string format,\n bool includeStacktrace\n )\n {\n List formattedEntries = new List();\n int retrievedCount = 0;\n\n try\n {\n // LogEntries requires calling Start/Stop around GetEntries/GetEntryInternal\n _startGettingEntriesMethod.Invoke(null, null);\n\n int totalEntries = (int)_getCountMethod.Invoke(null, null);\n // Create instance to pass to GetEntryInternal - Ensure the type is correct\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\n \"Could not find internal type UnityEditor.LogEntry during GetConsoleEntries.\"\n );\n object logEntryInstance = Activator.CreateInstance(logEntryType);\n\n for (int i = 0; i < totalEntries; i++)\n {\n // Get the entry data into our instance using reflection\n _getEntryMethod.Invoke(null, new object[] { i, logEntryInstance });\n\n // Extract data using reflection\n int mode = (int)_modeField.GetValue(logEntryInstance);\n string message = (string)_messageField.GetValue(logEntryInstance);\n string file = (string)_fileField.GetValue(logEntryInstance);\n\n int line = (int)_lineField.GetValue(logEntryInstance);\n // int instanceId = (int)_instanceIdField.GetValue(logEntryInstance);\n\n if (string.IsNullOrEmpty(message))\n continue; // Skip empty messages\n\n // --- Filtering ---\n // Filter by type\n LogType currentType = GetLogTypeFromMode(mode);\n if (!types.Contains(currentType.ToString().ToLowerInvariant()))\n {\n continue;\n }\n\n // Filter by text (case-insensitive)\n if (\n !string.IsNullOrEmpty(filterText)\n && message.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) < 0\n )\n {\n continue;\n }\n\n // TODO: Filter by timestamp (requires timestamp data)\n\n // --- Formatting ---\n string stackTrace = includeStacktrace ? ExtractStackTrace(message) : null;\n // Get first line if stack is present and requested, otherwise use full message\n string messageOnly =\n (includeStacktrace && !string.IsNullOrEmpty(stackTrace))\n ? message.Split(\n new[] { '\\n', '\\r' },\n StringSplitOptions.RemoveEmptyEntries\n )[0]\n : message;\n\n object formattedEntry = null;\n switch (format)\n {\n case \"plain\":\n formattedEntry = messageOnly;\n break;\n case \"json\":\n case \"detailed\": // Treat detailed as json for structured return\n default:\n formattedEntry = new\n {\n type = currentType.ToString(),\n message = messageOnly,\n file = file,\n line = line,\n // timestamp = \"\", // TODO\n stackTrace = stackTrace, // Will be null if includeStacktrace is false or no stack found\n };\n break;\n }\n\n formattedEntries.Add(formattedEntry);\n retrievedCount++;\n\n // Apply count limit (after filtering)\n if (count.HasValue && retrievedCount >= count.Value)\n {\n break;\n }\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Error while retrieving log entries: {e}\");\n // Ensure EndGettingEntries is called even if there's an error during iteration\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch\n { /* Ignore nested exception */\n }\n return Response.Error($\"Error retrieving log entries: {e.Message}\");\n }\n finally\n {\n // Ensure we always call EndGettingEntries\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to call EndGettingEntries: {e}\");\n // Don't return error here as we might have valid data, but log it.\n }\n }\n\n // Return the filtered and formatted list (might be empty)\n return Response.Success(\n $\"Retrieved {formattedEntries.Count} log entries.\",\n formattedEntries\n );\n }\n\n // --- Internal Helpers ---\n\n // Mapping from LogEntry.mode bits to LogType enum\n // Based on decompiled UnityEditor code or common patterns. Precise bits might change between Unity versions.\n // See comments below for LogEntry mode bits exploration.\n // Note: This mapping is simplified and might not cover all edge cases or future Unity versions perfectly.\n private const int ModeBitError = 1 << 0;\n private const int ModeBitAssert = 1 << 1;\n private const int ModeBitWarning = 1 << 2;\n private const int ModeBitLog = 1 << 3;\n private const int ModeBitException = 1 << 4; // Often combined with Error bits\n private const int ModeBitScriptingError = 1 << 9;\n private const int ModeBitScriptingWarning = 1 << 10;\n private const int ModeBitScriptingLog = 1 << 11;\n private const int ModeBitScriptingException = 1 << 18;\n private const int ModeBitScriptingAssertion = 1 << 22;\n\n private static LogType GetLogTypeFromMode(int mode)\n {\n // First, determine the type based on the original logic (most severe first)\n LogType initialType;\n if (\n (\n mode\n & (\n ModeBitError\n | ModeBitScriptingError\n | ModeBitException\n | ModeBitScriptingException\n )\n ) != 0\n )\n {\n initialType = LogType.Error;\n }\n else if ((mode & (ModeBitAssert | ModeBitScriptingAssertion)) != 0)\n {\n initialType = LogType.Assert;\n }\n else if ((mode & (ModeBitWarning | ModeBitScriptingWarning)) != 0)\n {\n initialType = LogType.Warning;\n }\n else\n {\n initialType = LogType.Log;\n }\n\n // Apply the observed \"one level lower\" correction\n switch (initialType)\n {\n case LogType.Error:\n return LogType.Warning; // Error becomes Warning\n case LogType.Warning:\n return LogType.Log; // Warning becomes Log\n case LogType.Assert:\n return LogType.Assert; // Assert remains Assert (no lower level defined)\n case LogType.Log:\n return LogType.Log; // Log remains Log\n default:\n return LogType.Log; // Default fallback\n }\n }\n\n /// \n /// Attempts to extract the stack trace part from a log message.\n /// Unity log messages often have the stack trace appended after the main message,\n /// starting on a new line and typically indented or beginning with \"at \".\n /// \n /// The complete log message including potential stack trace.\n /// The extracted stack trace string, or null if none is found.\n private static string ExtractStackTrace(string fullMessage)\n {\n if (string.IsNullOrEmpty(fullMessage))\n return null;\n\n // Split into lines, removing empty ones to handle different line endings gracefully.\n // Using StringSplitOptions.None might be better if empty lines matter within stack trace, but RemoveEmptyEntries is usually safer here.\n string[] lines = fullMessage.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n // If there's only one line or less, there's no separate stack trace.\n if (lines.Length <= 1)\n return null;\n\n int stackStartIndex = -1;\n\n // Start checking from the second line onwards.\n for (int i = 1; i < lines.Length; ++i)\n {\n // Performance: TrimStart creates a new string. Consider using IsWhiteSpace check if performance critical.\n string trimmedLine = lines[i].TrimStart();\n\n // Check for common stack trace patterns.\n if (\n trimmedLine.StartsWith(\"at \")\n || trimmedLine.StartsWith(\"UnityEngine.\")\n || trimmedLine.StartsWith(\"UnityEditor.\")\n || trimmedLine.Contains(\"(at \")\n || // Covers \"(at Assets/...\" pattern\n // Heuristic: Check if line starts with likely namespace/class pattern (Uppercase.Something)\n (\n trimmedLine.Length > 0\n && char.IsUpper(trimmedLine[0])\n && trimmedLine.Contains('.')\n )\n )\n {\n stackStartIndex = i;\n break; // Found the likely start of the stack trace\n }\n }\n\n // If a potential start index was found...\n if (stackStartIndex > 0)\n {\n // Join the lines from the stack start index onwards using standard newline characters.\n // This reconstructs the stack trace part of the message.\n return string.Join(\"\\n\", lines.Skip(stackStartIndex));\n }\n\n // No clear stack trace found based on the patterns.\n return null;\n }\n\n /* LogEntry.mode bits exploration (based on Unity decompilation/observation):\n May change between versions.\n\n Basic Types:\n kError = 1 << 0 (1)\n kAssert = 1 << 1 (2)\n kWarning = 1 << 2 (4)\n kLog = 1 << 3 (8)\n kFatal = 1 << 4 (16) - Often treated as Exception/Error\n\n Modifiers/Context:\n kAssetImportError = 1 << 7 (128)\n kAssetImportWarning = 1 << 8 (256)\n kScriptingError = 1 << 9 (512)\n kScriptingWarning = 1 << 10 (1024)\n kScriptingLog = 1 << 11 (2048)\n kScriptCompileError = 1 << 12 (4096)\n kScriptCompileWarning = 1 << 13 (8192)\n kStickyError = 1 << 14 (16384) - Stays visible even after Clear On Play\n kMayIgnoreLineNumber = 1 << 15 (32768)\n kReportBug = 1 << 16 (65536) - Shows the \"Report Bug\" button\n kDisplayPreviousErrorInStatusBar = 1 << 17 (131072)\n kScriptingException = 1 << 18 (262144)\n kDontExtractStacktrace = 1 << 19 (524288) - Hint to the console UI\n kShouldClearOnPlay = 1 << 20 (1048576) - Default behavior\n kGraphCompileError = 1 << 21 (2097152)\n kScriptingAssertion = 1 << 22 (4194304)\n kVisualScriptingError = 1 << 23 (8388608)\n\n Example observed values:\n Log: 2048 (ScriptingLog) or 8 (Log)\n Warning: 1028 (ScriptingWarning | Warning) or 4 (Warning)\n Error: 513 (ScriptingError | Error) or 1 (Error)\n Exception: 262161 (ScriptingException | Error | kFatal?) - Complex combination\n Assertion: 4194306 (ScriptingAssertion | Assert) or 2 (Assert)\n */\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScene.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles scene management operations like loading, saving, creating, and querying hierarchy.\n /// \n public static class ManageScene\n {\n /// \n /// Main handler for scene management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n int? buildIndex = @params[\"buildIndex\"]?.ToObject();\n // bool loadAdditive = @params[\"loadAdditive\"]?.ToObject() ?? false; // Example for future extension\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n string relativeDir = path ?? string.Empty;\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n\n // Apply default *after* sanitizing, using the original path variable for the check\n if (string.IsNullOrEmpty(path) && action == \"create\") // Check original path for emptiness\n {\n relativeDir = \"Scenes\"; // Default relative directory\n }\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n string sceneFileName = string.IsNullOrEmpty(name) ? null : $\"{name}.unity\";\n // Construct full system path correctly: ProjectRoot/Assets/relativeDir/sceneFileName\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Combine with Assets path (Application.dataPath ends in Assets)\n string fullPath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(fullPathDir, sceneFileName);\n // Ensure relativePath always starts with \"Assets/\" and uses forward slashes\n string relativePath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(\"Assets\", relativeDir, sceneFileName).Replace('\\\\', '/');\n\n // Ensure directory exists for 'create'\n if (action == \"create\" && !string.IsNullOrEmpty(fullPathDir))\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route action\n switch (action)\n {\n case \"create\":\n if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(relativePath))\n return Response.Error(\n \"'name' and 'path' parameters are required for 'create' action.\"\n );\n return CreateScene(fullPath, relativePath);\n case \"load\":\n // Loading can be done by path/name or build index\n if (!string.IsNullOrEmpty(relativePath))\n return LoadScene(relativePath);\n else if (buildIndex.HasValue)\n return LoadScene(buildIndex.Value);\n else\n return Response.Error(\n \"Either 'name'/'path' or 'buildIndex' must be provided for 'load' action.\"\n );\n case \"save\":\n // Save current scene, optionally to a new path\n return SaveScene(fullPath, relativePath);\n case \"get_hierarchy\":\n return GetSceneHierarchy();\n case \"get_active\":\n return GetActiveSceneInfo();\n case \"get_build_settings\":\n return GetBuildSettingsScenes();\n // Add cases for modifying build settings, additive loading, unloading etc.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions: create, load, save, get_hierarchy, get_active, get_build_settings.\"\n );\n }\n }\n\n private static object CreateScene(string fullPath, string relativePath)\n {\n if (File.Exists(fullPath))\n {\n return Response.Error($\"Scene already exists at '{relativePath}'.\");\n }\n\n try\n {\n // Create a new empty scene\n Scene newScene = EditorSceneManager.NewScene(\n NewSceneSetup.EmptyScene,\n NewSceneMode.Single\n );\n // Save it to the specified path\n bool saved = EditorSceneManager.SaveScene(newScene, relativePath);\n\n if (saved)\n {\n AssetDatabase.Refresh(); // Ensure Unity sees the new scene file\n return Response.Success(\n $\"Scene '{Path.GetFileName(relativePath)}' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n else\n {\n // If SaveScene fails, it might leave an untitled scene open.\n // Optionally try to close it, but be cautious.\n return Response.Error($\"Failed to save new scene to '{relativePath}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error creating scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(string relativePath)\n {\n if (\n !File.Exists(\n Path.Combine(\n Application.dataPath.Substring(\n 0,\n Application.dataPath.Length - \"Assets\".Length\n ),\n relativePath\n )\n )\n )\n {\n return Response.Error($\"Scene file not found at '{relativePath}'.\");\n }\n\n // Check for unsaved changes in the current scene\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n // Optionally prompt the user or save automatically before loading\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n // Example: bool saveOK = EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();\n // if (!saveOK) return Response.Error(\"Load cancelled by user.\");\n }\n\n try\n {\n EditorSceneManager.OpenScene(relativePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene '{relativePath}' loaded successfully.\",\n new\n {\n path = relativePath,\n name = Path.GetFileNameWithoutExtension(relativePath),\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error loading scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(int buildIndex)\n {\n if (buildIndex < 0 || buildIndex >= SceneManager.sceneCountInBuildSettings)\n {\n return Response.Error(\n $\"Invalid build index: {buildIndex}. Must be between 0 and {SceneManager.sceneCountInBuildSettings - 1}.\"\n );\n }\n\n // Check for unsaved changes\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n }\n\n try\n {\n string scenePath = SceneUtility.GetScenePathByBuildIndex(buildIndex);\n EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene at build index {buildIndex} ('{scenePath}') loaded successfully.\",\n new\n {\n path = scenePath,\n name = Path.GetFileNameWithoutExtension(scenePath),\n buildIndex = buildIndex,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error loading scene with build index {buildIndex}: {e.Message}\"\n );\n }\n }\n\n private static object SaveScene(string fullPath, string relativePath)\n {\n try\n {\n Scene currentScene = EditorSceneManager.GetActiveScene();\n if (!currentScene.IsValid())\n {\n return Response.Error(\"No valid scene is currently active to save.\");\n }\n\n bool saved;\n string finalPath = currentScene.path; // Path where it was last saved or will be saved\n\n if (!string.IsNullOrEmpty(relativePath) && currentScene.path != relativePath)\n {\n // Save As...\n // Ensure directory exists\n string dir = Path.GetDirectoryName(fullPath);\n if (!Directory.Exists(dir))\n Directory.CreateDirectory(dir);\n\n saved = EditorSceneManager.SaveScene(currentScene, relativePath);\n finalPath = relativePath;\n }\n else\n {\n // Save (overwrite existing or save untitled)\n if (string.IsNullOrEmpty(currentScene.path))\n {\n // Scene is untitled, needs a path\n return Response.Error(\n \"Cannot save an untitled scene without providing a 'name' and 'path'. Use Save As functionality.\"\n );\n }\n saved = EditorSceneManager.SaveScene(currentScene);\n }\n\n if (saved)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Scene '{currentScene.name}' saved successfully to '{finalPath}'.\",\n new { path = finalPath, name = currentScene.name }\n );\n }\n else\n {\n return Response.Error($\"Failed to save scene '{currentScene.name}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error saving scene: {e.Message}\");\n }\n }\n\n private static object GetActiveSceneInfo()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid())\n {\n return Response.Error(\"No active scene found.\");\n }\n\n var sceneInfo = new\n {\n name = activeScene.name,\n path = activeScene.path,\n buildIndex = activeScene.buildIndex, // -1 if not in build settings\n isDirty = activeScene.isDirty,\n isLoaded = activeScene.isLoaded,\n rootCount = activeScene.rootCount,\n };\n\n return Response.Success(\"Retrieved active scene information.\", sceneInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active scene info: {e.Message}\");\n }\n }\n\n private static object GetBuildSettingsScenes()\n {\n try\n {\n var scenes = new List();\n for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)\n {\n var scene = EditorBuildSettings.scenes[i];\n scenes.Add(\n new\n {\n path = scene.path,\n guid = scene.guid.ToString(),\n enabled = scene.enabled,\n buildIndex = i, // Actual build index considering only enabled scenes might differ\n }\n );\n }\n return Response.Success(\"Retrieved scenes from Build Settings.\", scenes);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scenes from Build Settings: {e.Message}\");\n }\n }\n\n private static object GetSceneHierarchy()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid() || !activeScene.isLoaded)\n {\n return Response.Error(\n \"No valid and loaded scene is active to get hierarchy from.\"\n );\n }\n\n GameObject[] rootObjects = activeScene.GetRootGameObjects();\n var hierarchy = rootObjects.Select(go => GetGameObjectDataRecursive(go)).ToList();\n\n return Response.Success(\n $\"Retrieved hierarchy for scene '{activeScene.name}'.\",\n hierarchy\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scene hierarchy: {e.Message}\");\n }\n }\n\n /// \n /// Recursively builds a data representation of a GameObject and its children.\n /// \n private static object GetGameObjectDataRecursive(GameObject go)\n {\n if (go == null)\n return null;\n\n var childrenData = new List();\n foreach (Transform child in go.transform)\n {\n childrenData.Add(GetGameObjectDataRecursive(child.gameObject));\n }\n\n var gameObjectData = new Dictionary\n {\n { \"name\", go.name },\n { \"activeSelf\", go.activeSelf },\n { \"activeInHierarchy\", go.activeInHierarchy },\n { \"tag\", go.tag },\n { \"layer\", go.layer },\n { \"isStatic\", go.isStatic },\n { \"instanceID\", go.GetInstanceID() }, // Useful unique identifier\n {\n \"transform\",\n new\n {\n position = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n }, // Euler for simplicity\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n }\n },\n { \"children\", childrenData },\n };\n\n return gameObjectData;\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageEditor.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal; // Required for tag management\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles operations related to controlling and querying the Unity Editor state,\n /// including managing Tags and Layers.\n /// \n public static class ManageEditor\n {\n // Constant for starting user layer index\n private const int FirstUserLayerIndex = 8;\n\n // Constant for total layer count\n private const int TotalLayerCount = 32;\n\n /// \n /// Main handler for editor management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n // Parameters for specific actions\n string tagName = @params[\"tagName\"]?.ToString();\n string layerName = @params[\"layerName\"]?.ToString();\n bool waitForCompletion = @params[\"waitForCompletion\"]?.ToObject() ?? false; // Example - not used everywhere\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Route action\n switch (action)\n {\n // Play Mode Control\n case \"play\":\n try\n {\n if (!EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = true;\n return Response.Success(\"Entered play mode.\");\n }\n return Response.Success(\"Already in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error entering play mode: {e.Message}\");\n }\n case \"pause\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPaused = !EditorApplication.isPaused;\n return Response.Success(\n EditorApplication.isPaused ? \"Game paused.\" : \"Game resumed.\"\n );\n }\n return Response.Error(\"Cannot pause/resume: Not in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error pausing/resuming game: {e.Message}\");\n }\n case \"stop\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = false;\n return Response.Success(\"Exited play mode.\");\n }\n return Response.Success(\"Already stopped (not in play mode).\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error stopping play mode: {e.Message}\");\n }\n\n // Editor State/Info\n case \"get_state\":\n return GetEditorState();\n case \"get_windows\":\n return GetEditorWindows();\n case \"get_active_tool\":\n return GetActiveTool();\n case \"get_selection\":\n return GetSelection();\n case \"set_active_tool\":\n string toolName = @params[\"toolName\"]?.ToString();\n if (string.IsNullOrEmpty(toolName))\n return Response.Error(\"'toolName' parameter required for set_active_tool.\");\n return SetActiveTool(toolName);\n\n // Tag Management\n case \"add_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for add_tag.\");\n return AddTag(tagName);\n case \"remove_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for remove_tag.\");\n return RemoveTag(tagName);\n case \"get_tags\":\n return GetTags(); // Helper to list current tags\n\n // Layer Management\n case \"add_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for add_layer.\");\n return AddLayer(layerName);\n case \"remove_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for remove_layer.\");\n return RemoveLayer(layerName);\n case \"get_layers\":\n return GetLayers(); // Helper to list current layers\n\n // --- Settings (Example) ---\n // case \"set_resolution\":\n // int? width = @params[\"width\"]?.ToObject();\n // int? height = @params[\"height\"]?.ToObject();\n // if (!width.HasValue || !height.HasValue) return Response.Error(\"'width' and 'height' parameters required.\");\n // return SetGameViewResolution(width.Value, height.Value);\n // case \"set_quality\":\n // // Handle string name or int index\n // return SetQualityLevel(@params[\"qualityLevel\"]);\n\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Supported actions include play, pause, stop, get_state, get_windows, get_active_tool, get_selection, set_active_tool, add_tag, remove_tag, get_tags, add_layer, remove_layer, get_layers.\"\n );\n }\n }\n\n // --- Editor State/Info Methods ---\n private static object GetEditorState()\n {\n try\n {\n var state = new\n {\n isPlaying = EditorApplication.isPlaying,\n isPaused = EditorApplication.isPaused,\n isCompiling = EditorApplication.isCompiling,\n isUpdating = EditorApplication.isUpdating,\n applicationPath = EditorApplication.applicationPath,\n applicationContentsPath = EditorApplication.applicationContentsPath,\n timeSinceStartup = EditorApplication.timeSinceStartup,\n };\n return Response.Success(\"Retrieved editor state.\", state);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor state: {e.Message}\");\n }\n }\n\n private static object GetEditorWindows()\n {\n try\n {\n // Get all types deriving from EditorWindow\n var windowTypes = AppDomain\n .CurrentDomain.GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => type.IsSubclassOf(typeof(EditorWindow)))\n .ToList();\n\n var openWindows = new List();\n\n // Find currently open instances\n // Resources.FindObjectsOfTypeAll seems more reliable than GetWindow for finding *all* open windows\n EditorWindow[] allWindows = Resources.FindObjectsOfTypeAll();\n\n foreach (EditorWindow window in allWindows)\n {\n if (window == null)\n continue; // Skip potentially destroyed windows\n\n try\n {\n openWindows.Add(\n new\n {\n title = window.titleContent.text,\n typeName = window.GetType().FullName,\n isFocused = EditorWindow.focusedWindow == window,\n position = new\n {\n x = window.position.x,\n y = window.position.y,\n width = window.position.width,\n height = window.position.height,\n },\n instanceID = window.GetInstanceID(),\n }\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Could not get info for window {window.GetType().Name}: {ex.Message}\"\n );\n }\n }\n\n return Response.Success(\"Retrieved list of open editor windows.\", openWindows);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor windows: {e.Message}\");\n }\n }\n\n private static object GetActiveTool()\n {\n try\n {\n Tool currentTool = UnityEditor.Tools.current;\n string toolName = currentTool.ToString(); // Enum to string\n bool customToolActive = UnityEditor.Tools.current == Tool.Custom; // Check if a custom tool is active\n string activeToolName = customToolActive\n ? EditorTools.GetActiveToolName()\n : toolName; // Get custom name if needed\n\n var toolInfo = new\n {\n activeTool = activeToolName,\n isCustom = customToolActive,\n pivotMode = UnityEditor.Tools.pivotMode.ToString(),\n pivotRotation = UnityEditor.Tools.pivotRotation.ToString(),\n handleRotation = UnityEditor.Tools.handleRotation.eulerAngles, // Euler for simplicity\n handlePosition = UnityEditor.Tools.handlePosition,\n };\n\n return Response.Success(\"Retrieved active tool information.\", toolInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active tool: {e.Message}\");\n }\n }\n\n private static object SetActiveTool(string toolName)\n {\n try\n {\n Tool targetTool;\n if (Enum.TryParse(toolName, true, out targetTool)) // Case-insensitive parse\n {\n // Check if it's a valid built-in tool\n if (targetTool != Tool.None && targetTool <= Tool.Custom) // Tool.Custom is the last standard tool\n {\n UnityEditor.Tools.current = targetTool;\n return Response.Success($\"Set active tool to '{targetTool}'.\");\n }\n else\n {\n return Response.Error(\n $\"Cannot directly set tool to '{toolName}'. It might be None, Custom, or invalid.\"\n );\n }\n }\n else\n {\n // Potentially try activating a custom tool by name here if needed\n // This often requires specific editor scripting knowledge for that tool.\n return Response.Error(\n $\"Could not parse '{toolName}' as a standard Unity Tool (View, Move, Rotate, Scale, Rect, Transform, Custom).\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error setting active tool: {e.Message}\");\n }\n }\n\n private static object GetSelection()\n {\n try\n {\n var selectionInfo = new\n {\n activeObject = Selection.activeObject?.name,\n activeGameObject = Selection.activeGameObject?.name,\n activeTransform = Selection.activeTransform?.name,\n activeInstanceID = Selection.activeInstanceID,\n count = Selection.count,\n objects = Selection\n .objects.Select(obj => new\n {\n name = obj?.name,\n type = obj?.GetType().FullName,\n instanceID = obj?.GetInstanceID(),\n })\n .ToList(),\n gameObjects = Selection\n .gameObjects.Select(go => new\n {\n name = go?.name,\n instanceID = go?.GetInstanceID(),\n })\n .ToList(),\n assetGUIDs = Selection.assetGUIDs, // GUIDs for selected assets in Project view\n };\n\n return Response.Success(\"Retrieved current selection details.\", selectionInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting selection: {e.Message}\");\n }\n }\n\n // --- Tag Management Methods ---\n\n private static object AddTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n\n // Check if tag already exists\n if (InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' already exists.\");\n }\n\n try\n {\n // Add the tag using the internal utility\n InternalEditorUtility.AddTag(tagName);\n // Force save assets to ensure the change persists in the TagManager asset\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' added successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object RemoveTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n if (tagName.Equals(\"Untagged\", StringComparison.OrdinalIgnoreCase))\n return Response.Error(\"Cannot remove the built-in 'Untagged' tag.\");\n\n // Check if tag exists before attempting removal\n if (!InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' does not exist.\");\n }\n\n try\n {\n // Remove the tag using the internal utility\n InternalEditorUtility.RemoveTag(tagName);\n // Force save assets\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' removed successfully.\");\n }\n catch (Exception e)\n {\n // Catch potential issues if the tag is somehow in use or removal fails\n return Response.Error($\"Failed to remove tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object GetTags()\n {\n try\n {\n string[] tags = InternalEditorUtility.tags;\n return Response.Success(\"Retrieved current tags.\", tags);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve tags: {e.Message}\");\n }\n }\n\n // --- Layer Management Methods ---\n\n private static object AddLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Check if layer name already exists (case-insensitive check recommended)\n for (int i = 0; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n return Response.Error($\"Layer '{layerName}' already exists at index {i}.\");\n }\n }\n\n // Find the first empty user layer slot (indices 8 to 31)\n int firstEmptyUserLayer = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (layerSP != null && string.IsNullOrEmpty(layerSP.stringValue))\n {\n firstEmptyUserLayer = i;\n break;\n }\n }\n\n if (firstEmptyUserLayer == -1)\n {\n return Response.Error(\"No empty User Layer slots available (8-31 are full).\");\n }\n\n // Assign the name to the found slot\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n firstEmptyUserLayer\n );\n targetLayerSP.stringValue = layerName;\n // Apply the changes to the TagManager asset\n tagManager.ApplyModifiedProperties();\n // Save assets to make sure it's written to disk\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' added successfully to slot {firstEmptyUserLayer}.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object RemoveLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Find the layer by name (must be user layer)\n int layerIndexToRemove = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++) // Start from user layers\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n // Case-insensitive comparison is safer\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n layerIndexToRemove = i;\n break;\n }\n }\n\n if (layerIndexToRemove == -1)\n {\n return Response.Error($\"User layer '{layerName}' not found.\");\n }\n\n // Clear the name for that index\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n layerIndexToRemove\n );\n targetLayerSP.stringValue = string.Empty; // Set to empty string to remove\n // Apply the changes\n tagManager.ApplyModifiedProperties();\n // Save assets\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' (slot {layerIndexToRemove}) removed successfully.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to remove layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object GetLayers()\n {\n try\n {\n var layers = new Dictionary();\n for (int i = 0; i < TotalLayerCount; i++)\n {\n string layerName = LayerMask.LayerToName(i);\n if (!string.IsNullOrEmpty(layerName)) // Only include layers that have names\n {\n layers.Add(i, layerName);\n }\n }\n return Response.Success(\"Retrieved current named layers.\", layers);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve layers: {e.Message}\");\n }\n }\n\n // --- Helper Methods ---\n\n /// \n /// Gets the SerializedObject for the TagManager asset.\n /// \n private static SerializedObject GetTagManager()\n {\n try\n {\n // Load the TagManager asset from the ProjectSettings folder\n UnityEngine.Object[] tagManagerAssets = AssetDatabase.LoadAllAssetsAtPath(\n \"ProjectSettings/TagManager.asset\"\n );\n if (tagManagerAssets == null || tagManagerAssets.Length == 0)\n {\n Debug.LogError(\"[ManageEditor] TagManager.asset not found in ProjectSettings.\");\n return null;\n }\n // The first object in the asset file should be the TagManager\n return new SerializedObject(tagManagerAssets[0]);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageEditor] Error accessing TagManager.asset: {e.Message}\");\n return null;\n }\n }\n\n // --- Example Implementations for Settings ---\n /*\n private static object SetGameViewResolution(int width, int height) { ... }\n private static object SetQualityLevel(JToken qualityLevelToken) { ... }\n */\n }\n\n // Helper class to get custom tool names (remains the same)\n internal static class EditorTools\n {\n public static string GetActiveToolName()\n {\n // This is a placeholder. Real implementation depends on how custom tools\n // are registered and tracked in the specific Unity project setup.\n // It might involve checking static variables, calling methods on specific tool managers, etc.\n if (UnityEditor.Tools.current == Tool.Custom)\n {\n // Example: Check a known custom tool manager\n // if (MyCustomToolManager.IsActive) return MyCustomToolManager.ActiveToolName;\n return \"Unknown Custom Tool\";\n }\n return UnityEditor.Tools.current.ToString();\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScript.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\n#if USE_ROSLYN\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\n#endif\n\n#if UNITY_EDITOR\nusing UnityEditor.Compilation;\n#endif\n\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for C# scripts within the Unity project.\n /// \n /// ROSLYN INSTALLATION GUIDE:\n /// To enable advanced syntax validation with Roslyn compiler services:\n /// \n /// 1. Install Microsoft.CodeAnalysis.CSharp NuGet package:\n /// - Open Package Manager in Unity\n /// - Follow the instruction on https://github.com/GlitchEnzo/NuGetForUnity\n /// \n /// 2. Open NuGet Package Manager and Install Microsoft.CodeAnalysis.CSharp:\n /// \n /// 3. Alternative: Manual DLL installation:\n /// - Download Microsoft.CodeAnalysis.CSharp.dll and dependencies\n /// - Place in Assets/Plugins/ folder\n /// - Ensure .NET compatibility settings are correct\n /// \n /// 4. Define USE_ROSLYN symbol:\n /// - Go to Player Settings > Scripting Define Symbols\n /// - Add \"USE_ROSLYN\" to enable Roslyn-based validation\n /// \n /// 5. Restart Unity after installation\n /// \n /// Note: Without Roslyn, the system falls back to basic structural validation.\n /// Roslyn provides full C# compiler diagnostics with line numbers and detailed error messages.\n /// \n public static class ManageScript\n {\n /// \n /// Main handler for script management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode script contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n string scriptType = @params[\"scriptType\"]?.ToString(); // For templates/validation\n string namespaceName = @params[\"namespace\"]?.ToString(); // For organizing code\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid script name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Scripts\" if path is not provided\n string relativeDir = path ?? \"Scripts\"; // Default to \"Scripts\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Scripts\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string scriptFileName = $\"{name}.cs\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Application.dataPath ends in \"Assets\"\n string fullPath = Path.Combine(fullPathDir, scriptFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, scriptFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateScript(\n fullPath,\n relativePath,\n name,\n contents,\n scriptType,\n namespaceName\n );\n case \"read\":\n return ReadScript(fullPath, relativePath);\n case \"update\":\n return UpdateScript(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteScript(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents,\n string scriptType,\n string namespaceName\n )\n {\n // Check if script already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultScriptContent(name, scriptType, namespaceName);\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block creation\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new script\n return Response.Success(\n $\"Script '{name}.cs' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script not found at '{relativePath}'. Use 'create' action to add a new script.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block update\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath); // Re-import to reflect changes\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{name}.cs' updated successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'. Cannot delete.\");\n }\n\n try\n {\n // Use AssetDatabase.MoveAssetToTrash for safer deletion (allows undo)\n bool deleted = AssetDatabase.MoveAssetToTrash(relativePath);\n if (deleted)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' moved to trash successfully.\"\n );\n }\n else\n {\n // Fallback or error if MoveAssetToTrash fails\n return Response.Error(\n $\"Failed to move script '{relativePath}' to trash. It might be locked or in use.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting script '{relativePath}': {e.Message}\");\n }\n }\n\n /// \n /// Generates basic C# script content based on name and type.\n /// \n private static string GenerateDefaultScriptContent(\n string name,\n string scriptType,\n string namespaceName\n )\n {\n string usingStatements = \"using UnityEngine;\\nusing System.Collections;\\n\";\n string classDeclaration;\n string body =\n \"\\n // Use this for initialization\\n void Start() {\\n\\n }\\n\\n // Update is called once per frame\\n void Update() {\\n\\n }\\n\";\n\n string baseClass = \"\";\n if (!string.IsNullOrEmpty(scriptType))\n {\n if (scriptType.Equals(\"MonoBehaviour\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : MonoBehaviour\";\n else if (scriptType.Equals(\"ScriptableObject\", StringComparison.OrdinalIgnoreCase))\n {\n baseClass = \" : ScriptableObject\";\n body = \"\"; // ScriptableObjects don't usually need Start/Update\n }\n else if (\n scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase)\n || scriptType.Equals(\"EditorWindow\", StringComparison.OrdinalIgnoreCase)\n )\n {\n usingStatements += \"using UnityEditor;\\n\";\n if (scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : Editor\";\n else\n baseClass = \" : EditorWindow\";\n body = \"\"; // Editor scripts have different structures\n }\n // Add more types as needed\n }\n\n classDeclaration = $\"public class {name}{baseClass}\";\n\n string fullContent = $\"{usingStatements}\\n\";\n bool useNamespace = !string.IsNullOrEmpty(namespaceName);\n\n if (useNamespace)\n {\n fullContent += $\"namespace {namespaceName}\\n{{\\n\";\n // Indent class and body if using namespace\n classDeclaration = \" \" + classDeclaration;\n body = string.Join(\"\\n\", body.Split('\\n').Select(line => \" \" + line));\n }\n\n fullContent += $\"{classDeclaration}\\n{{\\n{body}\\n}}\";\n\n if (useNamespace)\n {\n fullContent += \"\\n}\"; // Close namespace\n }\n\n return fullContent.Trim() + \"\\n\"; // Ensure a trailing newline\n }\n\n /// \n /// Gets the validation level from the GUI settings\n /// \n private static ValidationLevel GetValidationLevelFromGUI()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel.ToLower() switch\n {\n \"basic\" => ValidationLevel.Basic,\n \"standard\" => ValidationLevel.Standard,\n \"comprehensive\" => ValidationLevel.Comprehensive,\n \"strict\" => ValidationLevel.Strict,\n _ => ValidationLevel.Standard // Default fallback\n };\n }\n\n /// \n /// Validates C# script syntax using multiple validation layers.\n /// \n private static bool ValidateScriptSyntax(string contents)\n {\n return ValidateScriptSyntax(contents, ValidationLevel.Standard, out _);\n }\n\n /// \n /// Advanced syntax validation with detailed diagnostics and configurable strictness.\n /// \n private static bool ValidateScriptSyntax(string contents, ValidationLevel level, out string[] errors)\n {\n var errorList = new System.Collections.Generic.List();\n errors = null;\n\n if (string.IsNullOrEmpty(contents))\n {\n return true; // Empty content is valid\n }\n\n // Basic structural validation\n if (!ValidateBasicStructure(contents, errorList))\n {\n errors = errorList.ToArray();\n return false;\n }\n\n#if USE_ROSLYN\n // Advanced Roslyn-based validation\n if (!ValidateScriptSyntaxRoslyn(contents, level, errorList))\n {\n errors = errorList.ToArray();\n return level != ValidationLevel.Standard; //TODO: Allow standard to run roslyn right now, might formalize it in the future\n }\n#endif\n\n // Unity-specific validation\n if (level >= ValidationLevel.Standard)\n {\n ValidateScriptSyntaxUnity(contents, errorList);\n }\n\n // Semantic analysis for common issues\n if (level >= ValidationLevel.Comprehensive)\n {\n ValidateSemanticRules(contents, errorList);\n }\n\n#if USE_ROSLYN\n // Full semantic compilation validation for Strict level\n if (level == ValidationLevel.Strict)\n {\n if (!ValidateScriptSemantics(contents, errorList))\n {\n errors = errorList.ToArray();\n return false; // Strict level fails on any semantic errors\n }\n }\n#endif\n\n errors = errorList.ToArray();\n return errorList.Count == 0 || (level != ValidationLevel.Strict && !errorList.Any(e => e.StartsWith(\"ERROR:\")));\n }\n\n /// \n /// Validation strictness levels\n /// \n private enum ValidationLevel\n {\n Basic, // Only syntax errors\n Standard, // Syntax + Unity best practices\n Comprehensive, // All checks + semantic analysis\n Strict // Treat all issues as errors\n }\n\n /// \n /// Validates basic code structure (braces, quotes, comments)\n /// \n private static bool ValidateBasicStructure(string contents, System.Collections.Generic.List errors)\n {\n bool isValid = true;\n int braceBalance = 0;\n int parenBalance = 0;\n int bracketBalance = 0;\n bool inStringLiteral = false;\n bool inCharLiteral = false;\n bool inSingleLineComment = false;\n bool inMultiLineComment = false;\n bool escaped = false;\n\n for (int i = 0; i < contents.Length; i++)\n {\n char c = contents[i];\n char next = i + 1 < contents.Length ? contents[i + 1] : '\\0';\n\n // Handle escape sequences\n if (escaped)\n {\n escaped = false;\n continue;\n }\n\n if (c == '\\\\' && (inStringLiteral || inCharLiteral))\n {\n escaped = true;\n continue;\n }\n\n // Handle comments\n if (!inStringLiteral && !inCharLiteral)\n {\n if (c == '/' && next == '/' && !inMultiLineComment)\n {\n inSingleLineComment = true;\n continue;\n }\n if (c == '/' && next == '*' && !inSingleLineComment)\n {\n inMultiLineComment = true;\n i++; // Skip next character\n continue;\n }\n if (c == '*' && next == '/' && inMultiLineComment)\n {\n inMultiLineComment = false;\n i++; // Skip next character\n continue;\n }\n }\n\n if (c == '\\n')\n {\n inSingleLineComment = false;\n continue;\n }\n\n if (inSingleLineComment || inMultiLineComment)\n continue;\n\n // Handle string and character literals\n if (c == '\"' && !inCharLiteral)\n {\n inStringLiteral = !inStringLiteral;\n continue;\n }\n if (c == '\\'' && !inStringLiteral)\n {\n inCharLiteral = !inCharLiteral;\n continue;\n }\n\n if (inStringLiteral || inCharLiteral)\n continue;\n\n // Count brackets and braces\n switch (c)\n {\n case '{': braceBalance++; break;\n case '}': braceBalance--; break;\n case '(': parenBalance++; break;\n case ')': parenBalance--; break;\n case '[': bracketBalance++; break;\n case ']': bracketBalance--; break;\n }\n\n // Check for negative balances (closing without opening)\n if (braceBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing brace '}'\");\n isValid = false;\n }\n if (parenBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing parenthesis ')'\");\n isValid = false;\n }\n if (bracketBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing bracket ']'\");\n isValid = false;\n }\n }\n\n // Check final balances\n if (braceBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced braces (difference: {braceBalance})\");\n isValid = false;\n }\n if (parenBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced parentheses (difference: {parenBalance})\");\n isValid = false;\n }\n if (bracketBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced brackets (difference: {bracketBalance})\");\n isValid = false;\n }\n if (inStringLiteral)\n {\n errors.Add(\"ERROR: Unterminated string literal\");\n isValid = false;\n }\n if (inCharLiteral)\n {\n errors.Add(\"ERROR: Unterminated character literal\");\n isValid = false;\n }\n if (inMultiLineComment)\n {\n errors.Add(\"WARNING: Unterminated multi-line comment\");\n }\n\n return isValid;\n }\n\n#if USE_ROSLYN\n /// \n /// Cached compilation references for performance\n /// \n private static System.Collections.Generic.List _cachedReferences = null;\n private static DateTime _cacheTime = DateTime.MinValue;\n private static readonly TimeSpan CacheExpiry = TimeSpan.FromMinutes(5);\n\n /// \n /// Validates syntax using Roslyn compiler services\n /// \n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n try\n {\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n var diagnostics = syntaxTree.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n string severity = diagnostic.Severity.ToString().ToUpper();\n string message = $\"{severity}: {diagnostic.GetMessage()}\";\n \n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n }\n \n // Include warnings in comprehensive mode\n if (level >= ValidationLevel.Standard || diagnostic.Severity == DiagnosticSeverity.Error) //Also use Standard for now\n {\n var location = diagnostic.Location.GetLineSpan();\n if (location.IsValid)\n {\n message += $\" (Line {location.StartLinePosition.Line + 1})\";\n }\n errors.Add(message);\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Roslyn validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Validates script semantics using full compilation context to catch namespace, type, and method resolution errors\n /// \n private static bool ValidateScriptSemantics(string contents, System.Collections.Generic.List errors)\n {\n try\n {\n // Get compilation references with caching\n var references = GetCompilationReferences();\n if (references == null || references.Count == 0)\n {\n errors.Add(\"WARNING: Could not load compilation references for semantic validation\");\n return true; // Don't fail if we can't get references\n }\n\n // Create syntax tree\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n\n // Create compilation with full context\n var compilation = CSharpCompilation.Create(\n \"TempValidation\",\n new[] { syntaxTree },\n references,\n new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)\n );\n\n // Get semantic diagnostics - this catches all the issues you mentioned!\n var diagnostics = compilation.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n // Include diagnostic ID for better error identification\n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"ERROR: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n else if (diagnostic.Severity == DiagnosticSeverity.Warning)\n {\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"WARNING: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Semantic validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets compilation references with caching for performance\n /// \n private static System.Collections.Generic.List GetCompilationReferences()\n {\n // Check cache validity\n if (_cachedReferences != null && DateTime.Now - _cacheTime < CacheExpiry)\n {\n return _cachedReferences;\n }\n\n try\n {\n var references = new System.Collections.Generic.List();\n\n // Core .NET assemblies\n references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); // mscorlib/System.Private.CoreLib\n references.Add(MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location)); // System.Linq\n references.Add(MetadataReference.CreateFromFile(typeof(System.Collections.Generic.List<>).Assembly.Location)); // System.Collections\n\n // Unity assemblies\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEngine.Debug).Assembly.Location)); // UnityEngine\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEngine assembly: {ex.Message}\");\n }\n\n#if UNITY_EDITOR\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEditor.Editor).Assembly.Location)); // UnityEditor\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEditor assembly: {ex.Message}\");\n }\n\n // Get Unity project assemblies\n try\n {\n var assemblies = CompilationPipeline.GetAssemblies();\n foreach (var assembly in assemblies)\n {\n if (File.Exists(assembly.outputPath))\n {\n references.Add(MetadataReference.CreateFromFile(assembly.outputPath));\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load Unity project assemblies: {ex.Message}\");\n }\n#endif\n\n // Cache the results\n _cachedReferences = references;\n _cacheTime = DateTime.Now;\n\n return references;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to get compilation references: {ex.Message}\");\n return new System.Collections.Generic.List();\n }\n }\n#else\n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n // Fallback when Roslyn is not available\n return true;\n }\n#endif\n\n /// \n /// Validates Unity-specific coding rules and best practices\n /// //TODO: Naive Unity Checks and not really yield any results, need to be improved\n /// \n private static void ValidateScriptSyntaxUnity(string contents, System.Collections.Generic.List errors)\n {\n // Check for common Unity anti-patterns\n if (contents.Contains(\"FindObjectOfType\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: FindObjectOfType in Update() can cause performance issues\");\n }\n\n if (contents.Contains(\"GameObject.Find\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: GameObject.Find in Update() can cause performance issues\");\n }\n\n // Check for proper MonoBehaviour usage\n if (contents.Contains(\": MonoBehaviour\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: MonoBehaviour requires 'using UnityEngine;'\");\n }\n\n // Check for SerializeField usage\n if (contents.Contains(\"[SerializeField]\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: SerializeField requires 'using UnityEngine;'\");\n }\n\n // Check for proper coroutine usage\n if (contents.Contains(\"StartCoroutine\") && !contents.Contains(\"IEnumerator\"))\n {\n errors.Add(\"WARNING: StartCoroutine typically requires IEnumerator methods\");\n }\n\n // Check for Update without FixedUpdate for physics\n if (contents.Contains(\"Rigidbody\") && contents.Contains(\"Update()\") && !contents.Contains(\"FixedUpdate()\"))\n {\n errors.Add(\"WARNING: Consider using FixedUpdate() for Rigidbody operations\");\n }\n\n // Check for missing null checks on Unity objects\n if (contents.Contains(\"GetComponent<\") && !contents.Contains(\"!= null\"))\n {\n errors.Add(\"WARNING: Consider null checking GetComponent results\");\n }\n\n // Check for proper event function signatures\n if (contents.Contains(\"void Start(\") && !contents.Contains(\"void Start()\"))\n {\n errors.Add(\"WARNING: Start() should not have parameters\");\n }\n\n if (contents.Contains(\"void Update(\") && !contents.Contains(\"void Update()\"))\n {\n errors.Add(\"WARNING: Update() should not have parameters\");\n }\n\n // Check for inefficient string operations\n if (contents.Contains(\"Update()\") && contents.Contains(\"\\\"\") && contents.Contains(\"+\"))\n {\n errors.Add(\"WARNING: String concatenation in Update() can cause garbage collection issues\");\n }\n }\n\n /// \n /// Validates semantic rules and common coding issues\n /// \n private static void ValidateSemanticRules(string contents, System.Collections.Generic.List errors)\n {\n // Check for potential memory leaks\n if (contents.Contains(\"new \") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: Creating objects in Update() may cause memory issues\");\n }\n\n // Check for magic numbers\n var magicNumberPattern = new Regex(@\"\\b\\d+\\.?\\d*f?\\b(?!\\s*[;})\\]])\");\n var matches = magicNumberPattern.Matches(contents);\n if (matches.Count > 5)\n {\n errors.Add(\"WARNING: Consider using named constants instead of magic numbers\");\n }\n\n // Check for long methods (simple line count check)\n var methodPattern = new Regex(@\"(public|private|protected|internal)?\\s*(static)?\\s*\\w+\\s+\\w+\\s*\\([^)]*\\)\\s*{\");\n var methodMatches = methodPattern.Matches(contents);\n foreach (Match match in methodMatches)\n {\n int startIndex = match.Index;\n int braceCount = 0;\n int lineCount = 0;\n bool inMethod = false;\n\n for (int i = startIndex; i < contents.Length; i++)\n {\n if (contents[i] == '{')\n {\n braceCount++;\n inMethod = true;\n }\n else if (contents[i] == '}')\n {\n braceCount--;\n if (braceCount == 0 && inMethod)\n break;\n }\n else if (contents[i] == '\\n' && inMethod)\n {\n lineCount++;\n }\n }\n\n if (lineCount > 50)\n {\n errors.Add(\"WARNING: Method is very long, consider breaking it into smaller methods\");\n break; // Only report once\n }\n }\n\n // Check for proper exception handling\n if (contents.Contains(\"catch\") && contents.Contains(\"catch()\"))\n {\n errors.Add(\"WARNING: Empty catch blocks should be avoided\");\n }\n\n // Check for proper async/await usage\n if (contents.Contains(\"async \") && !contents.Contains(\"await\"))\n {\n errors.Add(\"WARNING: Async method should contain await or return Task\");\n }\n\n // Check for hardcoded tags and layers\n if (contents.Contains(\"\\\"Player\\\"\") || contents.Contains(\"\\\"Enemy\\\"\"))\n {\n errors.Add(\"WARNING: Consider using constants for tags instead of hardcoded strings\");\n }\n }\n\n //TODO: A easier way for users to update incorrect scripts (now duplicated with the updateScript method and need to also update server side, put aside for now)\n /// \n /// Public method to validate script syntax with configurable validation level\n /// Returns detailed validation results including errors and warnings\n /// \n // public static object ValidateScript(JObject @params)\n // {\n // string contents = @params[\"contents\"]?.ToString();\n // string validationLevel = @params[\"validationLevel\"]?.ToString() ?? \"standard\";\n\n // if (string.IsNullOrEmpty(contents))\n // {\n // return Response.Error(\"Contents parameter is required for validation.\");\n // }\n\n // // Parse validation level\n // ValidationLevel level = ValidationLevel.Standard;\n // switch (validationLevel.ToLower())\n // {\n // case \"basic\": level = ValidationLevel.Basic; break;\n // case \"standard\": level = ValidationLevel.Standard; break;\n // case \"comprehensive\": level = ValidationLevel.Comprehensive; break;\n // case \"strict\": level = ValidationLevel.Strict; break;\n // default:\n // return Response.Error($\"Invalid validation level: '{validationLevel}'. Valid levels are: basic, standard, comprehensive, strict.\");\n // }\n\n // // Perform validation\n // bool isValid = ValidateScriptSyntax(contents, level, out string[] validationErrors);\n\n // var errors = validationErrors?.Where(e => e.StartsWith(\"ERROR:\")).ToArray() ?? new string[0];\n // var warnings = validationErrors?.Where(e => e.StartsWith(\"WARNING:\")).ToArray() ?? new string[0];\n\n // var result = new\n // {\n // isValid = isValid,\n // validationLevel = validationLevel,\n // errorCount = errors.Length,\n // warningCount = warnings.Length,\n // errors = errors,\n // warnings = warnings,\n // summary = isValid \n // ? (warnings.Length > 0 ? $\"Validation passed with {warnings.Length} warnings\" : \"Validation passed with no issues\")\n // : $\"Validation failed with {errors.Length} errors and {warnings.Length} warnings\"\n // };\n\n // if (isValid)\n // {\n // return Response.Success(\"Script validation completed successfully.\", result);\n // }\n // else\n // {\n // return Response.Error(\"Script validation failed.\", result);\n // }\n // }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/UnityMcpBridge.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\nusing UnityMcpBridge.Editor.Tools;\n\nnamespace UnityMcpBridge.Editor\n{\n [InitializeOnLoad]\n public static partial class UnityMcpBridge\n {\n private static TcpListener listener;\n private static bool isRunning = false;\n private static readonly object lockObj = new();\n private static Dictionary<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > commandQueue = new();\n private static readonly int unityPort = 6400; // Hardcoded port\n\n public static bool IsRunning => isRunning;\n\n public static bool FolderExists(string path)\n {\n if (string.IsNullOrEmpty(path))\n {\n return false;\n }\n\n if (path.Equals(\"Assets\", StringComparison.OrdinalIgnoreCase))\n {\n return true;\n }\n\n string fullPath = Path.Combine(\n Application.dataPath,\n path.StartsWith(\"Assets/\") ? path[7..] : path\n );\n return Directory.Exists(fullPath);\n }\n\n static UnityMcpBridge()\n {\n Start();\n EditorApplication.quitting += Stop;\n }\n\n public static void Start()\n {\n Stop();\n\n try\n {\n ServerInstaller.EnsureServerInstalled();\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure UnityMcpServer is installed: {ex.Message}\");\n }\n\n if (isRunning)\n {\n return;\n }\n\n try\n {\n listener = new TcpListener(IPAddress.Loopback, unityPort);\n listener.Start();\n isRunning = true;\n Debug.Log($\"UnityMcpBridge started on port {unityPort}.\");\n // Assuming ListenerLoop and ProcessCommands are defined elsewhere\n Task.Run(ListenerLoop);\n EditorApplication.update += ProcessCommands;\n }\n catch (SocketException ex)\n {\n if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)\n {\n Debug.LogError(\n $\"Port {unityPort} is already in use. Ensure no other instances are running or change the port.\"\n );\n }\n else\n {\n Debug.LogError($\"Failed to start TCP listener: {ex.Message}\");\n }\n }\n }\n\n public static void Stop()\n {\n if (!isRunning)\n {\n return;\n }\n\n try\n {\n listener?.Stop();\n listener = null;\n isRunning = false;\n EditorApplication.update -= ProcessCommands;\n Debug.Log(\"UnityMcpBridge stopped.\");\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error stopping UnityMcpBridge: {ex.Message}\");\n }\n }\n\n private static async Task ListenerLoop()\n {\n while (isRunning)\n {\n try\n {\n TcpClient client = await listener.AcceptTcpClientAsync();\n // Enable basic socket keepalive\n client.Client.SetSocketOption(\n SocketOptionLevel.Socket,\n SocketOptionName.KeepAlive,\n true\n );\n\n // Set longer receive timeout to prevent quick disconnections\n client.ReceiveTimeout = 60000; // 60 seconds\n\n // Fire and forget each client connection\n _ = HandleClientAsync(client);\n }\n catch (Exception ex)\n {\n if (isRunning)\n {\n Debug.LogError($\"Listener error: {ex.Message}\");\n }\n }\n }\n }\n\n private static async Task HandleClientAsync(TcpClient client)\n {\n using (client)\n using (NetworkStream stream = client.GetStream())\n {\n byte[] buffer = new byte[8192];\n while (isRunning)\n {\n try\n {\n int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);\n if (bytesRead == 0)\n {\n break; // Client disconnected\n }\n\n string commandText = System.Text.Encoding.UTF8.GetString(\n buffer,\n 0,\n bytesRead\n );\n string commandId = Guid.NewGuid().ToString();\n TaskCompletionSource tcs = new();\n\n // Special handling for ping command to avoid JSON parsing\n if (commandText.Trim() == \"ping\")\n {\n // Direct response to ping without going through JSON parsing\n byte[] pingResponseBytes = System.Text.Encoding.UTF8.GetBytes(\n /*lang=json,strict*/\n \"{\\\"status\\\":\\\"success\\\",\\\"result\\\":{\\\"message\\\":\\\"pong\\\"}}\"\n );\n await stream.WriteAsync(pingResponseBytes, 0, pingResponseBytes.Length);\n continue;\n }\n\n lock (lockObj)\n {\n commandQueue[commandId] = (commandText, tcs);\n }\n\n string response = await tcs.Task;\n byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);\n await stream.WriteAsync(responseBytes, 0, responseBytes.Length);\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Client handler error: {ex.Message}\");\n break;\n }\n }\n }\n }\n\n private static void ProcessCommands()\n {\n List processedIds = new();\n lock (lockObj)\n {\n foreach (\n KeyValuePair<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > kvp in commandQueue.ToList()\n )\n {\n string id = kvp.Key;\n string commandText = kvp.Value.commandJson;\n TaskCompletionSource tcs = kvp.Value.tcs;\n\n try\n {\n // Special case handling\n if (string.IsNullOrEmpty(commandText))\n {\n var emptyResponse = new\n {\n status = \"error\",\n error = \"Empty command received\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(emptyResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Trim the command text to remove any whitespace\n commandText = commandText.Trim();\n\n // Non-JSON direct commands handling (like ping)\n if (commandText == \"ping\")\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n tcs.SetResult(JsonConvert.SerializeObject(pingResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Check if the command is valid JSON before attempting to deserialize\n if (!IsValidJson(commandText))\n {\n var invalidJsonResponse = new\n {\n status = \"error\",\n error = \"Invalid JSON format\",\n receivedText = commandText.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n tcs.SetResult(JsonConvert.SerializeObject(invalidJsonResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Normal JSON command processing\n Command command = JsonConvert.DeserializeObject(commandText);\n \n if (command == null)\n {\n var nullCommandResponse = new\n {\n status = \"error\",\n error = \"Command deserialized to null\",\n details = \"The command was valid JSON but could not be deserialized to a Command object\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(nullCommandResponse));\n }\n else\n {\n string responseJson = ExecuteCommand(command);\n tcs.SetResult(responseJson);\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error processing command: {ex.Message}\\n{ex.StackTrace}\");\n\n var response = new\n {\n status = \"error\",\n error = ex.Message,\n commandType = \"Unknown (error during processing)\",\n receivedText = commandText?.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n string responseJson = JsonConvert.SerializeObject(response);\n tcs.SetResult(responseJson);\n }\n\n processedIds.Add(id);\n }\n\n foreach (string id in processedIds)\n {\n commandQueue.Remove(id);\n }\n }\n }\n\n // Helper method to check if a string is valid JSON\n private static bool IsValidJson(string text)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n return false;\n }\n\n text = text.Trim();\n if (\n (text.StartsWith(\"{\") && text.EndsWith(\"}\"))\n || // Object\n (text.StartsWith(\"[\") && text.EndsWith(\"]\"))\n ) // Array\n {\n try\n {\n JToken.Parse(text);\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n return false;\n }\n\n private static string ExecuteCommand(Command command)\n {\n try\n {\n if (string.IsNullOrEmpty(command.type))\n {\n var errorResponse = new\n {\n status = \"error\",\n error = \"Command type cannot be empty\",\n details = \"A valid command type is required for processing\",\n };\n return JsonConvert.SerializeObject(errorResponse);\n }\n\n // Handle ping command for connection verification\n if (command.type.Equals(\"ping\", StringComparison.OrdinalIgnoreCase))\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n return JsonConvert.SerializeObject(pingResponse);\n }\n\n // Use JObject for parameters as the new handlers likely expect this\n JObject paramsObject = command.@params ?? new JObject();\n\n // Route command based on the new tool structure from the refactor plan\n object result = command.type switch\n {\n // Maps the command type (tool name) to the corresponding handler's static HandleCommand method\n // Assumes each handler class has a static method named 'HandleCommand' that takes JObject parameters\n \"manage_script\" => ManageScript.HandleCommand(paramsObject),\n \"manage_scene\" => ManageScene.HandleCommand(paramsObject),\n \"manage_editor\" => ManageEditor.HandleCommand(paramsObject),\n \"manage_gameobject\" => ManageGameObject.HandleCommand(paramsObject),\n \"manage_asset\" => ManageAsset.HandleCommand(paramsObject),\n \"manage_shader\" => ManageShader.HandleCommand(paramsObject),\n \"read_console\" => ReadConsole.HandleCommand(paramsObject),\n \"execute_menu_item\" => ExecuteMenuItem.HandleCommand(paramsObject),\n _ => throw new ArgumentException(\n $\"Unknown or unsupported command type: {command.type}\"\n ),\n };\n\n // Standard success response format\n var response = new { status = \"success\", result };\n return JsonConvert.SerializeObject(response);\n }\n catch (Exception ex)\n {\n // Log the detailed error in Unity for debugging\n Debug.LogError(\n $\"Error executing command '{command?.type ?? \"Unknown\"}': {ex.Message}\\n{ex.StackTrace}\"\n );\n\n // Standard error response format\n var response = new\n {\n status = \"error\",\n error = ex.Message, // Provide the specific error message\n command = command?.type ?? \"Unknown\", // Include the command type if available\n stackTrace = ex.StackTrace, // Include stack trace for detailed debugging\n paramsSummary = command?.@params != null\n ? GetParamsSummary(command.@params)\n : \"No parameters\", // Summarize parameters for context\n };\n return JsonConvert.SerializeObject(response);\n }\n }\n\n // Helper method to get a summary of parameters for error reporting\n private static string GetParamsSummary(JObject @params)\n {\n try\n {\n return @params == null || !@params.HasValues\n ? \"No parameters\"\n : string.Join(\n \", \",\n @params\n .Properties()\n .Select(static p =>\n $\"{p.Name}: {p.Value?.ToString()?[..Math.Min(20, p.Value?.ToString()?.Length ?? 0)]}\"\n )\n );\n }\n catch\n {\n return \"Could not summarize parameters\";\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Windows/UnityMcpEditorWindow.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing Newtonsoft.Json;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Data;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class UnityMcpEditorWindow : EditorWindow\n {\n private bool isUnityBridgeRunning = false;\n private Vector2 scrollPosition;\n private string pythonServerInstallationStatus = \"Not Installed\";\n private Color pythonServerInstallationStatusColor = Color.red;\n private const int unityPort = 6400; // Hardcoded Unity port\n private const int mcpPort = 6500; // Hardcoded MCP port\n private readonly McpClients mcpClients = new();\n \n // Script validation settings\n private int validationLevelIndex = 1; // Default to Standard\n private readonly string[] validationLevelOptions = new string[]\n {\n \"Basic - Only syntax checks\",\n \"Standard - Syntax + Unity practices\", \n \"Comprehensive - All checks + semantic analysis\",\n \"Strict - Full semantic validation (requires Roslyn)\"\n };\n \n // UI state\n private int selectedClientIndex = 0;\n\n [MenuItem(\"Window/Unity MCP\")]\n public static void ShowWindow()\n {\n GetWindow(\"MCP Editor\");\n }\n\n private void OnEnable()\n {\n UpdatePythonServerInstallationStatus();\n\n isUnityBridgeRunning = UnityMcpBridge.IsRunning;\n foreach (McpClient mcpClient in mcpClients.clients)\n {\n CheckMcpConfiguration(mcpClient);\n }\n \n // Load validation level setting\n LoadValidationLevelSetting();\n }\n\n private Color GetStatusColor(McpStatus status)\n {\n // Return appropriate color based on the status enum\n return status switch\n {\n McpStatus.Configured => Color.green,\n McpStatus.Running => Color.green,\n McpStatus.Connected => Color.green,\n McpStatus.IncorrectPath => Color.yellow,\n McpStatus.CommunicationError => Color.yellow,\n McpStatus.NoResponse => Color.yellow,\n _ => Color.red, // Default to red for error states or not configured\n };\n }\n\n private void UpdatePythonServerInstallationStatus()\n {\n string serverPath = ServerInstaller.GetServerPath();\n\n if (File.Exists(Path.Combine(serverPath, \"server.py\")))\n {\n string installedVersion = ServerInstaller.GetInstalledVersion();\n string latestVersion = ServerInstaller.GetLatestVersion();\n\n if (ServerInstaller.IsNewerVersion(latestVersion, installedVersion))\n {\n pythonServerInstallationStatus = \"Newer Version Available\";\n pythonServerInstallationStatusColor = Color.yellow;\n }\n else\n {\n pythonServerInstallationStatus = \"Up to Date\";\n pythonServerInstallationStatusColor = Color.green;\n }\n }\n else\n {\n pythonServerInstallationStatus = \"Not Installed\";\n pythonServerInstallationStatusColor = Color.red;\n }\n }\n\n\n private void DrawStatusDot(Rect statusRect, Color statusColor, float size = 12)\n {\n float offsetX = (statusRect.width - size) / 2;\n float offsetY = (statusRect.height - size) / 2;\n Rect dotRect = new(statusRect.x + offsetX, statusRect.y + offsetY, size, size);\n Vector3 center = new(\n dotRect.x + (dotRect.width / 2),\n dotRect.y + (dotRect.height / 2),\n 0\n );\n float radius = size / 2;\n\n // Draw the main dot\n Handles.color = statusColor;\n Handles.DrawSolidDisc(center, Vector3.forward, radius);\n\n // Draw the border\n Color borderColor = new(\n statusColor.r * 0.7f,\n statusColor.g * 0.7f,\n statusColor.b * 0.7f\n );\n Handles.color = borderColor;\n Handles.DrawWireDisc(center, Vector3.forward, radius);\n }\n\n private void OnGUI()\n {\n scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);\n\n // Header\n DrawHeader();\n \n // Main sections in a more compact layout\n EditorGUILayout.BeginHorizontal();\n \n // Left column - Status and Bridge\n EditorGUILayout.BeginVertical(GUILayout.Width(position.width * 0.5f));\n DrawServerStatusSection();\n EditorGUILayout.Space(5);\n DrawBridgeSection();\n EditorGUILayout.EndVertical();\n \n // Right column - Validation Settings\n EditorGUILayout.BeginVertical();\n DrawValidationSection();\n EditorGUILayout.EndVertical();\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Unified MCP Client Configuration\n DrawUnifiedClientConfiguration();\n\n EditorGUILayout.EndScrollView();\n }\n\n private void DrawHeader()\n {\n EditorGUILayout.Space(15);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 40);\n EditorGUI.DrawRect(titleRect, new Color(0.2f, 0.2f, 0.2f, 0.1f));\n \n GUIStyle titleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 16,\n alignment = TextAnchor.MiddleLeft\n };\n \n GUI.Label(\n new Rect(titleRect.x + 15, titleRect.y + 8, titleRect.width - 30, titleRect.height),\n \"Unity MCP Editor\",\n titleStyle\n );\n EditorGUILayout.Space(15);\n }\n\n private void DrawServerStatusSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Server Status\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(statusRect, pythonServerInstallationStatusColor, 16);\n \n GUIStyle statusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(pythonServerInstallationStatus, statusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(5);\n GUIStyle portStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 11\n };\n EditorGUILayout.LabelField($\"Ports: Unity {unityPort}, MCP {mcpPort}\", portStyle);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawBridgeSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Unity Bridge\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUILayout.BeginHorizontal();\n Color bridgeColor = isUnityBridgeRunning ? Color.green : Color.red;\n Rect bridgeStatusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(bridgeStatusRect, bridgeColor, 16);\n \n GUIStyle bridgeStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(isUnityBridgeRunning ? \"Running\" : \"Stopped\", bridgeStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(8);\n if (GUILayout.Button(isUnityBridgeRunning ? \"Stop Bridge\" : \"Start Bridge\", GUILayout.Height(32)))\n {\n ToggleUnityBridge();\n }\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawValidationSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Script Validation\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUI.BeginChangeCheck();\n validationLevelIndex = EditorGUILayout.Popup(\"Validation Level\", validationLevelIndex, validationLevelOptions, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n SaveValidationLevelSetting();\n }\n \n EditorGUILayout.Space(8);\n string description = GetValidationLevelDescription(validationLevelIndex);\n EditorGUILayout.HelpBox(description, MessageType.Info);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawUnifiedClientConfiguration()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"MCP Client Configuration\", sectionTitleStyle);\n EditorGUILayout.Space(10);\n \n // Client selector\n string[] clientNames = mcpClients.clients.Select(c => c.name).ToArray();\n EditorGUI.BeginChangeCheck();\n selectedClientIndex = EditorGUILayout.Popup(\"Select Client\", selectedClientIndex, clientNames, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n selectedClientIndex = Mathf.Clamp(selectedClientIndex, 0, mcpClients.clients.Count - 1);\n }\n \n EditorGUILayout.Space(10);\n \n if (mcpClients.clients.Count > 0 && selectedClientIndex < mcpClients.clients.Count)\n {\n McpClient selectedClient = mcpClients.clients[selectedClientIndex];\n DrawClientConfigurationCompact(selectedClient);\n }\n \n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawClientConfigurationCompact(McpClient mcpClient)\n {\n // Status display\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n Color statusColor = GetStatusColor(mcpClient.status);\n DrawStatusDot(statusRect, statusColor, 16);\n \n GUIStyle clientStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(mcpClient.configStatus, clientStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Action buttons in horizontal layout\n EditorGUILayout.BeginHorizontal();\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n if (GUILayout.Button(\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n else\n {\n if (GUILayout.Button($\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n \n if (GUILayout.Button(\"Manual Setup\", GUILayout.Height(32)))\n {\n string configPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)\n ? mcpClient.windowsConfigPath\n : mcpClient.linuxConfigPath;\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n string pythonDir = FindPackagePythonDirectory();\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n VSCodeManualSetupWindow.ShowWindow(configPath, manualConfigJson);\n }\n else\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n }\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(8);\n // Quick info\n GUIStyle configInfoStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 10\n };\n EditorGUILayout.LabelField($\"Config: {Path.GetFileName(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? mcpClient.windowsConfigPath : mcpClient.linuxConfigPath)}\", configInfoStyle);\n }\n\n private void ToggleUnityBridge()\n {\n if (isUnityBridgeRunning)\n {\n UnityMcpBridge.Stop();\n }\n else\n {\n UnityMcpBridge.Start();\n }\n\n isUnityBridgeRunning = !isUnityBridgeRunning;\n }\n\n private string WriteToConfig(string pythonDir, string configPath, McpClient mcpClient = null)\n {\n // Create configuration object for unityMCP\n McpConfigServer unityMCPConfig = new()\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n\n // Read existing config if it exists\n string existingJson = \"{}\";\n if (File.Exists(configPath))\n {\n try\n {\n existingJson = File.ReadAllText(configPath);\n }\n catch (Exception e)\n {\n Debug.LogWarning($\"Error reading existing config: {e.Message}.\");\n }\n }\n\n // Parse the existing JSON while preserving all properties\n dynamic existingConfig = JsonConvert.DeserializeObject(existingJson);\n existingConfig ??= new Newtonsoft.Json.Linq.JObject();\n\n // Handle different client types with a switch statement\n //Comments: Interestingly, VSCode has mcp.servers.unityMCP while others have mcpServers.unityMCP, which is why we need to prevent this\n switch (mcpClient?.mcpType)\n {\n case McpTypes.VSCode:\n // VSCode specific configuration\n // Ensure mcp object exists\n if (existingConfig.mcp == null)\n {\n existingConfig.mcp = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Ensure mcp.servers object exists\n if (existingConfig.mcp.servers == null)\n {\n existingConfig.mcp.servers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in VSCode settings\n existingConfig.mcp.servers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n\n default:\n // Standard MCP configuration (Claude Desktop, Cursor, etc.)\n // Ensure mcpServers object exists\n if (existingConfig.mcpServers == null)\n {\n existingConfig.mcpServers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in standard MCP settings\n existingConfig.mcpServers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n }\n\n // Write the merged configuration back to file\n string mergedJson = JsonConvert.SerializeObject(existingConfig, jsonSettings);\n File.WriteAllText(configPath, mergedJson);\n\n return \"Configured successfully\";\n }\n\n private void ShowManualConfigurationInstructions(string configPath, McpClient mcpClient)\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n\n // New method to show manual instructions without changing status\n private void ShowManualInstructionsWindow(string configPath, McpClient mcpClient)\n {\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n string manualConfigJson;\n \n // Create common JsonSerializerSettings\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n \n // Use switch statement to handle different client types\n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n // Create VSCode-specific configuration with proper format\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n break;\n \n default:\n // Create standard MCP configuration for other clients\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n break;\n }\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private string FindPackagePythonDirectory()\n {\n string pythonDir = ServerInstaller.GetServerPath();\n\n try\n {\n // Try to find the package using Package Manager API\n UnityEditor.PackageManager.Requests.ListRequest request =\n UnityEditor.PackageManager.Client.List();\n while (!request.IsCompleted) { } // Wait for the request to complete\n\n if (request.Status == UnityEditor.PackageManager.StatusCode.Success)\n {\n foreach (UnityEditor.PackageManager.PackageInfo package in request.Result)\n {\n if (package.name == \"com.justinpbarnett.unity-mcp\")\n {\n string packagePath = package.resolvedPath;\n string potentialPythonDir = Path.Combine(packagePath, \"Python\");\n\n if (\n Directory.Exists(potentialPythonDir)\n && File.Exists(Path.Combine(potentialPythonDir, \"server.py\"))\n )\n {\n return potentialPythonDir;\n }\n }\n }\n }\n else if (request.Error != null)\n {\n Debug.LogError(\"Failed to list packages: \" + request.Error.message);\n }\n\n // If not found via Package Manager, try manual approaches\n // First check for local installation\n string[] possibleDirs =\n {\n Path.GetFullPath(Path.Combine(Application.dataPath, \"unity-mcp\", \"Python\")),\n };\n\n foreach (string dir in possibleDirs)\n {\n if (Directory.Exists(dir) && File.Exists(Path.Combine(dir, \"server.py\")))\n {\n return dir;\n }\n }\n\n // If still not found, return the placeholder path\n Debug.LogWarning(\"Could not find Python directory, using placeholder path\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"Error finding package path: {e.Message}\");\n }\n\n return pythonDir;\n }\n\n private string ConfigureMcpClient(McpClient mcpClient)\n {\n try\n {\n // Determine the config file path based on OS\n string configPath;\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n return \"Unsupported OS\";\n }\n\n // Create directory if it doesn't exist\n Directory.CreateDirectory(Path.GetDirectoryName(configPath));\n\n // Find the server.py file location\n string pythonDir = ServerInstaller.GetServerPath();\n\n if (pythonDir == null || !File.Exists(Path.Combine(pythonDir, \"server.py\")))\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n return \"Manual Configuration Required\";\n }\n\n string result = WriteToConfig(pythonDir, configPath, mcpClient);\n\n // Update the client status after successful configuration\n if (result == \"Configured successfully\")\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n\n return result;\n }\n catch (Exception e)\n {\n // Determine the config file path based on OS for error message\n string configPath = \"\";\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n Debug.LogError(\n $\"Failed to configure {mcpClient.name}: {e.Message}\\n{e.StackTrace}\"\n );\n return $\"Failed to configure {mcpClient.name}\";\n }\n }\n\n private void ShowCursorManualConfigurationInstructions(\n string configPath,\n McpClient mcpClient\n )\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n\n // Create the manual configuration message\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private void LoadValidationLevelSetting()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n validationLevelIndex = savedLevel.ToLower() switch\n {\n \"basic\" => 0,\n \"standard\" => 1,\n \"comprehensive\" => 2,\n \"strict\" => 3,\n _ => 1 // Default to Standard\n };\n }\n\n private void SaveValidationLevelSetting()\n {\n string levelString = validationLevelIndex switch\n {\n 0 => \"basic\",\n 1 => \"standard\",\n 2 => \"comprehensive\",\n 3 => \"strict\",\n _ => \"standard\"\n };\n EditorPrefs.SetString(\"UnityMCP_ScriptValidationLevel\", levelString);\n }\n\n private string GetValidationLevelDescription(int index)\n {\n return index switch\n {\n 0 => \"Only basic syntax checks (braces, quotes, comments)\",\n 1 => \"Syntax checks + Unity best practices and warnings\",\n 2 => \"All checks + semantic analysis and performance warnings\",\n 3 => \"Full semantic validation with namespace/type resolution (requires Roslyn)\",\n _ => \"Standard validation\"\n };\n }\n\n public static string GetCurrentValidationLevel()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel;\n }\n\n private void CheckMcpConfiguration(McpClient mcpClient)\n {\n try\n {\n string configPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n mcpClient.SetStatus(McpStatus.UnsupportedOS);\n return;\n }\n\n if (!File.Exists(configPath))\n {\n mcpClient.SetStatus(McpStatus.NotConfigured);\n return;\n }\n\n string configJson = File.ReadAllText(configPath);\n string pythonDir = ServerInstaller.GetServerPath();\n \n // Use switch statement to handle different client types, extracting common logic\n string[] args = null;\n bool configExists = false;\n \n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n dynamic config = JsonConvert.DeserializeObject(configJson);\n \n if (config?.mcp?.servers?.unityMCP != null)\n {\n // Extract args from VSCode config format\n args = config.mcp.servers.unityMCP.args.ToObject();\n configExists = true;\n }\n break;\n \n default:\n // Standard MCP configuration check for Claude Desktop, Cursor, etc.\n McpConfig standardConfig = JsonConvert.DeserializeObject(configJson);\n \n if (standardConfig?.mcpServers?.unityMCP != null)\n {\n args = standardConfig.mcpServers.unityMCP.args;\n configExists = true;\n }\n break;\n }\n \n // Common logic for checking configuration status\n if (configExists)\n {\n if (pythonDir != null && \n Array.Exists(args, arg => arg.Contains(pythonDir, StringComparison.Ordinal)))\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n else\n {\n mcpClient.SetStatus(McpStatus.IncorrectPath);\n }\n }\n else\n {\n mcpClient.SetStatus(McpStatus.MissingConfig);\n }\n }\n catch (Exception e)\n {\n mcpClient.SetStatus(McpStatus.Error, e.Message);\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Runtime/Serialization/UnityTypeConverters.cs", "using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing UnityEngine;\n#if UNITY_EDITOR\nusing UnityEditor; // Required for AssetDatabase and EditorUtility\n#endif\n\nnamespace UnityMcpBridge.Runtime.Serialization\n{\n public class Vector3Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector3 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WriteEndObject();\n }\n\n public override Vector3 ReadJson(JsonReader reader, Type objectType, Vector3 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector3(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"]\n );\n }\n }\n\n public class Vector2Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WriteEndObject();\n }\n\n public override Vector2 ReadJson(JsonReader reader, Type objectType, Vector2 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector2(\n (float)jo[\"x\"],\n (float)jo[\"y\"]\n );\n }\n }\n\n public class QuaternionConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Quaternion value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WritePropertyName(\"w\");\n writer.WriteValue(value.w);\n writer.WriteEndObject();\n }\n\n public override Quaternion ReadJson(JsonReader reader, Type objectType, Quaternion existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Quaternion(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"],\n (float)jo[\"w\"]\n );\n }\n }\n\n public class ColorConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Color value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"r\");\n writer.WriteValue(value.r);\n writer.WritePropertyName(\"g\");\n writer.WriteValue(value.g);\n writer.WritePropertyName(\"b\");\n writer.WriteValue(value.b);\n writer.WritePropertyName(\"a\");\n writer.WriteValue(value.a);\n writer.WriteEndObject();\n }\n\n public override Color ReadJson(JsonReader reader, Type objectType, Color existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Color(\n (float)jo[\"r\"],\n (float)jo[\"g\"],\n (float)jo[\"b\"],\n (float)jo[\"a\"]\n );\n }\n }\n \n public class RectConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Rect value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"width\");\n writer.WriteValue(value.width);\n writer.WritePropertyName(\"height\");\n writer.WriteValue(value.height);\n writer.WriteEndObject();\n }\n\n public override Rect ReadJson(JsonReader reader, Type objectType, Rect existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Rect(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"width\"],\n (float)jo[\"height\"]\n );\n }\n }\n \n public class BoundsConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Bounds value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"center\");\n serializer.Serialize(writer, value.center); // Use serializer to handle nested Vector3\n writer.WritePropertyName(\"size\");\n serializer.Serialize(writer, value.size); // Use serializer to handle nested Vector3\n writer.WriteEndObject();\n }\n\n public override Bounds ReadJson(JsonReader reader, Type objectType, Bounds existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n Vector3 center = jo[\"center\"].ToObject(serializer); // Use serializer to handle nested Vector3\n Vector3 size = jo[\"size\"].ToObject(serializer); // Use serializer to handle nested Vector3\n return new Bounds(center, size);\n }\n }\n\n // Converter for UnityEngine.Object references (GameObjects, Components, Materials, Textures, etc.)\n public class UnityEngineObjectConverter : JsonConverter\n {\n public override bool CanRead => true; // We need to implement ReadJson\n public override bool CanWrite => true;\n\n public override void WriteJson(JsonWriter writer, UnityEngine.Object value, JsonSerializer serializer)\n {\n if (value == null)\n {\n writer.WriteNull();\n return;\n }\n\n#if UNITY_EDITOR // AssetDatabase and EditorUtility are Editor-only\n if (UnityEditor.AssetDatabase.Contains(value))\n {\n // It's an asset (Material, Texture, Prefab, etc.)\n string path = UnityEditor.AssetDatabase.GetAssetPath(value);\n if (!string.IsNullOrEmpty(path))\n {\n writer.WriteValue(path);\n }\n else\n {\n // Asset exists but path couldn't be found? Write minimal info.\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"isAssetWithoutPath\");\n writer.WriteValue(true);\n writer.WriteEndObject();\n }\n }\n else\n {\n // It's a scene object (GameObject, Component, etc.)\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WriteEndObject();\n }\n#else\n // Runtime fallback: Write basic info without AssetDatabase\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"warning\");\n writer.WriteValue(\"UnityEngineObjectConverter running in non-Editor mode, asset path unavailable.\");\n writer.WriteEndObject();\n#endif\n }\n\n public override UnityEngine.Object ReadJson(JsonReader reader, Type objectType, UnityEngine.Object existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n if (reader.TokenType == JsonToken.Null)\n {\n return null;\n }\n\n#if UNITY_EDITOR\n if (reader.TokenType == JsonToken.String)\n {\n // Assume it's an asset path\n string path = reader.Value.ToString();\n return UnityEditor.AssetDatabase.LoadAssetAtPath(path, objectType);\n }\n\n if (reader.TokenType == JsonToken.StartObject)\n {\n JObject jo = JObject.Load(reader);\n if (jo.TryGetValue(\"instanceID\", out JToken idToken) && idToken.Type == JTokenType.Integer)\n {\n int instanceId = idToken.ToObject();\n UnityEngine.Object obj = UnityEditor.EditorUtility.InstanceIDToObject(instanceId);\n if (obj != null && objectType.IsAssignableFrom(obj.GetType()))\n {\n return obj;\n }\n }\n // Could potentially try finding by name as a fallback if ID lookup fails/isn't present\n // but that's less reliable.\n }\n#else\n // Runtime deserialization is tricky without AssetDatabase/EditorUtility\n // Maybe log a warning and return null or existingValue?\n Debug.LogWarning(\"UnityEngineObjectConverter cannot deserialize complex objects in non-Editor mode.\");\n // Skip the token to avoid breaking the reader\n if (reader.TokenType == JsonToken.StartObject) JObject.Load(reader);\n else if (reader.TokenType == JsonToken.String) reader.ReadAsString(); \n // Return null or existing value, depending on desired behavior\n return existingValue; \n#endif\n\n throw new JsonSerializationException($\"Unexpected token type '{reader.TokenType}' when deserializing UnityEngine.Object\");\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageShader.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for shader files within the Unity project.\n /// \n public static class ManageShader\n {\n /// \n /// Main handler for shader management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode shader contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid shader name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Shaders\" if path is not provided\n string relativeDir = path ?? \"Shaders\"; // Default to \"Shaders\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Shaders\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string shaderFileName = $\"{name}.shader\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir);\n string fullPath = Path.Combine(fullPathDir, shaderFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, shaderFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n if (!Directory.Exists(fullPathDir))\n {\n Directory.CreateDirectory(fullPathDir);\n // Refresh AssetDatabase to recognize new folders\n AssetDatabase.Refresh();\n }\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateShader(fullPath, relativePath, name, contents);\n case \"read\":\n return ReadShader(fullPath, relativePath);\n case \"update\":\n return UpdateShader(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteShader(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n // Check if shader already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Add validation for shader name conflicts in Unity\n if (Shader.Find(name) != null)\n {\n return Response.Error(\n $\"A shader with name '{name}' already exists in the project. Choose a different name.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultShaderContent(name);\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new shader\n return Response.Success(\n $\"Shader '{name}.shader' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n //TODO: Consider a threshold for large files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader not found at '{relativePath}'. Use 'create' action to add a new shader.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' updated successfully.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n // Delete the asset through Unity's AssetDatabase first\n bool success = AssetDatabase.DeleteAsset(relativePath);\n if (!success)\n {\n return Response.Error($\"Failed to delete shader through Unity's AssetDatabase: '{relativePath}'\");\n }\n\n // If the file still exists (rare case), try direct deletion\n if (File.Exists(fullPath))\n {\n File.Delete(fullPath);\n }\n\n return Response.Success($\"Shader '{Path.GetFileName(relativePath)}' deleted successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to delete shader '{relativePath}': {e.Message}\");\n }\n }\n\n //This is a CGProgram template\n //TODO: making a HLSL template as well?\n private static string GenerateDefaultShaderContent(string name)\n {\n return @\"Shader \"\"\" + name + @\"\"\"\n {\n Properties\n {\n _MainTex (\"\"Texture\"\", 2D) = \"\"white\"\" {}\n }\n SubShader\n {\n Tags { \"\"RenderType\"\"=\"\"Opaque\"\" }\n LOD 100\n\n Pass\n {\n CGPROGRAM\n #pragma vertex vert\n #pragma fragment frag\n #include \"\"UnityCG.cginc\"\"\n\n struct appdata\n {\n float4 vertex : POSITION;\n float2 uv : TEXCOORD0;\n };\n\n struct v2f\n {\n float2 uv : TEXCOORD0;\n float4 vertex : SV_POSITION;\n };\n\n sampler2D _MainTex;\n float4 _MainTex_ST;\n\n v2f vert (appdata v)\n {\n v2f o;\n o.vertex = UnityObjectToClipPos(v.vertex);\n o.uv = TRANSFORM_TEX(v.uv, _MainTex);\n return o;\n }\n\n fixed4 frag (v2f i) : SV_Target\n {\n fixed4 col = tex2D(_MainTex, i.uv);\n return col;\n }\n ENDCG\n }\n }\n }\";\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ExecuteMenuItem.cs", "using System;\nusing System.Collections.Generic; // Added for HashSet\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles executing Unity Editor menu items by path.\n /// \n public static class ExecuteMenuItem\n {\n // Basic blacklist to prevent accidental execution of potentially disruptive menu items.\n // This can be expanded based on needs.\n private static readonly HashSet _menuPathBlacklist = new HashSet(\n StringComparer.OrdinalIgnoreCase\n )\n {\n \"File/Quit\",\n // Add other potentially dangerous items like \"Edit/Preferences...\", \"File/Build Settings...\" if needed\n };\n\n /// \n /// Main handler for executing menu items or getting available ones.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"execute\"; // Default action\n\n try\n {\n switch (action)\n {\n case \"execute\":\n return ExecuteItem(@params);\n case \"get_available_menus\":\n // Getting a comprehensive list of *all* menu items dynamically is very difficult\n // and often requires complex reflection or maintaining a manual list.\n // Returning a placeholder/acknowledgement for now.\n Debug.LogWarning(\n \"[ExecuteMenuItem] 'get_available_menus' action is not fully implemented. Dynamically listing all menu items is complex.\"\n );\n // Returning an empty list as per the refactor plan's requirements.\n return Response.Success(\n \"'get_available_menus' action is not fully implemented. Returning empty list.\",\n new List()\n );\n // TODO: Consider implementing a basic list of common/known menu items or exploring reflection techniques if this feature becomes critical.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'execute', 'get_available_menus'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ExecuteMenuItem] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n /// \n /// Executes a specific menu item.\n /// \n private static object ExecuteItem(JObject @params)\n {\n // Try both naming conventions: snake_case and camelCase\n string menuPath = @params[\"menu_path\"]?.ToString() ?? @params[\"menuPath\"]?.ToString();\n\n // string alias = @params[\"alias\"]?.ToString(); // TODO: Implement alias mapping based on refactor plan requirements.\n // JObject parameters = @params[\"parameters\"] as JObject; // TODO: Investigate parameter passing (often not directly supported by ExecuteMenuItem).\n\n if (string.IsNullOrWhiteSpace(menuPath))\n {\n return Response.Error(\"Required parameter 'menu_path' or 'menuPath' is missing or empty.\");\n }\n\n // Validate against blacklist\n if (_menuPathBlacklist.Contains(menuPath))\n {\n return Response.Error(\n $\"Execution of menu item '{menuPath}' is blocked for safety reasons.\"\n );\n }\n\n // TODO: Implement alias lookup here if needed (Map alias to actual menuPath).\n // if (!string.IsNullOrEmpty(alias)) { menuPath = LookupAlias(alias); if(menuPath == null) return Response.Error(...); }\n\n // TODO: Handle parameters ('parameters' object) if a viable method is found.\n // This is complex as EditorApplication.ExecuteMenuItem doesn't take arguments directly.\n // It might require finding the underlying EditorWindow or command if parameters are needed.\n\n try\n {\n // Attempt to execute the menu item on the main thread using delayCall for safety.\n EditorApplication.delayCall += () =>\n {\n try\n {\n bool executed = EditorApplication.ExecuteMenuItem(menuPath);\n // Log potential failure inside the delayed call.\n if (!executed)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to find or execute menu item via delayCall: '{menuPath}'. It might be invalid, disabled, or context-dependent.\"\n );\n }\n }\n catch (Exception delayEx)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Exception during delayed execution of '{menuPath}': {delayEx}\"\n );\n }\n };\n\n // Report attempt immediately, as execution is delayed.\n return Response.Success(\n $\"Attempted to execute menu item: '{menuPath}'. Check Unity logs for confirmation or errors.\"\n );\n }\n catch (Exception e)\n {\n // Catch errors during setup phase.\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to setup execution for '{menuPath}': {e}\"\n );\n return Response.Error(\n $\"Error setting up execution for menu item '{menuPath}': {e.Message}\"\n );\n }\n }\n\n // TODO: Add helper for alias lookup if implementing aliases.\n // private static string LookupAlias(string alias) { ... return actualMenuPath or null ... }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/ServerInstaller.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Runtime.InteropServices;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n public static class ServerInstaller\n {\n private const string RootFolder = \"UnityMCP\";\n private const string ServerFolder = \"UnityMcpServer\";\n private const string BranchName = \"master\";\n private const string GitUrl = \"https://github.com/justinpbarnett/unity-mcp.git\";\n private const string PyprojectUrl =\n \"https://raw.githubusercontent.com/justinpbarnett/unity-mcp/refs/heads/\"\n + BranchName\n + \"/UnityMcpServer/src/pyproject.toml\";\n\n /// \n /// Ensures the unity-mcp-server is installed and up to date.\n /// \n public static void EnsureServerInstalled()\n {\n try\n {\n string saveLocation = GetSaveLocation();\n\n if (!IsServerInstalled(saveLocation))\n {\n InstallServer(saveLocation);\n }\n else\n {\n string installedVersion = GetInstalledVersion();\n string latestVersion = GetLatestVersion();\n\n if (IsNewerVersion(latestVersion, installedVersion))\n {\n UpdateServer(saveLocation);\n }\n else { }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure server installation: {ex.Message}\");\n }\n }\n\n public static string GetServerPath()\n {\n return Path.Combine(GetSaveLocation(), ServerFolder, \"src\");\n }\n\n /// \n /// Gets the platform-specific save location for the server.\n /// \n private static string GetSaveLocation()\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"AppData\",\n \"Local\",\n \"Programs\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"bin\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n string path = \"/usr/local/bin\";\n return !Directory.Exists(path) || !IsDirectoryWritable(path)\n ? Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Applications\",\n RootFolder\n )\n : Path.Combine(path, RootFolder);\n }\n throw new Exception(\"Unsupported operating system.\");\n }\n\n private static bool IsDirectoryWritable(string path)\n {\n try\n {\n File.Create(Path.Combine(path, \"test.txt\")).Dispose();\n File.Delete(Path.Combine(path, \"test.txt\"));\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Checks if the server is installed at the specified location.\n /// \n private static bool IsServerInstalled(string location)\n {\n return Directory.Exists(location)\n && File.Exists(Path.Combine(location, ServerFolder, \"src\", \"pyproject.toml\"));\n }\n\n /// \n /// Installs the server by cloning only the UnityMcpServer folder from the repository and setting up dependencies.\n /// \n private static void InstallServer(string location)\n {\n // Create the src directory where the server code will reside\n Directory.CreateDirectory(location);\n\n // Initialize git repo in the src directory\n RunCommand(\"git\", $\"init\", workingDirectory: location);\n\n // Add remote\n RunCommand(\"git\", $\"remote add origin {GitUrl}\", workingDirectory: location);\n\n // Configure sparse checkout\n RunCommand(\"git\", \"config core.sparseCheckout true\", workingDirectory: location);\n\n // Set sparse checkout path to only include UnityMcpServer folder\n string sparseCheckoutPath = Path.Combine(location, \".git\", \"info\", \"sparse-checkout\");\n File.WriteAllText(sparseCheckoutPath, $\"{ServerFolder}/\");\n\n // Fetch and checkout the branch\n RunCommand(\"git\", $\"fetch --depth=1 origin {BranchName}\", workingDirectory: location);\n RunCommand(\"git\", $\"checkout {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Fetches the currently installed version from the local pyproject.toml file.\n /// \n public static string GetInstalledVersion()\n {\n string pyprojectPath = Path.Combine(\n GetSaveLocation(),\n ServerFolder,\n \"src\",\n \"pyproject.toml\"\n );\n return ParseVersionFromPyproject(File.ReadAllText(pyprojectPath));\n }\n\n /// \n /// Fetches the latest version from the GitHub pyproject.toml file.\n /// \n public static string GetLatestVersion()\n {\n using WebClient webClient = new();\n string pyprojectContent = webClient.DownloadString(PyprojectUrl);\n return ParseVersionFromPyproject(pyprojectContent);\n }\n\n /// \n /// Updates the server by pulling the latest changes for the UnityMcpServer folder only.\n /// \n private static void UpdateServer(string location)\n {\n RunCommand(\"git\", $\"pull origin {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Parses the version number from pyproject.toml content.\n /// \n private static string ParseVersionFromPyproject(string content)\n {\n foreach (string line in content.Split('\\n'))\n {\n if (line.Trim().StartsWith(\"version =\"))\n {\n string[] parts = line.Split('=');\n if (parts.Length == 2)\n {\n return parts[1].Trim().Trim('\"');\n }\n }\n }\n throw new Exception(\"Version not found in pyproject.toml\");\n }\n\n /// \n /// Compares two version strings to determine if the latest is newer.\n /// \n public static bool IsNewerVersion(string latest, string installed)\n {\n int[] latestParts = latest.Split('.').Select(int.Parse).ToArray();\n int[] installedParts = installed.Split('.').Select(int.Parse).ToArray();\n for (int i = 0; i < Math.Min(latestParts.Length, installedParts.Length); i++)\n {\n if (latestParts[i] > installedParts[i])\n {\n return true;\n }\n\n if (latestParts[i] < installedParts[i])\n {\n return false;\n }\n }\n return latestParts.Length > installedParts.Length;\n }\n\n /// \n /// Runs a command-line process and handles output/errors.\n /// \n private static void RunCommand(\n string command,\n string arguments,\n string workingDirectory = null\n )\n {\n System.Diagnostics.Process process = new()\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = command,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n WorkingDirectory = workingDirectory ?? string.Empty,\n },\n };\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n if (process.ExitCode != 0)\n {\n throw new Exception(\n $\"Command failed: {command} {arguments}\\nOutput: {output}\\nError: {error}\"\n );\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Windows/VSCodeManualSetupWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class VSCodeManualSetupWindow : ManualConfigEditorWindow\n {\n public static new void ShowWindow(string configPath, string configJson)\n {\n var window = GetWindow(\"VSCode GitHub Copilot Setup\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.minSize = new Vector2(550, 500);\n \n // Create a McpClient for VSCode\n window.mcpClient = new McpClient\n {\n name = \"VSCode GitHub Copilot\",\n mcpType = McpTypes.VSCode\n };\n \n window.Show();\n }\n\n protected override void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n \"VSCode GitHub Copilot MCP Setup\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"Setting up GitHub Copilot in VSCode with Unity MCP\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Prerequisites\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have VSCode installed\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have GitHub Copilot extension installed in VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have a valid GitHub Copilot subscription\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"2. Steps to Configure\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"a) Open VSCode Settings (File > Preferences > Settings)\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"b) Click on the 'Open Settings (JSON)' button in the top right\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"c) Add the MCP configuration shown below to your settings.json file\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"d) Save the file and restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"3. VSCode settings.json location:\",\n EditorStyles.boldLabel\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n else \n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n\n // Store the path in the base class config path\n if (string.IsNullOrEmpty(configPath))\n {\n configPath = displayPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"4. Add this configuration to your settings.json:\",\n EditorStyles.boldLabel\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"5. After configuration:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• GitHub Copilot will now be able to interact with your Unity project through the MCP protocol\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Remember to have the Unity MCP Bridge running in Unity Editor\",\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected override void Update()\n {\n // Call the base implementation which handles the copy feedback timer\n base.Update();\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Windows/ManualConfigEditorWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n // Editor window to display manual configuration instructions\n public class ManualConfigEditorWindow : EditorWindow\n {\n protected string configPath;\n protected string configJson;\n protected Vector2 scrollPos;\n protected bool pathCopied = false;\n protected bool jsonCopied = false;\n protected float copyFeedbackTimer = 0;\n protected McpClient mcpClient;\n\n public static void ShowWindow(string configPath, string configJson, McpClient mcpClient)\n {\n var window = GetWindow(\"Manual Configuration\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.mcpClient = mcpClient;\n window.minSize = new Vector2(500, 400);\n window.Show();\n }\n\n protected virtual void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n mcpClient.name + \" Manual Configuration\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"The automatic configuration failed. Please follow these steps:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Open \" + mcpClient.name + \" config file by either:\",\n instructionStyle\n );\n if (mcpClient.mcpType == McpTypes.ClaudeDesktop)\n {\n EditorGUILayout.LabelField(\n \" a) Going to Settings > Developer > Edit Config\",\n instructionStyle\n );\n }\n else if (mcpClient.mcpType == McpTypes.Cursor)\n {\n EditorGUILayout.LabelField(\n \" a) Going to File > Preferences > Cursor Settings > MCP > Add new global MCP server\",\n instructionStyle\n );\n }\n EditorGUILayout.LabelField(\" OR\", instructionStyle);\n EditorGUILayout.LabelField(\n \" b) Opening the configuration file at:\",\n instructionStyle\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n displayPath = mcpClient.linuxConfigPath;\n }\n else\n {\n displayPath = configPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"2. Paste the following JSON configuration:\",\n instructionStyle\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"3. Save the file and restart \" + mcpClient.name,\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected virtual void Update()\n {\n // Handle the feedback message timer\n if (copyFeedbackTimer > 0)\n {\n copyFeedbackTimer -= Time.deltaTime;\n if (copyFeedbackTimer <= 0)\n {\n pathCopied = false;\n jsonCopied = false;\n Repaint();\n }\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/CommandRegistry.cs", "using System;\nusing System.Collections.Generic;\nusing Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Registry for all MCP command handlers (Refactored Version)\n /// \n public static class CommandRegistry\n {\n // Maps command names (matching those called from Python via ctx.bridge.unity_editor.HandlerName)\n // to the corresponding static HandleCommand method in the appropriate tool class.\n private static readonly Dictionary> _handlers = new()\n {\n { \"HandleManageScript\", ManageScript.HandleCommand },\n { \"HandleManageScene\", ManageScene.HandleCommand },\n { \"HandleManageEditor\", ManageEditor.HandleCommand },\n { \"HandleManageGameObject\", ManageGameObject.HandleCommand },\n { \"HandleManageAsset\", ManageAsset.HandleCommand },\n { \"HandleReadConsole\", ReadConsole.HandleCommand },\n { \"HandleExecuteMenuItem\", ExecuteMenuItem.HandleCommand },\n { \"HandleManageShader\", ManageShader.HandleCommand},\n };\n\n /// \n /// Gets a command handler by name.\n /// \n /// Name of the command handler (e.g., \"HandleManageAsset\").\n /// The command handler function if found, null otherwise.\n public static Func GetHandler(string commandName)\n {\n // Use case-insensitive comparison for flexibility, although Python side should be consistent\n return _handlers.TryGetValue(commandName, out var handler) ? handler : null;\n // Consider adding logging here if a handler is not found\n /*\n if (_handlers.TryGetValue(commandName, out var handler)) {\n return handler;\n } else {\n UnityEngine.Debug.LogError($\\\"[CommandRegistry] No handler found for command: {commandName}\\\");\n return null;\n }\n */\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Response.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Provides static methods for creating standardized success and error response objects.\n /// Ensures consistent JSON structure for communication back to the Python server.\n /// \n public static class Response\n {\n /// \n /// Creates a standardized success response object.\n /// \n /// A message describing the successful operation.\n /// Optional additional data to include in the response.\n /// An object representing the success response.\n public static object Success(string message, object data = null)\n {\n if (data != null)\n {\n return new\n {\n success = true,\n message = message,\n data = data,\n };\n }\n else\n {\n return new { success = true, message = message };\n }\n }\n\n /// \n /// Creates a standardized error response object.\n /// \n /// A message describing the error.\n /// Optional additional data (e.g., error details) to include.\n /// An object representing the error response.\n public static object Error(string errorMessage, object data = null)\n {\n if (data != null)\n {\n // Note: The key is \"error\" for error messages, not \"message\"\n return new\n {\n success = false,\n error = errorMessage,\n data = data,\n };\n }\n else\n {\n return new { success = false, error = errorMessage };\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Data/McpClients.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class McpClients\n {\n public List clients = new()\n {\n new()\n {\n name = \"Claude Desktop\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n mcpType = McpTypes.ClaudeDesktop,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"Cursor\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n mcpType = McpTypes.Cursor,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"VSCode GitHub Copilot\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n mcpType = McpTypes.VSCode,\n configStatus = \"Not Configured\",\n },\n };\n\n // Initialize status enums after construction\n public McpClients()\n {\n foreach (var client in clients)\n {\n if (client.configStatus == \"Not Configured\")\n {\n client.status = McpStatus.NotConfigured;\n }\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpClient.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public class McpClient\n {\n public string name;\n public string windowsConfigPath;\n public string linuxConfigPath;\n public McpTypes mcpType;\n public string configStatus;\n public McpStatus status = McpStatus.NotConfigured;\n\n // Helper method to convert the enum to a display string\n public string GetStatusDisplayString()\n {\n return status switch\n {\n McpStatus.NotConfigured => \"Not Configured\",\n McpStatus.Configured => \"Configured\",\n McpStatus.Running => \"Running\",\n McpStatus.Connected => \"Connected\",\n McpStatus.IncorrectPath => \"Incorrect Path\",\n McpStatus.CommunicationError => \"Communication Error\",\n McpStatus.NoResponse => \"No Response\",\n McpStatus.UnsupportedOS => \"Unsupported OS\",\n McpStatus.MissingConfig => \"Missing UnityMCP Config\",\n McpStatus.Error => configStatus.StartsWith(\"Error:\") ? configStatus : \"Error\",\n _ => \"Unknown\",\n };\n }\n\n // Helper method to set both status enum and string for backward compatibility\n public void SetStatus(McpStatus newStatus, string errorDetails = null)\n {\n status = newStatus;\n\n if (newStatus == McpStatus.Error && !string.IsNullOrEmpty(errorDetails))\n {\n configStatus = $\"Error: {errorDetails}\";\n }\n else\n {\n configStatus = GetStatusDisplayString();\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Vector3Helper.cs", "using Newtonsoft.Json.Linq;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Helper class for Vector3 operations\n /// \n public static class Vector3Helper\n {\n /// \n /// Parses a JArray into a Vector3\n /// \n /// The array containing x, y, z coordinates\n /// A Vector3 with the parsed coordinates\n /// Thrown when array is invalid\n public static Vector3 ParseVector3(JArray array)\n {\n if (array == null || array.Count != 3)\n throw new System.Exception(\"Vector3 must be an array of 3 floats [x, y, z].\");\n return new Vector3((float)array[0], (float)array[1], (float)array[2]);\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/Command.cs", "using Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n /// \n /// Represents a command received from the MCP client\n /// \n public class Command\n {\n /// \n /// The type of command to execute\n /// \n public string type { get; set; }\n\n /// \n /// The parameters for the command\n /// \n public JObject @params { get; set; }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Data/DefaultServerConfig.cs", "using UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class DefaultServerConfig : ServerConfig\n {\n public new string unityHost = \"localhost\";\n public new int unityPort = 6400;\n public new int mcpPort = 6500;\n public new float connectionTimeout = 15.0f;\n public new int bufferSize = 32768;\n public new string logLevel = \"INFO\";\n public new string logFormat = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\";\n public new int maxRetries = 3;\n public new float retryDelay = 1.0f;\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpStatus.cs", "namespace UnityMcpBridge.Editor.Models\n{\n // Enum representing the various status states for MCP clients\n public enum McpStatus\n {\n NotConfigured, // Not set up yet\n Configured, // Successfully configured\n Running, // Service is running\n Connected, // Successfully connected\n IncorrectPath, // Configuration has incorrect paths\n CommunicationError, // Connected but communication issues\n NoResponse, // Connected but not responding\n MissingConfig, // Config file exists but missing required elements\n UnsupportedOS, // OS is not supported\n Error, // General error state\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/ServerConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class ServerConfig\n {\n [JsonProperty(\"unity_host\")]\n public string unityHost = \"localhost\";\n\n [JsonProperty(\"unity_port\")]\n public int unityPort;\n\n [JsonProperty(\"mcp_port\")]\n public int mcpPort;\n\n [JsonProperty(\"connection_timeout\")]\n public float connectionTimeout;\n\n [JsonProperty(\"buffer_size\")]\n public int bufferSize;\n\n [JsonProperty(\"log_level\")]\n public string logLevel;\n\n [JsonProperty(\"log_format\")]\n public string logFormat;\n\n [JsonProperty(\"max_retries\")]\n public int maxRetries;\n\n [JsonProperty(\"retry_delay\")]\n public float retryDelay;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServer.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServer\n {\n [JsonProperty(\"command\")]\n public string command;\n\n [JsonProperty(\"args\")]\n public string[] args;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfig\n {\n [JsonProperty(\"mcpServers\")]\n public McpConfigServers mcpServers;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServers.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServers\n {\n [JsonProperty(\"unityMCP\")]\n public McpConfigServer unityMCP;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpTypes.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public enum McpTypes\n {\n ClaudeDesktop,\n Cursor,\n VSCode,\n }\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-20 19:14:43", "created_task_model": "DeepSeek-R1", "function_skeleton": "private static JToken CreateTokenFromValue (object value, Type type) {}", "code_description": "This code segment functions to: Convert runtime objects into JSON-compatible data structures using predefined serialization rules while gracefully handling type-specific conversion errors and omitting problematic values from the final output."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n private static JToken CreateTokenFromValue(object value, Type type)\n {\n if (value == null)\n return null;\n\n try\n {\n // Use our custom serializer settings that include converters for Unity types\n return JToken.FromObject(value, _outputSerializer);\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not serialize value of type {type?.Name}: {ex.Message}\");\n return null;\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-15-03"}, "editdistance_info": {"edit_distance": 47.482, "calculate_time": "2025-08-20 19:15:03", "true_code_clean": "private static JToken CreateTokenFromValue(object value, Type type)\n {\n if (value == null) return JValue.CreateNull();\n try\n {\n return JToken.FromObject(value, _outputSerializer);\n }\n catch (JsonSerializationException e)\n {\n Debug.LogWarning($\"[GameObjectSerializer] Newtonsoft.Json Error serializing value of type {type.FullName}: {e.Message}. Skipping property/field.\");\n return null; \n }\n catch (Exception e) \n {\n Debug.LogWarning($\"[GameObjectSerializer] Unexpected error serializing value of type {type.FullName}: {e}. Skipping property/field.\");\n return null; \n }\n }", "predict_code_clean": "private static JToken CreateTokenFromValue(object value, Type type)\n {\n if (value == null)\n return null;\n try\n {\n return JToken.FromObject(value, _outputSerializer);\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not serialize value of type {type?.Name}: {ex.Message}\");\n return null;\n }\n }"}} {"repo_name": "unity-mcp", "file_name": "/unity-mcp/UnityMcpBridge/Editor/Tools/ExecuteMenuItem.cs", "inference_info": {"prefix_code": "using System;\nusing System.Collections.Generic; // Added for HashSet\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles executing Unity Editor menu items by path.\n /// \n public static class ExecuteMenuItem\n {\n // Basic blacklist to prevent accidental execution of potentially disruptive menu items.\n // This can be expanded based on needs.\n private static readonly HashSet _menuPathBlacklist = new HashSet(\n StringComparer.OrdinalIgnoreCase\n )\n {\n \"File/Quit\",\n // Add other potentially dangerous items like \"Edit/Preferences...\", \"File/Build Settings...\" if needed\n };\n\n /// \n /// Main handler for executing menu items or getting available ones.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"execute\"; // Default action\n\n try\n {\n switch (action)\n {\n case \"execute\":\n return ExecuteItem(@params);\n case \"get_available_menus\":\n // Getting a comprehensive list of *all* menu items dynamically is very difficult\n // and often requires complex reflection or maintaining a manual list.\n // Returning a placeholder/acknowledgement for now.\n Debug.LogWarning(\n \"[ExecuteMenuItem] 'get_available_menus' action is not fully implemented. Dynamically listing all menu items is complex.\"\n );\n // Returning an empty list as per the refactor plan's requirements.\n return Response.Success(\n \"'get_available_menus' action is not fully implemented. Returning empty list.\",\n new List()\n );\n // TODO: Consider implementing a basic list of common/known menu items or exploring reflection techniques if this feature becomes critical.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'execute', 'get_available_menus'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ExecuteMenuItem] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n /// \n /// Executes a specific menu item.\n /// \n ", "suffix_code": "\n\n // TODO: Add helper for alias lookup if implementing aliases.\n // private static string LookupAlias(string alias) { ... return actualMenuPath or null ... }\n }\n}\n\n", "middle_code": "private static object ExecuteItem(JObject @params)\n {\n string menuPath = @params[\"menu_path\"]?.ToString() ?? @params[\"menuPath\"]?.ToString();\n if (string.IsNullOrWhiteSpace(menuPath))\n {\n return Response.Error(\"Required parameter 'menu_path' or 'menuPath' is missing or empty.\");\n }\n if (_menuPathBlacklist.Contains(menuPath))\n {\n return Response.Error(\n $\"Execution of menu item '{menuPath}' is blocked for safety reasons.\"\n );\n }\n try\n {\n EditorApplication.delayCall += () =>\n {\n try\n {\n bool executed = EditorApplication.ExecuteMenuItem(menuPath);\n if (!executed)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to find or execute menu item via delayCall: '{menuPath}'. It might be invalid, disabled, or context-dependent.\"\n );\n }\n }\n catch (Exception delayEx)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Exception during delayed execution of '{menuPath}': {delayEx}\"\n );\n }\n };\n return Response.Success(\n $\"Attempted to execute menu item: '{menuPath}'. Check Unity logs for confirmation or errors.\"\n );\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to setup execution for '{menuPath}': {e}\"\n );\n return Response.Error(\n $\"Error setting up execution for menu item '{menuPath}': {e.Message}\"\n );\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageGameObject.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json; // Added for JsonSerializationException\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\nusing UnityMcpBridge.Runtime.Serialization;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles GameObject manipulation within the current scene (CRUD, find, components).\n /// \n public static class ManageGameObject\n {\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Parameters used by various actions\n JToken targetToken = @params[\"target\"]; // Can be string (name/path) or int (instanceID)\n string searchMethod = @params[\"searchMethod\"]?.ToString().ToLower();\n\n // Get common parameters (consolidated)\n string name = @params[\"name\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString();\n string layer = @params[\"layer\"]?.ToString();\n JToken parentToken = @params[\"parent\"];\n\n // --- Add parameter for controlling non-public field inclusion ---\n bool includeNonPublicSerialized = @params[\"includeNonPublicSerialized\"]?.ToObject() ?? true; // Default to true\n // --- End add parameter ---\n\n // --- Prefab Redirection Check ---\n string targetPath =\n targetToken?.Type == JTokenType.String ? targetToken.ToString() : null;\n if (\n !string.IsNullOrEmpty(targetPath)\n && targetPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n // Allow 'create' (instantiate), 'find' (?), 'get_components' (?)\n if (action == \"modify\" || action == \"set_component_property\")\n {\n Debug.Log(\n $\"[ManageGameObject->ManageAsset] Redirecting action '{action}' for prefab '{targetPath}' to ManageAsset.\"\n );\n // Prepare params for ManageAsset.ModifyAsset\n JObject assetParams = new JObject();\n assetParams[\"action\"] = \"modify\"; // ManageAsset uses \"modify\"\n assetParams[\"path\"] = targetPath;\n\n // Extract properties.\n // For 'set_component_property', combine componentName and componentProperties.\n // For 'modify', directly use componentProperties.\n JObject properties = null;\n if (action == \"set_component_property\")\n {\n string compName = @params[\"componentName\"]?.ToString();\n JObject compProps = @params[\"componentProperties\"]?[compName] as JObject; // Handle potential nesting\n if (string.IsNullOrEmpty(compName))\n return Response.Error(\n \"Missing 'componentName' for 'set_component_property' on prefab.\"\n );\n if (compProps == null)\n return Response.Error(\n $\"Missing or invalid 'componentProperties' for component '{compName}' for 'set_component_property' on prefab.\"\n );\n\n properties = new JObject();\n properties[compName] = compProps;\n }\n else // action == \"modify\"\n {\n properties = @params[\"componentProperties\"] as JObject;\n if (properties == null)\n return Response.Error(\n \"Missing 'componentProperties' for 'modify' action on prefab.\"\n );\n }\n\n assetParams[\"properties\"] = properties;\n\n // Call ManageAsset handler\n return ManageAsset.HandleCommand(assetParams);\n }\n else if (\n action == \"delete\"\n || action == \"add_component\"\n || action == \"remove_component\"\n || action == \"get_components\"\n ) // Added get_components here too\n {\n // Explicitly block other modifications on the prefab asset itself via manage_gameobject\n return Response.Error(\n $\"Action '{action}' on a prefab asset ('{targetPath}') should be performed using the 'manage_asset' command.\"\n );\n }\n // Allow 'create' (instantiation) and 'find' to proceed, although finding a prefab asset by path might be less common via manage_gameobject.\n // No specific handling needed here, the code below will run.\n }\n // --- End Prefab Redirection Check ---\n\n try\n {\n switch (action)\n {\n case \"create\":\n return CreateGameObject(@params);\n case \"modify\":\n return ModifyGameObject(@params, targetToken, searchMethod);\n case \"delete\":\n return DeleteGameObject(targetToken, searchMethod);\n case \"find\":\n return FindGameObjects(@params, targetToken, searchMethod);\n case \"get_components\":\n string getCompTarget = targetToken?.ToString(); // Expect name, path, or ID string\n if (getCompTarget == null)\n return Response.Error(\n \"'target' parameter required for get_components.\"\n );\n // Pass the includeNonPublicSerialized flag here\n return GetComponentsFromTarget(getCompTarget, searchMethod, includeNonPublicSerialized);\n case \"add_component\":\n return AddComponentToTarget(@params, targetToken, searchMethod);\n case \"remove_component\":\n return RemoveComponentFromTarget(@params, targetToken, searchMethod);\n case \"set_component_property\":\n return SetComponentPropertyOnTarget(@params, targetToken, searchMethod);\n\n default:\n return Response.Error($\"Unknown action: '{action}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageGameObject] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object CreateGameObject(JObject @params)\n {\n string name = @params[\"name\"]?.ToString();\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"'name' parameter is required for 'create' action.\");\n }\n\n // Get prefab creation parameters\n bool saveAsPrefab = @params[\"saveAsPrefab\"]?.ToObject() ?? false;\n string prefabPath = @params[\"prefabPath\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString(); // Get tag for creation\n string primitiveType = @params[\"primitiveType\"]?.ToString(); // Keep primitiveType check\n GameObject newGo = null; // Initialize as null\n\n // --- Try Instantiating Prefab First ---\n string originalPrefabPath = prefabPath; // Keep original for messages\n if (!string.IsNullOrEmpty(prefabPath))\n {\n // If no extension, search for the prefab by name\n if (\n !prefabPath.Contains(\"/\")\n && !prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n string prefabNameOnly = prefabPath;\n Debug.Log(\n $\"[ManageGameObject.Create] Searching for prefab named: '{prefabNameOnly}'\"\n );\n string[] guids = AssetDatabase.FindAssets($\"t:Prefab {prefabNameOnly}\");\n if (guids.Length == 0)\n {\n return Response.Error(\n $\"Prefab named '{prefabNameOnly}' not found anywhere in the project.\"\n );\n }\n else if (guids.Length > 1)\n {\n string foundPaths = string.Join(\n \", \",\n guids.Select(g => AssetDatabase.GUIDToAssetPath(g))\n );\n return Response.Error(\n $\"Multiple prefabs found matching name '{prefabNameOnly}': {foundPaths}. Please provide a more specific path.\"\n );\n }\n else // Exactly one found\n {\n prefabPath = AssetDatabase.GUIDToAssetPath(guids[0]); // Update prefabPath with the full path\n Debug.Log(\n $\"[ManageGameObject.Create] Found unique prefab at path: '{prefabPath}'\"\n );\n }\n }\n else if (!prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n // If it looks like a path but doesn't end with .prefab, assume user forgot it and append it.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Provided prefabPath '{prefabPath}' does not end with .prefab. Assuming it's missing and appending.\"\n );\n prefabPath += \".prefab\";\n // Note: This path might still not exist, AssetDatabase.LoadAssetAtPath will handle that.\n }\n // The logic above now handles finding or assuming the .prefab extension.\n\n GameObject prefabAsset = AssetDatabase.LoadAssetAtPath(prefabPath);\n if (prefabAsset != null)\n {\n try\n {\n // Instantiate the prefab, initially place it at the root\n // Parent will be set later if specified\n newGo = PrefabUtility.InstantiatePrefab(prefabAsset) as GameObject;\n\n if (newGo == null)\n {\n // This might happen if the asset exists but isn't a valid GameObject prefab somehow\n Debug.LogError(\n $\"[ManageGameObject.Create] Failed to instantiate prefab at '{prefabPath}', asset might be corrupted or not a GameObject.\"\n );\n return Response.Error(\n $\"Failed to instantiate prefab at '{prefabPath}'.\"\n );\n }\n // Name the instance based on the 'name' parameter, not the prefab's default name\n if (!string.IsNullOrEmpty(name))\n {\n newGo.name = name;\n }\n // Register Undo for prefab instantiation\n Undo.RegisterCreatedObjectUndo(\n newGo,\n $\"Instantiate Prefab '{prefabAsset.name}' as '{newGo.name}'\"\n );\n Debug.Log(\n $\"[ManageGameObject.Create] Instantiated prefab '{prefabAsset.name}' from path '{prefabPath}' as '{newGo.name}'.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error instantiating prefab '{prefabPath}': {e.Message}\"\n );\n }\n }\n else\n {\n // Only return error if prefabPath was specified but not found.\n // If prefabPath was empty/null, we proceed to create primitive/empty.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Prefab asset not found at path: '{prefabPath}'. Will proceed to create new object if specified.\"\n );\n // Do not return error here, allow fallback to primitive/empty creation\n }\n }\n\n // --- Fallback: Create Primitive or Empty GameObject ---\n bool createdNewObject = false; // Flag to track if we created (not instantiated)\n if (newGo == null) // Only proceed if prefab instantiation didn't happen\n {\n if (!string.IsNullOrEmpty(primitiveType))\n {\n try\n {\n PrimitiveType type = (PrimitiveType)\n Enum.Parse(typeof(PrimitiveType), primitiveType, true);\n newGo = GameObject.CreatePrimitive(type);\n // Set name *after* creation for primitives\n if (!string.IsNullOrEmpty(name))\n newGo.name = name;\n else\n return Response.Error(\n \"'name' parameter is required when creating a primitive.\"\n ); // Name is essential\n createdNewObject = true;\n }\n catch (ArgumentException)\n {\n return Response.Error(\n $\"Invalid primitive type: '{primitiveType}'. Valid types: {string.Join(\", \", Enum.GetNames(typeof(PrimitiveType)))}\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Failed to create primitive '{primitiveType}': {e.Message}\"\n );\n }\n }\n else // Create empty GameObject\n {\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\n \"'name' parameter is required for 'create' action when not instantiating a prefab or creating a primitive.\"\n );\n }\n newGo = new GameObject(name);\n createdNewObject = true;\n }\n // Record creation for Undo *only* if we created a new object\n if (createdNewObject)\n {\n Undo.RegisterCreatedObjectUndo(newGo, $\"Create GameObject '{newGo.name}'\");\n }\n }\n // --- Common Setup (Parent, Transform, Tag, Components) - Applied AFTER object exists ---\n if (newGo == null)\n {\n // Should theoretically not happen if logic above is correct, but safety check.\n return Response.Error(\"Failed to create or instantiate the GameObject.\");\n }\n\n // Record potential changes to the existing prefab instance or the new GO\n // Record transform separately in case parent changes affect it\n Undo.RecordObject(newGo.transform, \"Set GameObject Transform\");\n Undo.RecordObject(newGo, \"Set GameObject Properties\");\n\n // Set Parent\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject parentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\"); // Flexible parent finding\n if (parentGo == null)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up created object\n return Response.Error($\"Parent specified ('{parentToken}') but not found.\");\n }\n newGo.transform.SetParent(parentGo.transform, true); // worldPositionStays = true\n }\n\n // Set Transform\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue)\n newGo.transform.localPosition = position.Value;\n if (rotation.HasValue)\n newGo.transform.localEulerAngles = rotation.Value;\n if (scale.HasValue)\n newGo.transform.localScale = scale.Value;\n\n // Set Tag (added for create action)\n if (!string.IsNullOrEmpty(tag))\n {\n // Similar logic as in ModifyGameObject for setting/creating tags\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n newGo.tag = tagToSet;\n }\n catch (UnityException ex)\n {\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n InternalEditorUtility.AddTag(tagToSet);\n newGo.tag = tagToSet; // Retry\n Debug.Log(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}' during creation: {innerEx.Message}.\"\n );\n }\n }\n else\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to set tag to '{tagToSet}' during creation: {ex.Message}.\"\n );\n }\n }\n }\n\n // Set Layer (new for create action)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId != -1)\n {\n newGo.layer = layerId;\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Layer '{layerName}' not found. Using default layer.\"\n );\n }\n }\n\n // Add Components\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArray)\n {\n foreach (var compToken in componentsToAddArray)\n {\n string typeName = null;\n JObject properties = null;\n\n if (compToken.Type == JTokenType.String)\n {\n typeName = compToken.ToString();\n }\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(newGo, typeName, properties);\n if (addResult != null) // Check if AddComponentInternal returned an error object\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return addResult; // Return the error response\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Invalid component format in componentsToAdd: {compToken}\"\n );\n }\n }\n }\n\n // Save as Prefab ONLY if we *created* a new object AND saveAsPrefab is true\n GameObject finalInstance = newGo; // Use this for selection and return data\n if (createdNewObject && saveAsPrefab)\n {\n string finalPrefabPath = prefabPath; // Use a separate variable for saving path\n // This check should now happen *before* attempting to save\n if (string.IsNullOrEmpty(finalPrefabPath))\n {\n // Clean up the created object before returning error\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n \"'prefabPath' is required when 'saveAsPrefab' is true and creating a new object.\"\n );\n }\n // Ensure the *saving* path ends with .prefab\n if (!finalPrefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n Debug.Log(\n $\"[ManageGameObject.Create] Appending .prefab extension to save path: '{finalPrefabPath}' -> '{finalPrefabPath}.prefab'\"\n );\n finalPrefabPath += \".prefab\";\n }\n\n try\n {\n // Ensure directory exists using the final saving path\n string directoryPath = System.IO.Path.GetDirectoryName(finalPrefabPath);\n if (\n !string.IsNullOrEmpty(directoryPath)\n && !System.IO.Directory.Exists(directoryPath)\n )\n {\n System.IO.Directory.CreateDirectory(directoryPath);\n AssetDatabase.Refresh(); // Refresh asset database to recognize the new folder\n Debug.Log(\n $\"[ManageGameObject.Create] Created directory for prefab: {directoryPath}\"\n );\n }\n // Use SaveAsPrefabAssetAndConnect with the final saving path\n finalInstance = PrefabUtility.SaveAsPrefabAssetAndConnect(\n newGo,\n finalPrefabPath,\n InteractionMode.UserAction\n );\n\n if (finalInstance == null)\n {\n // Destroy the original if saving failed somehow (shouldn't usually happen if path is valid)\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n $\"Failed to save GameObject '{name}' as prefab at '{finalPrefabPath}'. Check path and permissions.\"\n );\n }\n Debug.Log(\n $\"[ManageGameObject.Create] GameObject '{name}' saved as prefab to '{finalPrefabPath}' and instance connected.\"\n );\n // Mark the new prefab asset as dirty? Not usually necessary, SaveAsPrefabAsset handles it.\n // EditorUtility.SetDirty(finalInstance); // Instance is handled by SaveAsPrefabAssetAndConnect\n }\n catch (Exception e)\n {\n // Clean up the instance if prefab saving fails\n UnityEngine.Object.DestroyImmediate(newGo); // Destroy the original attempt\n return Response.Error($\"Error saving prefab '{finalPrefabPath}': {e.Message}\");\n }\n }\n\n // Select the instance in the scene (either prefab instance or newly created/saved one)\n Selection.activeGameObject = finalInstance;\n\n // Determine appropriate success message using the potentially updated or original path\n string messagePrefabPath =\n finalInstance == null\n ? originalPrefabPath\n : AssetDatabase.GetAssetPath(\n PrefabUtility.GetCorrespondingObjectFromSource(finalInstance)\n ?? (UnityEngine.Object)finalInstance\n );\n string successMessage;\n if (!createdNewObject && !string.IsNullOrEmpty(messagePrefabPath)) // Instantiated existing prefab\n {\n successMessage =\n $\"Prefab '{messagePrefabPath}' instantiated successfully as '{finalInstance.name}'.\";\n }\n else if (createdNewObject && saveAsPrefab && !string.IsNullOrEmpty(messagePrefabPath)) // Created new and saved as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created and saved as prefab to '{messagePrefabPath}'.\";\n }\n else // Created new primitive or empty GO, didn't save as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created successfully in scene.\";\n }\n\n // Use the new serializer helper\n //return Response.Success(successMessage, GetGameObjectData(finalInstance));\n return Response.Success(successMessage, Helpers.GameObjectSerializer.GetGameObjectData(finalInstance));\n }\n\n private static object ModifyGameObject(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n // Record state for Undo *before* modifications\n Undo.RecordObject(targetGo.transform, \"Modify GameObject Transform\");\n Undo.RecordObject(targetGo, \"Modify GameObject Properties\");\n\n bool modified = false;\n\n // Rename (using consolidated 'name' parameter)\n string name = @params[\"name\"]?.ToString();\n if (!string.IsNullOrEmpty(name) && targetGo.name != name)\n {\n targetGo.name = name;\n modified = true;\n }\n\n // Change Parent (using consolidated 'parent' parameter)\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject newParentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\");\n // Check for hierarchy loops\n if (\n newParentGo == null\n && !(\n parentToken.Type == JTokenType.Null\n || (\n parentToken.Type == JTokenType.String\n && string.IsNullOrEmpty(parentToken.ToString())\n )\n )\n )\n {\n return Response.Error($\"New parent ('{parentToken}') not found.\");\n }\n if (newParentGo != null && newParentGo.transform.IsChildOf(targetGo.transform))\n {\n return Response.Error(\n $\"Cannot parent '{targetGo.name}' to '{newParentGo.name}', as it would create a hierarchy loop.\"\n );\n }\n if (targetGo.transform.parent != (newParentGo?.transform))\n {\n targetGo.transform.SetParent(newParentGo?.transform, true); // worldPositionStays = true\n modified = true;\n }\n }\n\n // Set Active State\n bool? setActive = @params[\"setActive\"]?.ToObject();\n if (setActive.HasValue && targetGo.activeSelf != setActive.Value)\n {\n targetGo.SetActive(setActive.Value);\n modified = true;\n }\n\n // Change Tag (using consolidated 'tag' parameter)\n string tag = @params[\"tag\"]?.ToString();\n // Only attempt to change tag if a non-null tag is provided and it's different from the current one.\n // Allow setting an empty string to remove the tag (Unity uses \"Untagged\").\n if (tag != null && targetGo.tag != tag)\n {\n // Ensure the tag is not empty, if empty, it means \"Untagged\" implicitly\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n targetGo.tag = tagToSet;\n modified = true;\n }\n catch (UnityException ex)\n {\n // Check if the error is specifically because the tag doesn't exist\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n // Attempt to create the tag using internal utility\n InternalEditorUtility.AddTag(tagToSet);\n // Wait a frame maybe? Not strictly necessary but sometimes helps editor updates.\n // yield return null; // Cannot yield here, editor script limitation\n\n // Retry setting the tag immediately after creation\n targetGo.tag = tagToSet;\n modified = true;\n Debug.Log(\n $\"[ManageGameObject] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n // Handle failure during tag creation or the second assignment attempt\n Debug.LogError(\n $\"[ManageGameObject] Failed to create or assign tag '{tagToSet}' after attempting creation: {innerEx.Message}\"\n );\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}': {innerEx.Message}. Check Tag Manager and permissions.\"\n );\n }\n }\n else\n {\n // If the exception was for a different reason, return the original error\n return Response.Error($\"Failed to set tag to '{tagToSet}': {ex.Message}.\");\n }\n }\n }\n\n // Change Layer (using consolidated 'layer' parameter)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId == -1 && layerName != \"Default\")\n {\n return Response.Error(\n $\"Invalid layer specified: '{layerName}'. Use a valid layer name.\"\n );\n }\n if (layerId != -1 && targetGo.layer != layerId)\n {\n targetGo.layer = layerId;\n modified = true;\n }\n }\n\n // Transform Modifications\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue && targetGo.transform.localPosition != position.Value)\n {\n targetGo.transform.localPosition = position.Value;\n modified = true;\n }\n if (rotation.HasValue && targetGo.transform.localEulerAngles != rotation.Value)\n {\n targetGo.transform.localEulerAngles = rotation.Value;\n modified = true;\n }\n if (scale.HasValue && targetGo.transform.localScale != scale.Value)\n {\n targetGo.transform.localScale = scale.Value;\n modified = true;\n }\n\n // --- Component Modifications ---\n // Note: These might need more specific Undo recording per component\n\n // Remove Components\n if (@params[\"componentsToRemove\"] is JArray componentsToRemoveArray)\n {\n foreach (var compToken in componentsToRemoveArray)\n {\n // ... (parsing logic as in CreateGameObject) ...\n string typeName = compToken.ToString();\n if (!string.IsNullOrEmpty(typeName))\n {\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error if removal failed\n modified = true;\n }\n }\n }\n\n // Add Components (similar to create)\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArrayModify)\n {\n foreach (var compToken in componentsToAddArrayModify)\n {\n string typeName = null;\n JObject properties = null;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult;\n modified = true;\n }\n }\n }\n\n // Set Component Properties\n if (@params[\"componentProperties\"] is JObject componentPropertiesObj)\n {\n foreach (var prop in componentPropertiesObj.Properties())\n {\n string compName = prop.Name;\n JObject propertiesToSet = prop.Value as JObject;\n if (propertiesToSet != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n compName,\n propertiesToSet\n );\n if (setResult != null)\n return setResult;\n modified = true;\n }\n }\n }\n\n if (!modified)\n {\n // Use the new serializer helper\n // return Response.Success(\n // $\"No modifications applied to GameObject '{targetGo.name}'.\",\n // GetGameObjectData(targetGo));\n\n return Response.Success(\n $\"No modifications applied to GameObject '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n EditorUtility.SetDirty(targetGo); // Mark scene as dirty\n // Use the new serializer helper\n return Response.Success(\n $\"GameObject '{targetGo.name}' modified successfully.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n // return Response.Success(\n // $\"GameObject '{targetGo.name}' modified successfully.\",\n // GetGameObjectData(targetGo));\n \n }\n\n private static object DeleteGameObject(JToken targetToken, string searchMethod)\n {\n // Find potentially multiple objects if name/tag search is used without find_all=false implicitly\n List targets = FindObjectsInternal(targetToken, searchMethod, true); // find_all=true for delete safety\n\n if (targets.Count == 0)\n {\n return Response.Error(\n $\"Target GameObject(s) ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n List deletedObjects = new List();\n foreach (var targetGo in targets)\n {\n if (targetGo != null)\n {\n string goName = targetGo.name;\n int goId = targetGo.GetInstanceID();\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(targetGo);\n deletedObjects.Add(new { name = goName, instanceID = goId });\n }\n }\n\n if (deletedObjects.Count > 0)\n {\n string message =\n targets.Count == 1\n ? $\"GameObject '{deletedObjects[0].GetType().GetProperty(\"name\").GetValue(deletedObjects[0])}' deleted successfully.\"\n : $\"{deletedObjects.Count} GameObjects deleted successfully.\";\n return Response.Success(message, deletedObjects);\n }\n else\n {\n // Should not happen if targets.Count > 0 initially, but defensive check\n return Response.Error(\"Failed to delete target GameObject(s).\");\n }\n }\n\n private static object FindGameObjects(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n bool findAll = @params[\"findAll\"]?.ToObject() ?? false;\n List foundObjects = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n @params\n );\n\n if (foundObjects.Count == 0)\n {\n return Response.Success(\"No matching GameObjects found.\", new List());\n }\n\n // Use the new serializer helper\n //var results = foundObjects.Select(go => GetGameObjectData(go)).ToList();\n var results = foundObjects.Select(go => Helpers.GameObjectSerializer.GetGameObjectData(go)).ToList();\n return Response.Success($\"Found {results.Count} GameObject(s).\", results);\n }\n\n private static object GetComponentsFromTarget(string target, string searchMethod, bool includeNonPublicSerialized = true)\n {\n GameObject targetGo = FindObjectInternal(target, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{target}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n try\n {\n // --- Get components, immediately copy to list, and null original array --- \n Component[] originalComponents = targetGo.GetComponents();\n List componentsToIterate = new List(originalComponents ?? Array.Empty()); // Copy immediately, handle null case\n int componentCount = componentsToIterate.Count; \n originalComponents = null; // Null the original reference\n // Debug.Log($\"[GetComponentsFromTarget] Found {componentCount} components on {targetGo.name}. Copied to list, nulled original. Starting REVERSE for loop...\");\n // --- End Copy and Null --- \n \n var componentData = new List();\n \n for (int i = componentCount - 1; i >= 0; i--) // Iterate backwards over the COPY\n {\n Component c = componentsToIterate[i]; // Use the copy\n if (c == null) \n {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] Encountered a null component at index {i} on {targetGo.name}. Skipping.\");\n continue; // Safety check\n }\n // Debug.Log($\"[GetComponentsFromTarget REVERSE for] Processing component: {c.GetType()?.FullName ?? \"null\"} (ID: {c.GetInstanceID()}) at index {i} on {targetGo.name}\");\n try \n {\n var data = Helpers.GameObjectSerializer.GetComponentData(c, includeNonPublicSerialized);\n if (data != null) // Ensure GetComponentData didn't return null\n {\n componentData.Insert(0, data); // Insert at beginning to maintain original order in final list\n }\n // else\n // {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] GetComponentData returned null for component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}. Skipping addition.\");\n // }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"[GetComponentsFromTarget REVERSE for] Error processing component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}: {ex.Message}\\n{ex.StackTrace}\");\n // Optionally add placeholder data or just skip\n componentData.Insert(0, new JObject( // Insert error marker at beginning\n new JProperty(\"typeName\", c.GetType().FullName + \" (Serialization Error)\"),\n new JProperty(\"instanceID\", c.GetInstanceID()),\n new JProperty(\"error\", ex.Message)\n ));\n }\n }\n // Debug.Log($\"[GetComponentsFromTarget] Finished REVERSE for loop.\");\n \n // Cleanup the list we created\n componentsToIterate.Clear();\n componentsToIterate = null;\n\n return Response.Success(\n $\"Retrieved {componentData.Count} components from '{targetGo.name}'.\",\n componentData // List was built in original order\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error getting components from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n private static object AddComponentToTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n JObject properties = null;\n\n // Allow adding component specified directly or via componentsToAdd array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n properties = @params[\"componentProperties\"]?[typeName] as JObject; // Check if props are nested under name\n }\n else if (\n @params[\"componentsToAdd\"] is JArray componentsToAddArray\n && componentsToAddArray.Count > 0\n )\n {\n var compToken = componentsToAddArray.First;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToAdd') is required.\"\n );\n }\n\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' added to '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n ); // Return updated GO data\n }\n\n private static object RemoveComponentFromTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n // Allow removing component specified directly or via componentsToRemove array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n }\n else if (\n @params[\"componentsToRemove\"] is JArray componentsToRemoveArray\n && componentsToRemoveArray.Count > 0\n )\n {\n typeName = componentsToRemoveArray.First?.ToString();\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToRemove') is required.\"\n );\n }\n\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' removed from '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n private static object SetComponentPropertyOnTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string compName = @params[\"componentName\"]?.ToString();\n JObject propertiesToSet = null;\n\n if (!string.IsNullOrEmpty(compName))\n {\n // Properties might be directly under componentProperties or nested under the component name\n if (@params[\"componentProperties\"] is JObject compProps)\n {\n propertiesToSet = compProps[compName] as JObject ?? compProps; // Allow flat or nested structure\n }\n }\n else\n {\n return Response.Error(\"'componentName' parameter is required.\");\n }\n\n if (propertiesToSet == null || !propertiesToSet.HasValues)\n {\n return Response.Error(\n \"'componentProperties' dictionary for the specified component is required and cannot be empty.\"\n );\n }\n\n var setResult = SetComponentPropertiesInternal(targetGo, compName, propertiesToSet);\n if (setResult != null)\n return setResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Properties set for component '{compName}' on '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Finds a single GameObject based on token (ID, name, path) and search method.\n /// \n private static GameObject FindObjectInternal(\n JToken targetToken,\n string searchMethod,\n JObject findParams = null\n )\n {\n // If find_all is not explicitly false, we still want only one for most single-target operations.\n bool findAll = findParams?[\"findAll\"]?.ToObject() ?? false;\n // If a specific target ID is given, always find just that one.\n if (\n targetToken?.Type == JTokenType.Integer\n || (searchMethod == \"by_id\" && int.TryParse(targetToken?.ToString(), out _))\n )\n {\n findAll = false;\n }\n List results = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n findParams\n );\n return results.Count > 0 ? results[0] : null;\n }\n\n /// \n /// Core logic for finding GameObjects based on various criteria.\n /// \n private static List FindObjectsInternal(\n JToken targetToken,\n string searchMethod,\n bool findAll,\n JObject findParams = null\n )\n {\n List results = new List();\n string searchTerm = findParams?[\"searchTerm\"]?.ToString() ?? targetToken?.ToString(); // Use searchTerm if provided, else the target itself\n bool searchInChildren = findParams?[\"searchInChildren\"]?.ToObject() ?? false;\n bool searchInactive = findParams?[\"searchInactive\"]?.ToObject() ?? false;\n\n // Default search method if not specified\n if (string.IsNullOrEmpty(searchMethod))\n {\n if (targetToken?.Type == JTokenType.Integer)\n searchMethod = \"by_id\";\n else if (!string.IsNullOrEmpty(searchTerm) && searchTerm.Contains('/'))\n searchMethod = \"by_path\";\n else\n searchMethod = \"by_name\"; // Default fallback\n }\n\n GameObject rootSearchObject = null;\n // If searching in children, find the initial target first\n if (searchInChildren && targetToken != null)\n {\n rootSearchObject = FindObjectInternal(targetToken, \"by_id_or_name_or_path\"); // Find the root for child search\n if (rootSearchObject == null)\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Root object '{targetToken}' for child search not found.\"\n );\n return results; // Return empty if root not found\n }\n }\n\n switch (searchMethod)\n {\n case \"by_id\":\n if (int.TryParse(searchTerm, out int instanceId))\n {\n // EditorUtility.InstanceIDToObject is slow, iterate manually if possible\n // GameObject obj = EditorUtility.InstanceIDToObject(instanceId) as GameObject;\n var allObjects = GetAllSceneObjects(searchInactive); // More efficient\n GameObject obj = allObjects.FirstOrDefault(go =>\n go.GetInstanceID() == instanceId\n );\n if (obj != null)\n results.Add(obj);\n }\n break;\n case \"by_name\":\n var searchPoolName = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolName.Where(go => go.name == searchTerm));\n break;\n case \"by_path\":\n // Path is relative to scene root or rootSearchObject\n Transform foundTransform = rootSearchObject\n ? rootSearchObject.transform.Find(searchTerm)\n : GameObject.Find(searchTerm)?.transform;\n if (foundTransform != null)\n results.Add(foundTransform.gameObject);\n break;\n case \"by_tag\":\n var searchPoolTag = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolTag.Where(go => go.CompareTag(searchTerm)));\n break;\n case \"by_layer\":\n var searchPoolLayer = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n if (int.TryParse(searchTerm, out int layerIndex))\n {\n results.AddRange(searchPoolLayer.Where(go => go.layer == layerIndex));\n }\n else\n {\n int namedLayer = LayerMask.NameToLayer(searchTerm);\n if (namedLayer != -1)\n results.AddRange(searchPoolLayer.Where(go => go.layer == namedLayer));\n }\n break;\n case \"by_component\":\n Type componentType = FindType(searchTerm);\n if (componentType != null)\n {\n // Determine FindObjectsInactive based on the searchInactive flag\n FindObjectsInactive findInactive = searchInactive\n ? FindObjectsInactive.Include\n : FindObjectsInactive.Exclude;\n // Replace FindObjectsOfType with FindObjectsByType, specifying the sorting mode and inactive state\n var searchPoolComp = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(componentType, searchInactive)\n .Select(c => (c as Component).gameObject)\n : UnityEngine\n .Object.FindObjectsByType(\n componentType,\n findInactive,\n FindObjectsSortMode.None\n )\n .Select(c => (c as Component).gameObject);\n results.AddRange(searchPoolComp.Where(go => go != null)); // Ensure GO is valid\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Component type not found: {searchTerm}\"\n );\n }\n break;\n case \"by_id_or_name_or_path\": // Helper method used internally\n if (int.TryParse(searchTerm, out int id))\n {\n var allObjectsId = GetAllSceneObjects(true); // Search inactive for internal lookup\n GameObject objById = allObjectsId.FirstOrDefault(go =>\n go.GetInstanceID() == id\n );\n if (objById != null)\n {\n results.Add(objById);\n break;\n }\n }\n GameObject objByPath = GameObject.Find(searchTerm);\n if (objByPath != null)\n {\n results.Add(objByPath);\n break;\n }\n\n var allObjectsName = GetAllSceneObjects(true);\n results.AddRange(allObjectsName.Where(go => go.name == searchTerm));\n break;\n default:\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Unknown search method: {searchMethod}\"\n );\n break;\n }\n\n // If only one result is needed, return just the first one found.\n if (!findAll && results.Count > 1)\n {\n return new List { results[0] };\n }\n\n return results.Distinct().ToList(); // Ensure uniqueness\n }\n\n // Helper to get all scene objects efficiently\n private static IEnumerable GetAllSceneObjects(bool includeInactive)\n {\n // SceneManager.GetActiveScene().GetRootGameObjects() is faster than FindObjectsOfType()\n var rootObjects = SceneManager.GetActiveScene().GetRootGameObjects();\n var allObjects = new List();\n foreach (var root in rootObjects)\n {\n allObjects.AddRange(\n root.GetComponentsInChildren(includeInactive)\n .Select(t => t.gameObject)\n );\n }\n return allObjects;\n }\n\n /// \n /// Adds a component by type name and optionally sets properties.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object AddComponentInternal(\n GameObject targetGo,\n string typeName,\n JObject properties\n )\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error(\n $\"Component type '{typeName}' not found or is not a valid Component.\"\n );\n }\n if (!typeof(Component).IsAssignableFrom(componentType))\n {\n return Response.Error($\"Type '{typeName}' is not a Component.\");\n }\n\n // Prevent adding Transform again\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot add another Transform component.\");\n }\n\n // Check for 2D/3D physics component conflicts\n bool isAdding2DPhysics =\n typeof(Rigidbody2D).IsAssignableFrom(componentType)\n || typeof(Collider2D).IsAssignableFrom(componentType);\n bool isAdding3DPhysics =\n typeof(Rigidbody).IsAssignableFrom(componentType)\n || typeof(Collider).IsAssignableFrom(componentType);\n\n if (isAdding2DPhysics)\n {\n // Check if the GameObject already has any 3D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 2D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 3D Rigidbody or Collider.\"\n );\n }\n }\n else if (isAdding3DPhysics)\n {\n // Check if the GameObject already has any 2D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 3D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 2D Rigidbody or Collider.\"\n );\n }\n }\n\n try\n {\n // Use Undo.AddComponent for undo support\n Component newComponent = Undo.AddComponent(targetGo, componentType);\n if (newComponent == null)\n {\n return Response.Error(\n $\"Failed to add component '{typeName}' to '{targetGo.name}'. It might be disallowed (e.g., adding script twice).\"\n );\n }\n\n // Set default values for specific component types\n if (newComponent is Light light)\n {\n // Default newly added lights to directional\n light.type = LightType.Directional;\n }\n\n // Set properties if provided\n if (properties != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n typeName,\n properties,\n newComponent\n ); // Pass the new component instance\n if (setResult != null)\n {\n // If setting properties failed, maybe remove the added component?\n Undo.DestroyObjectImmediate(newComponent);\n return setResult; // Return the error from setting properties\n }\n }\n\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error adding component '{typeName}' to '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Removes a component by type name.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object RemoveComponentInternal(GameObject targetGo, string typeName)\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error($\"Component type '{typeName}' not found for removal.\");\n }\n\n // Prevent removing essential components\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot remove the Transform component.\");\n }\n\n Component componentToRemove = targetGo.GetComponent(componentType);\n if (componentToRemove == null)\n {\n return Response.Error(\n $\"Component '{typeName}' not found on '{targetGo.name}' to remove.\"\n );\n }\n\n try\n {\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(componentToRemove);\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error removing component '{typeName}' from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Sets properties on a component.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object SetComponentPropertiesInternal(\n GameObject targetGo,\n string compName,\n JObject propertiesToSet,\n Component targetComponentInstance = null\n )\n {\n Component targetComponent = targetComponentInstance ?? targetGo.GetComponent(compName);\n if (targetComponent == null)\n {\n return Response.Error(\n $\"Component '{compName}' not found on '{targetGo.name}' to set properties.\"\n );\n }\n\n Undo.RecordObject(targetComponent, \"Set Component Properties\");\n\n foreach (var prop in propertiesToSet.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n\n try\n {\n if (!SetProperty(targetComponent, propName, propValue))\n {\n // Log warning if property could not be set\n Debug.LogWarning(\n $\"[ManageGameObject] Could not set property '{propName}' on component '{compName}' ('{targetComponent.GetType().Name}'). Property might not exist, be read-only, or type mismatch.\"\n );\n // Optionally return an error here instead of just logging\n // return Response.Error($\"Could not set property '{propName}' on component '{compName}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageGameObject] Error setting property '{propName}' on '{compName}': {e.Message}\"\n );\n // Optionally return an error here\n // return Response.Error($\"Error setting property '{propName}' on '{compName}': {e.Message}\");\n }\n }\n EditorUtility.SetDirty(targetComponent);\n return null; // Success (or partial success if warnings were logged)\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types.\n /// \n private static bool SetProperty(object target, string memberName, JToken value)\n {\n Type type = target.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // --- Use a dedicated serializer for input conversion ---\n // Define this somewhere accessible, maybe static readonly field\n JsonSerializerSettings inputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n // Add specific converters needed for INPUT deserialization if different from output\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Crucial for finding references from instructions\n }\n // No ReferenceLoopHandling needed typically for input\n };\n JsonSerializer inputSerializer = JsonSerializer.Create(inputSerializerSettings);\n // --- End Serializer Setup ---\n\n try\n {\n // Handle special case for materials with dot notation (material.property)\n // Examples: material.color, sharedMaterial.color, materials[0].color\n if (memberName.Contains('.') || memberName.Contains('['))\n {\n // Pass the inputSerializer down for nested conversions\n return SetNestedProperty(target, memberName, value, inputSerializer);\n }\n\n PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for property '{memberName}' (Type: {propInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null) // Check if !IsLiteral?\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for field '{memberName}' (Type: {fieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetProperty] Failed to set '{memberName}' on {type.Name}: {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n return false;\n }\n\n /// \n /// Sets a nested property using dot notation (e.g., \"material.color\") or array access (e.g., \"materials[0]\")\n /// \n // Pass the input serializer for conversions\n //Using the serializer helper\n private static bool SetNestedProperty(object target, string path, JToken value, JsonSerializer inputSerializer)\n {\n try\n {\n // Split the path into parts (handling both dot notation and array indexing)\n string[] pathParts = SplitPropertyPath(path);\n if (pathParts.Length == 0)\n return false;\n\n object currentObject = target;\n Type currentType = currentObject.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // Traverse the path until we reach the final property\n for (int i = 0; i < pathParts.Length - 1; i++)\n {\n string part = pathParts[i];\n bool isArray = false;\n int arrayIndex = -1;\n\n // Check if this part contains array indexing\n if (part.Contains(\"[\"))\n {\n int startBracket = part.IndexOf('[');\n int endBracket = part.IndexOf(']');\n if (startBracket > 0 && endBracket > startBracket)\n {\n string indexStr = part.Substring(\n startBracket + 1,\n endBracket - startBracket - 1\n );\n if (int.TryParse(indexStr, out arrayIndex))\n {\n isArray = true;\n part = part.Substring(0, startBracket);\n }\n }\n }\n // Get the property/field\n PropertyInfo propInfo = currentType.GetProperty(part, flags);\n FieldInfo fieldInfo = null;\n if (propInfo == null)\n {\n fieldInfo = currentType.GetField(part, flags);\n if (fieldInfo == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find property or field '{part}' on type '{currentType.Name}'\"\n );\n return false;\n }\n }\n\n // Get the value\n currentObject =\n propInfo != null\n ? propInfo.GetValue(currentObject)\n : fieldInfo.GetValue(currentObject);\n //Need to stop if current property is null\n if (currentObject == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is null, cannot access nested properties.\"\n );\n return false;\n }\n // If this part was an array or list, access the specific index\n if (isArray)\n {\n if (currentObject is Material[])\n {\n var materials = currentObject as Material[];\n if (arrayIndex < 0 || arrayIndex >= materials.Length)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Material index {arrayIndex} out of range (0-{materials.Length - 1})\"\n );\n return false;\n }\n currentObject = materials[arrayIndex];\n }\n else if (currentObject is System.Collections.IList)\n {\n var list = currentObject as System.Collections.IList;\n if (arrayIndex < 0 || arrayIndex >= list.Count)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Index {arrayIndex} out of range (0-{list.Count - 1})\"\n );\n return false;\n }\n currentObject = list[arrayIndex];\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is not an array or list, cannot access by index.\"\n );\n return false;\n }\n }\n currentType = currentObject.GetType();\n }\n\n // Set the final property\n string finalPart = pathParts[pathParts.Length - 1];\n\n // Special handling for Material properties (shader properties)\n if (currentObject is Material material && finalPart.StartsWith(\"_\"))\n {\n // Use the serializer to convert the JToken value first\n if (value is JArray jArray)\n {\n // Try converting to known types that SetColor/SetVector accept\n if (jArray.Count == 4) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { }\n try { Vector4 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n } else if (jArray.Count == 3) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { } // ToObject handles conversion to Color\n } else if (jArray.Count == 2) {\n try { Vector2 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n }\n }\n else if (value.Type == JTokenType.Float || value.Type == JTokenType.Integer)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer)); return true; } catch { }\n }\n else if (value.Type == JTokenType.Boolean)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer) ? 1f : 0f); return true; } catch { }\n }\n else if (value.Type == JTokenType.String)\n {\n // Try converting to Texture using the serializer/converter\n try {\n Texture texture = value.ToObject(inputSerializer);\n if (texture != null) {\n material.SetTexture(finalPart, texture);\n return true;\n }\n } catch { }\n }\n\n Debug.LogWarning(\n $\"[SetNestedProperty] Unsupported or failed conversion for material property '{finalPart}' from value: {value.ToString(Formatting.None)}\"\n );\n return false;\n }\n\n // For standard properties (not shader specific)\n PropertyInfo finalPropInfo = currentType.GetProperty(finalPart, flags);\n if (finalPropInfo != null && finalPropInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalPropInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalPropInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for property '{finalPart}' (Type: {finalPropInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo finalFieldInfo = currentType.GetField(finalPart, flags);\n if (finalFieldInfo != null)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalFieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalFieldInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for field '{finalPart}' (Type: {finalFieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find final writable property or field '{finalPart}' on type '{currentType.Name}'\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetNestedProperty] Error setting nested property '{path}': {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n\n return false;\n }\n\n\n /// \n /// Split a property path into parts, handling both dot notation and array indexers\n /// \n private static string[] SplitPropertyPath(string path)\n {\n // Handle complex paths with both dots and array indexers\n List parts = new List();\n int startIndex = 0;\n bool inBrackets = false;\n\n for (int i = 0; i < path.Length; i++)\n {\n char c = path[i];\n\n if (c == '[')\n {\n inBrackets = true;\n }\n else if (c == ']')\n {\n inBrackets = false;\n }\n else if (c == '.' && !inBrackets)\n {\n // Found a dot separator outside of brackets\n parts.Add(path.Substring(startIndex, i - startIndex));\n startIndex = i + 1;\n }\n }\n if (startIndex < path.Length)\n {\n parts.Add(path.Substring(startIndex));\n }\n return parts.ToArray();\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types, using JsonSerializer.\n /// \n // Pass the input serializer\n private static object ConvertJTokenToType(JToken token, Type targetType, JsonSerializer inputSerializer)\n {\n if (token == null || token.Type == JTokenType.Null)\n {\n if (targetType.IsValueType && Nullable.GetUnderlyingType(targetType) == null)\n {\n Debug.LogWarning($\"Cannot assign null to non-nullable value type {targetType.Name}. Returning default value.\");\n return Activator.CreateInstance(targetType);\n }\n return null;\n }\n\n try\n {\n // Use the provided serializer instance which includes our custom converters\n return token.ToObject(targetType, inputSerializer);\n }\n catch (JsonSerializationException jsonEx)\n {\n Debug.LogError($\"JSON Deserialization Error converting token to {targetType.FullName}: {jsonEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n // Optionally re-throw or return null/default\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n throw; // Re-throw to indicate failure higher up\n }\n catch (ArgumentException argEx)\n {\n Debug.LogError($\"Argument Error converting token to {targetType.FullName}: {argEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Unexpected error converting token to {targetType.FullName}: {ex}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n // If ToObject succeeded, it would have returned. If it threw, we wouldn't reach here.\n // This fallback logic is likely unreachable if ToObject covers all cases or throws on failure.\n // Debug.LogWarning($\"Conversion failed for token to {targetType.FullName}. Token: {token.ToString(Formatting.None)}\");\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n }\n\n // --- ParseJTokenTo... helpers are likely redundant now with the serializer approach ---\n // Keep them temporarily for reference or if specific fallback logic is ever needed.\n\n private static Vector3 ParseJTokenToVector3(JToken token)\n {\n // ... (implementation - likely replaced by Vector3Converter) ...\n // Consider removing these if the serializer handles them reliably.\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\"))\n {\n return new Vector3(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 3)\n {\n return new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector3 using fallback. Returning Vector3.zero.\");\n return Vector3.zero;\n\n }\n private static Vector2 ParseJTokenToVector2(JToken token)\n {\n // ... (implementation - likely replaced by Vector2Converter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\"))\n {\n return new Vector2(obj[\"x\"].ToObject(), obj[\"y\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 2)\n {\n return new Vector2(arr[0].ToObject(), arr[1].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector2 using fallback. Returning Vector2.zero.\");\n return Vector2.zero;\n }\n private static Quaternion ParseJTokenToQuaternion(JToken token)\n {\n // ... (implementation - likely replaced by QuaternionConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\") && obj.ContainsKey(\"w\"))\n {\n return new Quaternion(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject(), obj[\"w\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Quaternion(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Quaternion using fallback. Returning Quaternion.identity.\");\n return Quaternion.identity;\n }\n private static Color ParseJTokenToColor(JToken token)\n {\n // ... (implementation - likely replaced by ColorConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"r\") && obj.ContainsKey(\"g\") && obj.ContainsKey(\"b\") && obj.ContainsKey(\"a\"))\n {\n return new Color(obj[\"r\"].ToObject(), obj[\"g\"].ToObject(), obj[\"b\"].ToObject(), obj[\"a\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Color(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Color using fallback. Returning Color.white.\");\n return Color.white;\n }\n private static Rect ParseJTokenToRect(JToken token)\n {\n // ... (implementation - likely replaced by RectConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"width\") && obj.ContainsKey(\"height\"))\n {\n return new Rect(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"width\"].ToObject(), obj[\"height\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Rect(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Rect using fallback. Returning Rect.zero.\");\n return Rect.zero;\n }\n private static Bounds ParseJTokenToBounds(JToken token)\n {\n // ... (implementation - likely replaced by BoundsConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"center\") && obj.ContainsKey(\"size\"))\n {\n // Requires Vector3 conversion, which should ideally use the serializer too\n Vector3 center = ParseJTokenToVector3(obj[\"center\"]); // Or use obj[\"center\"].ToObject(inputSerializer)\n Vector3 size = ParseJTokenToVector3(obj[\"size\"]); // Or use obj[\"size\"].ToObject(inputSerializer)\n return new Bounds(center, size);\n }\n // Array fallback for Bounds is less intuitive, maybe remove?\n // if (token is JArray arr && arr.Count >= 6)\n // {\n // return new Bounds(new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject()), new Vector3(arr[3].ToObject(), arr[4].ToObject(), arr[5].ToObject()));\n // }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Bounds using fallback. Returning new Bounds(Vector3.zero, Vector3.zero).\");\n return new Bounds(Vector3.zero, Vector3.zero);\n }\n // --- End Redundant Parse Helpers ---\n\n /// \n /// Finds a specific UnityEngine.Object based on a find instruction JObject.\n /// Primarily used by UnityEngineObjectConverter during deserialization.\n /// \n // Made public static so UnityEngineObjectConverter can call it. Moved from ConvertJTokenToType.\n public static UnityEngine.Object FindObjectByInstruction(JObject instruction, Type targetType)\n {\n string findTerm = instruction[\"find\"]?.ToString();\n string method = instruction[\"method\"]?.ToString()?.ToLower();\n string componentName = instruction[\"component\"]?.ToString(); // Specific component to get\n\n if (string.IsNullOrEmpty(findTerm))\n {\n Debug.LogWarning(\"Find instruction missing 'find' term.\");\n return null;\n }\n\n // Use a flexible default search method if none provided\n string searchMethodToUse = string.IsNullOrEmpty(method) ? \"by_id_or_name_or_path\" : method;\n\n // If the target is an asset (Material, Texture, ScriptableObject etc.) try AssetDatabase first\n if (typeof(Material).IsAssignableFrom(targetType) ||\n typeof(Texture).IsAssignableFrom(targetType) ||\n typeof(ScriptableObject).IsAssignableFrom(targetType) ||\n targetType.FullName.StartsWith(\"UnityEngine.U2D\") || // Sprites etc.\n typeof(AudioClip).IsAssignableFrom(targetType) ||\n typeof(AnimationClip).IsAssignableFrom(targetType) ||\n typeof(Font).IsAssignableFrom(targetType) ||\n typeof(Shader).IsAssignableFrom(targetType) ||\n typeof(ComputeShader).IsAssignableFrom(targetType) ||\n typeof(GameObject).IsAssignableFrom(targetType) && findTerm.StartsWith(\"Assets/\")) // Prefab check\n {\n // Try loading directly by path/GUID first\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(findTerm, targetType);\n if (asset != null) return asset;\n asset = AssetDatabase.LoadAssetAtPath(findTerm); // Try generic if type specific failed\n if (asset != null && targetType.IsAssignableFrom(asset.GetType())) return asset;\n\n\n // If direct path failed, try finding by name/type using FindAssets\n string searchFilter = $\"t:{targetType.Name} {System.IO.Path.GetFileNameWithoutExtension(findTerm)}\"; // Search by type and name\n string[] guids = AssetDatabase.FindAssets(searchFilter);\n\n if (guids.Length == 1)\n {\n asset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]), targetType);\n if (asset != null) return asset;\n }\n else if (guids.Length > 1)\n {\n Debug.LogWarning($\"[FindObjectByInstruction] Ambiguous asset find: Found {guids.Length} assets matching filter '{searchFilter}'. Provide a full path or unique name.\");\n // Optionally return the first one? Or null? Returning null is safer.\n return null;\n }\n // If still not found, fall through to scene search (though unlikely for assets)\n }\n\n\n // --- Scene Object Search ---\n // Find the GameObject using the internal finder\n GameObject foundGo = FindObjectInternal(new JValue(findTerm), searchMethodToUse);\n\n if (foundGo == null)\n {\n // Don't warn yet, could still be an asset not found above\n // Debug.LogWarning($\"Could not find GameObject using instruction: {instruction}\");\n return null;\n }\n\n // Now, get the target object/component from the found GameObject\n if (targetType == typeof(GameObject))\n {\n return foundGo; // We were looking for a GameObject\n }\n else if (typeof(Component).IsAssignableFrom(targetType))\n {\n Type componentToGetType = targetType;\n if (!string.IsNullOrEmpty(componentName))\n {\n Type specificCompType = FindType(componentName);\n if (specificCompType != null && typeof(Component).IsAssignableFrom(specificCompType))\n {\n componentToGetType = specificCompType;\n }\n else\n {\n Debug.LogWarning($\"Could not find component type '{componentName}' specified in find instruction. Falling back to target type '{targetType.Name}'.\");\n }\n }\n\n Component foundComp = foundGo.GetComponent(componentToGetType);\n if (foundComp == null)\n {\n Debug.LogWarning($\"Found GameObject '{foundGo.name}' but could not find component of type '{componentToGetType.Name}'.\");\n }\n return foundComp;\n }\n else\n {\n Debug.LogWarning($\"Find instruction handling not implemented for target type: {targetType.Name}\");\n return null;\n }\n }\n\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Handle fully qualified names first\n Type type = Type.GetType(typeName);\n if (type != null) return type;\n\n // Handle common namespaces implicitly (add more as needed)\n string[] namespaces = { \"UnityEngine\", \"UnityEngine.UI\", \"UnityEngine.AI\", \"UnityEngine.Animations\", \"UnityEngine.Audio\", \"UnityEngine.EventSystems\", \"UnityEngine.InputSystem\", \"UnityEngine.Networking\", \"UnityEngine.Rendering\", \"UnityEngine.SceneManagement\", \"UnityEngine.Tilemaps\", \"UnityEngine.U2D\", \"UnityEngine.Video\", \"UnityEditor\", \"UnityEditor.AI\", \"UnityEditor.Animations\", \"UnityEditor.Experimental.GraphView\", \"UnityEditor.IMGUI.Controls\", \"UnityEditor.PackageManager.UI\", \"UnityEditor.SceneManagement\", \"UnityEditor.UI\", \"UnityEditor.U2D\", \"UnityEditor.VersionControl\" }; // Add more relevant namespaces\n\n foreach (string ns in namespaces) {\n type = Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}.CoreModule\") ?? // Heuristic: Check CoreModule first for UnityEngine/UnityEditor\n Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}\"); // Try assembly matching namespace root\n if (type != null) return type;\n }\n\n\n // If not found, search all loaded assemblies (slower, last resort)\n // Prioritize assemblies likely to contain game/editor types\n Assembly[] priorityAssemblies = {\n Assembly.Load(\"Assembly-CSharp\"), // Main game scripts\n Assembly.Load(\"Assembly-CSharp-Editor\"), // Main editor scripts\n // Add other important project assemblies if known\n };\n foreach (var assembly in priorityAssemblies.Where(a => a != null))\n {\n type = assembly.GetType(typeName) ?? assembly.GetType(\"UnityEngine.\" + typeName) ?? assembly.GetType(\"UnityEditor.\" + typeName);\n if (type != null) return type;\n }\n\n // Search remaining assemblies\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Except(priorityAssemblies))\n {\n try { // Protect against assembly loading errors\n type = assembly.GetType(typeName);\n if (type != null) return type;\n // Also check with common namespaces if simple name given\n foreach (string ns in namespaces) {\n type = assembly.GetType($\"{ns}.{typeName}\");\n if (type != null) return type;\n }\n } catch (Exception ex) {\n Debug.LogWarning($\"[FindType] Error searching assembly {assembly.FullName}: {ex.Message}\");\n }\n }\n\n Debug.LogWarning($\"[FindType] Type not found after extensive search: '{typeName}'\");\n return null; // Not found\n }\n\n /// \n /// Parses a JArray like [x, y, z] into a Vector3.\n /// \n private static Vector3? ParseVector3(JArray array)\n {\n if (array != null && array.Count == 3)\n {\n try\n {\n // Use ToObject for potentially better handling than direct indexing\n return new Vector3(\n array[0].ToObject(),\n array[1].ToObject(),\n array[2].ToObject()\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Failed to parse JArray as Vector3: {array}. Error: {ex.Message}\");\n }\n }\n return null;\n }\n\n // Removed GetGameObjectData, GetComponentData, and related private helpers/caching/serializer setup.\n // They are now in Helpers.GameObjectSerializer\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageAsset.cs", "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\n#if UNITY_6000_0_OR_NEWER\nusing PhysicsMaterialType = UnityEngine.PhysicsMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicsMaterialCombine; \n#else\nusing PhysicsMaterialType = UnityEngine.PhysicMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicMaterialCombine;\n#endif\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles asset management operations within the Unity project.\n /// \n public static class ManageAsset\n {\n // --- Main Handler ---\n\n // Define the list of valid actions\n private static readonly List ValidActions = new List\n {\n \"import\",\n \"create\",\n \"modify\",\n \"delete\",\n \"duplicate\",\n \"move\",\n \"rename\",\n \"search\",\n \"get_info\",\n \"create_folder\",\n \"get_components\",\n };\n\n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Check if the action is valid before switching\n if (!ValidActions.Contains(action))\n {\n string validActionsList = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsList}\"\n );\n }\n\n // Common parameters\n string path = @params[\"path\"]?.ToString();\n\n try\n {\n switch (action)\n {\n case \"import\":\n // Note: Unity typically auto-imports. This might re-import or configure import settings.\n return ReimportAsset(path, @params[\"properties\"] as JObject);\n case \"create\":\n return CreateAsset(@params);\n case \"modify\":\n return ModifyAsset(path, @params[\"properties\"] as JObject);\n case \"delete\":\n return DeleteAsset(path);\n case \"duplicate\":\n return DuplicateAsset(path, @params[\"destination\"]?.ToString());\n case \"move\": // Often same as rename if within Assets/\n case \"rename\":\n return MoveOrRenameAsset(path, @params[\"destination\"]?.ToString());\n case \"search\":\n return SearchAssets(@params);\n case \"get_info\":\n return GetAssetInfo(\n path,\n @params[\"generatePreview\"]?.ToObject() ?? false\n );\n case \"create_folder\": // Added specific action for clarity\n return CreateFolder(path);\n case \"get_components\":\n return GetComponentsFromAsset(path);\n\n default:\n // This error message is less likely to be hit now, but kept here as a fallback or for potential future modifications.\n string validActionsListDefault = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsListDefault}\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageAsset] Action '{action}' failed for path '{path}': {e}\");\n return Response.Error(\n $\"Internal error processing action '{action}' on '{path}': {e.Message}\"\n );\n }\n }\n\n // --- Action Implementations ---\n\n private static object ReimportAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for reimport.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // TODO: Apply importer properties before reimporting?\n // This is complex as it requires getting the AssetImporter, casting it,\n // applying properties via reflection or specific methods, saving, then reimporting.\n if (properties != null && properties.HasValues)\n {\n Debug.LogWarning(\n \"[ManageAsset.Reimport] Modifying importer properties before reimport is not fully implemented yet.\"\n );\n // AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n // if (importer != null) { /* Apply properties */ AssetDatabase.WriteImportSettingsIfDirty(fullPath); }\n }\n\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate);\n // AssetDatabase.Refresh(); // Usually ImportAsset handles refresh\n return Response.Success($\"Asset '{fullPath}' reimported.\", GetAssetData(fullPath));\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to reimport asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateAsset(JObject @params)\n {\n string path = @params[\"path\"]?.ToString();\n string assetType = @params[\"assetType\"]?.ToString();\n JObject properties = @params[\"properties\"] as JObject;\n\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create.\");\n if (string.IsNullOrEmpty(assetType))\n return Response.Error(\"'assetType' is required for create.\");\n\n string fullPath = SanitizeAssetPath(path);\n string directory = Path.GetDirectoryName(fullPath);\n\n // Ensure directory exists\n if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), directory)))\n {\n Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), directory));\n AssetDatabase.Refresh(); // Make sure Unity knows about the new folder\n }\n\n if (AssetExists(fullPath))\n return Response.Error($\"Asset already exists at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object newAsset = null;\n string lowerAssetType = assetType.ToLowerInvariant();\n\n // Handle common asset types\n if (lowerAssetType == \"folder\")\n {\n return CreateFolder(path); // Use dedicated method\n }\n else if (lowerAssetType == \"material\")\n {\n Material mat = new Material(Shader.Find(\"Standard\")); // Default shader\n // TODO: Apply properties from JObject (e.g., shader name, color, texture assignments)\n if (properties != null)\n ApplyMaterialProperties(mat, properties);\n AssetDatabase.CreateAsset(mat, fullPath);\n newAsset = mat;\n }\n else if (lowerAssetType == \"physicsmaterial\")\n {\n PhysicsMaterialType pmat = new PhysicsMaterialType();\n if (properties != null)\n ApplyPhysicsMaterialProperties(pmat, properties);\n AssetDatabase.CreateAsset(pmat, fullPath);\n newAsset = pmat;\n }\n else if (lowerAssetType == \"scriptableobject\")\n {\n string scriptClassName = properties?[\"scriptClass\"]?.ToString();\n if (string.IsNullOrEmpty(scriptClassName))\n return Response.Error(\n \"'scriptClass' property required when creating ScriptableObject asset.\"\n );\n\n Type scriptType = FindType(scriptClassName);\n if (\n scriptType == null\n || !typeof(ScriptableObject).IsAssignableFrom(scriptType)\n )\n {\n return Response.Error(\n $\"Script class '{scriptClassName}' not found or does not inherit from ScriptableObject.\"\n );\n }\n\n ScriptableObject so = ScriptableObject.CreateInstance(scriptType);\n // TODO: Apply properties from JObject to the ScriptableObject instance?\n AssetDatabase.CreateAsset(so, fullPath);\n newAsset = so;\n }\n else if (lowerAssetType == \"prefab\")\n {\n // Creating prefabs usually involves saving an existing GameObject hierarchy.\n // A common pattern is to create an empty GameObject, configure it, and then save it.\n return Response.Error(\n \"Creating prefabs programmatically usually requires a source GameObject. Use manage_gameobject to create/configure, then save as prefab via a separate mechanism or future enhancement.\"\n );\n // Example (conceptual):\n // GameObject source = GameObject.Find(properties[\"sourceGameObject\"].ToString());\n // if(source != null) PrefabUtility.SaveAsPrefabAsset(source, fullPath);\n }\n // TODO: Add more asset types (Animation Controller, Scene, etc.)\n else\n {\n // Generic creation attempt (might fail or create empty files)\n // For some types, just creating the file might be enough if Unity imports it.\n // File.Create(Path.Combine(Directory.GetCurrentDirectory(), fullPath)).Close();\n // AssetDatabase.ImportAsset(fullPath); // Let Unity try to import it\n // newAsset = AssetDatabase.LoadAssetAtPath(fullPath);\n return Response.Error(\n $\"Creation for asset type '{assetType}' is not explicitly supported yet. Supported: Folder, Material, ScriptableObject.\"\n );\n }\n\n if (\n newAsset == null\n && !Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), fullPath))\n ) // Check if it wasn't a folder and asset wasn't created\n {\n return Response.Error(\n $\"Failed to create asset '{assetType}' at '{fullPath}'. See logs for details.\"\n );\n }\n\n AssetDatabase.SaveAssets();\n // AssetDatabase.Refresh(); // CreateAsset often handles refresh\n return Response.Success(\n $\"Asset '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create asset at '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateFolder(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create_folder.\");\n string fullPath = SanitizeAssetPath(path);\n string parentDir = Path.GetDirectoryName(fullPath);\n string folderName = Path.GetFileName(fullPath);\n\n if (AssetExists(fullPath))\n {\n // Check if it's actually a folder already\n if (AssetDatabase.IsValidFolder(fullPath))\n {\n return Response.Success(\n $\"Folder already exists at path: {fullPath}\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n return Response.Error(\n $\"An asset (not a folder) already exists at path: {fullPath}\"\n );\n }\n }\n\n try\n {\n // Ensure parent exists\n if (!string.IsNullOrEmpty(parentDir) && !AssetDatabase.IsValidFolder(parentDir))\n {\n // Recursively create parent folders if needed (AssetDatabase handles this internally)\n // Or we can do it manually: Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), parentDir)); AssetDatabase.Refresh();\n }\n\n string guid = AssetDatabase.CreateFolder(parentDir, folderName);\n if (string.IsNullOrEmpty(guid))\n {\n return Response.Error(\n $\"Failed to create folder '{fullPath}'. Check logs and permissions.\"\n );\n }\n\n // AssetDatabase.Refresh(); // CreateFolder usually handles refresh\n return Response.Success(\n $\"Folder '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create folder '{fullPath}': {e.Message}\");\n }\n }\n\n private static object ModifyAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for modify.\");\n if (properties == null || !properties.HasValues)\n return Response.Error(\"'properties' are required for modify.\");\n\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n bool modified = false; // Flag to track if any changes were made\n\n // --- NEW: Handle GameObject / Prefab Component Modification ---\n if (asset is GameObject gameObject)\n {\n // Iterate through the properties JSON: keys are component names, values are properties objects for that component\n foreach (var prop in properties.Properties())\n {\n string componentName = prop.Name; // e.g., \"Collectible\"\n // Check if the value associated with the component name is actually an object containing properties\n if (\n prop.Value is JObject componentProperties\n && componentProperties.HasValues\n ) // e.g., {\"bobSpeed\": 2.0}\n {\n // Find the component on the GameObject using the name from the JSON key\n // Using GetComponent(string) is convenient but might require exact type name or be ambiguous.\n // Consider using FindType helper if needed for more complex scenarios.\n Component targetComponent = gameObject.GetComponent(componentName);\n\n if (targetComponent != null)\n {\n // Apply the nested properties (e.g., bobSpeed) to the found component instance\n // Use |= to ensure 'modified' becomes true if any component is successfully modified\n modified |= ApplyObjectProperties(\n targetComponent,\n componentProperties\n );\n }\n else\n {\n // Log a warning if a specified component couldn't be found\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Component '{componentName}' not found on GameObject '{gameObject.name}' in asset '{fullPath}'. Skipping modification for this component.\"\n );\n }\n }\n else\n {\n // Log a warning if the structure isn't {\"ComponentName\": {\"prop\": value}}\n // We could potentially try to apply this property directly to the GameObject here if needed,\n // but the primary goal is component modification.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Property '{prop.Name}' for GameObject modification should have a JSON object value containing component properties. Value was: {prop.Value.Type}. Skipping.\"\n );\n }\n }\n // Note: 'modified' is now true if ANY component property was successfully changed.\n }\n // --- End NEW ---\n\n // --- Existing logic for other asset types (now as else-if) ---\n // Example: Modifying a Material\n else if (asset is Material material)\n {\n // Apply properties directly to the material. If this modifies, it sets modified=true.\n // Use |= in case the asset was already marked modified by previous logic (though unlikely here)\n modified |= ApplyMaterialProperties(material, properties);\n }\n // Example: Modifying a ScriptableObject\n else if (asset is ScriptableObject so)\n {\n // Apply properties directly to the ScriptableObject.\n modified |= ApplyObjectProperties(so, properties); // General helper\n }\n // Example: Modifying TextureImporter settings\n else if (asset is Texture)\n {\n AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n if (importer is TextureImporter textureImporter)\n {\n bool importerModified = ApplyObjectProperties(textureImporter, properties);\n if (importerModified)\n {\n // Importer settings need saving and reimporting\n AssetDatabase.WriteImportSettingsIfDirty(fullPath);\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate); // Reimport to apply changes\n modified = true; // Mark overall operation as modified\n }\n }\n else\n {\n Debug.LogWarning($\"Could not get TextureImporter for {fullPath}.\");\n }\n }\n // TODO: Add modification logic for other common asset types (Models, AudioClips importers, etc.)\n else // Fallback for other asset types OR direct properties on non-GameObject assets\n {\n // This block handles non-GameObject/Material/ScriptableObject/Texture assets.\n // Attempts to apply properties directly to the asset itself.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Asset type '{asset.GetType().Name}' at '{fullPath}' is not explicitly handled for component modification. Attempting generic property setting on the asset itself.\"\n );\n modified |= ApplyObjectProperties(asset, properties);\n }\n // --- End Existing Logic ---\n\n // Check if any modification happened (either component or direct asset modification)\n if (modified)\n {\n // Mark the asset as dirty (important for prefabs/SOs) so Unity knows to save it.\n EditorUtility.SetDirty(asset);\n // Save all modified assets to disk.\n AssetDatabase.SaveAssets();\n // Refresh might be needed in some edge cases, but SaveAssets usually covers it.\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{fullPath}' modified successfully.\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n // If no changes were made (e.g., component not found, property names incorrect, value unchanged), return a success message indicating nothing changed.\n return Response.Success(\n $\"No applicable or modifiable properties found for asset '{fullPath}'. Check component names, property names, and values.\",\n GetAssetData(fullPath)\n );\n // Previous message: return Response.Success($\"No applicable properties found to modify for asset '{fullPath}'.\", GetAssetData(fullPath));\n }\n }\n catch (Exception e)\n {\n // Log the detailed error internally\n Debug.LogError($\"[ManageAsset] Action 'modify' failed for path '{path}': {e}\");\n // Return a user-friendly error message\n return Response.Error($\"Failed to modify asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DeleteAsset(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for delete.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n bool success = AssetDatabase.DeleteAsset(fullPath);\n if (success)\n {\n // AssetDatabase.Refresh(); // DeleteAsset usually handles refresh\n return Response.Success($\"Asset '{fullPath}' deleted successfully.\");\n }\n else\n {\n // This might happen if the file couldn't be deleted (e.g., locked)\n return Response.Error(\n $\"Failed to delete asset '{fullPath}'. Check logs or if the file is locked.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DuplicateAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for duplicate.\");\n\n string sourcePath = SanitizeAssetPath(path);\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n\n string destPath;\n if (string.IsNullOrEmpty(destinationPath))\n {\n // Generate a unique path if destination is not provided\n destPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath);\n }\n else\n {\n destPath = SanitizeAssetPath(destinationPath);\n if (AssetExists(destPath))\n return Response.Error($\"Asset already exists at destination path: {destPath}\");\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n }\n\n try\n {\n bool success = AssetDatabase.CopyAsset(sourcePath, destPath);\n if (success)\n {\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{sourcePath}' duplicated to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n return Response.Error(\n $\"Failed to duplicate asset from '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error duplicating asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object MoveOrRenameAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for move/rename.\");\n if (string.IsNullOrEmpty(destinationPath))\n return Response.Error(\"'destination' path is required for move/rename.\");\n\n string sourcePath = SanitizeAssetPath(path);\n string destPath = SanitizeAssetPath(destinationPath);\n\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n if (AssetExists(destPath))\n return Response.Error(\n $\"An asset already exists at the destination path: {destPath}\"\n );\n\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n\n try\n {\n // Validate will return an error string if failed, null if successful\n string error = AssetDatabase.ValidateMoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(error))\n {\n return Response.Error(\n $\"Failed to move/rename asset from '{sourcePath}' to '{destPath}': {error}\"\n );\n }\n\n string guid = AssetDatabase.MoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(guid)) // MoveAsset returns the new GUID on success\n {\n // AssetDatabase.Refresh(); // MoveAsset usually handles refresh\n return Response.Success(\n $\"Asset moved/renamed from '{sourcePath}' to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n // This case might not be reachable if ValidateMoveAsset passes, but good to have\n return Response.Error(\n $\"MoveAsset call failed unexpectedly for '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error moving/renaming asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object SearchAssets(JObject @params)\n {\n string searchPattern = @params[\"searchPattern\"]?.ToString();\n string filterType = @params[\"filterType\"]?.ToString();\n string pathScope = @params[\"path\"]?.ToString(); // Use path as folder scope\n string filterDateAfterStr = @params[\"filterDateAfter\"]?.ToString();\n int pageSize = @params[\"pageSize\"]?.ToObject() ?? 50; // Default page size\n int pageNumber = @params[\"pageNumber\"]?.ToObject() ?? 1; // Default page number (1-based)\n bool generatePreview = @params[\"generatePreview\"]?.ToObject() ?? false;\n\n List searchFilters = new List();\n if (!string.IsNullOrEmpty(searchPattern))\n searchFilters.Add(searchPattern);\n if (!string.IsNullOrEmpty(filterType))\n searchFilters.Add($\"t:{filterType}\");\n\n string[] folderScope = null;\n if (!string.IsNullOrEmpty(pathScope))\n {\n folderScope = new string[] { SanitizeAssetPath(pathScope) };\n if (!AssetDatabase.IsValidFolder(folderScope[0]))\n {\n // Maybe the user provided a file path instead of a folder?\n // We could search in the containing folder, or return an error.\n Debug.LogWarning(\n $\"Search path '{folderScope[0]}' is not a valid folder. Searching entire project.\"\n );\n folderScope = null; // Search everywhere if path isn't a folder\n }\n }\n\n DateTime? filterDateAfter = null;\n if (!string.IsNullOrEmpty(filterDateAfterStr))\n {\n if (\n DateTime.TryParse(\n filterDateAfterStr,\n CultureInfo.InvariantCulture,\n DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,\n out DateTime parsedDate\n )\n )\n {\n filterDateAfter = parsedDate;\n }\n else\n {\n Debug.LogWarning(\n $\"Could not parse filterDateAfter: '{filterDateAfterStr}'. Expected ISO 8601 format.\"\n );\n }\n }\n\n try\n {\n string[] guids = AssetDatabase.FindAssets(\n string.Join(\" \", searchFilters),\n folderScope\n );\n List results = new List();\n int totalFound = 0;\n\n foreach (string guid in guids)\n {\n string assetPath = AssetDatabase.GUIDToAssetPath(guid);\n if (string.IsNullOrEmpty(assetPath))\n continue;\n\n // Apply date filter if present\n if (filterDateAfter.HasValue)\n {\n DateTime lastWriteTime = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), assetPath)\n );\n if (lastWriteTime <= filterDateAfter.Value)\n {\n continue; // Skip assets older than or equal to the filter date\n }\n }\n\n totalFound++; // Count matching assets before pagination\n results.Add(GetAssetData(assetPath, generatePreview));\n }\n\n // Apply pagination\n int startIndex = (pageNumber - 1) * pageSize;\n var pagedResults = results.Skip(startIndex).Take(pageSize).ToList();\n\n return Response.Success(\n $\"Found {totalFound} asset(s). Returning page {pageNumber} ({pagedResults.Count} assets).\",\n new\n {\n totalAssets = totalFound,\n pageSize = pageSize,\n pageNumber = pageNumber,\n assets = pagedResults,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error searching assets: {e.Message}\");\n }\n }\n\n private static object GetAssetInfo(string path, bool generatePreview)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_info.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n return Response.Success(\n \"Asset info retrieved.\",\n GetAssetData(fullPath, generatePreview)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting info for asset '{fullPath}': {e.Message}\");\n }\n }\n\n /// \n /// Retrieves components attached to a GameObject asset (like a Prefab).\n /// \n /// The asset path of the GameObject or Prefab.\n /// A response object containing a list of component type names or an error.\n private static object GetComponentsFromAsset(string path)\n {\n // 1. Validate input path\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_components.\");\n\n // 2. Sanitize and check existence\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // 3. Load the asset\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n // 4. Check if it's a GameObject (Prefabs load as GameObjects)\n GameObject gameObject = asset as GameObject;\n if (gameObject == null)\n {\n // Also check if it's *directly* a Component type (less common for primary assets)\n Component componentAsset = asset as Component;\n if (componentAsset != null)\n {\n // If the asset itself *is* a component, maybe return just its info?\n // This is an edge case. Let's stick to GameObjects for now.\n return Response.Error(\n $\"Asset at '{fullPath}' is a Component ({asset.GetType().FullName}), not a GameObject. Components are typically retrieved *from* a GameObject.\"\n );\n }\n return Response.Error(\n $\"Asset at '{fullPath}' is not a GameObject (Type: {asset.GetType().FullName}). Cannot get components from this asset type.\"\n );\n }\n\n // 5. Get components\n Component[] components = gameObject.GetComponents();\n\n // 6. Format component data\n List componentList = components\n .Select(comp => new\n {\n typeName = comp.GetType().FullName,\n instanceID = comp.GetInstanceID(),\n // TODO: Add more component-specific details here if needed in the future?\n // Requires reflection or specific handling per component type.\n })\n .ToList(); // Explicit cast for clarity if needed\n\n // 7. Return success response\n return Response.Success(\n $\"Found {componentList.Count} component(s) on asset '{fullPath}'.\",\n componentList\n );\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageAsset.GetComponentsFromAsset] Error getting components for '{fullPath}': {e}\"\n );\n return Response.Error(\n $\"Error getting components for asset '{fullPath}': {e.Message}\"\n );\n }\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Ensures the asset path starts with \"Assets/\".\n /// \n private static string SanitizeAssetPath(string path)\n {\n if (string.IsNullOrEmpty(path))\n return path;\n path = path.Replace('\\\\', '/'); // Normalize separators\n if (!path.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n return \"Assets/\" + path.TrimStart('/');\n }\n return path;\n }\n\n /// \n /// Checks if an asset exists at the given path (file or folder).\n /// \n private static bool AssetExists(string sanitizedPath)\n {\n // AssetDatabase APIs are generally preferred over raw File/Directory checks for assets.\n // Check if it's a known asset GUID.\n if (!string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath)))\n {\n return true;\n }\n // AssetPathToGUID might not work for newly created folders not yet refreshed.\n // Check directory explicitly for folders.\n if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n // Check if it's considered a *valid* folder by Unity\n return AssetDatabase.IsValidFolder(sanitizedPath);\n }\n // Check file existence for non-folder assets.\n if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n return true; // Assume if file exists, it's an asset or will be imported\n }\n\n return false;\n // Alternative: return !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath));\n }\n\n /// \n /// Ensures the directory for a given asset path exists, creating it if necessary.\n /// \n private static void EnsureDirectoryExists(string directoryPath)\n {\n if (string.IsNullOrEmpty(directoryPath))\n return;\n string fullDirPath = Path.Combine(Directory.GetCurrentDirectory(), directoryPath);\n if (!Directory.Exists(fullDirPath))\n {\n Directory.CreateDirectory(fullDirPath);\n AssetDatabase.Refresh(); // Let Unity know about the new folder\n }\n }\n\n /// \n /// Applies properties from JObject to a Material.\n /// \n private static bool ApplyMaterialProperties(Material mat, JObject properties)\n {\n if (mat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set shader\n if (properties[\"shader\"]?.Type == JTokenType.String)\n {\n Shader newShader = Shader.Find(properties[\"shader\"].ToString());\n if (newShader != null && mat.shader != newShader)\n {\n mat.shader = newShader;\n modified = true;\n }\n }\n // Example: Set color property\n if (properties[\"color\"] is JObject colorProps)\n {\n string propName = colorProps[\"name\"]?.ToString() ?? \"_Color\"; // Default main color\n if (colorProps[\"value\"] is JArray colArr && colArr.Count >= 3)\n {\n try\n {\n Color newColor = new Color(\n colArr[0].ToObject(),\n colArr[1].ToObject(),\n colArr[2].ToObject(),\n colArr.Count > 3 ? colArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n } else if (properties[\"color\"] is JArray colorArr) //Use color now with examples set in manage_asset.py\n {\n string propName = \"_Color\"; \n try {\n if (colorArr.Count >= 3)\n {\n Color newColor = new Color(\n colorArr[0].ToObject(),\n colorArr[1].ToObject(), \n colorArr[2].ToObject(), \n colorArr.Count > 3 ? colorArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n } \n catch (Exception ex) {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n // Example: Set float property\n if (properties[\"float\"] is JObject floatProps)\n {\n string propName = floatProps[\"name\"]?.ToString();\n if (\n !string.IsNullOrEmpty(propName) && floatProps[\"value\"]?.Type == JTokenType.Float\n || floatProps[\"value\"]?.Type == JTokenType.Integer\n )\n {\n try\n {\n float newVal = floatProps[\"value\"].ToObject();\n if (mat.HasProperty(propName) && mat.GetFloat(propName) != newVal)\n {\n mat.SetFloat(propName, newVal);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing float property '{propName}': {ex.Message}\"\n );\n }\n }\n }\n // Example: Set texture property\n if (properties[\"texture\"] is JObject texProps)\n {\n string propName = texProps[\"name\"]?.ToString() ?? \"_MainTex\"; // Default main texture\n string texPath = texProps[\"path\"]?.ToString();\n if (!string.IsNullOrEmpty(texPath))\n {\n Texture newTex = AssetDatabase.LoadAssetAtPath(\n SanitizeAssetPath(texPath)\n );\n if (\n newTex != null\n && mat.HasProperty(propName)\n && mat.GetTexture(propName) != newTex\n )\n {\n mat.SetTexture(propName, newTex);\n modified = true;\n }\n else if (newTex == null)\n {\n Debug.LogWarning($\"Texture not found at path: {texPath}\");\n }\n }\n }\n\n // TODO: Add handlers for other property types (Vectors, Ints, Keywords, RenderQueue, etc.)\n return modified;\n }\n\n /// \n /// Applies properties from JObject to a PhysicsMaterial.\n /// \n private static bool ApplyPhysicsMaterialProperties(PhysicsMaterialType pmat, JObject properties)\n {\n if (pmat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set dynamic friction\n if (properties[\"dynamicFriction\"]?.Type == JTokenType.Float)\n {\n float dynamicFriction = properties[\"dynamicFriction\"].ToObject();\n pmat.dynamicFriction = dynamicFriction;\n modified = true;\n }\n\n // Example: Set static friction\n if (properties[\"staticFriction\"]?.Type == JTokenType.Float)\n {\n float staticFriction = properties[\"staticFriction\"].ToObject();\n pmat.staticFriction = staticFriction;\n modified = true;\n }\n\n // Example: Set bounciness\n if (properties[\"bounciness\"]?.Type == JTokenType.Float)\n {\n float bounciness = properties[\"bounciness\"].ToObject();\n pmat.bounciness = bounciness;\n modified = true;\n }\n\n List averageList = new List { \"ave\", \"Ave\", \"average\", \"Average\" };\n List multiplyList = new List { \"mul\", \"Mul\", \"mult\", \"Mult\", \"multiply\", \"Multiply\" };\n List minimumList = new List { \"min\", \"Min\", \"minimum\", \"Minimum\" };\n List maximumList = new List { \"max\", \"Max\", \"maximum\", \"Maximum\" };\n\n // Example: Set friction combine\n if (properties[\"frictionCombine\"]?.Type == JTokenType.String)\n {\n string frictionCombine = properties[\"frictionCombine\"].ToString();\n if (averageList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n // Example: Set bounce combine\n if (properties[\"bounceCombine\"]?.Type == JTokenType.String)\n {\n string bounceCombine = properties[\"bounceCombine\"].ToString();\n if (averageList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n return modified;\n }\n\n /// \n /// Generic helper to set properties on any UnityEngine.Object using reflection.\n /// \n private static bool ApplyObjectProperties(UnityEngine.Object target, JObject properties)\n {\n if (target == null || properties == null)\n return false;\n bool modified = false;\n Type type = target.GetType();\n\n foreach (var prop in properties.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n if (SetPropertyOrField(target, propName, propValue, type))\n {\n modified = true;\n }\n }\n return modified;\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types and Unity objects.\n /// \n private static bool SetPropertyOrField(\n object target,\n string memberName,\n JToken value,\n Type type = null\n )\n {\n type = type ?? target.GetType();\n System.Reflection.BindingFlags flags =\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.Instance\n | System.Reflection.BindingFlags.IgnoreCase;\n\n try\n {\n System.Reflection.PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType);\n if (\n convertedValue != null\n && !object.Equals(propInfo.GetValue(target), convertedValue)\n )\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n else\n {\n System.Reflection.FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null)\n {\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType);\n if (\n convertedValue != null\n && !object.Equals(fieldInfo.GetValue(target), convertedValue)\n )\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[SetPropertyOrField] Failed to set '{memberName}' on {type.Name}: {ex.Message}\"\n );\n }\n return false;\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types and primitives.\n /// \n private static object ConvertJTokenToType(JToken token, Type targetType)\n {\n try\n {\n if (token == null || token.Type == JTokenType.Null)\n return null;\n\n if (targetType == typeof(string))\n return token.ToObject();\n if (targetType == typeof(int))\n return token.ToObject();\n if (targetType == typeof(float))\n return token.ToObject();\n if (targetType == typeof(bool))\n return token.ToObject();\n if (targetType == typeof(Vector2) && token is JArray arrV2 && arrV2.Count == 2)\n return new Vector2(arrV2[0].ToObject(), arrV2[1].ToObject());\n if (targetType == typeof(Vector3) && token is JArray arrV3 && arrV3.Count == 3)\n return new Vector3(\n arrV3[0].ToObject(),\n arrV3[1].ToObject(),\n arrV3[2].ToObject()\n );\n if (targetType == typeof(Vector4) && token is JArray arrV4 && arrV4.Count == 4)\n return new Vector4(\n arrV4[0].ToObject(),\n arrV4[1].ToObject(),\n arrV4[2].ToObject(),\n arrV4[3].ToObject()\n );\n if (targetType == typeof(Quaternion) && token is JArray arrQ && arrQ.Count == 4)\n return new Quaternion(\n arrQ[0].ToObject(),\n arrQ[1].ToObject(),\n arrQ[2].ToObject(),\n arrQ[3].ToObject()\n );\n if (targetType == typeof(Color) && token is JArray arrC && arrC.Count >= 3) // Allow RGB or RGBA\n return new Color(\n arrC[0].ToObject(),\n arrC[1].ToObject(),\n arrC[2].ToObject(),\n arrC.Count > 3 ? arrC[3].ToObject() : 1.0f\n );\n if (targetType.IsEnum)\n return Enum.Parse(targetType, token.ToString(), true); // Case-insensitive enum parsing\n\n // Handle loading Unity Objects (Materials, Textures, etc.) by path\n if (\n typeof(UnityEngine.Object).IsAssignableFrom(targetType)\n && token.Type == JTokenType.String\n )\n {\n string assetPath = SanitizeAssetPath(token.ToString());\n UnityEngine.Object loadedAsset = AssetDatabase.LoadAssetAtPath(\n assetPath,\n targetType\n );\n if (loadedAsset == null)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not load asset of type {targetType.Name} from path: {assetPath}\"\n );\n }\n return loadedAsset;\n }\n\n // Fallback: Try direct conversion (might work for other simple value types)\n return token.ToObject(targetType);\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not convert JToken '{token}' (type {token.Type}) to type '{targetType.Name}': {ex.Message}\"\n );\n return null;\n }\n }\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// Needed for creating ScriptableObjects or finding component types by name.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Try direct lookup first (common Unity types often don't need assembly qualified name)\n var type =\n Type.GetType(typeName)\n ?? Type.GetType($\"UnityEngine.{typeName}, UnityEngine.CoreModule\")\n ?? Type.GetType($\"UnityEngine.UI.{typeName}, UnityEngine.UI\")\n ?? Type.GetType($\"UnityEditor.{typeName}, UnityEditor.CoreModule\");\n\n if (type != null)\n return type;\n\n // If not found, search loaded assemblies (slower but more robust for user scripts)\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n {\n // Look for non-namespaced first\n type = assembly.GetType(typeName, false, true); // throwOnError=false, ignoreCase=true\n if (type != null)\n return type;\n\n // Check common namespaces if simple name given\n type = assembly.GetType(\"UnityEngine.\" + typeName, false, true);\n if (type != null)\n return type;\n type = assembly.GetType(\"UnityEditor.\" + typeName, false, true);\n if (type != null)\n return type;\n // Add other likely namespaces if needed (e.g., specific plugins)\n }\n\n Debug.LogWarning($\"[FindType] Type '{typeName}' not found in any loaded assembly.\");\n return null; // Not found\n }\n\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of an asset.\n /// \n private static object GetAssetData(string path, bool generatePreview = false)\n {\n if (string.IsNullOrEmpty(path) || !AssetExists(path))\n return null;\n\n string guid = AssetDatabase.AssetPathToGUID(path);\n Type assetType = AssetDatabase.GetMainAssetTypeAtPath(path);\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(path);\n string previewBase64 = null;\n int previewWidth = 0;\n int previewHeight = 0;\n\n if (generatePreview && asset != null)\n {\n Texture2D preview = AssetPreview.GetAssetPreview(asset);\n\n if (preview != null)\n {\n try\n {\n // Ensure texture is readable for EncodeToPNG\n // Creating a temporary readable copy is safer\n RenderTexture rt = RenderTexture.GetTemporary(\n preview.width,\n preview.height\n );\n Graphics.Blit(preview, rt);\n RenderTexture previous = RenderTexture.active;\n RenderTexture.active = rt;\n Texture2D readablePreview = new Texture2D(preview.width, preview.height);\n readablePreview.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);\n readablePreview.Apply();\n RenderTexture.active = previous;\n RenderTexture.ReleaseTemporary(rt);\n\n byte[] pngData = readablePreview.EncodeToPNG();\n previewBase64 = Convert.ToBase64String(pngData);\n previewWidth = readablePreview.width;\n previewHeight = readablePreview.height;\n UnityEngine.Object.DestroyImmediate(readablePreview); // Clean up temp texture\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Failed to generate readable preview for '{path}': {ex.Message}. Preview might not be readable.\"\n );\n // Fallback: Try getting static preview if available?\n // Texture2D staticPreview = AssetPreview.GetMiniThumbnail(asset);\n }\n }\n else\n {\n Debug.LogWarning(\n $\"Could not get asset preview for {path} (Type: {assetType?.Name}). Is it supported?\"\n );\n }\n }\n\n return new\n {\n path = path,\n guid = guid,\n assetType = assetType?.FullName ?? \"Unknown\",\n name = Path.GetFileNameWithoutExtension(path),\n fileName = Path.GetFileName(path),\n isFolder = AssetDatabase.IsValidFolder(path),\n instanceID = asset?.GetInstanceID() ?? 0,\n lastWriteTimeUtc = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), path)\n )\n .ToString(\"o\"), // ISO 8601\n // --- Preview Data ---\n previewBase64 = previewBase64, // PNG data as Base64 string\n previewWidth = previewWidth,\n previewHeight = previewHeight,\n // TODO: Add more metadata? Importer settings? Dependencies?\n };\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ReadConsole.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles reading and clearing Unity Editor console log entries.\n /// Uses reflection to access internal LogEntry methods/properties.\n /// \n public static class ReadConsole\n {\n // Reflection members for accessing internal LogEntry data\n // private static MethodInfo _getEntriesMethod; // Removed as it's unused and fails reflection\n private static MethodInfo _startGettingEntriesMethod;\n private static MethodInfo _endGettingEntriesMethod; // Renamed from _stopGettingEntriesMethod, trying End...\n private static MethodInfo _clearMethod;\n private static MethodInfo _getCountMethod;\n private static MethodInfo _getEntryMethod;\n private static FieldInfo _modeField;\n private static FieldInfo _messageField;\n private static FieldInfo _fileField;\n private static FieldInfo _lineField;\n private static FieldInfo _instanceIdField;\n\n // Note: Timestamp is not directly available in LogEntry; need to parse message or find alternative?\n\n // Static constructor for reflection setup\n static ReadConsole()\n {\n try\n {\n Type logEntriesType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntries\"\n );\n if (logEntriesType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntries\");\n\n // Include NonPublic binding flags as internal APIs might change accessibility\n BindingFlags staticFlags =\n BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;\n BindingFlags instanceFlags =\n BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\n\n _startGettingEntriesMethod = logEntriesType.GetMethod(\n \"StartGettingEntries\",\n staticFlags\n );\n if (_startGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.StartGettingEntries\");\n\n // Try reflecting EndGettingEntries based on warning message\n _endGettingEntriesMethod = logEntriesType.GetMethod(\n \"EndGettingEntries\",\n staticFlags\n );\n if (_endGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.EndGettingEntries\");\n\n _clearMethod = logEntriesType.GetMethod(\"Clear\", staticFlags);\n if (_clearMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.Clear\");\n\n _getCountMethod = logEntriesType.GetMethod(\"GetCount\", staticFlags);\n if (_getCountMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetCount\");\n\n _getEntryMethod = logEntriesType.GetMethod(\"GetEntryInternal\", staticFlags);\n if (_getEntryMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetEntryInternal\");\n\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntry\");\n\n _modeField = logEntryType.GetField(\"mode\", instanceFlags);\n if (_modeField == null)\n throw new Exception(\"Failed to reflect LogEntry.mode\");\n\n _messageField = logEntryType.GetField(\"message\", instanceFlags);\n if (_messageField == null)\n throw new Exception(\"Failed to reflect LogEntry.message\");\n\n _fileField = logEntryType.GetField(\"file\", instanceFlags);\n if (_fileField == null)\n throw new Exception(\"Failed to reflect LogEntry.file\");\n\n _lineField = logEntryType.GetField(\"line\", instanceFlags);\n if (_lineField == null)\n throw new Exception(\"Failed to reflect LogEntry.line\");\n\n _instanceIdField = logEntryType.GetField(\"instanceID\", instanceFlags);\n if (_instanceIdField == null)\n throw new Exception(\"Failed to reflect LogEntry.instanceID\");\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ReadConsole] Static Initialization Failed: Could not setup reflection for LogEntries/LogEntry. Console reading/clearing will likely fail. Specific Error: {e.Message}\"\n );\n // Set members to null to prevent NullReferenceExceptions later, HandleCommand should check this.\n _startGettingEntriesMethod =\n _endGettingEntriesMethod =\n _clearMethod =\n _getCountMethod =\n _getEntryMethod =\n null;\n _modeField = _messageField = _fileField = _lineField = _instanceIdField = null;\n }\n }\n\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n // Check if ALL required reflection members were successfully initialized.\n if (\n _startGettingEntriesMethod == null\n || _endGettingEntriesMethod == null\n || _clearMethod == null\n || _getCountMethod == null\n || _getEntryMethod == null\n || _modeField == null\n || _messageField == null\n || _fileField == null\n || _lineField == null\n || _instanceIdField == null\n )\n {\n // Log the error here as well for easier debugging in Unity Console\n Debug.LogError(\n \"[ReadConsole] HandleCommand called but reflection members are not initialized. Static constructor might have failed silently or there's an issue.\"\n );\n return Response.Error(\n \"ReadConsole handler failed to initialize due to reflection errors. Cannot access console logs.\"\n );\n }\n\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"get\";\n\n try\n {\n if (action == \"clear\")\n {\n return ClearConsole();\n }\n else if (action == \"get\")\n {\n // Extract parameters for 'get'\n var types =\n (@params[\"types\"] as JArray)?.Select(t => t.ToString().ToLower()).ToList()\n ?? new List { \"error\", \"warning\", \"log\" };\n int? count = @params[\"count\"]?.ToObject();\n string filterText = @params[\"filterText\"]?.ToString();\n string sinceTimestampStr = @params[\"sinceTimestamp\"]?.ToString(); // TODO: Implement timestamp filtering\n string format = (@params[\"format\"]?.ToString() ?? \"detailed\").ToLower();\n bool includeStacktrace =\n @params[\"includeStacktrace\"]?.ToObject() ?? true;\n\n if (types.Contains(\"all\"))\n {\n types = new List { \"error\", \"warning\", \"log\" }; // Expand 'all'\n }\n\n if (!string.IsNullOrEmpty(sinceTimestampStr))\n {\n Debug.LogWarning(\n \"[ReadConsole] Filtering by 'since_timestamp' is not currently implemented.\"\n );\n // Need a way to get timestamp per log entry.\n }\n\n return GetConsoleEntries(types, count, filterText, format, includeStacktrace);\n }\n else\n {\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'get' or 'clear'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object ClearConsole()\n {\n try\n {\n _clearMethod.Invoke(null, null); // Static method, no instance, no parameters\n return Response.Success(\"Console cleared successfully.\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to clear console: {e}\");\n return Response.Error($\"Failed to clear console: {e.Message}\");\n }\n }\n\n private static object GetConsoleEntries(\n List types,\n int? count,\n string filterText,\n string format,\n bool includeStacktrace\n )\n {\n List formattedEntries = new List();\n int retrievedCount = 0;\n\n try\n {\n // LogEntries requires calling Start/Stop around GetEntries/GetEntryInternal\n _startGettingEntriesMethod.Invoke(null, null);\n\n int totalEntries = (int)_getCountMethod.Invoke(null, null);\n // Create instance to pass to GetEntryInternal - Ensure the type is correct\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\n \"Could not find internal type UnityEditor.LogEntry during GetConsoleEntries.\"\n );\n object logEntryInstance = Activator.CreateInstance(logEntryType);\n\n for (int i = 0; i < totalEntries; i++)\n {\n // Get the entry data into our instance using reflection\n _getEntryMethod.Invoke(null, new object[] { i, logEntryInstance });\n\n // Extract data using reflection\n int mode = (int)_modeField.GetValue(logEntryInstance);\n string message = (string)_messageField.GetValue(logEntryInstance);\n string file = (string)_fileField.GetValue(logEntryInstance);\n\n int line = (int)_lineField.GetValue(logEntryInstance);\n // int instanceId = (int)_instanceIdField.GetValue(logEntryInstance);\n\n if (string.IsNullOrEmpty(message))\n continue; // Skip empty messages\n\n // --- Filtering ---\n // Filter by type\n LogType currentType = GetLogTypeFromMode(mode);\n if (!types.Contains(currentType.ToString().ToLowerInvariant()))\n {\n continue;\n }\n\n // Filter by text (case-insensitive)\n if (\n !string.IsNullOrEmpty(filterText)\n && message.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) < 0\n )\n {\n continue;\n }\n\n // TODO: Filter by timestamp (requires timestamp data)\n\n // --- Formatting ---\n string stackTrace = includeStacktrace ? ExtractStackTrace(message) : null;\n // Get first line if stack is present and requested, otherwise use full message\n string messageOnly =\n (includeStacktrace && !string.IsNullOrEmpty(stackTrace))\n ? message.Split(\n new[] { '\\n', '\\r' },\n StringSplitOptions.RemoveEmptyEntries\n )[0]\n : message;\n\n object formattedEntry = null;\n switch (format)\n {\n case \"plain\":\n formattedEntry = messageOnly;\n break;\n case \"json\":\n case \"detailed\": // Treat detailed as json for structured return\n default:\n formattedEntry = new\n {\n type = currentType.ToString(),\n message = messageOnly,\n file = file,\n line = line,\n // timestamp = \"\", // TODO\n stackTrace = stackTrace, // Will be null if includeStacktrace is false or no stack found\n };\n break;\n }\n\n formattedEntries.Add(formattedEntry);\n retrievedCount++;\n\n // Apply count limit (after filtering)\n if (count.HasValue && retrievedCount >= count.Value)\n {\n break;\n }\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Error while retrieving log entries: {e}\");\n // Ensure EndGettingEntries is called even if there's an error during iteration\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch\n { /* Ignore nested exception */\n }\n return Response.Error($\"Error retrieving log entries: {e.Message}\");\n }\n finally\n {\n // Ensure we always call EndGettingEntries\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to call EndGettingEntries: {e}\");\n // Don't return error here as we might have valid data, but log it.\n }\n }\n\n // Return the filtered and formatted list (might be empty)\n return Response.Success(\n $\"Retrieved {formattedEntries.Count} log entries.\",\n formattedEntries\n );\n }\n\n // --- Internal Helpers ---\n\n // Mapping from LogEntry.mode bits to LogType enum\n // Based on decompiled UnityEditor code or common patterns. Precise bits might change between Unity versions.\n // See comments below for LogEntry mode bits exploration.\n // Note: This mapping is simplified and might not cover all edge cases or future Unity versions perfectly.\n private const int ModeBitError = 1 << 0;\n private const int ModeBitAssert = 1 << 1;\n private const int ModeBitWarning = 1 << 2;\n private const int ModeBitLog = 1 << 3;\n private const int ModeBitException = 1 << 4; // Often combined with Error bits\n private const int ModeBitScriptingError = 1 << 9;\n private const int ModeBitScriptingWarning = 1 << 10;\n private const int ModeBitScriptingLog = 1 << 11;\n private const int ModeBitScriptingException = 1 << 18;\n private const int ModeBitScriptingAssertion = 1 << 22;\n\n private static LogType GetLogTypeFromMode(int mode)\n {\n // First, determine the type based on the original logic (most severe first)\n LogType initialType;\n if (\n (\n mode\n & (\n ModeBitError\n | ModeBitScriptingError\n | ModeBitException\n | ModeBitScriptingException\n )\n ) != 0\n )\n {\n initialType = LogType.Error;\n }\n else if ((mode & (ModeBitAssert | ModeBitScriptingAssertion)) != 0)\n {\n initialType = LogType.Assert;\n }\n else if ((mode & (ModeBitWarning | ModeBitScriptingWarning)) != 0)\n {\n initialType = LogType.Warning;\n }\n else\n {\n initialType = LogType.Log;\n }\n\n // Apply the observed \"one level lower\" correction\n switch (initialType)\n {\n case LogType.Error:\n return LogType.Warning; // Error becomes Warning\n case LogType.Warning:\n return LogType.Log; // Warning becomes Log\n case LogType.Assert:\n return LogType.Assert; // Assert remains Assert (no lower level defined)\n case LogType.Log:\n return LogType.Log; // Log remains Log\n default:\n return LogType.Log; // Default fallback\n }\n }\n\n /// \n /// Attempts to extract the stack trace part from a log message.\n /// Unity log messages often have the stack trace appended after the main message,\n /// starting on a new line and typically indented or beginning with \"at \".\n /// \n /// The complete log message including potential stack trace.\n /// The extracted stack trace string, or null if none is found.\n private static string ExtractStackTrace(string fullMessage)\n {\n if (string.IsNullOrEmpty(fullMessage))\n return null;\n\n // Split into lines, removing empty ones to handle different line endings gracefully.\n // Using StringSplitOptions.None might be better if empty lines matter within stack trace, but RemoveEmptyEntries is usually safer here.\n string[] lines = fullMessage.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n // If there's only one line or less, there's no separate stack trace.\n if (lines.Length <= 1)\n return null;\n\n int stackStartIndex = -1;\n\n // Start checking from the second line onwards.\n for (int i = 1; i < lines.Length; ++i)\n {\n // Performance: TrimStart creates a new string. Consider using IsWhiteSpace check if performance critical.\n string trimmedLine = lines[i].TrimStart();\n\n // Check for common stack trace patterns.\n if (\n trimmedLine.StartsWith(\"at \")\n || trimmedLine.StartsWith(\"UnityEngine.\")\n || trimmedLine.StartsWith(\"UnityEditor.\")\n || trimmedLine.Contains(\"(at \")\n || // Covers \"(at Assets/...\" pattern\n // Heuristic: Check if line starts with likely namespace/class pattern (Uppercase.Something)\n (\n trimmedLine.Length > 0\n && char.IsUpper(trimmedLine[0])\n && trimmedLine.Contains('.')\n )\n )\n {\n stackStartIndex = i;\n break; // Found the likely start of the stack trace\n }\n }\n\n // If a potential start index was found...\n if (stackStartIndex > 0)\n {\n // Join the lines from the stack start index onwards using standard newline characters.\n // This reconstructs the stack trace part of the message.\n return string.Join(\"\\n\", lines.Skip(stackStartIndex));\n }\n\n // No clear stack trace found based on the patterns.\n return null;\n }\n\n /* LogEntry.mode bits exploration (based on Unity decompilation/observation):\n May change between versions.\n\n Basic Types:\n kError = 1 << 0 (1)\n kAssert = 1 << 1 (2)\n kWarning = 1 << 2 (4)\n kLog = 1 << 3 (8)\n kFatal = 1 << 4 (16) - Often treated as Exception/Error\n\n Modifiers/Context:\n kAssetImportError = 1 << 7 (128)\n kAssetImportWarning = 1 << 8 (256)\n kScriptingError = 1 << 9 (512)\n kScriptingWarning = 1 << 10 (1024)\n kScriptingLog = 1 << 11 (2048)\n kScriptCompileError = 1 << 12 (4096)\n kScriptCompileWarning = 1 << 13 (8192)\n kStickyError = 1 << 14 (16384) - Stays visible even after Clear On Play\n kMayIgnoreLineNumber = 1 << 15 (32768)\n kReportBug = 1 << 16 (65536) - Shows the \"Report Bug\" button\n kDisplayPreviousErrorInStatusBar = 1 << 17 (131072)\n kScriptingException = 1 << 18 (262144)\n kDontExtractStacktrace = 1 << 19 (524288) - Hint to the console UI\n kShouldClearOnPlay = 1 << 20 (1048576) - Default behavior\n kGraphCompileError = 1 << 21 (2097152)\n kScriptingAssertion = 1 << 22 (4194304)\n kVisualScriptingError = 1 << 23 (8388608)\n\n Example observed values:\n Log: 2048 (ScriptingLog) or 8 (Log)\n Warning: 1028 (ScriptingWarning | Warning) or 4 (Warning)\n Error: 513 (ScriptingError | Error) or 1 (Error)\n Exception: 262161 (ScriptingException | Error | kFatal?) - Complex combination\n Assertion: 4194306 (ScriptingAssertion | Assert) or 2 (Assert)\n */\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageEditor.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal; // Required for tag management\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles operations related to controlling and querying the Unity Editor state,\n /// including managing Tags and Layers.\n /// \n public static class ManageEditor\n {\n // Constant for starting user layer index\n private const int FirstUserLayerIndex = 8;\n\n // Constant for total layer count\n private const int TotalLayerCount = 32;\n\n /// \n /// Main handler for editor management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n // Parameters for specific actions\n string tagName = @params[\"tagName\"]?.ToString();\n string layerName = @params[\"layerName\"]?.ToString();\n bool waitForCompletion = @params[\"waitForCompletion\"]?.ToObject() ?? false; // Example - not used everywhere\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Route action\n switch (action)\n {\n // Play Mode Control\n case \"play\":\n try\n {\n if (!EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = true;\n return Response.Success(\"Entered play mode.\");\n }\n return Response.Success(\"Already in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error entering play mode: {e.Message}\");\n }\n case \"pause\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPaused = !EditorApplication.isPaused;\n return Response.Success(\n EditorApplication.isPaused ? \"Game paused.\" : \"Game resumed.\"\n );\n }\n return Response.Error(\"Cannot pause/resume: Not in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error pausing/resuming game: {e.Message}\");\n }\n case \"stop\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = false;\n return Response.Success(\"Exited play mode.\");\n }\n return Response.Success(\"Already stopped (not in play mode).\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error stopping play mode: {e.Message}\");\n }\n\n // Editor State/Info\n case \"get_state\":\n return GetEditorState();\n case \"get_windows\":\n return GetEditorWindows();\n case \"get_active_tool\":\n return GetActiveTool();\n case \"get_selection\":\n return GetSelection();\n case \"set_active_tool\":\n string toolName = @params[\"toolName\"]?.ToString();\n if (string.IsNullOrEmpty(toolName))\n return Response.Error(\"'toolName' parameter required for set_active_tool.\");\n return SetActiveTool(toolName);\n\n // Tag Management\n case \"add_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for add_tag.\");\n return AddTag(tagName);\n case \"remove_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for remove_tag.\");\n return RemoveTag(tagName);\n case \"get_tags\":\n return GetTags(); // Helper to list current tags\n\n // Layer Management\n case \"add_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for add_layer.\");\n return AddLayer(layerName);\n case \"remove_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for remove_layer.\");\n return RemoveLayer(layerName);\n case \"get_layers\":\n return GetLayers(); // Helper to list current layers\n\n // --- Settings (Example) ---\n // case \"set_resolution\":\n // int? width = @params[\"width\"]?.ToObject();\n // int? height = @params[\"height\"]?.ToObject();\n // if (!width.HasValue || !height.HasValue) return Response.Error(\"'width' and 'height' parameters required.\");\n // return SetGameViewResolution(width.Value, height.Value);\n // case \"set_quality\":\n // // Handle string name or int index\n // return SetQualityLevel(@params[\"qualityLevel\"]);\n\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Supported actions include play, pause, stop, get_state, get_windows, get_active_tool, get_selection, set_active_tool, add_tag, remove_tag, get_tags, add_layer, remove_layer, get_layers.\"\n );\n }\n }\n\n // --- Editor State/Info Methods ---\n private static object GetEditorState()\n {\n try\n {\n var state = new\n {\n isPlaying = EditorApplication.isPlaying,\n isPaused = EditorApplication.isPaused,\n isCompiling = EditorApplication.isCompiling,\n isUpdating = EditorApplication.isUpdating,\n applicationPath = EditorApplication.applicationPath,\n applicationContentsPath = EditorApplication.applicationContentsPath,\n timeSinceStartup = EditorApplication.timeSinceStartup,\n };\n return Response.Success(\"Retrieved editor state.\", state);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor state: {e.Message}\");\n }\n }\n\n private static object GetEditorWindows()\n {\n try\n {\n // Get all types deriving from EditorWindow\n var windowTypes = AppDomain\n .CurrentDomain.GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => type.IsSubclassOf(typeof(EditorWindow)))\n .ToList();\n\n var openWindows = new List();\n\n // Find currently open instances\n // Resources.FindObjectsOfTypeAll seems more reliable than GetWindow for finding *all* open windows\n EditorWindow[] allWindows = Resources.FindObjectsOfTypeAll();\n\n foreach (EditorWindow window in allWindows)\n {\n if (window == null)\n continue; // Skip potentially destroyed windows\n\n try\n {\n openWindows.Add(\n new\n {\n title = window.titleContent.text,\n typeName = window.GetType().FullName,\n isFocused = EditorWindow.focusedWindow == window,\n position = new\n {\n x = window.position.x,\n y = window.position.y,\n width = window.position.width,\n height = window.position.height,\n },\n instanceID = window.GetInstanceID(),\n }\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Could not get info for window {window.GetType().Name}: {ex.Message}\"\n );\n }\n }\n\n return Response.Success(\"Retrieved list of open editor windows.\", openWindows);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor windows: {e.Message}\");\n }\n }\n\n private static object GetActiveTool()\n {\n try\n {\n Tool currentTool = UnityEditor.Tools.current;\n string toolName = currentTool.ToString(); // Enum to string\n bool customToolActive = UnityEditor.Tools.current == Tool.Custom; // Check if a custom tool is active\n string activeToolName = customToolActive\n ? EditorTools.GetActiveToolName()\n : toolName; // Get custom name if needed\n\n var toolInfo = new\n {\n activeTool = activeToolName,\n isCustom = customToolActive,\n pivotMode = UnityEditor.Tools.pivotMode.ToString(),\n pivotRotation = UnityEditor.Tools.pivotRotation.ToString(),\n handleRotation = UnityEditor.Tools.handleRotation.eulerAngles, // Euler for simplicity\n handlePosition = UnityEditor.Tools.handlePosition,\n };\n\n return Response.Success(\"Retrieved active tool information.\", toolInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active tool: {e.Message}\");\n }\n }\n\n private static object SetActiveTool(string toolName)\n {\n try\n {\n Tool targetTool;\n if (Enum.TryParse(toolName, true, out targetTool)) // Case-insensitive parse\n {\n // Check if it's a valid built-in tool\n if (targetTool != Tool.None && targetTool <= Tool.Custom) // Tool.Custom is the last standard tool\n {\n UnityEditor.Tools.current = targetTool;\n return Response.Success($\"Set active tool to '{targetTool}'.\");\n }\n else\n {\n return Response.Error(\n $\"Cannot directly set tool to '{toolName}'. It might be None, Custom, or invalid.\"\n );\n }\n }\n else\n {\n // Potentially try activating a custom tool by name here if needed\n // This often requires specific editor scripting knowledge for that tool.\n return Response.Error(\n $\"Could not parse '{toolName}' as a standard Unity Tool (View, Move, Rotate, Scale, Rect, Transform, Custom).\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error setting active tool: {e.Message}\");\n }\n }\n\n private static object GetSelection()\n {\n try\n {\n var selectionInfo = new\n {\n activeObject = Selection.activeObject?.name,\n activeGameObject = Selection.activeGameObject?.name,\n activeTransform = Selection.activeTransform?.name,\n activeInstanceID = Selection.activeInstanceID,\n count = Selection.count,\n objects = Selection\n .objects.Select(obj => new\n {\n name = obj?.name,\n type = obj?.GetType().FullName,\n instanceID = obj?.GetInstanceID(),\n })\n .ToList(),\n gameObjects = Selection\n .gameObjects.Select(go => new\n {\n name = go?.name,\n instanceID = go?.GetInstanceID(),\n })\n .ToList(),\n assetGUIDs = Selection.assetGUIDs, // GUIDs for selected assets in Project view\n };\n\n return Response.Success(\"Retrieved current selection details.\", selectionInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting selection: {e.Message}\");\n }\n }\n\n // --- Tag Management Methods ---\n\n private static object AddTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n\n // Check if tag already exists\n if (InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' already exists.\");\n }\n\n try\n {\n // Add the tag using the internal utility\n InternalEditorUtility.AddTag(tagName);\n // Force save assets to ensure the change persists in the TagManager asset\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' added successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object RemoveTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n if (tagName.Equals(\"Untagged\", StringComparison.OrdinalIgnoreCase))\n return Response.Error(\"Cannot remove the built-in 'Untagged' tag.\");\n\n // Check if tag exists before attempting removal\n if (!InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' does not exist.\");\n }\n\n try\n {\n // Remove the tag using the internal utility\n InternalEditorUtility.RemoveTag(tagName);\n // Force save assets\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' removed successfully.\");\n }\n catch (Exception e)\n {\n // Catch potential issues if the tag is somehow in use or removal fails\n return Response.Error($\"Failed to remove tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object GetTags()\n {\n try\n {\n string[] tags = InternalEditorUtility.tags;\n return Response.Success(\"Retrieved current tags.\", tags);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve tags: {e.Message}\");\n }\n }\n\n // --- Layer Management Methods ---\n\n private static object AddLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Check if layer name already exists (case-insensitive check recommended)\n for (int i = 0; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n return Response.Error($\"Layer '{layerName}' already exists at index {i}.\");\n }\n }\n\n // Find the first empty user layer slot (indices 8 to 31)\n int firstEmptyUserLayer = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (layerSP != null && string.IsNullOrEmpty(layerSP.stringValue))\n {\n firstEmptyUserLayer = i;\n break;\n }\n }\n\n if (firstEmptyUserLayer == -1)\n {\n return Response.Error(\"No empty User Layer slots available (8-31 are full).\");\n }\n\n // Assign the name to the found slot\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n firstEmptyUserLayer\n );\n targetLayerSP.stringValue = layerName;\n // Apply the changes to the TagManager asset\n tagManager.ApplyModifiedProperties();\n // Save assets to make sure it's written to disk\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' added successfully to slot {firstEmptyUserLayer}.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object RemoveLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Find the layer by name (must be user layer)\n int layerIndexToRemove = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++) // Start from user layers\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n // Case-insensitive comparison is safer\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n layerIndexToRemove = i;\n break;\n }\n }\n\n if (layerIndexToRemove == -1)\n {\n return Response.Error($\"User layer '{layerName}' not found.\");\n }\n\n // Clear the name for that index\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n layerIndexToRemove\n );\n targetLayerSP.stringValue = string.Empty; // Set to empty string to remove\n // Apply the changes\n tagManager.ApplyModifiedProperties();\n // Save assets\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' (slot {layerIndexToRemove}) removed successfully.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to remove layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object GetLayers()\n {\n try\n {\n var layers = new Dictionary();\n for (int i = 0; i < TotalLayerCount; i++)\n {\n string layerName = LayerMask.LayerToName(i);\n if (!string.IsNullOrEmpty(layerName)) // Only include layers that have names\n {\n layers.Add(i, layerName);\n }\n }\n return Response.Success(\"Retrieved current named layers.\", layers);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve layers: {e.Message}\");\n }\n }\n\n // --- Helper Methods ---\n\n /// \n /// Gets the SerializedObject for the TagManager asset.\n /// \n private static SerializedObject GetTagManager()\n {\n try\n {\n // Load the TagManager asset from the ProjectSettings folder\n UnityEngine.Object[] tagManagerAssets = AssetDatabase.LoadAllAssetsAtPath(\n \"ProjectSettings/TagManager.asset\"\n );\n if (tagManagerAssets == null || tagManagerAssets.Length == 0)\n {\n Debug.LogError(\"[ManageEditor] TagManager.asset not found in ProjectSettings.\");\n return null;\n }\n // The first object in the asset file should be the TagManager\n return new SerializedObject(tagManagerAssets[0]);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageEditor] Error accessing TagManager.asset: {e.Message}\");\n return null;\n }\n }\n\n // --- Example Implementations for Settings ---\n /*\n private static object SetGameViewResolution(int width, int height) { ... }\n private static object SetQualityLevel(JToken qualityLevelToken) { ... }\n */\n }\n\n // Helper class to get custom tool names (remains the same)\n internal static class EditorTools\n {\n public static string GetActiveToolName()\n {\n // This is a placeholder. Real implementation depends on how custom tools\n // are registered and tracked in the specific Unity project setup.\n // It might involve checking static variables, calling methods on specific tool managers, etc.\n if (UnityEditor.Tools.current == Tool.Custom)\n {\n // Example: Check a known custom tool manager\n // if (MyCustomToolManager.IsActive) return MyCustomToolManager.ActiveToolName;\n return \"Unknown Custom Tool\";\n }\n return UnityEditor.Tools.current.ToString();\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScene.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles scene management operations like loading, saving, creating, and querying hierarchy.\n /// \n public static class ManageScene\n {\n /// \n /// Main handler for scene management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n int? buildIndex = @params[\"buildIndex\"]?.ToObject();\n // bool loadAdditive = @params[\"loadAdditive\"]?.ToObject() ?? false; // Example for future extension\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n string relativeDir = path ?? string.Empty;\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n\n // Apply default *after* sanitizing, using the original path variable for the check\n if (string.IsNullOrEmpty(path) && action == \"create\") // Check original path for emptiness\n {\n relativeDir = \"Scenes\"; // Default relative directory\n }\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n string sceneFileName = string.IsNullOrEmpty(name) ? null : $\"{name}.unity\";\n // Construct full system path correctly: ProjectRoot/Assets/relativeDir/sceneFileName\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Combine with Assets path (Application.dataPath ends in Assets)\n string fullPath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(fullPathDir, sceneFileName);\n // Ensure relativePath always starts with \"Assets/\" and uses forward slashes\n string relativePath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(\"Assets\", relativeDir, sceneFileName).Replace('\\\\', '/');\n\n // Ensure directory exists for 'create'\n if (action == \"create\" && !string.IsNullOrEmpty(fullPathDir))\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route action\n switch (action)\n {\n case \"create\":\n if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(relativePath))\n return Response.Error(\n \"'name' and 'path' parameters are required for 'create' action.\"\n );\n return CreateScene(fullPath, relativePath);\n case \"load\":\n // Loading can be done by path/name or build index\n if (!string.IsNullOrEmpty(relativePath))\n return LoadScene(relativePath);\n else if (buildIndex.HasValue)\n return LoadScene(buildIndex.Value);\n else\n return Response.Error(\n \"Either 'name'/'path' or 'buildIndex' must be provided for 'load' action.\"\n );\n case \"save\":\n // Save current scene, optionally to a new path\n return SaveScene(fullPath, relativePath);\n case \"get_hierarchy\":\n return GetSceneHierarchy();\n case \"get_active\":\n return GetActiveSceneInfo();\n case \"get_build_settings\":\n return GetBuildSettingsScenes();\n // Add cases for modifying build settings, additive loading, unloading etc.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions: create, load, save, get_hierarchy, get_active, get_build_settings.\"\n );\n }\n }\n\n private static object CreateScene(string fullPath, string relativePath)\n {\n if (File.Exists(fullPath))\n {\n return Response.Error($\"Scene already exists at '{relativePath}'.\");\n }\n\n try\n {\n // Create a new empty scene\n Scene newScene = EditorSceneManager.NewScene(\n NewSceneSetup.EmptyScene,\n NewSceneMode.Single\n );\n // Save it to the specified path\n bool saved = EditorSceneManager.SaveScene(newScene, relativePath);\n\n if (saved)\n {\n AssetDatabase.Refresh(); // Ensure Unity sees the new scene file\n return Response.Success(\n $\"Scene '{Path.GetFileName(relativePath)}' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n else\n {\n // If SaveScene fails, it might leave an untitled scene open.\n // Optionally try to close it, but be cautious.\n return Response.Error($\"Failed to save new scene to '{relativePath}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error creating scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(string relativePath)\n {\n if (\n !File.Exists(\n Path.Combine(\n Application.dataPath.Substring(\n 0,\n Application.dataPath.Length - \"Assets\".Length\n ),\n relativePath\n )\n )\n )\n {\n return Response.Error($\"Scene file not found at '{relativePath}'.\");\n }\n\n // Check for unsaved changes in the current scene\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n // Optionally prompt the user or save automatically before loading\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n // Example: bool saveOK = EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();\n // if (!saveOK) return Response.Error(\"Load cancelled by user.\");\n }\n\n try\n {\n EditorSceneManager.OpenScene(relativePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene '{relativePath}' loaded successfully.\",\n new\n {\n path = relativePath,\n name = Path.GetFileNameWithoutExtension(relativePath),\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error loading scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(int buildIndex)\n {\n if (buildIndex < 0 || buildIndex >= SceneManager.sceneCountInBuildSettings)\n {\n return Response.Error(\n $\"Invalid build index: {buildIndex}. Must be between 0 and {SceneManager.sceneCountInBuildSettings - 1}.\"\n );\n }\n\n // Check for unsaved changes\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n }\n\n try\n {\n string scenePath = SceneUtility.GetScenePathByBuildIndex(buildIndex);\n EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene at build index {buildIndex} ('{scenePath}') loaded successfully.\",\n new\n {\n path = scenePath,\n name = Path.GetFileNameWithoutExtension(scenePath),\n buildIndex = buildIndex,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error loading scene with build index {buildIndex}: {e.Message}\"\n );\n }\n }\n\n private static object SaveScene(string fullPath, string relativePath)\n {\n try\n {\n Scene currentScene = EditorSceneManager.GetActiveScene();\n if (!currentScene.IsValid())\n {\n return Response.Error(\"No valid scene is currently active to save.\");\n }\n\n bool saved;\n string finalPath = currentScene.path; // Path where it was last saved or will be saved\n\n if (!string.IsNullOrEmpty(relativePath) && currentScene.path != relativePath)\n {\n // Save As...\n // Ensure directory exists\n string dir = Path.GetDirectoryName(fullPath);\n if (!Directory.Exists(dir))\n Directory.CreateDirectory(dir);\n\n saved = EditorSceneManager.SaveScene(currentScene, relativePath);\n finalPath = relativePath;\n }\n else\n {\n // Save (overwrite existing or save untitled)\n if (string.IsNullOrEmpty(currentScene.path))\n {\n // Scene is untitled, needs a path\n return Response.Error(\n \"Cannot save an untitled scene without providing a 'name' and 'path'. Use Save As functionality.\"\n );\n }\n saved = EditorSceneManager.SaveScene(currentScene);\n }\n\n if (saved)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Scene '{currentScene.name}' saved successfully to '{finalPath}'.\",\n new { path = finalPath, name = currentScene.name }\n );\n }\n else\n {\n return Response.Error($\"Failed to save scene '{currentScene.name}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error saving scene: {e.Message}\");\n }\n }\n\n private static object GetActiveSceneInfo()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid())\n {\n return Response.Error(\"No active scene found.\");\n }\n\n var sceneInfo = new\n {\n name = activeScene.name,\n path = activeScene.path,\n buildIndex = activeScene.buildIndex, // -1 if not in build settings\n isDirty = activeScene.isDirty,\n isLoaded = activeScene.isLoaded,\n rootCount = activeScene.rootCount,\n };\n\n return Response.Success(\"Retrieved active scene information.\", sceneInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active scene info: {e.Message}\");\n }\n }\n\n private static object GetBuildSettingsScenes()\n {\n try\n {\n var scenes = new List();\n for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)\n {\n var scene = EditorBuildSettings.scenes[i];\n scenes.Add(\n new\n {\n path = scene.path,\n guid = scene.guid.ToString(),\n enabled = scene.enabled,\n buildIndex = i, // Actual build index considering only enabled scenes might differ\n }\n );\n }\n return Response.Success(\"Retrieved scenes from Build Settings.\", scenes);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scenes from Build Settings: {e.Message}\");\n }\n }\n\n private static object GetSceneHierarchy()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid() || !activeScene.isLoaded)\n {\n return Response.Error(\n \"No valid and loaded scene is active to get hierarchy from.\"\n );\n }\n\n GameObject[] rootObjects = activeScene.GetRootGameObjects();\n var hierarchy = rootObjects.Select(go => GetGameObjectDataRecursive(go)).ToList();\n\n return Response.Success(\n $\"Retrieved hierarchy for scene '{activeScene.name}'.\",\n hierarchy\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scene hierarchy: {e.Message}\");\n }\n }\n\n /// \n /// Recursively builds a data representation of a GameObject and its children.\n /// \n private static object GetGameObjectDataRecursive(GameObject go)\n {\n if (go == null)\n return null;\n\n var childrenData = new List();\n foreach (Transform child in go.transform)\n {\n childrenData.Add(GetGameObjectDataRecursive(child.gameObject));\n }\n\n var gameObjectData = new Dictionary\n {\n { \"name\", go.name },\n { \"activeSelf\", go.activeSelf },\n { \"activeInHierarchy\", go.activeInHierarchy },\n { \"tag\", go.tag },\n { \"layer\", go.layer },\n { \"isStatic\", go.isStatic },\n { \"instanceID\", go.GetInstanceID() }, // Useful unique identifier\n {\n \"transform\",\n new\n {\n position = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n }, // Euler for simplicity\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n }\n },\n { \"children\", childrenData },\n };\n\n return gameObjectData;\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScript.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\n#if USE_ROSLYN\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\n#endif\n\n#if UNITY_EDITOR\nusing UnityEditor.Compilation;\n#endif\n\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for C# scripts within the Unity project.\n /// \n /// ROSLYN INSTALLATION GUIDE:\n /// To enable advanced syntax validation with Roslyn compiler services:\n /// \n /// 1. Install Microsoft.CodeAnalysis.CSharp NuGet package:\n /// - Open Package Manager in Unity\n /// - Follow the instruction on https://github.com/GlitchEnzo/NuGetForUnity\n /// \n /// 2. Open NuGet Package Manager and Install Microsoft.CodeAnalysis.CSharp:\n /// \n /// 3. Alternative: Manual DLL installation:\n /// - Download Microsoft.CodeAnalysis.CSharp.dll and dependencies\n /// - Place in Assets/Plugins/ folder\n /// - Ensure .NET compatibility settings are correct\n /// \n /// 4. Define USE_ROSLYN symbol:\n /// - Go to Player Settings > Scripting Define Symbols\n /// - Add \"USE_ROSLYN\" to enable Roslyn-based validation\n /// \n /// 5. Restart Unity after installation\n /// \n /// Note: Without Roslyn, the system falls back to basic structural validation.\n /// Roslyn provides full C# compiler diagnostics with line numbers and detailed error messages.\n /// \n public static class ManageScript\n {\n /// \n /// Main handler for script management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode script contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n string scriptType = @params[\"scriptType\"]?.ToString(); // For templates/validation\n string namespaceName = @params[\"namespace\"]?.ToString(); // For organizing code\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid script name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Scripts\" if path is not provided\n string relativeDir = path ?? \"Scripts\"; // Default to \"Scripts\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Scripts\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string scriptFileName = $\"{name}.cs\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Application.dataPath ends in \"Assets\"\n string fullPath = Path.Combine(fullPathDir, scriptFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, scriptFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateScript(\n fullPath,\n relativePath,\n name,\n contents,\n scriptType,\n namespaceName\n );\n case \"read\":\n return ReadScript(fullPath, relativePath);\n case \"update\":\n return UpdateScript(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteScript(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents,\n string scriptType,\n string namespaceName\n )\n {\n // Check if script already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultScriptContent(name, scriptType, namespaceName);\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block creation\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new script\n return Response.Success(\n $\"Script '{name}.cs' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script not found at '{relativePath}'. Use 'create' action to add a new script.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block update\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath); // Re-import to reflect changes\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{name}.cs' updated successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'. Cannot delete.\");\n }\n\n try\n {\n // Use AssetDatabase.MoveAssetToTrash for safer deletion (allows undo)\n bool deleted = AssetDatabase.MoveAssetToTrash(relativePath);\n if (deleted)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' moved to trash successfully.\"\n );\n }\n else\n {\n // Fallback or error if MoveAssetToTrash fails\n return Response.Error(\n $\"Failed to move script '{relativePath}' to trash. It might be locked or in use.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting script '{relativePath}': {e.Message}\");\n }\n }\n\n /// \n /// Generates basic C# script content based on name and type.\n /// \n private static string GenerateDefaultScriptContent(\n string name,\n string scriptType,\n string namespaceName\n )\n {\n string usingStatements = \"using UnityEngine;\\nusing System.Collections;\\n\";\n string classDeclaration;\n string body =\n \"\\n // Use this for initialization\\n void Start() {\\n\\n }\\n\\n // Update is called once per frame\\n void Update() {\\n\\n }\\n\";\n\n string baseClass = \"\";\n if (!string.IsNullOrEmpty(scriptType))\n {\n if (scriptType.Equals(\"MonoBehaviour\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : MonoBehaviour\";\n else if (scriptType.Equals(\"ScriptableObject\", StringComparison.OrdinalIgnoreCase))\n {\n baseClass = \" : ScriptableObject\";\n body = \"\"; // ScriptableObjects don't usually need Start/Update\n }\n else if (\n scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase)\n || scriptType.Equals(\"EditorWindow\", StringComparison.OrdinalIgnoreCase)\n )\n {\n usingStatements += \"using UnityEditor;\\n\";\n if (scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : Editor\";\n else\n baseClass = \" : EditorWindow\";\n body = \"\"; // Editor scripts have different structures\n }\n // Add more types as needed\n }\n\n classDeclaration = $\"public class {name}{baseClass}\";\n\n string fullContent = $\"{usingStatements}\\n\";\n bool useNamespace = !string.IsNullOrEmpty(namespaceName);\n\n if (useNamespace)\n {\n fullContent += $\"namespace {namespaceName}\\n{{\\n\";\n // Indent class and body if using namespace\n classDeclaration = \" \" + classDeclaration;\n body = string.Join(\"\\n\", body.Split('\\n').Select(line => \" \" + line));\n }\n\n fullContent += $\"{classDeclaration}\\n{{\\n{body}\\n}}\";\n\n if (useNamespace)\n {\n fullContent += \"\\n}\"; // Close namespace\n }\n\n return fullContent.Trim() + \"\\n\"; // Ensure a trailing newline\n }\n\n /// \n /// Gets the validation level from the GUI settings\n /// \n private static ValidationLevel GetValidationLevelFromGUI()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel.ToLower() switch\n {\n \"basic\" => ValidationLevel.Basic,\n \"standard\" => ValidationLevel.Standard,\n \"comprehensive\" => ValidationLevel.Comprehensive,\n \"strict\" => ValidationLevel.Strict,\n _ => ValidationLevel.Standard // Default fallback\n };\n }\n\n /// \n /// Validates C# script syntax using multiple validation layers.\n /// \n private static bool ValidateScriptSyntax(string contents)\n {\n return ValidateScriptSyntax(contents, ValidationLevel.Standard, out _);\n }\n\n /// \n /// Advanced syntax validation with detailed diagnostics and configurable strictness.\n /// \n private static bool ValidateScriptSyntax(string contents, ValidationLevel level, out string[] errors)\n {\n var errorList = new System.Collections.Generic.List();\n errors = null;\n\n if (string.IsNullOrEmpty(contents))\n {\n return true; // Empty content is valid\n }\n\n // Basic structural validation\n if (!ValidateBasicStructure(contents, errorList))\n {\n errors = errorList.ToArray();\n return false;\n }\n\n#if USE_ROSLYN\n // Advanced Roslyn-based validation\n if (!ValidateScriptSyntaxRoslyn(contents, level, errorList))\n {\n errors = errorList.ToArray();\n return level != ValidationLevel.Standard; //TODO: Allow standard to run roslyn right now, might formalize it in the future\n }\n#endif\n\n // Unity-specific validation\n if (level >= ValidationLevel.Standard)\n {\n ValidateScriptSyntaxUnity(contents, errorList);\n }\n\n // Semantic analysis for common issues\n if (level >= ValidationLevel.Comprehensive)\n {\n ValidateSemanticRules(contents, errorList);\n }\n\n#if USE_ROSLYN\n // Full semantic compilation validation for Strict level\n if (level == ValidationLevel.Strict)\n {\n if (!ValidateScriptSemantics(contents, errorList))\n {\n errors = errorList.ToArray();\n return false; // Strict level fails on any semantic errors\n }\n }\n#endif\n\n errors = errorList.ToArray();\n return errorList.Count == 0 || (level != ValidationLevel.Strict && !errorList.Any(e => e.StartsWith(\"ERROR:\")));\n }\n\n /// \n /// Validation strictness levels\n /// \n private enum ValidationLevel\n {\n Basic, // Only syntax errors\n Standard, // Syntax + Unity best practices\n Comprehensive, // All checks + semantic analysis\n Strict // Treat all issues as errors\n }\n\n /// \n /// Validates basic code structure (braces, quotes, comments)\n /// \n private static bool ValidateBasicStructure(string contents, System.Collections.Generic.List errors)\n {\n bool isValid = true;\n int braceBalance = 0;\n int parenBalance = 0;\n int bracketBalance = 0;\n bool inStringLiteral = false;\n bool inCharLiteral = false;\n bool inSingleLineComment = false;\n bool inMultiLineComment = false;\n bool escaped = false;\n\n for (int i = 0; i < contents.Length; i++)\n {\n char c = contents[i];\n char next = i + 1 < contents.Length ? contents[i + 1] : '\\0';\n\n // Handle escape sequences\n if (escaped)\n {\n escaped = false;\n continue;\n }\n\n if (c == '\\\\' && (inStringLiteral || inCharLiteral))\n {\n escaped = true;\n continue;\n }\n\n // Handle comments\n if (!inStringLiteral && !inCharLiteral)\n {\n if (c == '/' && next == '/' && !inMultiLineComment)\n {\n inSingleLineComment = true;\n continue;\n }\n if (c == '/' && next == '*' && !inSingleLineComment)\n {\n inMultiLineComment = true;\n i++; // Skip next character\n continue;\n }\n if (c == '*' && next == '/' && inMultiLineComment)\n {\n inMultiLineComment = false;\n i++; // Skip next character\n continue;\n }\n }\n\n if (c == '\\n')\n {\n inSingleLineComment = false;\n continue;\n }\n\n if (inSingleLineComment || inMultiLineComment)\n continue;\n\n // Handle string and character literals\n if (c == '\"' && !inCharLiteral)\n {\n inStringLiteral = !inStringLiteral;\n continue;\n }\n if (c == '\\'' && !inStringLiteral)\n {\n inCharLiteral = !inCharLiteral;\n continue;\n }\n\n if (inStringLiteral || inCharLiteral)\n continue;\n\n // Count brackets and braces\n switch (c)\n {\n case '{': braceBalance++; break;\n case '}': braceBalance--; break;\n case '(': parenBalance++; break;\n case ')': parenBalance--; break;\n case '[': bracketBalance++; break;\n case ']': bracketBalance--; break;\n }\n\n // Check for negative balances (closing without opening)\n if (braceBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing brace '}'\");\n isValid = false;\n }\n if (parenBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing parenthesis ')'\");\n isValid = false;\n }\n if (bracketBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing bracket ']'\");\n isValid = false;\n }\n }\n\n // Check final balances\n if (braceBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced braces (difference: {braceBalance})\");\n isValid = false;\n }\n if (parenBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced parentheses (difference: {parenBalance})\");\n isValid = false;\n }\n if (bracketBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced brackets (difference: {bracketBalance})\");\n isValid = false;\n }\n if (inStringLiteral)\n {\n errors.Add(\"ERROR: Unterminated string literal\");\n isValid = false;\n }\n if (inCharLiteral)\n {\n errors.Add(\"ERROR: Unterminated character literal\");\n isValid = false;\n }\n if (inMultiLineComment)\n {\n errors.Add(\"WARNING: Unterminated multi-line comment\");\n }\n\n return isValid;\n }\n\n#if USE_ROSLYN\n /// \n /// Cached compilation references for performance\n /// \n private static System.Collections.Generic.List _cachedReferences = null;\n private static DateTime _cacheTime = DateTime.MinValue;\n private static readonly TimeSpan CacheExpiry = TimeSpan.FromMinutes(5);\n\n /// \n /// Validates syntax using Roslyn compiler services\n /// \n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n try\n {\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n var diagnostics = syntaxTree.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n string severity = diagnostic.Severity.ToString().ToUpper();\n string message = $\"{severity}: {diagnostic.GetMessage()}\";\n \n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n }\n \n // Include warnings in comprehensive mode\n if (level >= ValidationLevel.Standard || diagnostic.Severity == DiagnosticSeverity.Error) //Also use Standard for now\n {\n var location = diagnostic.Location.GetLineSpan();\n if (location.IsValid)\n {\n message += $\" (Line {location.StartLinePosition.Line + 1})\";\n }\n errors.Add(message);\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Roslyn validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Validates script semantics using full compilation context to catch namespace, type, and method resolution errors\n /// \n private static bool ValidateScriptSemantics(string contents, System.Collections.Generic.List errors)\n {\n try\n {\n // Get compilation references with caching\n var references = GetCompilationReferences();\n if (references == null || references.Count == 0)\n {\n errors.Add(\"WARNING: Could not load compilation references for semantic validation\");\n return true; // Don't fail if we can't get references\n }\n\n // Create syntax tree\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n\n // Create compilation with full context\n var compilation = CSharpCompilation.Create(\n \"TempValidation\",\n new[] { syntaxTree },\n references,\n new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)\n );\n\n // Get semantic diagnostics - this catches all the issues you mentioned!\n var diagnostics = compilation.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n // Include diagnostic ID for better error identification\n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"ERROR: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n else if (diagnostic.Severity == DiagnosticSeverity.Warning)\n {\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"WARNING: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Semantic validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets compilation references with caching for performance\n /// \n private static System.Collections.Generic.List GetCompilationReferences()\n {\n // Check cache validity\n if (_cachedReferences != null && DateTime.Now - _cacheTime < CacheExpiry)\n {\n return _cachedReferences;\n }\n\n try\n {\n var references = new System.Collections.Generic.List();\n\n // Core .NET assemblies\n references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); // mscorlib/System.Private.CoreLib\n references.Add(MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location)); // System.Linq\n references.Add(MetadataReference.CreateFromFile(typeof(System.Collections.Generic.List<>).Assembly.Location)); // System.Collections\n\n // Unity assemblies\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEngine.Debug).Assembly.Location)); // UnityEngine\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEngine assembly: {ex.Message}\");\n }\n\n#if UNITY_EDITOR\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEditor.Editor).Assembly.Location)); // UnityEditor\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEditor assembly: {ex.Message}\");\n }\n\n // Get Unity project assemblies\n try\n {\n var assemblies = CompilationPipeline.GetAssemblies();\n foreach (var assembly in assemblies)\n {\n if (File.Exists(assembly.outputPath))\n {\n references.Add(MetadataReference.CreateFromFile(assembly.outputPath));\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load Unity project assemblies: {ex.Message}\");\n }\n#endif\n\n // Cache the results\n _cachedReferences = references;\n _cacheTime = DateTime.Now;\n\n return references;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to get compilation references: {ex.Message}\");\n return new System.Collections.Generic.List();\n }\n }\n#else\n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n // Fallback when Roslyn is not available\n return true;\n }\n#endif\n\n /// \n /// Validates Unity-specific coding rules and best practices\n /// //TODO: Naive Unity Checks and not really yield any results, need to be improved\n /// \n private static void ValidateScriptSyntaxUnity(string contents, System.Collections.Generic.List errors)\n {\n // Check for common Unity anti-patterns\n if (contents.Contains(\"FindObjectOfType\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: FindObjectOfType in Update() can cause performance issues\");\n }\n\n if (contents.Contains(\"GameObject.Find\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: GameObject.Find in Update() can cause performance issues\");\n }\n\n // Check for proper MonoBehaviour usage\n if (contents.Contains(\": MonoBehaviour\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: MonoBehaviour requires 'using UnityEngine;'\");\n }\n\n // Check for SerializeField usage\n if (contents.Contains(\"[SerializeField]\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: SerializeField requires 'using UnityEngine;'\");\n }\n\n // Check for proper coroutine usage\n if (contents.Contains(\"StartCoroutine\") && !contents.Contains(\"IEnumerator\"))\n {\n errors.Add(\"WARNING: StartCoroutine typically requires IEnumerator methods\");\n }\n\n // Check for Update without FixedUpdate for physics\n if (contents.Contains(\"Rigidbody\") && contents.Contains(\"Update()\") && !contents.Contains(\"FixedUpdate()\"))\n {\n errors.Add(\"WARNING: Consider using FixedUpdate() for Rigidbody operations\");\n }\n\n // Check for missing null checks on Unity objects\n if (contents.Contains(\"GetComponent<\") && !contents.Contains(\"!= null\"))\n {\n errors.Add(\"WARNING: Consider null checking GetComponent results\");\n }\n\n // Check for proper event function signatures\n if (contents.Contains(\"void Start(\") && !contents.Contains(\"void Start()\"))\n {\n errors.Add(\"WARNING: Start() should not have parameters\");\n }\n\n if (contents.Contains(\"void Update(\") && !contents.Contains(\"void Update()\"))\n {\n errors.Add(\"WARNING: Update() should not have parameters\");\n }\n\n // Check for inefficient string operations\n if (contents.Contains(\"Update()\") && contents.Contains(\"\\\"\") && contents.Contains(\"+\"))\n {\n errors.Add(\"WARNING: String concatenation in Update() can cause garbage collection issues\");\n }\n }\n\n /// \n /// Validates semantic rules and common coding issues\n /// \n private static void ValidateSemanticRules(string contents, System.Collections.Generic.List errors)\n {\n // Check for potential memory leaks\n if (contents.Contains(\"new \") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: Creating objects in Update() may cause memory issues\");\n }\n\n // Check for magic numbers\n var magicNumberPattern = new Regex(@\"\\b\\d+\\.?\\d*f?\\b(?!\\s*[;})\\]])\");\n var matches = magicNumberPattern.Matches(contents);\n if (matches.Count > 5)\n {\n errors.Add(\"WARNING: Consider using named constants instead of magic numbers\");\n }\n\n // Check for long methods (simple line count check)\n var methodPattern = new Regex(@\"(public|private|protected|internal)?\\s*(static)?\\s*\\w+\\s+\\w+\\s*\\([^)]*\\)\\s*{\");\n var methodMatches = methodPattern.Matches(contents);\n foreach (Match match in methodMatches)\n {\n int startIndex = match.Index;\n int braceCount = 0;\n int lineCount = 0;\n bool inMethod = false;\n\n for (int i = startIndex; i < contents.Length; i++)\n {\n if (contents[i] == '{')\n {\n braceCount++;\n inMethod = true;\n }\n else if (contents[i] == '}')\n {\n braceCount--;\n if (braceCount == 0 && inMethod)\n break;\n }\n else if (contents[i] == '\\n' && inMethod)\n {\n lineCount++;\n }\n }\n\n if (lineCount > 50)\n {\n errors.Add(\"WARNING: Method is very long, consider breaking it into smaller methods\");\n break; // Only report once\n }\n }\n\n // Check for proper exception handling\n if (contents.Contains(\"catch\") && contents.Contains(\"catch()\"))\n {\n errors.Add(\"WARNING: Empty catch blocks should be avoided\");\n }\n\n // Check for proper async/await usage\n if (contents.Contains(\"async \") && !contents.Contains(\"await\"))\n {\n errors.Add(\"WARNING: Async method should contain await or return Task\");\n }\n\n // Check for hardcoded tags and layers\n if (contents.Contains(\"\\\"Player\\\"\") || contents.Contains(\"\\\"Enemy\\\"\"))\n {\n errors.Add(\"WARNING: Consider using constants for tags instead of hardcoded strings\");\n }\n }\n\n //TODO: A easier way for users to update incorrect scripts (now duplicated with the updateScript method and need to also update server side, put aside for now)\n /// \n /// Public method to validate script syntax with configurable validation level\n /// Returns detailed validation results including errors and warnings\n /// \n // public static object ValidateScript(JObject @params)\n // {\n // string contents = @params[\"contents\"]?.ToString();\n // string validationLevel = @params[\"validationLevel\"]?.ToString() ?? \"standard\";\n\n // if (string.IsNullOrEmpty(contents))\n // {\n // return Response.Error(\"Contents parameter is required for validation.\");\n // }\n\n // // Parse validation level\n // ValidationLevel level = ValidationLevel.Standard;\n // switch (validationLevel.ToLower())\n // {\n // case \"basic\": level = ValidationLevel.Basic; break;\n // case \"standard\": level = ValidationLevel.Standard; break;\n // case \"comprehensive\": level = ValidationLevel.Comprehensive; break;\n // case \"strict\": level = ValidationLevel.Strict; break;\n // default:\n // return Response.Error($\"Invalid validation level: '{validationLevel}'. Valid levels are: basic, standard, comprehensive, strict.\");\n // }\n\n // // Perform validation\n // bool isValid = ValidateScriptSyntax(contents, level, out string[] validationErrors);\n\n // var errors = validationErrors?.Where(e => e.StartsWith(\"ERROR:\")).ToArray() ?? new string[0];\n // var warnings = validationErrors?.Where(e => e.StartsWith(\"WARNING:\")).ToArray() ?? new string[0];\n\n // var result = new\n // {\n // isValid = isValid,\n // validationLevel = validationLevel,\n // errorCount = errors.Length,\n // warningCount = warnings.Length,\n // errors = errors,\n // warnings = warnings,\n // summary = isValid \n // ? (warnings.Length > 0 ? $\"Validation passed with {warnings.Length} warnings\" : \"Validation passed with no issues\")\n // : $\"Validation failed with {errors.Length} errors and {warnings.Length} warnings\"\n // };\n\n // if (isValid)\n // {\n // return Response.Success(\"Script validation completed successfully.\", result);\n // }\n // else\n // {\n // return Response.Error(\"Script validation failed.\", result);\n // }\n // }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageShader.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for shader files within the Unity project.\n /// \n public static class ManageShader\n {\n /// \n /// Main handler for shader management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode shader contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid shader name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Shaders\" if path is not provided\n string relativeDir = path ?? \"Shaders\"; // Default to \"Shaders\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Shaders\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string shaderFileName = $\"{name}.shader\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir);\n string fullPath = Path.Combine(fullPathDir, shaderFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, shaderFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n if (!Directory.Exists(fullPathDir))\n {\n Directory.CreateDirectory(fullPathDir);\n // Refresh AssetDatabase to recognize new folders\n AssetDatabase.Refresh();\n }\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateShader(fullPath, relativePath, name, contents);\n case \"read\":\n return ReadShader(fullPath, relativePath);\n case \"update\":\n return UpdateShader(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteShader(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n // Check if shader already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Add validation for shader name conflicts in Unity\n if (Shader.Find(name) != null)\n {\n return Response.Error(\n $\"A shader with name '{name}' already exists in the project. Choose a different name.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultShaderContent(name);\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new shader\n return Response.Success(\n $\"Shader '{name}.shader' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n //TODO: Consider a threshold for large files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader not found at '{relativePath}'. Use 'create' action to add a new shader.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' updated successfully.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n // Delete the asset through Unity's AssetDatabase first\n bool success = AssetDatabase.DeleteAsset(relativePath);\n if (!success)\n {\n return Response.Error($\"Failed to delete shader through Unity's AssetDatabase: '{relativePath}'\");\n }\n\n // If the file still exists (rare case), try direct deletion\n if (File.Exists(fullPath))\n {\n File.Delete(fullPath);\n }\n\n return Response.Success($\"Shader '{Path.GetFileName(relativePath)}' deleted successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to delete shader '{relativePath}': {e.Message}\");\n }\n }\n\n //This is a CGProgram template\n //TODO: making a HLSL template as well?\n private static string GenerateDefaultShaderContent(string name)\n {\n return @\"Shader \"\"\" + name + @\"\"\"\n {\n Properties\n {\n _MainTex (\"\"Texture\"\", 2D) = \"\"white\"\" {}\n }\n SubShader\n {\n Tags { \"\"RenderType\"\"=\"\"Opaque\"\" }\n LOD 100\n\n Pass\n {\n CGPROGRAM\n #pragma vertex vert\n #pragma fragment frag\n #include \"\"UnityCG.cginc\"\"\n\n struct appdata\n {\n float4 vertex : POSITION;\n float2 uv : TEXCOORD0;\n };\n\n struct v2f\n {\n float2 uv : TEXCOORD0;\n float4 vertex : SV_POSITION;\n };\n\n sampler2D _MainTex;\n float4 _MainTex_ST;\n\n v2f vert (appdata v)\n {\n v2f o;\n o.vertex = UnityObjectToClipPos(v.vertex);\n o.uv = TRANSFORM_TEX(v.uv, _MainTex);\n return o;\n }\n\n fixed4 frag (v2f i) : SV_Target\n {\n fixed4 col = tex2D(_MainTex, i.uv);\n return col;\n }\n ENDCG\n }\n }\n }\";\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/UnityMcpBridge.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\nusing UnityMcpBridge.Editor.Tools;\n\nnamespace UnityMcpBridge.Editor\n{\n [InitializeOnLoad]\n public static partial class UnityMcpBridge\n {\n private static TcpListener listener;\n private static bool isRunning = false;\n private static readonly object lockObj = new();\n private static Dictionary<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > commandQueue = new();\n private static readonly int unityPort = 6400; // Hardcoded port\n\n public static bool IsRunning => isRunning;\n\n public static bool FolderExists(string path)\n {\n if (string.IsNullOrEmpty(path))\n {\n return false;\n }\n\n if (path.Equals(\"Assets\", StringComparison.OrdinalIgnoreCase))\n {\n return true;\n }\n\n string fullPath = Path.Combine(\n Application.dataPath,\n path.StartsWith(\"Assets/\") ? path[7..] : path\n );\n return Directory.Exists(fullPath);\n }\n\n static UnityMcpBridge()\n {\n Start();\n EditorApplication.quitting += Stop;\n }\n\n public static void Start()\n {\n Stop();\n\n try\n {\n ServerInstaller.EnsureServerInstalled();\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure UnityMcpServer is installed: {ex.Message}\");\n }\n\n if (isRunning)\n {\n return;\n }\n\n try\n {\n listener = new TcpListener(IPAddress.Loopback, unityPort);\n listener.Start();\n isRunning = true;\n Debug.Log($\"UnityMcpBridge started on port {unityPort}.\");\n // Assuming ListenerLoop and ProcessCommands are defined elsewhere\n Task.Run(ListenerLoop);\n EditorApplication.update += ProcessCommands;\n }\n catch (SocketException ex)\n {\n if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)\n {\n Debug.LogError(\n $\"Port {unityPort} is already in use. Ensure no other instances are running or change the port.\"\n );\n }\n else\n {\n Debug.LogError($\"Failed to start TCP listener: {ex.Message}\");\n }\n }\n }\n\n public static void Stop()\n {\n if (!isRunning)\n {\n return;\n }\n\n try\n {\n listener?.Stop();\n listener = null;\n isRunning = false;\n EditorApplication.update -= ProcessCommands;\n Debug.Log(\"UnityMcpBridge stopped.\");\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error stopping UnityMcpBridge: {ex.Message}\");\n }\n }\n\n private static async Task ListenerLoop()\n {\n while (isRunning)\n {\n try\n {\n TcpClient client = await listener.AcceptTcpClientAsync();\n // Enable basic socket keepalive\n client.Client.SetSocketOption(\n SocketOptionLevel.Socket,\n SocketOptionName.KeepAlive,\n true\n );\n\n // Set longer receive timeout to prevent quick disconnections\n client.ReceiveTimeout = 60000; // 60 seconds\n\n // Fire and forget each client connection\n _ = HandleClientAsync(client);\n }\n catch (Exception ex)\n {\n if (isRunning)\n {\n Debug.LogError($\"Listener error: {ex.Message}\");\n }\n }\n }\n }\n\n private static async Task HandleClientAsync(TcpClient client)\n {\n using (client)\n using (NetworkStream stream = client.GetStream())\n {\n byte[] buffer = new byte[8192];\n while (isRunning)\n {\n try\n {\n int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);\n if (bytesRead == 0)\n {\n break; // Client disconnected\n }\n\n string commandText = System.Text.Encoding.UTF8.GetString(\n buffer,\n 0,\n bytesRead\n );\n string commandId = Guid.NewGuid().ToString();\n TaskCompletionSource tcs = new();\n\n // Special handling for ping command to avoid JSON parsing\n if (commandText.Trim() == \"ping\")\n {\n // Direct response to ping without going through JSON parsing\n byte[] pingResponseBytes = System.Text.Encoding.UTF8.GetBytes(\n /*lang=json,strict*/\n \"{\\\"status\\\":\\\"success\\\",\\\"result\\\":{\\\"message\\\":\\\"pong\\\"}}\"\n );\n await stream.WriteAsync(pingResponseBytes, 0, pingResponseBytes.Length);\n continue;\n }\n\n lock (lockObj)\n {\n commandQueue[commandId] = (commandText, tcs);\n }\n\n string response = await tcs.Task;\n byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);\n await stream.WriteAsync(responseBytes, 0, responseBytes.Length);\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Client handler error: {ex.Message}\");\n break;\n }\n }\n }\n }\n\n private static void ProcessCommands()\n {\n List processedIds = new();\n lock (lockObj)\n {\n foreach (\n KeyValuePair<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > kvp in commandQueue.ToList()\n )\n {\n string id = kvp.Key;\n string commandText = kvp.Value.commandJson;\n TaskCompletionSource tcs = kvp.Value.tcs;\n\n try\n {\n // Special case handling\n if (string.IsNullOrEmpty(commandText))\n {\n var emptyResponse = new\n {\n status = \"error\",\n error = \"Empty command received\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(emptyResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Trim the command text to remove any whitespace\n commandText = commandText.Trim();\n\n // Non-JSON direct commands handling (like ping)\n if (commandText == \"ping\")\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n tcs.SetResult(JsonConvert.SerializeObject(pingResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Check if the command is valid JSON before attempting to deserialize\n if (!IsValidJson(commandText))\n {\n var invalidJsonResponse = new\n {\n status = \"error\",\n error = \"Invalid JSON format\",\n receivedText = commandText.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n tcs.SetResult(JsonConvert.SerializeObject(invalidJsonResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Normal JSON command processing\n Command command = JsonConvert.DeserializeObject(commandText);\n \n if (command == null)\n {\n var nullCommandResponse = new\n {\n status = \"error\",\n error = \"Command deserialized to null\",\n details = \"The command was valid JSON but could not be deserialized to a Command object\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(nullCommandResponse));\n }\n else\n {\n string responseJson = ExecuteCommand(command);\n tcs.SetResult(responseJson);\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error processing command: {ex.Message}\\n{ex.StackTrace}\");\n\n var response = new\n {\n status = \"error\",\n error = ex.Message,\n commandType = \"Unknown (error during processing)\",\n receivedText = commandText?.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n string responseJson = JsonConvert.SerializeObject(response);\n tcs.SetResult(responseJson);\n }\n\n processedIds.Add(id);\n }\n\n foreach (string id in processedIds)\n {\n commandQueue.Remove(id);\n }\n }\n }\n\n // Helper method to check if a string is valid JSON\n private static bool IsValidJson(string text)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n return false;\n }\n\n text = text.Trim();\n if (\n (text.StartsWith(\"{\") && text.EndsWith(\"}\"))\n || // Object\n (text.StartsWith(\"[\") && text.EndsWith(\"]\"))\n ) // Array\n {\n try\n {\n JToken.Parse(text);\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n return false;\n }\n\n private static string ExecuteCommand(Command command)\n {\n try\n {\n if (string.IsNullOrEmpty(command.type))\n {\n var errorResponse = new\n {\n status = \"error\",\n error = \"Command type cannot be empty\",\n details = \"A valid command type is required for processing\",\n };\n return JsonConvert.SerializeObject(errorResponse);\n }\n\n // Handle ping command for connection verification\n if (command.type.Equals(\"ping\", StringComparison.OrdinalIgnoreCase))\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n return JsonConvert.SerializeObject(pingResponse);\n }\n\n // Use JObject for parameters as the new handlers likely expect this\n JObject paramsObject = command.@params ?? new JObject();\n\n // Route command based on the new tool structure from the refactor plan\n object result = command.type switch\n {\n // Maps the command type (tool name) to the corresponding handler's static HandleCommand method\n // Assumes each handler class has a static method named 'HandleCommand' that takes JObject parameters\n \"manage_script\" => ManageScript.HandleCommand(paramsObject),\n \"manage_scene\" => ManageScene.HandleCommand(paramsObject),\n \"manage_editor\" => ManageEditor.HandleCommand(paramsObject),\n \"manage_gameobject\" => ManageGameObject.HandleCommand(paramsObject),\n \"manage_asset\" => ManageAsset.HandleCommand(paramsObject),\n \"manage_shader\" => ManageShader.HandleCommand(paramsObject),\n \"read_console\" => ReadConsole.HandleCommand(paramsObject),\n \"execute_menu_item\" => ExecuteMenuItem.HandleCommand(paramsObject),\n _ => throw new ArgumentException(\n $\"Unknown or unsupported command type: {command.type}\"\n ),\n };\n\n // Standard success response format\n var response = new { status = \"success\", result };\n return JsonConvert.SerializeObject(response);\n }\n catch (Exception ex)\n {\n // Log the detailed error in Unity for debugging\n Debug.LogError(\n $\"Error executing command '{command?.type ?? \"Unknown\"}': {ex.Message}\\n{ex.StackTrace}\"\n );\n\n // Standard error response format\n var response = new\n {\n status = \"error\",\n error = ex.Message, // Provide the specific error message\n command = command?.type ?? \"Unknown\", // Include the command type if available\n stackTrace = ex.StackTrace, // Include stack trace for detailed debugging\n paramsSummary = command?.@params != null\n ? GetParamsSummary(command.@params)\n : \"No parameters\", // Summarize parameters for context\n };\n return JsonConvert.SerializeObject(response);\n }\n }\n\n // Helper method to get a summary of parameters for error reporting\n private static string GetParamsSummary(JObject @params)\n {\n try\n {\n return @params == null || !@params.HasValues\n ? \"No parameters\"\n : string.Join(\n \", \",\n @params\n .Properties()\n .Select(static p =>\n $\"{p.Name}: {p.Value?.ToString()?[..Math.Min(20, p.Value?.ToString()?.Length ?? 0)]}\"\n )\n );\n }\n catch\n {\n return \"Could not summarize parameters\";\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/GameObjectSerializer.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Runtime.Serialization; // For Converters\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Handles serialization of GameObjects and Components for MCP responses.\n /// Includes reflection helpers and caching for performance.\n /// \n public static class GameObjectSerializer\n {\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of a GameObject.\n /// \n public static object GetGameObjectData(GameObject go)\n {\n if (go == null)\n return null;\n return new\n {\n name = go.name,\n instanceID = go.GetInstanceID(),\n tag = go.tag,\n layer = go.layer,\n activeSelf = go.activeSelf,\n activeInHierarchy = go.activeInHierarchy,\n isStatic = go.isStatic,\n scenePath = go.scene.path, // Identify which scene it belongs to\n transform = new // Serialize transform components carefully to avoid JSON issues\n {\n // Serialize Vector3 components individually to prevent self-referencing loops.\n // The default serializer can struggle with properties like Vector3.normalized.\n position = new\n {\n x = go.transform.position.x,\n y = go.transform.position.y,\n z = go.transform.position.z,\n },\n localPosition = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.rotation.eulerAngles.x,\n y = go.transform.rotation.eulerAngles.y,\n z = go.transform.rotation.eulerAngles.z,\n },\n localRotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n },\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n forward = new\n {\n x = go.transform.forward.x,\n y = go.transform.forward.y,\n z = go.transform.forward.z,\n },\n up = new\n {\n x = go.transform.up.x,\n y = go.transform.up.y,\n z = go.transform.up.z,\n },\n right = new\n {\n x = go.transform.right.x,\n y = go.transform.right.y,\n z = go.transform.right.z,\n },\n },\n parentInstanceID = go.transform.parent?.gameObject.GetInstanceID() ?? 0, // 0 if no parent\n // Optionally include components, but can be large\n // components = go.GetComponents().Select(c => GetComponentData(c)).ToList()\n // Or just component names:\n componentNames = go.GetComponents()\n .Select(c => c.GetType().FullName)\n .ToList(),\n };\n }\n\n // --- Metadata Caching for Reflection ---\n private class CachedMetadata\n {\n public readonly List SerializableProperties;\n public readonly List SerializableFields;\n\n public CachedMetadata(List properties, List fields)\n {\n SerializableProperties = properties;\n SerializableFields = fields;\n }\n }\n // Key becomes Tuple\n private static readonly Dictionary, CachedMetadata> _metadataCache = new Dictionary, CachedMetadata>();\n // --- End Metadata Caching ---\n\n /// \n /// Creates a serializable representation of a Component, attempting to serialize\n /// public properties and fields using reflection, with caching and control over non-public fields.\n /// \n // Add the flag parameter here\n public static object GetComponentData(Component c, bool includeNonPublicSerializedFields = true)\n {\n // --- Add Early Logging --- \n // Debug.Log($\"[GetComponentData] Starting for component: {c?.GetType()?.FullName ?? \"null\"} (ID: {c?.GetInstanceID() ?? 0})\");\n // --- End Early Logging ---\n \n if (c == null) return null;\n Type componentType = c.GetType();\n\n // --- Special handling for Transform to avoid reflection crashes and problematic properties --- \n if (componentType == typeof(Transform))\n {\n Transform tr = c as Transform;\n // Debug.Log($\"[GetComponentData] Manually serializing Transform (ID: {tr.GetInstanceID()})\");\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", tr.GetInstanceID() },\n // Manually extract known-safe properties. Avoid Quaternion 'rotation' and 'lossyScale'.\n { \"position\", CreateTokenFromValue(tr.position, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localPosition\", CreateTokenFromValue(tr.localPosition, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"eulerAngles\", CreateTokenFromValue(tr.eulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() }, // Use Euler angles\n { \"localEulerAngles\", CreateTokenFromValue(tr.localEulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localScale\", CreateTokenFromValue(tr.localScale, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"right\", CreateTokenFromValue(tr.right, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"up\", CreateTokenFromValue(tr.up, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"forward\", CreateTokenFromValue(tr.forward, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"parentInstanceID\", tr.parent?.gameObject.GetInstanceID() ?? 0 },\n { \"rootInstanceID\", tr.root?.gameObject.GetInstanceID() ?? 0 },\n { \"childCount\", tr.childCount },\n // Include standard Object/Component properties\n { \"name\", tr.name }, \n { \"tag\", tr.tag }, \n { \"gameObjectInstanceID\", tr.gameObject?.GetInstanceID() ?? 0 }\n };\n }\n // --- End Special handling for Transform --- \n\n // --- Special handling for Camera to avoid matrix-related crashes ---\n if (componentType == typeof(Camera))\n {\n Camera cam = c as Camera;\n var cameraProperties = new Dictionary();\n\n // List of safe properties to serialize\n var safeProperties = new Dictionary>\n {\n { \"nearClipPlane\", () => cam.nearClipPlane },\n { \"farClipPlane\", () => cam.farClipPlane },\n { \"fieldOfView\", () => cam.fieldOfView },\n { \"renderingPath\", () => (int)cam.renderingPath },\n { \"actualRenderingPath\", () => (int)cam.actualRenderingPath },\n { \"allowHDR\", () => cam.allowHDR },\n { \"allowMSAA\", () => cam.allowMSAA },\n { \"allowDynamicResolution\", () => cam.allowDynamicResolution },\n { \"forceIntoRenderTexture\", () => cam.forceIntoRenderTexture },\n { \"orthographicSize\", () => cam.orthographicSize },\n { \"orthographic\", () => cam.orthographic },\n { \"opaqueSortMode\", () => (int)cam.opaqueSortMode },\n { \"transparencySortMode\", () => (int)cam.transparencySortMode },\n { \"depth\", () => cam.depth },\n { \"aspect\", () => cam.aspect },\n { \"cullingMask\", () => cam.cullingMask },\n { \"eventMask\", () => cam.eventMask },\n { \"backgroundColor\", () => cam.backgroundColor },\n { \"clearFlags\", () => (int)cam.clearFlags },\n { \"stereoEnabled\", () => cam.stereoEnabled },\n { \"stereoSeparation\", () => cam.stereoSeparation },\n { \"stereoConvergence\", () => cam.stereoConvergence },\n { \"enabled\", () => cam.enabled },\n { \"name\", () => cam.name },\n { \"tag\", () => cam.tag },\n { \"gameObject\", () => new { name = cam.gameObject.name, instanceID = cam.gameObject.GetInstanceID() } }\n };\n\n foreach (var prop in safeProperties)\n {\n try\n {\n var value = prop.Value();\n if (value != null)\n {\n AddSerializableValue(cameraProperties, prop.Key, value.GetType(), value);\n }\n }\n catch (Exception)\n {\n // Silently skip any property that fails\n continue;\n }\n }\n\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", cam.GetInstanceID() },\n { \"properties\", cameraProperties }\n };\n }\n // --- End Special handling for Camera ---\n\n var data = new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", c.GetInstanceID() }\n };\n\n // --- Get Cached or Generate Metadata (using new cache key) ---\n Tuple cacheKey = new Tuple(componentType, includeNonPublicSerializedFields);\n if (!_metadataCache.TryGetValue(cacheKey, out CachedMetadata cachedData))\n {\n var propertiesToCache = new List();\n var fieldsToCache = new List();\n\n // Traverse the hierarchy from the component type up to MonoBehaviour\n Type currentType = componentType;\n while (currentType != null && currentType != typeof(MonoBehaviour) && currentType != typeof(object))\n {\n // Get properties declared only at the current type level\n BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n foreach (var propInfo in currentType.GetProperties(propFlags))\n {\n // Basic filtering (readable, not indexer, not transform which is handled elsewhere)\n if (!propInfo.CanRead || propInfo.GetIndexParameters().Length > 0 || propInfo.Name == \"transform\") continue;\n // Add if not already added (handles overrides - keep the most derived version)\n if (!propertiesToCache.Any(p => p.Name == propInfo.Name)) {\n propertiesToCache.Add(propInfo);\n }\n }\n\n // Get fields declared only at the current type level (both public and non-public)\n BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n var declaredFields = currentType.GetFields(fieldFlags);\n\n // Process the declared Fields for caching\n foreach (var fieldInfo in declaredFields)\n {\n if (fieldInfo.Name.EndsWith(\"k__BackingField\")) continue; // Skip backing fields\n\n // Add if not already added (handles hiding - keep the most derived version)\n if (fieldsToCache.Any(f => f.Name == fieldInfo.Name)) continue;\n\n bool shouldInclude = false;\n if (includeNonPublicSerializedFields)\n {\n // If TRUE, include Public OR NonPublic with [SerializeField]\n shouldInclude = fieldInfo.IsPublic || (fieldInfo.IsPrivate && fieldInfo.IsDefined(typeof(SerializeField), inherit: false));\n }\n else // includeNonPublicSerializedFields is FALSE\n {\n // If FALSE, include ONLY if it is explicitly Public.\n shouldInclude = fieldInfo.IsPublic;\n }\n\n if (shouldInclude)\n {\n fieldsToCache.Add(fieldInfo);\n }\n }\n\n // Move to the base type\n currentType = currentType.BaseType;\n }\n // --- End Hierarchy Traversal ---\n\n cachedData = new CachedMetadata(propertiesToCache, fieldsToCache);\n _metadataCache[cacheKey] = cachedData; // Add to cache with combined key\n }\n // --- End Get Cached or Generate Metadata ---\n\n // --- Use cached metadata ---\n var serializablePropertiesOutput = new Dictionary();\n \n // --- Add Logging Before Property Loop ---\n // Debug.Log($\"[GetComponentData] Starting property loop for {componentType.Name}...\");\n // --- End Logging Before Property Loop ---\n\n // Use cached properties\n foreach (var propInfo in cachedData.SerializableProperties)\n {\n string propName = propInfo.Name;\n\n // --- Skip known obsolete/problematic Component shortcut properties ---\n bool skipProperty = false;\n if (propName == \"rigidbody\" || propName == \"rigidbody2D\" || propName == \"camera\" ||\n propName == \"light\" || propName == \"animation\" || propName == \"constantForce\" ||\n propName == \"renderer\" || propName == \"audio\" || propName == \"networkView\" ||\n propName == \"collider\" || propName == \"collider2D\" || propName == \"hingeJoint\" ||\n propName == \"particleSystem\" ||\n // Also skip potentially problematic Matrix properties prone to cycles/errors\n propName == \"worldToLocalMatrix\" || propName == \"localToWorldMatrix\")\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping generic property: {propName}\"); // Optional log\n skipProperty = true;\n }\n // --- End Skip Generic Properties ---\n\n // --- Skip specific potentially problematic Camera properties ---\n if (componentType == typeof(Camera) && \n (propName == \"pixelRect\" || \n propName == \"rect\" || \n propName == \"cullingMatrix\" ||\n propName == \"useOcclusionCulling\" ||\n propName == \"worldToCameraMatrix\" ||\n propName == \"projectionMatrix\" ||\n propName == \"nonJitteredProjectionMatrix\" ||\n propName == \"previousViewProjectionMatrix\" ||\n propName == \"cameraToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Camera property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Camera Properties ---\n\n // --- Skip specific potentially problematic Transform properties ---\n if (componentType == typeof(Transform) && \n (propName == \"lossyScale\" || \n propName == \"rotation\" ||\n propName == \"worldToLocalMatrix\" ||\n propName == \"localToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Transform property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Transform Properties ---\n\n // Skip if flagged\n if (skipProperty)\n {\n continue;\n }\n\n try\n {\n // --- Add detailed logging --- \n // Debug.Log($\"[GetComponentData] Accessing: {componentType.Name}.{propName}\");\n // --- End detailed logging ---\n object value = propInfo.GetValue(c);\n Type propType = propInfo.PropertyType;\n AddSerializableValue(serializablePropertiesOutput, propName, propType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read property {propName} on {componentType.Name}: {ex.Message}\");\n }\n }\n\n // --- Add Logging Before Field Loop ---\n // Debug.Log($\"[GetComponentData] Starting field loop for {componentType.Name}...\");\n // --- End Logging Before Field Loop ---\n\n // Use cached fields\n foreach (var fieldInfo in cachedData.SerializableFields)\n {\n try\n {\n // --- Add detailed logging for fields --- \n // Debug.Log($\"[GetComponentData] Accessing Field: {componentType.Name}.{fieldInfo.Name}\");\n // --- End detailed logging for fields ---\n object value = fieldInfo.GetValue(c);\n string fieldName = fieldInfo.Name;\n Type fieldType = fieldInfo.FieldType;\n AddSerializableValue(serializablePropertiesOutput, fieldName, fieldType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read field {fieldInfo.Name} on {componentType.Name}: {ex.Message}\");\n }\n }\n // --- End Use cached metadata ---\n\n if (serializablePropertiesOutput.Count > 0)\n {\n data[\"properties\"] = serializablePropertiesOutput;\n }\n\n return data;\n }\n\n // Helper function to decide how to serialize different types\n private static void AddSerializableValue(Dictionary dict, string name, Type type, object value)\n {\n // Simplified: Directly use CreateTokenFromValue which uses the serializer\n if (value == null)\n {\n dict[name] = null;\n return;\n }\n\n try\n {\n // Use the helper that employs our custom serializer settings\n JToken token = CreateTokenFromValue(value, type);\n if (token != null) // Check if serialization succeeded in the helper\n {\n // Convert JToken back to a basic object structure for the dictionary\n dict[name] = ConvertJTokenToPlainObject(token);\n }\n // If token is null, it means serialization failed and a warning was logged.\n }\n catch (Exception e)\n {\n // Catch potential errors during JToken conversion or addition to dictionary\n Debug.LogWarning($\"[AddSerializableValue] Error processing value for '{name}' (Type: {type.FullName}): {e.Message}. Skipping.\");\n }\n }\n\n // Helper to convert JToken back to basic object structure\n private static object ConvertJTokenToPlainObject(JToken token)\n {\n if (token == null) return null;\n\n switch (token.Type)\n {\n case JTokenType.Object:\n var objDict = new Dictionary();\n foreach (var prop in ((JObject)token).Properties())\n {\n objDict[prop.Name] = ConvertJTokenToPlainObject(prop.Value);\n }\n return objDict;\n\n case JTokenType.Array:\n var list = new List();\n foreach (var item in (JArray)token)\n {\n list.Add(ConvertJTokenToPlainObject(item));\n }\n return list;\n\n case JTokenType.Integer:\n return token.ToObject(); // Use long for safety\n case JTokenType.Float:\n return token.ToObject(); // Use double for safety\n case JTokenType.String:\n return token.ToObject();\n case JTokenType.Boolean:\n return token.ToObject();\n case JTokenType.Date:\n return token.ToObject();\n case JTokenType.Guid:\n return token.ToObject();\n case JTokenType.Uri:\n return token.ToObject();\n case JTokenType.TimeSpan:\n return token.ToObject();\n case JTokenType.Bytes:\n return token.ToObject();\n case JTokenType.Null:\n return null;\n case JTokenType.Undefined:\n return null; // Treat undefined as null\n\n default:\n // Fallback for simple value types not explicitly listed\n if (token is JValue jValue && jValue.Value != null)\n {\n return jValue.Value;\n }\n // Debug.LogWarning($\"Unsupported JTokenType encountered: {token.Type}. Returning null.\");\n return null;\n }\n }\n\n // --- Define custom JsonSerializerSettings for OUTPUT ---\n private static readonly JsonSerializerSettings _outputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Handles serialization of references\n },\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore,\n // ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } // Example if needed\n };\n private static readonly JsonSerializer _outputSerializer = JsonSerializer.Create(_outputSerializerSettings);\n // --- End Define custom JsonSerializerSettings ---\n\n // Helper to create JToken using the output serializer\n private static JToken CreateTokenFromValue(object value, Type type)\n {\n if (value == null) return JValue.CreateNull();\n\n try\n {\n // Use the pre-configured OUTPUT serializer instance\n return JToken.FromObject(value, _outputSerializer);\n }\n catch (JsonSerializationException e)\n {\n Debug.LogWarning($\"[GameObjectSerializer] Newtonsoft.Json Error serializing value of type {type.FullName}: {e.Message}. Skipping property/field.\");\n return null; // Indicate serialization failure\n }\n catch (Exception e) // Catch other unexpected errors\n {\n Debug.LogWarning($\"[GameObjectSerializer] Unexpected error serializing value of type {type.FullName}: {e}. Skipping property/field.\");\n return null; // Indicate serialization failure\n }\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Windows/UnityMcpEditorWindow.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing Newtonsoft.Json;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Data;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class UnityMcpEditorWindow : EditorWindow\n {\n private bool isUnityBridgeRunning = false;\n private Vector2 scrollPosition;\n private string pythonServerInstallationStatus = \"Not Installed\";\n private Color pythonServerInstallationStatusColor = Color.red;\n private const int unityPort = 6400; // Hardcoded Unity port\n private const int mcpPort = 6500; // Hardcoded MCP port\n private readonly McpClients mcpClients = new();\n \n // Script validation settings\n private int validationLevelIndex = 1; // Default to Standard\n private readonly string[] validationLevelOptions = new string[]\n {\n \"Basic - Only syntax checks\",\n \"Standard - Syntax + Unity practices\", \n \"Comprehensive - All checks + semantic analysis\",\n \"Strict - Full semantic validation (requires Roslyn)\"\n };\n \n // UI state\n private int selectedClientIndex = 0;\n\n [MenuItem(\"Window/Unity MCP\")]\n public static void ShowWindow()\n {\n GetWindow(\"MCP Editor\");\n }\n\n private void OnEnable()\n {\n UpdatePythonServerInstallationStatus();\n\n isUnityBridgeRunning = UnityMcpBridge.IsRunning;\n foreach (McpClient mcpClient in mcpClients.clients)\n {\n CheckMcpConfiguration(mcpClient);\n }\n \n // Load validation level setting\n LoadValidationLevelSetting();\n }\n\n private Color GetStatusColor(McpStatus status)\n {\n // Return appropriate color based on the status enum\n return status switch\n {\n McpStatus.Configured => Color.green,\n McpStatus.Running => Color.green,\n McpStatus.Connected => Color.green,\n McpStatus.IncorrectPath => Color.yellow,\n McpStatus.CommunicationError => Color.yellow,\n McpStatus.NoResponse => Color.yellow,\n _ => Color.red, // Default to red for error states or not configured\n };\n }\n\n private void UpdatePythonServerInstallationStatus()\n {\n string serverPath = ServerInstaller.GetServerPath();\n\n if (File.Exists(Path.Combine(serverPath, \"server.py\")))\n {\n string installedVersion = ServerInstaller.GetInstalledVersion();\n string latestVersion = ServerInstaller.GetLatestVersion();\n\n if (ServerInstaller.IsNewerVersion(latestVersion, installedVersion))\n {\n pythonServerInstallationStatus = \"Newer Version Available\";\n pythonServerInstallationStatusColor = Color.yellow;\n }\n else\n {\n pythonServerInstallationStatus = \"Up to Date\";\n pythonServerInstallationStatusColor = Color.green;\n }\n }\n else\n {\n pythonServerInstallationStatus = \"Not Installed\";\n pythonServerInstallationStatusColor = Color.red;\n }\n }\n\n\n private void DrawStatusDot(Rect statusRect, Color statusColor, float size = 12)\n {\n float offsetX = (statusRect.width - size) / 2;\n float offsetY = (statusRect.height - size) / 2;\n Rect dotRect = new(statusRect.x + offsetX, statusRect.y + offsetY, size, size);\n Vector3 center = new(\n dotRect.x + (dotRect.width / 2),\n dotRect.y + (dotRect.height / 2),\n 0\n );\n float radius = size / 2;\n\n // Draw the main dot\n Handles.color = statusColor;\n Handles.DrawSolidDisc(center, Vector3.forward, radius);\n\n // Draw the border\n Color borderColor = new(\n statusColor.r * 0.7f,\n statusColor.g * 0.7f,\n statusColor.b * 0.7f\n );\n Handles.color = borderColor;\n Handles.DrawWireDisc(center, Vector3.forward, radius);\n }\n\n private void OnGUI()\n {\n scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);\n\n // Header\n DrawHeader();\n \n // Main sections in a more compact layout\n EditorGUILayout.BeginHorizontal();\n \n // Left column - Status and Bridge\n EditorGUILayout.BeginVertical(GUILayout.Width(position.width * 0.5f));\n DrawServerStatusSection();\n EditorGUILayout.Space(5);\n DrawBridgeSection();\n EditorGUILayout.EndVertical();\n \n // Right column - Validation Settings\n EditorGUILayout.BeginVertical();\n DrawValidationSection();\n EditorGUILayout.EndVertical();\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Unified MCP Client Configuration\n DrawUnifiedClientConfiguration();\n\n EditorGUILayout.EndScrollView();\n }\n\n private void DrawHeader()\n {\n EditorGUILayout.Space(15);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 40);\n EditorGUI.DrawRect(titleRect, new Color(0.2f, 0.2f, 0.2f, 0.1f));\n \n GUIStyle titleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 16,\n alignment = TextAnchor.MiddleLeft\n };\n \n GUI.Label(\n new Rect(titleRect.x + 15, titleRect.y + 8, titleRect.width - 30, titleRect.height),\n \"Unity MCP Editor\",\n titleStyle\n );\n EditorGUILayout.Space(15);\n }\n\n private void DrawServerStatusSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Server Status\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(statusRect, pythonServerInstallationStatusColor, 16);\n \n GUIStyle statusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(pythonServerInstallationStatus, statusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(5);\n GUIStyle portStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 11\n };\n EditorGUILayout.LabelField($\"Ports: Unity {unityPort}, MCP {mcpPort}\", portStyle);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawBridgeSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Unity Bridge\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUILayout.BeginHorizontal();\n Color bridgeColor = isUnityBridgeRunning ? Color.green : Color.red;\n Rect bridgeStatusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(bridgeStatusRect, bridgeColor, 16);\n \n GUIStyle bridgeStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(isUnityBridgeRunning ? \"Running\" : \"Stopped\", bridgeStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(8);\n if (GUILayout.Button(isUnityBridgeRunning ? \"Stop Bridge\" : \"Start Bridge\", GUILayout.Height(32)))\n {\n ToggleUnityBridge();\n }\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawValidationSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Script Validation\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUI.BeginChangeCheck();\n validationLevelIndex = EditorGUILayout.Popup(\"Validation Level\", validationLevelIndex, validationLevelOptions, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n SaveValidationLevelSetting();\n }\n \n EditorGUILayout.Space(8);\n string description = GetValidationLevelDescription(validationLevelIndex);\n EditorGUILayout.HelpBox(description, MessageType.Info);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawUnifiedClientConfiguration()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"MCP Client Configuration\", sectionTitleStyle);\n EditorGUILayout.Space(10);\n \n // Client selector\n string[] clientNames = mcpClients.clients.Select(c => c.name).ToArray();\n EditorGUI.BeginChangeCheck();\n selectedClientIndex = EditorGUILayout.Popup(\"Select Client\", selectedClientIndex, clientNames, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n selectedClientIndex = Mathf.Clamp(selectedClientIndex, 0, mcpClients.clients.Count - 1);\n }\n \n EditorGUILayout.Space(10);\n \n if (mcpClients.clients.Count > 0 && selectedClientIndex < mcpClients.clients.Count)\n {\n McpClient selectedClient = mcpClients.clients[selectedClientIndex];\n DrawClientConfigurationCompact(selectedClient);\n }\n \n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawClientConfigurationCompact(McpClient mcpClient)\n {\n // Status display\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n Color statusColor = GetStatusColor(mcpClient.status);\n DrawStatusDot(statusRect, statusColor, 16);\n \n GUIStyle clientStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(mcpClient.configStatus, clientStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Action buttons in horizontal layout\n EditorGUILayout.BeginHorizontal();\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n if (GUILayout.Button(\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n else\n {\n if (GUILayout.Button($\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n \n if (GUILayout.Button(\"Manual Setup\", GUILayout.Height(32)))\n {\n string configPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)\n ? mcpClient.windowsConfigPath\n : mcpClient.linuxConfigPath;\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n string pythonDir = FindPackagePythonDirectory();\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n VSCodeManualSetupWindow.ShowWindow(configPath, manualConfigJson);\n }\n else\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n }\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(8);\n // Quick info\n GUIStyle configInfoStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 10\n };\n EditorGUILayout.LabelField($\"Config: {Path.GetFileName(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? mcpClient.windowsConfigPath : mcpClient.linuxConfigPath)}\", configInfoStyle);\n }\n\n private void ToggleUnityBridge()\n {\n if (isUnityBridgeRunning)\n {\n UnityMcpBridge.Stop();\n }\n else\n {\n UnityMcpBridge.Start();\n }\n\n isUnityBridgeRunning = !isUnityBridgeRunning;\n }\n\n private string WriteToConfig(string pythonDir, string configPath, McpClient mcpClient = null)\n {\n // Create configuration object for unityMCP\n McpConfigServer unityMCPConfig = new()\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n\n // Read existing config if it exists\n string existingJson = \"{}\";\n if (File.Exists(configPath))\n {\n try\n {\n existingJson = File.ReadAllText(configPath);\n }\n catch (Exception e)\n {\n Debug.LogWarning($\"Error reading existing config: {e.Message}.\");\n }\n }\n\n // Parse the existing JSON while preserving all properties\n dynamic existingConfig = JsonConvert.DeserializeObject(existingJson);\n existingConfig ??= new Newtonsoft.Json.Linq.JObject();\n\n // Handle different client types with a switch statement\n //Comments: Interestingly, VSCode has mcp.servers.unityMCP while others have mcpServers.unityMCP, which is why we need to prevent this\n switch (mcpClient?.mcpType)\n {\n case McpTypes.VSCode:\n // VSCode specific configuration\n // Ensure mcp object exists\n if (existingConfig.mcp == null)\n {\n existingConfig.mcp = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Ensure mcp.servers object exists\n if (existingConfig.mcp.servers == null)\n {\n existingConfig.mcp.servers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in VSCode settings\n existingConfig.mcp.servers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n\n default:\n // Standard MCP configuration (Claude Desktop, Cursor, etc.)\n // Ensure mcpServers object exists\n if (existingConfig.mcpServers == null)\n {\n existingConfig.mcpServers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in standard MCP settings\n existingConfig.mcpServers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n }\n\n // Write the merged configuration back to file\n string mergedJson = JsonConvert.SerializeObject(existingConfig, jsonSettings);\n File.WriteAllText(configPath, mergedJson);\n\n return \"Configured successfully\";\n }\n\n private void ShowManualConfigurationInstructions(string configPath, McpClient mcpClient)\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n\n // New method to show manual instructions without changing status\n private void ShowManualInstructionsWindow(string configPath, McpClient mcpClient)\n {\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n string manualConfigJson;\n \n // Create common JsonSerializerSettings\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n \n // Use switch statement to handle different client types\n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n // Create VSCode-specific configuration with proper format\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n break;\n \n default:\n // Create standard MCP configuration for other clients\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n break;\n }\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private string FindPackagePythonDirectory()\n {\n string pythonDir = ServerInstaller.GetServerPath();\n\n try\n {\n // Try to find the package using Package Manager API\n UnityEditor.PackageManager.Requests.ListRequest request =\n UnityEditor.PackageManager.Client.List();\n while (!request.IsCompleted) { } // Wait for the request to complete\n\n if (request.Status == UnityEditor.PackageManager.StatusCode.Success)\n {\n foreach (UnityEditor.PackageManager.PackageInfo package in request.Result)\n {\n if (package.name == \"com.justinpbarnett.unity-mcp\")\n {\n string packagePath = package.resolvedPath;\n string potentialPythonDir = Path.Combine(packagePath, \"Python\");\n\n if (\n Directory.Exists(potentialPythonDir)\n && File.Exists(Path.Combine(potentialPythonDir, \"server.py\"))\n )\n {\n return potentialPythonDir;\n }\n }\n }\n }\n else if (request.Error != null)\n {\n Debug.LogError(\"Failed to list packages: \" + request.Error.message);\n }\n\n // If not found via Package Manager, try manual approaches\n // First check for local installation\n string[] possibleDirs =\n {\n Path.GetFullPath(Path.Combine(Application.dataPath, \"unity-mcp\", \"Python\")),\n };\n\n foreach (string dir in possibleDirs)\n {\n if (Directory.Exists(dir) && File.Exists(Path.Combine(dir, \"server.py\")))\n {\n return dir;\n }\n }\n\n // If still not found, return the placeholder path\n Debug.LogWarning(\"Could not find Python directory, using placeholder path\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"Error finding package path: {e.Message}\");\n }\n\n return pythonDir;\n }\n\n private string ConfigureMcpClient(McpClient mcpClient)\n {\n try\n {\n // Determine the config file path based on OS\n string configPath;\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n return \"Unsupported OS\";\n }\n\n // Create directory if it doesn't exist\n Directory.CreateDirectory(Path.GetDirectoryName(configPath));\n\n // Find the server.py file location\n string pythonDir = ServerInstaller.GetServerPath();\n\n if (pythonDir == null || !File.Exists(Path.Combine(pythonDir, \"server.py\")))\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n return \"Manual Configuration Required\";\n }\n\n string result = WriteToConfig(pythonDir, configPath, mcpClient);\n\n // Update the client status after successful configuration\n if (result == \"Configured successfully\")\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n\n return result;\n }\n catch (Exception e)\n {\n // Determine the config file path based on OS for error message\n string configPath = \"\";\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n Debug.LogError(\n $\"Failed to configure {mcpClient.name}: {e.Message}\\n{e.StackTrace}\"\n );\n return $\"Failed to configure {mcpClient.name}\";\n }\n }\n\n private void ShowCursorManualConfigurationInstructions(\n string configPath,\n McpClient mcpClient\n )\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n\n // Create the manual configuration message\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private void LoadValidationLevelSetting()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n validationLevelIndex = savedLevel.ToLower() switch\n {\n \"basic\" => 0,\n \"standard\" => 1,\n \"comprehensive\" => 2,\n \"strict\" => 3,\n _ => 1 // Default to Standard\n };\n }\n\n private void SaveValidationLevelSetting()\n {\n string levelString = validationLevelIndex switch\n {\n 0 => \"basic\",\n 1 => \"standard\",\n 2 => \"comprehensive\",\n 3 => \"strict\",\n _ => \"standard\"\n };\n EditorPrefs.SetString(\"UnityMCP_ScriptValidationLevel\", levelString);\n }\n\n private string GetValidationLevelDescription(int index)\n {\n return index switch\n {\n 0 => \"Only basic syntax checks (braces, quotes, comments)\",\n 1 => \"Syntax checks + Unity best practices and warnings\",\n 2 => \"All checks + semantic analysis and performance warnings\",\n 3 => \"Full semantic validation with namespace/type resolution (requires Roslyn)\",\n _ => \"Standard validation\"\n };\n }\n\n public static string GetCurrentValidationLevel()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel;\n }\n\n private void CheckMcpConfiguration(McpClient mcpClient)\n {\n try\n {\n string configPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n mcpClient.SetStatus(McpStatus.UnsupportedOS);\n return;\n }\n\n if (!File.Exists(configPath))\n {\n mcpClient.SetStatus(McpStatus.NotConfigured);\n return;\n }\n\n string configJson = File.ReadAllText(configPath);\n string pythonDir = ServerInstaller.GetServerPath();\n \n // Use switch statement to handle different client types, extracting common logic\n string[] args = null;\n bool configExists = false;\n \n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n dynamic config = JsonConvert.DeserializeObject(configJson);\n \n if (config?.mcp?.servers?.unityMCP != null)\n {\n // Extract args from VSCode config format\n args = config.mcp.servers.unityMCP.args.ToObject();\n configExists = true;\n }\n break;\n \n default:\n // Standard MCP configuration check for Claude Desktop, Cursor, etc.\n McpConfig standardConfig = JsonConvert.DeserializeObject(configJson);\n \n if (standardConfig?.mcpServers?.unityMCP != null)\n {\n args = standardConfig.mcpServers.unityMCP.args;\n configExists = true;\n }\n break;\n }\n \n // Common logic for checking configuration status\n if (configExists)\n {\n if (pythonDir != null && \n Array.Exists(args, arg => arg.Contains(pythonDir, StringComparison.Ordinal)))\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n else\n {\n mcpClient.SetStatus(McpStatus.IncorrectPath);\n }\n }\n else\n {\n mcpClient.SetStatus(McpStatus.MissingConfig);\n }\n }\n catch (Exception e)\n {\n mcpClient.SetStatus(McpStatus.Error, e.Message);\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/ServerInstaller.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Runtime.InteropServices;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n public static class ServerInstaller\n {\n private const string RootFolder = \"UnityMCP\";\n private const string ServerFolder = \"UnityMcpServer\";\n private const string BranchName = \"master\";\n private const string GitUrl = \"https://github.com/justinpbarnett/unity-mcp.git\";\n private const string PyprojectUrl =\n \"https://raw.githubusercontent.com/justinpbarnett/unity-mcp/refs/heads/\"\n + BranchName\n + \"/UnityMcpServer/src/pyproject.toml\";\n\n /// \n /// Ensures the unity-mcp-server is installed and up to date.\n /// \n public static void EnsureServerInstalled()\n {\n try\n {\n string saveLocation = GetSaveLocation();\n\n if (!IsServerInstalled(saveLocation))\n {\n InstallServer(saveLocation);\n }\n else\n {\n string installedVersion = GetInstalledVersion();\n string latestVersion = GetLatestVersion();\n\n if (IsNewerVersion(latestVersion, installedVersion))\n {\n UpdateServer(saveLocation);\n }\n else { }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure server installation: {ex.Message}\");\n }\n }\n\n public static string GetServerPath()\n {\n return Path.Combine(GetSaveLocation(), ServerFolder, \"src\");\n }\n\n /// \n /// Gets the platform-specific save location for the server.\n /// \n private static string GetSaveLocation()\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"AppData\",\n \"Local\",\n \"Programs\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"bin\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n string path = \"/usr/local/bin\";\n return !Directory.Exists(path) || !IsDirectoryWritable(path)\n ? Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Applications\",\n RootFolder\n )\n : Path.Combine(path, RootFolder);\n }\n throw new Exception(\"Unsupported operating system.\");\n }\n\n private static bool IsDirectoryWritable(string path)\n {\n try\n {\n File.Create(Path.Combine(path, \"test.txt\")).Dispose();\n File.Delete(Path.Combine(path, \"test.txt\"));\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Checks if the server is installed at the specified location.\n /// \n private static bool IsServerInstalled(string location)\n {\n return Directory.Exists(location)\n && File.Exists(Path.Combine(location, ServerFolder, \"src\", \"pyproject.toml\"));\n }\n\n /// \n /// Installs the server by cloning only the UnityMcpServer folder from the repository and setting up dependencies.\n /// \n private static void InstallServer(string location)\n {\n // Create the src directory where the server code will reside\n Directory.CreateDirectory(location);\n\n // Initialize git repo in the src directory\n RunCommand(\"git\", $\"init\", workingDirectory: location);\n\n // Add remote\n RunCommand(\"git\", $\"remote add origin {GitUrl}\", workingDirectory: location);\n\n // Configure sparse checkout\n RunCommand(\"git\", \"config core.sparseCheckout true\", workingDirectory: location);\n\n // Set sparse checkout path to only include UnityMcpServer folder\n string sparseCheckoutPath = Path.Combine(location, \".git\", \"info\", \"sparse-checkout\");\n File.WriteAllText(sparseCheckoutPath, $\"{ServerFolder}/\");\n\n // Fetch and checkout the branch\n RunCommand(\"git\", $\"fetch --depth=1 origin {BranchName}\", workingDirectory: location);\n RunCommand(\"git\", $\"checkout {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Fetches the currently installed version from the local pyproject.toml file.\n /// \n public static string GetInstalledVersion()\n {\n string pyprojectPath = Path.Combine(\n GetSaveLocation(),\n ServerFolder,\n \"src\",\n \"pyproject.toml\"\n );\n return ParseVersionFromPyproject(File.ReadAllText(pyprojectPath));\n }\n\n /// \n /// Fetches the latest version from the GitHub pyproject.toml file.\n /// \n public static string GetLatestVersion()\n {\n using WebClient webClient = new();\n string pyprojectContent = webClient.DownloadString(PyprojectUrl);\n return ParseVersionFromPyproject(pyprojectContent);\n }\n\n /// \n /// Updates the server by pulling the latest changes for the UnityMcpServer folder only.\n /// \n private static void UpdateServer(string location)\n {\n RunCommand(\"git\", $\"pull origin {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Parses the version number from pyproject.toml content.\n /// \n private static string ParseVersionFromPyproject(string content)\n {\n foreach (string line in content.Split('\\n'))\n {\n if (line.Trim().StartsWith(\"version =\"))\n {\n string[] parts = line.Split('=');\n if (parts.Length == 2)\n {\n return parts[1].Trim().Trim('\"');\n }\n }\n }\n throw new Exception(\"Version not found in pyproject.toml\");\n }\n\n /// \n /// Compares two version strings to determine if the latest is newer.\n /// \n public static bool IsNewerVersion(string latest, string installed)\n {\n int[] latestParts = latest.Split('.').Select(int.Parse).ToArray();\n int[] installedParts = installed.Split('.').Select(int.Parse).ToArray();\n for (int i = 0; i < Math.Min(latestParts.Length, installedParts.Length); i++)\n {\n if (latestParts[i] > installedParts[i])\n {\n return true;\n }\n\n if (latestParts[i] < installedParts[i])\n {\n return false;\n }\n }\n return latestParts.Length > installedParts.Length;\n }\n\n /// \n /// Runs a command-line process and handles output/errors.\n /// \n private static void RunCommand(\n string command,\n string arguments,\n string workingDirectory = null\n )\n {\n System.Diagnostics.Process process = new()\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = command,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n WorkingDirectory = workingDirectory ?? string.Empty,\n },\n };\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n if (process.ExitCode != 0)\n {\n throw new Exception(\n $\"Command failed: {command} {arguments}\\nOutput: {output}\\nError: {error}\"\n );\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/CommandRegistry.cs", "using System;\nusing System.Collections.Generic;\nusing Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Registry for all MCP command handlers (Refactored Version)\n /// \n public static class CommandRegistry\n {\n // Maps command names (matching those called from Python via ctx.bridge.unity_editor.HandlerName)\n // to the corresponding static HandleCommand method in the appropriate tool class.\n private static readonly Dictionary> _handlers = new()\n {\n { \"HandleManageScript\", ManageScript.HandleCommand },\n { \"HandleManageScene\", ManageScene.HandleCommand },\n { \"HandleManageEditor\", ManageEditor.HandleCommand },\n { \"HandleManageGameObject\", ManageGameObject.HandleCommand },\n { \"HandleManageAsset\", ManageAsset.HandleCommand },\n { \"HandleReadConsole\", ReadConsole.HandleCommand },\n { \"HandleExecuteMenuItem\", ExecuteMenuItem.HandleCommand },\n { \"HandleManageShader\", ManageShader.HandleCommand},\n };\n\n /// \n /// Gets a command handler by name.\n /// \n /// Name of the command handler (e.g., \"HandleManageAsset\").\n /// The command handler function if found, null otherwise.\n public static Func GetHandler(string commandName)\n {\n // Use case-insensitive comparison for flexibility, although Python side should be consistent\n return _handlers.TryGetValue(commandName, out var handler) ? handler : null;\n // Consider adding logging here if a handler is not found\n /*\n if (_handlers.TryGetValue(commandName, out var handler)) {\n return handler;\n } else {\n UnityEngine.Debug.LogError($\\\"[CommandRegistry] No handler found for command: {commandName}\\\");\n return null;\n }\n */\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Runtime/Serialization/UnityTypeConverters.cs", "using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing UnityEngine;\n#if UNITY_EDITOR\nusing UnityEditor; // Required for AssetDatabase and EditorUtility\n#endif\n\nnamespace UnityMcpBridge.Runtime.Serialization\n{\n public class Vector3Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector3 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WriteEndObject();\n }\n\n public override Vector3 ReadJson(JsonReader reader, Type objectType, Vector3 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector3(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"]\n );\n }\n }\n\n public class Vector2Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WriteEndObject();\n }\n\n public override Vector2 ReadJson(JsonReader reader, Type objectType, Vector2 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector2(\n (float)jo[\"x\"],\n (float)jo[\"y\"]\n );\n }\n }\n\n public class QuaternionConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Quaternion value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WritePropertyName(\"w\");\n writer.WriteValue(value.w);\n writer.WriteEndObject();\n }\n\n public override Quaternion ReadJson(JsonReader reader, Type objectType, Quaternion existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Quaternion(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"],\n (float)jo[\"w\"]\n );\n }\n }\n\n public class ColorConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Color value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"r\");\n writer.WriteValue(value.r);\n writer.WritePropertyName(\"g\");\n writer.WriteValue(value.g);\n writer.WritePropertyName(\"b\");\n writer.WriteValue(value.b);\n writer.WritePropertyName(\"a\");\n writer.WriteValue(value.a);\n writer.WriteEndObject();\n }\n\n public override Color ReadJson(JsonReader reader, Type objectType, Color existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Color(\n (float)jo[\"r\"],\n (float)jo[\"g\"],\n (float)jo[\"b\"],\n (float)jo[\"a\"]\n );\n }\n }\n \n public class RectConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Rect value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"width\");\n writer.WriteValue(value.width);\n writer.WritePropertyName(\"height\");\n writer.WriteValue(value.height);\n writer.WriteEndObject();\n }\n\n public override Rect ReadJson(JsonReader reader, Type objectType, Rect existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Rect(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"width\"],\n (float)jo[\"height\"]\n );\n }\n }\n \n public class BoundsConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Bounds value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"center\");\n serializer.Serialize(writer, value.center); // Use serializer to handle nested Vector3\n writer.WritePropertyName(\"size\");\n serializer.Serialize(writer, value.size); // Use serializer to handle nested Vector3\n writer.WriteEndObject();\n }\n\n public override Bounds ReadJson(JsonReader reader, Type objectType, Bounds existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n Vector3 center = jo[\"center\"].ToObject(serializer); // Use serializer to handle nested Vector3\n Vector3 size = jo[\"size\"].ToObject(serializer); // Use serializer to handle nested Vector3\n return new Bounds(center, size);\n }\n }\n\n // Converter for UnityEngine.Object references (GameObjects, Components, Materials, Textures, etc.)\n public class UnityEngineObjectConverter : JsonConverter\n {\n public override bool CanRead => true; // We need to implement ReadJson\n public override bool CanWrite => true;\n\n public override void WriteJson(JsonWriter writer, UnityEngine.Object value, JsonSerializer serializer)\n {\n if (value == null)\n {\n writer.WriteNull();\n return;\n }\n\n#if UNITY_EDITOR // AssetDatabase and EditorUtility are Editor-only\n if (UnityEditor.AssetDatabase.Contains(value))\n {\n // It's an asset (Material, Texture, Prefab, etc.)\n string path = UnityEditor.AssetDatabase.GetAssetPath(value);\n if (!string.IsNullOrEmpty(path))\n {\n writer.WriteValue(path);\n }\n else\n {\n // Asset exists but path couldn't be found? Write minimal info.\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"isAssetWithoutPath\");\n writer.WriteValue(true);\n writer.WriteEndObject();\n }\n }\n else\n {\n // It's a scene object (GameObject, Component, etc.)\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WriteEndObject();\n }\n#else\n // Runtime fallback: Write basic info without AssetDatabase\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"warning\");\n writer.WriteValue(\"UnityEngineObjectConverter running in non-Editor mode, asset path unavailable.\");\n writer.WriteEndObject();\n#endif\n }\n\n public override UnityEngine.Object ReadJson(JsonReader reader, Type objectType, UnityEngine.Object existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n if (reader.TokenType == JsonToken.Null)\n {\n return null;\n }\n\n#if UNITY_EDITOR\n if (reader.TokenType == JsonToken.String)\n {\n // Assume it's an asset path\n string path = reader.Value.ToString();\n return UnityEditor.AssetDatabase.LoadAssetAtPath(path, objectType);\n }\n\n if (reader.TokenType == JsonToken.StartObject)\n {\n JObject jo = JObject.Load(reader);\n if (jo.TryGetValue(\"instanceID\", out JToken idToken) && idToken.Type == JTokenType.Integer)\n {\n int instanceId = idToken.ToObject();\n UnityEngine.Object obj = UnityEditor.EditorUtility.InstanceIDToObject(instanceId);\n if (obj != null && objectType.IsAssignableFrom(obj.GetType()))\n {\n return obj;\n }\n }\n // Could potentially try finding by name as a fallback if ID lookup fails/isn't present\n // but that's less reliable.\n }\n#else\n // Runtime deserialization is tricky without AssetDatabase/EditorUtility\n // Maybe log a warning and return null or existingValue?\n Debug.LogWarning(\"UnityEngineObjectConverter cannot deserialize complex objects in non-Editor mode.\");\n // Skip the token to avoid breaking the reader\n if (reader.TokenType == JsonToken.StartObject) JObject.Load(reader);\n else if (reader.TokenType == JsonToken.String) reader.ReadAsString(); \n // Return null or existing value, depending on desired behavior\n return existingValue; \n#endif\n\n throw new JsonSerializationException($\"Unexpected token type '{reader.TokenType}' when deserializing UnityEngine.Object\");\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Windows/VSCodeManualSetupWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class VSCodeManualSetupWindow : ManualConfigEditorWindow\n {\n public static new void ShowWindow(string configPath, string configJson)\n {\n var window = GetWindow(\"VSCode GitHub Copilot Setup\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.minSize = new Vector2(550, 500);\n \n // Create a McpClient for VSCode\n window.mcpClient = new McpClient\n {\n name = \"VSCode GitHub Copilot\",\n mcpType = McpTypes.VSCode\n };\n \n window.Show();\n }\n\n protected override void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n \"VSCode GitHub Copilot MCP Setup\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"Setting up GitHub Copilot in VSCode with Unity MCP\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Prerequisites\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have VSCode installed\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have GitHub Copilot extension installed in VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have a valid GitHub Copilot subscription\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"2. Steps to Configure\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"a) Open VSCode Settings (File > Preferences > Settings)\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"b) Click on the 'Open Settings (JSON)' button in the top right\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"c) Add the MCP configuration shown below to your settings.json file\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"d) Save the file and restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"3. VSCode settings.json location:\",\n EditorStyles.boldLabel\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n else \n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n\n // Store the path in the base class config path\n if (string.IsNullOrEmpty(configPath))\n {\n configPath = displayPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"4. Add this configuration to your settings.json:\",\n EditorStyles.boldLabel\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"5. After configuration:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• GitHub Copilot will now be able to interact with your Unity project through the MCP protocol\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Remember to have the Unity MCP Bridge running in Unity Editor\",\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected override void Update()\n {\n // Call the base implementation which handles the copy feedback timer\n base.Update();\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Response.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Provides static methods for creating standardized success and error response objects.\n /// Ensures consistent JSON structure for communication back to the Python server.\n /// \n public static class Response\n {\n /// \n /// Creates a standardized success response object.\n /// \n /// A message describing the successful operation.\n /// Optional additional data to include in the response.\n /// An object representing the success response.\n public static object Success(string message, object data = null)\n {\n if (data != null)\n {\n return new\n {\n success = true,\n message = message,\n data = data,\n };\n }\n else\n {\n return new { success = true, message = message };\n }\n }\n\n /// \n /// Creates a standardized error response object.\n /// \n /// A message describing the error.\n /// Optional additional data (e.g., error details) to include.\n /// An object representing the error response.\n public static object Error(string errorMessage, object data = null)\n {\n if (data != null)\n {\n // Note: The key is \"error\" for error messages, not \"message\"\n return new\n {\n success = false,\n error = errorMessage,\n data = data,\n };\n }\n else\n {\n return new { success = false, error = errorMessage };\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Windows/ManualConfigEditorWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n // Editor window to display manual configuration instructions\n public class ManualConfigEditorWindow : EditorWindow\n {\n protected string configPath;\n protected string configJson;\n protected Vector2 scrollPos;\n protected bool pathCopied = false;\n protected bool jsonCopied = false;\n protected float copyFeedbackTimer = 0;\n protected McpClient mcpClient;\n\n public static void ShowWindow(string configPath, string configJson, McpClient mcpClient)\n {\n var window = GetWindow(\"Manual Configuration\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.mcpClient = mcpClient;\n window.minSize = new Vector2(500, 400);\n window.Show();\n }\n\n protected virtual void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n mcpClient.name + \" Manual Configuration\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"The automatic configuration failed. Please follow these steps:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Open \" + mcpClient.name + \" config file by either:\",\n instructionStyle\n );\n if (mcpClient.mcpType == McpTypes.ClaudeDesktop)\n {\n EditorGUILayout.LabelField(\n \" a) Going to Settings > Developer > Edit Config\",\n instructionStyle\n );\n }\n else if (mcpClient.mcpType == McpTypes.Cursor)\n {\n EditorGUILayout.LabelField(\n \" a) Going to File > Preferences > Cursor Settings > MCP > Add new global MCP server\",\n instructionStyle\n );\n }\n EditorGUILayout.LabelField(\" OR\", instructionStyle);\n EditorGUILayout.LabelField(\n \" b) Opening the configuration file at:\",\n instructionStyle\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n displayPath = mcpClient.linuxConfigPath;\n }\n else\n {\n displayPath = configPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"2. Paste the following JSON configuration:\",\n instructionStyle\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"3. Save the file and restart \" + mcpClient.name,\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected virtual void Update()\n {\n // Handle the feedback message timer\n if (copyFeedbackTimer > 0)\n {\n copyFeedbackTimer -= Time.deltaTime;\n if (copyFeedbackTimer <= 0)\n {\n pathCopied = false;\n jsonCopied = false;\n Repaint();\n }\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpClient.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public class McpClient\n {\n public string name;\n public string windowsConfigPath;\n public string linuxConfigPath;\n public McpTypes mcpType;\n public string configStatus;\n public McpStatus status = McpStatus.NotConfigured;\n\n // Helper method to convert the enum to a display string\n public string GetStatusDisplayString()\n {\n return status switch\n {\n McpStatus.NotConfigured => \"Not Configured\",\n McpStatus.Configured => \"Configured\",\n McpStatus.Running => \"Running\",\n McpStatus.Connected => \"Connected\",\n McpStatus.IncorrectPath => \"Incorrect Path\",\n McpStatus.CommunicationError => \"Communication Error\",\n McpStatus.NoResponse => \"No Response\",\n McpStatus.UnsupportedOS => \"Unsupported OS\",\n McpStatus.MissingConfig => \"Missing UnityMCP Config\",\n McpStatus.Error => configStatus.StartsWith(\"Error:\") ? configStatus : \"Error\",\n _ => \"Unknown\",\n };\n }\n\n // Helper method to set both status enum and string for backward compatibility\n public void SetStatus(McpStatus newStatus, string errorDetails = null)\n {\n status = newStatus;\n\n if (newStatus == McpStatus.Error && !string.IsNullOrEmpty(errorDetails))\n {\n configStatus = $\"Error: {errorDetails}\";\n }\n else\n {\n configStatus = GetStatusDisplayString();\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Vector3Helper.cs", "using Newtonsoft.Json.Linq;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Helper class for Vector3 operations\n /// \n public static class Vector3Helper\n {\n /// \n /// Parses a JArray into a Vector3\n /// \n /// The array containing x, y, z coordinates\n /// A Vector3 with the parsed coordinates\n /// Thrown when array is invalid\n public static Vector3 ParseVector3(JArray array)\n {\n if (array == null || array.Count != 3)\n throw new System.Exception(\"Vector3 must be an array of 3 floats [x, y, z].\");\n return new Vector3((float)array[0], (float)array[1], (float)array[2]);\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Data/McpClients.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class McpClients\n {\n public List clients = new()\n {\n new()\n {\n name = \"Claude Desktop\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n mcpType = McpTypes.ClaudeDesktop,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"Cursor\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n mcpType = McpTypes.Cursor,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"VSCode GitHub Copilot\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n mcpType = McpTypes.VSCode,\n configStatus = \"Not Configured\",\n },\n };\n\n // Initialize status enums after construction\n public McpClients()\n {\n foreach (var client in clients)\n {\n if (client.configStatus == \"Not Configured\")\n {\n client.status = McpStatus.NotConfigured;\n }\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/Command.cs", "using Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n /// \n /// Represents a command received from the MCP client\n /// \n public class Command\n {\n /// \n /// The type of command to execute\n /// \n public string type { get; set; }\n\n /// \n /// The parameters for the command\n /// \n public JObject @params { get; set; }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpStatus.cs", "namespace UnityMcpBridge.Editor.Models\n{\n // Enum representing the various status states for MCP clients\n public enum McpStatus\n {\n NotConfigured, // Not set up yet\n Configured, // Successfully configured\n Running, // Service is running\n Connected, // Successfully connected\n IncorrectPath, // Configuration has incorrect paths\n CommunicationError, // Connected but communication issues\n NoResponse, // Connected but not responding\n MissingConfig, // Config file exists but missing required elements\n UnsupportedOS, // OS is not supported\n Error, // General error state\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Data/DefaultServerConfig.cs", "using UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class DefaultServerConfig : ServerConfig\n {\n public new string unityHost = \"localhost\";\n public new int unityPort = 6400;\n public new int mcpPort = 6500;\n public new float connectionTimeout = 15.0f;\n public new int bufferSize = 32768;\n public new string logLevel = \"INFO\";\n public new string logFormat = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\";\n public new int maxRetries = 3;\n public new float retryDelay = 1.0f;\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/ServerConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class ServerConfig\n {\n [JsonProperty(\"unity_host\")]\n public string unityHost = \"localhost\";\n\n [JsonProperty(\"unity_port\")]\n public int unityPort;\n\n [JsonProperty(\"mcp_port\")]\n public int mcpPort;\n\n [JsonProperty(\"connection_timeout\")]\n public float connectionTimeout;\n\n [JsonProperty(\"buffer_size\")]\n public int bufferSize;\n\n [JsonProperty(\"log_level\")]\n public string logLevel;\n\n [JsonProperty(\"log_format\")]\n public string logFormat;\n\n [JsonProperty(\"max_retries\")]\n public int maxRetries;\n\n [JsonProperty(\"retry_delay\")]\n public float retryDelay;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServer.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServer\n {\n [JsonProperty(\"command\")]\n public string command;\n\n [JsonProperty(\"args\")]\n public string[] args;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfig\n {\n [JsonProperty(\"mcpServers\")]\n public McpConfigServers mcpServers;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServers.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServers\n {\n [JsonProperty(\"unityMCP\")]\n public McpConfigServer unityMCP;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpTypes.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public enum McpTypes\n {\n ClaudeDesktop,\n Cursor,\n VSCode,\n }\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-20 19:14:42", "created_task_model": "DeepSeek-R1", "function_skeleton": "private static object ExecuteItem (JObject @params) {}", "code_description": "This code segment functions to: Validate input parameters against a restricted list and schedule deferred execution of a specified command while handling potential errors during operation setup."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n private static object ExecuteItem(JObject @params)\n {\n string menuPath = @params[\"menuPath\"]?.ToString();\n \n if (string.IsNullOrWhiteSpace(menuPath))\n {\n return Response.Error(\"Missing required 'menuPath' parameter\");\n }\n\n if (_menuPathBlacklist.Contains(menuPath))\n {\n return Response.Error($\"Menu item '{menuPath}' is blacklisted for safety reasons\");\n }\n\n if (!MenuItemExists(menuPath))\n {\n return Response.Error($\"Menu item '{menuPath}' does not exist\");\n }\n\n EditorApplication.ExecuteMenuItem(menuPath);\n Debug.Log($\"[ExecuteMenuItem] Successfully executed menu item: {menuPath}\");\n return Response.Success($\"Executed menu item: {menuPath}\", menuPath);\n\n bool MenuItemExists(string path) => Menu.GetMenuItem(path) != null;\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-15-04"}, "editdistance_info": {"edit_distance": 31.9749, "calculate_time": "2025-08-20 19:15:04", "true_code_clean": "private static object ExecuteItem(JObject @params)\n {\n string menuPath = @params[\"menu_path\"]?.ToString() ?? @params[\"menuPath\"]?.ToString();\n if (string.IsNullOrWhiteSpace(menuPath))\n {\n return Response.Error(\"Required parameter 'menu_path' or 'menuPath' is missing or empty.\");\n }\n if (_menuPathBlacklist.Contains(menuPath))\n {\n return Response.Error(\n $\"Execution of menu item '{menuPath}' is blocked for safety reasons.\"\n );\n }\n try\n {\n EditorApplication.delayCall += () =>\n {\n try\n {\n bool executed = EditorApplication.ExecuteMenuItem(menuPath);\n if (!executed)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to find or execute menu item via delayCall: '{menuPath}'. It might be invalid, disabled, or context-dependent.\"\n );\n }\n }\n catch (Exception delayEx)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Exception during delayed execution of '{menuPath}': {delayEx}\"\n );\n }\n };\n return Response.Success(\n $\"Attempted to execute menu item: '{menuPath}'. Check Unity logs for confirmation or errors.\"\n );\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to setup execution for '{menuPath}': {e}\"\n );\n return Response.Error(\n $\"Error setting up execution for menu item '{menuPath}': {e.Message}\"\n );\n }\n }", "predict_code_clean": "private static object ExecuteItem(JObject @params)\n {\n string menuPath = @params[\"menuPath\"]?.ToString();\n if (string.IsNullOrWhiteSpace(menuPath))\n {\n return Response.Error(\"Missing required 'menuPath' parameter\");\n }\n if (_menuPathBlacklist.Contains(menuPath))\n {\n return Response.Error($\"Menu item '{menuPath}' is blacklisted for safety reasons\");\n }\n if (!MenuItemExists(menuPath))\n {\n return Response.Error($\"Menu item '{menuPath}' does not exist\");\n }\n EditorApplication.ExecuteMenuItem(menuPath);\n Debug.Log($\"[ExecuteMenuItem] Successfully executed menu item: {menuPath}\");\n return Response.Success($\"Executed menu item: {menuPath}\", menuPath);\n bool MenuItemExists(string path) => Menu.GetMenuItem(path) != null;\n }"}} {"repo_name": "unity-mcp", "file_name": "/unity-mcp/UnityMcpBridge/Editor/Windows/ManualConfigEditorWindow.cs", "inference_info": {"prefix_code": "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n // Editor window to display manual configuration instructions\n public class ManualConfigEditorWindow : EditorWindow\n {\n protected string configPath;\n protected string configJson;\n protected Vector2 scrollPos;\n protected bool pathCopied = false;\n protected bool jsonCopied = false;\n protected float copyFeedbackTimer = 0;\n protected McpClient mcpClient;\n\n public static void ShowWindow(string configPath, string configJson, McpClient mcpClient)\n {\n var window = GetWindow(\"Manual Configuration\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.mcpClient = mcpClient;\n window.minSize = new Vector2(500, 400);\n window.Show();\n }\n\n ", "suffix_code": "\n\n protected virtual void Update()\n {\n // Handle the feedback message timer\n if (copyFeedbackTimer > 0)\n {\n copyFeedbackTimer -= Time.deltaTime;\n if (copyFeedbackTimer <= 0)\n {\n pathCopied = false;\n jsonCopied = false;\n Repaint();\n }\n }\n }\n }\n}\n", "middle_code": "protected virtual void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n mcpClient.name + \" Manual Configuration\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"The automatic configuration failed. Please follow these steps:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n EditorGUILayout.LabelField(\n \"1. Open \" + mcpClient.name + \" config file by either:\",\n instructionStyle\n );\n if (mcpClient.mcpType == McpTypes.ClaudeDesktop)\n {\n EditorGUILayout.LabelField(\n \" a) Going to Settings > Developer > Edit Config\",\n instructionStyle\n );\n }\n else if (mcpClient.mcpType == McpTypes.Cursor)\n {\n EditorGUILayout.LabelField(\n \" a) Going to File > Preferences > Cursor Settings > MCP > Add new global MCP server\",\n instructionStyle\n );\n }\n EditorGUILayout.LabelField(\" OR\", instructionStyle);\n EditorGUILayout.LabelField(\n \" b) Opening the configuration file at:\",\n instructionStyle\n );\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n displayPath = mcpClient.linuxConfigPath;\n }\n else\n {\n displayPath = configPath;\n }\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"2. Paste the following JSON configuration:\",\n instructionStyle\n );\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); \n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"3. Save the file and restart \" + mcpClient.name,\n instructionStyle\n );\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndScrollView();\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/unity-mcp/UnityMcpBridge/Editor/Windows/VSCodeManualSetupWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class VSCodeManualSetupWindow : ManualConfigEditorWindow\n {\n public static new void ShowWindow(string configPath, string configJson)\n {\n var window = GetWindow(\"VSCode GitHub Copilot Setup\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.minSize = new Vector2(550, 500);\n \n // Create a McpClient for VSCode\n window.mcpClient = new McpClient\n {\n name = \"VSCode GitHub Copilot\",\n mcpType = McpTypes.VSCode\n };\n \n window.Show();\n }\n\n protected override void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n \"VSCode GitHub Copilot MCP Setup\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"Setting up GitHub Copilot in VSCode with Unity MCP\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Prerequisites\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have VSCode installed\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have GitHub Copilot extension installed in VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have a valid GitHub Copilot subscription\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"2. Steps to Configure\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"a) Open VSCode Settings (File > Preferences > Settings)\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"b) Click on the 'Open Settings (JSON)' button in the top right\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"c) Add the MCP configuration shown below to your settings.json file\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"d) Save the file and restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"3. VSCode settings.json location:\",\n EditorStyles.boldLabel\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n else \n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n\n // Store the path in the base class config path\n if (string.IsNullOrEmpty(configPath))\n {\n configPath = displayPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"4. Add this configuration to your settings.json:\",\n EditorStyles.boldLabel\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"5. After configuration:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• GitHub Copilot will now be able to interact with your Unity project through the MCP protocol\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Remember to have the Unity MCP Bridge running in Unity Editor\",\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected override void Update()\n {\n // Call the base implementation which handles the copy feedback timer\n base.Update();\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Windows/UnityMcpEditorWindow.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing Newtonsoft.Json;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Data;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class UnityMcpEditorWindow : EditorWindow\n {\n private bool isUnityBridgeRunning = false;\n private Vector2 scrollPosition;\n private string pythonServerInstallationStatus = \"Not Installed\";\n private Color pythonServerInstallationStatusColor = Color.red;\n private const int unityPort = 6400; // Hardcoded Unity port\n private const int mcpPort = 6500; // Hardcoded MCP port\n private readonly McpClients mcpClients = new();\n \n // Script validation settings\n private int validationLevelIndex = 1; // Default to Standard\n private readonly string[] validationLevelOptions = new string[]\n {\n \"Basic - Only syntax checks\",\n \"Standard - Syntax + Unity practices\", \n \"Comprehensive - All checks + semantic analysis\",\n \"Strict - Full semantic validation (requires Roslyn)\"\n };\n \n // UI state\n private int selectedClientIndex = 0;\n\n [MenuItem(\"Window/Unity MCP\")]\n public static void ShowWindow()\n {\n GetWindow(\"MCP Editor\");\n }\n\n private void OnEnable()\n {\n UpdatePythonServerInstallationStatus();\n\n isUnityBridgeRunning = UnityMcpBridge.IsRunning;\n foreach (McpClient mcpClient in mcpClients.clients)\n {\n CheckMcpConfiguration(mcpClient);\n }\n \n // Load validation level setting\n LoadValidationLevelSetting();\n }\n\n private Color GetStatusColor(McpStatus status)\n {\n // Return appropriate color based on the status enum\n return status switch\n {\n McpStatus.Configured => Color.green,\n McpStatus.Running => Color.green,\n McpStatus.Connected => Color.green,\n McpStatus.IncorrectPath => Color.yellow,\n McpStatus.CommunicationError => Color.yellow,\n McpStatus.NoResponse => Color.yellow,\n _ => Color.red, // Default to red for error states or not configured\n };\n }\n\n private void UpdatePythonServerInstallationStatus()\n {\n string serverPath = ServerInstaller.GetServerPath();\n\n if (File.Exists(Path.Combine(serverPath, \"server.py\")))\n {\n string installedVersion = ServerInstaller.GetInstalledVersion();\n string latestVersion = ServerInstaller.GetLatestVersion();\n\n if (ServerInstaller.IsNewerVersion(latestVersion, installedVersion))\n {\n pythonServerInstallationStatus = \"Newer Version Available\";\n pythonServerInstallationStatusColor = Color.yellow;\n }\n else\n {\n pythonServerInstallationStatus = \"Up to Date\";\n pythonServerInstallationStatusColor = Color.green;\n }\n }\n else\n {\n pythonServerInstallationStatus = \"Not Installed\";\n pythonServerInstallationStatusColor = Color.red;\n }\n }\n\n\n private void DrawStatusDot(Rect statusRect, Color statusColor, float size = 12)\n {\n float offsetX = (statusRect.width - size) / 2;\n float offsetY = (statusRect.height - size) / 2;\n Rect dotRect = new(statusRect.x + offsetX, statusRect.y + offsetY, size, size);\n Vector3 center = new(\n dotRect.x + (dotRect.width / 2),\n dotRect.y + (dotRect.height / 2),\n 0\n );\n float radius = size / 2;\n\n // Draw the main dot\n Handles.color = statusColor;\n Handles.DrawSolidDisc(center, Vector3.forward, radius);\n\n // Draw the border\n Color borderColor = new(\n statusColor.r * 0.7f,\n statusColor.g * 0.7f,\n statusColor.b * 0.7f\n );\n Handles.color = borderColor;\n Handles.DrawWireDisc(center, Vector3.forward, radius);\n }\n\n private void OnGUI()\n {\n scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);\n\n // Header\n DrawHeader();\n \n // Main sections in a more compact layout\n EditorGUILayout.BeginHorizontal();\n \n // Left column - Status and Bridge\n EditorGUILayout.BeginVertical(GUILayout.Width(position.width * 0.5f));\n DrawServerStatusSection();\n EditorGUILayout.Space(5);\n DrawBridgeSection();\n EditorGUILayout.EndVertical();\n \n // Right column - Validation Settings\n EditorGUILayout.BeginVertical();\n DrawValidationSection();\n EditorGUILayout.EndVertical();\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Unified MCP Client Configuration\n DrawUnifiedClientConfiguration();\n\n EditorGUILayout.EndScrollView();\n }\n\n private void DrawHeader()\n {\n EditorGUILayout.Space(15);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 40);\n EditorGUI.DrawRect(titleRect, new Color(0.2f, 0.2f, 0.2f, 0.1f));\n \n GUIStyle titleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 16,\n alignment = TextAnchor.MiddleLeft\n };\n \n GUI.Label(\n new Rect(titleRect.x + 15, titleRect.y + 8, titleRect.width - 30, titleRect.height),\n \"Unity MCP Editor\",\n titleStyle\n );\n EditorGUILayout.Space(15);\n }\n\n private void DrawServerStatusSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Server Status\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(statusRect, pythonServerInstallationStatusColor, 16);\n \n GUIStyle statusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(pythonServerInstallationStatus, statusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(5);\n GUIStyle portStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 11\n };\n EditorGUILayout.LabelField($\"Ports: Unity {unityPort}, MCP {mcpPort}\", portStyle);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawBridgeSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Unity Bridge\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUILayout.BeginHorizontal();\n Color bridgeColor = isUnityBridgeRunning ? Color.green : Color.red;\n Rect bridgeStatusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(bridgeStatusRect, bridgeColor, 16);\n \n GUIStyle bridgeStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(isUnityBridgeRunning ? \"Running\" : \"Stopped\", bridgeStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(8);\n if (GUILayout.Button(isUnityBridgeRunning ? \"Stop Bridge\" : \"Start Bridge\", GUILayout.Height(32)))\n {\n ToggleUnityBridge();\n }\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawValidationSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Script Validation\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUI.BeginChangeCheck();\n validationLevelIndex = EditorGUILayout.Popup(\"Validation Level\", validationLevelIndex, validationLevelOptions, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n SaveValidationLevelSetting();\n }\n \n EditorGUILayout.Space(8);\n string description = GetValidationLevelDescription(validationLevelIndex);\n EditorGUILayout.HelpBox(description, MessageType.Info);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawUnifiedClientConfiguration()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"MCP Client Configuration\", sectionTitleStyle);\n EditorGUILayout.Space(10);\n \n // Client selector\n string[] clientNames = mcpClients.clients.Select(c => c.name).ToArray();\n EditorGUI.BeginChangeCheck();\n selectedClientIndex = EditorGUILayout.Popup(\"Select Client\", selectedClientIndex, clientNames, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n selectedClientIndex = Mathf.Clamp(selectedClientIndex, 0, mcpClients.clients.Count - 1);\n }\n \n EditorGUILayout.Space(10);\n \n if (mcpClients.clients.Count > 0 && selectedClientIndex < mcpClients.clients.Count)\n {\n McpClient selectedClient = mcpClients.clients[selectedClientIndex];\n DrawClientConfigurationCompact(selectedClient);\n }\n \n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawClientConfigurationCompact(McpClient mcpClient)\n {\n // Status display\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n Color statusColor = GetStatusColor(mcpClient.status);\n DrawStatusDot(statusRect, statusColor, 16);\n \n GUIStyle clientStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(mcpClient.configStatus, clientStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Action buttons in horizontal layout\n EditorGUILayout.BeginHorizontal();\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n if (GUILayout.Button(\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n else\n {\n if (GUILayout.Button($\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n \n if (GUILayout.Button(\"Manual Setup\", GUILayout.Height(32)))\n {\n string configPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)\n ? mcpClient.windowsConfigPath\n : mcpClient.linuxConfigPath;\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n string pythonDir = FindPackagePythonDirectory();\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n VSCodeManualSetupWindow.ShowWindow(configPath, manualConfigJson);\n }\n else\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n }\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(8);\n // Quick info\n GUIStyle configInfoStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 10\n };\n EditorGUILayout.LabelField($\"Config: {Path.GetFileName(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? mcpClient.windowsConfigPath : mcpClient.linuxConfigPath)}\", configInfoStyle);\n }\n\n private void ToggleUnityBridge()\n {\n if (isUnityBridgeRunning)\n {\n UnityMcpBridge.Stop();\n }\n else\n {\n UnityMcpBridge.Start();\n }\n\n isUnityBridgeRunning = !isUnityBridgeRunning;\n }\n\n private string WriteToConfig(string pythonDir, string configPath, McpClient mcpClient = null)\n {\n // Create configuration object for unityMCP\n McpConfigServer unityMCPConfig = new()\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n\n // Read existing config if it exists\n string existingJson = \"{}\";\n if (File.Exists(configPath))\n {\n try\n {\n existingJson = File.ReadAllText(configPath);\n }\n catch (Exception e)\n {\n Debug.LogWarning($\"Error reading existing config: {e.Message}.\");\n }\n }\n\n // Parse the existing JSON while preserving all properties\n dynamic existingConfig = JsonConvert.DeserializeObject(existingJson);\n existingConfig ??= new Newtonsoft.Json.Linq.JObject();\n\n // Handle different client types with a switch statement\n //Comments: Interestingly, VSCode has mcp.servers.unityMCP while others have mcpServers.unityMCP, which is why we need to prevent this\n switch (mcpClient?.mcpType)\n {\n case McpTypes.VSCode:\n // VSCode specific configuration\n // Ensure mcp object exists\n if (existingConfig.mcp == null)\n {\n existingConfig.mcp = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Ensure mcp.servers object exists\n if (existingConfig.mcp.servers == null)\n {\n existingConfig.mcp.servers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in VSCode settings\n existingConfig.mcp.servers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n\n default:\n // Standard MCP configuration (Claude Desktop, Cursor, etc.)\n // Ensure mcpServers object exists\n if (existingConfig.mcpServers == null)\n {\n existingConfig.mcpServers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in standard MCP settings\n existingConfig.mcpServers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n }\n\n // Write the merged configuration back to file\n string mergedJson = JsonConvert.SerializeObject(existingConfig, jsonSettings);\n File.WriteAllText(configPath, mergedJson);\n\n return \"Configured successfully\";\n }\n\n private void ShowManualConfigurationInstructions(string configPath, McpClient mcpClient)\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n\n // New method to show manual instructions without changing status\n private void ShowManualInstructionsWindow(string configPath, McpClient mcpClient)\n {\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n string manualConfigJson;\n \n // Create common JsonSerializerSettings\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n \n // Use switch statement to handle different client types\n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n // Create VSCode-specific configuration with proper format\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n break;\n \n default:\n // Create standard MCP configuration for other clients\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n break;\n }\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private string FindPackagePythonDirectory()\n {\n string pythonDir = ServerInstaller.GetServerPath();\n\n try\n {\n // Try to find the package using Package Manager API\n UnityEditor.PackageManager.Requests.ListRequest request =\n UnityEditor.PackageManager.Client.List();\n while (!request.IsCompleted) { } // Wait for the request to complete\n\n if (request.Status == UnityEditor.PackageManager.StatusCode.Success)\n {\n foreach (UnityEditor.PackageManager.PackageInfo package in request.Result)\n {\n if (package.name == \"com.justinpbarnett.unity-mcp\")\n {\n string packagePath = package.resolvedPath;\n string potentialPythonDir = Path.Combine(packagePath, \"Python\");\n\n if (\n Directory.Exists(potentialPythonDir)\n && File.Exists(Path.Combine(potentialPythonDir, \"server.py\"))\n )\n {\n return potentialPythonDir;\n }\n }\n }\n }\n else if (request.Error != null)\n {\n Debug.LogError(\"Failed to list packages: \" + request.Error.message);\n }\n\n // If not found via Package Manager, try manual approaches\n // First check for local installation\n string[] possibleDirs =\n {\n Path.GetFullPath(Path.Combine(Application.dataPath, \"unity-mcp\", \"Python\")),\n };\n\n foreach (string dir in possibleDirs)\n {\n if (Directory.Exists(dir) && File.Exists(Path.Combine(dir, \"server.py\")))\n {\n return dir;\n }\n }\n\n // If still not found, return the placeholder path\n Debug.LogWarning(\"Could not find Python directory, using placeholder path\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"Error finding package path: {e.Message}\");\n }\n\n return pythonDir;\n }\n\n private string ConfigureMcpClient(McpClient mcpClient)\n {\n try\n {\n // Determine the config file path based on OS\n string configPath;\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n return \"Unsupported OS\";\n }\n\n // Create directory if it doesn't exist\n Directory.CreateDirectory(Path.GetDirectoryName(configPath));\n\n // Find the server.py file location\n string pythonDir = ServerInstaller.GetServerPath();\n\n if (pythonDir == null || !File.Exists(Path.Combine(pythonDir, \"server.py\")))\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n return \"Manual Configuration Required\";\n }\n\n string result = WriteToConfig(pythonDir, configPath, mcpClient);\n\n // Update the client status after successful configuration\n if (result == \"Configured successfully\")\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n\n return result;\n }\n catch (Exception e)\n {\n // Determine the config file path based on OS for error message\n string configPath = \"\";\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n Debug.LogError(\n $\"Failed to configure {mcpClient.name}: {e.Message}\\n{e.StackTrace}\"\n );\n return $\"Failed to configure {mcpClient.name}\";\n }\n }\n\n private void ShowCursorManualConfigurationInstructions(\n string configPath,\n McpClient mcpClient\n )\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n\n // Create the manual configuration message\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private void LoadValidationLevelSetting()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n validationLevelIndex = savedLevel.ToLower() switch\n {\n \"basic\" => 0,\n \"standard\" => 1,\n \"comprehensive\" => 2,\n \"strict\" => 3,\n _ => 1 // Default to Standard\n };\n }\n\n private void SaveValidationLevelSetting()\n {\n string levelString = validationLevelIndex switch\n {\n 0 => \"basic\",\n 1 => \"standard\",\n 2 => \"comprehensive\",\n 3 => \"strict\",\n _ => \"standard\"\n };\n EditorPrefs.SetString(\"UnityMCP_ScriptValidationLevel\", levelString);\n }\n\n private string GetValidationLevelDescription(int index)\n {\n return index switch\n {\n 0 => \"Only basic syntax checks (braces, quotes, comments)\",\n 1 => \"Syntax checks + Unity best practices and warnings\",\n 2 => \"All checks + semantic analysis and performance warnings\",\n 3 => \"Full semantic validation with namespace/type resolution (requires Roslyn)\",\n _ => \"Standard validation\"\n };\n }\n\n public static string GetCurrentValidationLevel()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel;\n }\n\n private void CheckMcpConfiguration(McpClient mcpClient)\n {\n try\n {\n string configPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n mcpClient.SetStatus(McpStatus.UnsupportedOS);\n return;\n }\n\n if (!File.Exists(configPath))\n {\n mcpClient.SetStatus(McpStatus.NotConfigured);\n return;\n }\n\n string configJson = File.ReadAllText(configPath);\n string pythonDir = ServerInstaller.GetServerPath();\n \n // Use switch statement to handle different client types, extracting common logic\n string[] args = null;\n bool configExists = false;\n \n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n dynamic config = JsonConvert.DeserializeObject(configJson);\n \n if (config?.mcp?.servers?.unityMCP != null)\n {\n // Extract args from VSCode config format\n args = config.mcp.servers.unityMCP.args.ToObject();\n configExists = true;\n }\n break;\n \n default:\n // Standard MCP configuration check for Claude Desktop, Cursor, etc.\n McpConfig standardConfig = JsonConvert.DeserializeObject(configJson);\n \n if (standardConfig?.mcpServers?.unityMCP != null)\n {\n args = standardConfig.mcpServers.unityMCP.args;\n configExists = true;\n }\n break;\n }\n \n // Common logic for checking configuration status\n if (configExists)\n {\n if (pythonDir != null && \n Array.Exists(args, arg => arg.Contains(pythonDir, StringComparison.Ordinal)))\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n else\n {\n mcpClient.SetStatus(McpStatus.IncorrectPath);\n }\n }\n else\n {\n mcpClient.SetStatus(McpStatus.MissingConfig);\n }\n }\n catch (Exception e)\n {\n mcpClient.SetStatus(McpStatus.Error, e.Message);\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageAsset.cs", "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\n#if UNITY_6000_0_OR_NEWER\nusing PhysicsMaterialType = UnityEngine.PhysicsMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicsMaterialCombine; \n#else\nusing PhysicsMaterialType = UnityEngine.PhysicMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicMaterialCombine;\n#endif\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles asset management operations within the Unity project.\n /// \n public static class ManageAsset\n {\n // --- Main Handler ---\n\n // Define the list of valid actions\n private static readonly List ValidActions = new List\n {\n \"import\",\n \"create\",\n \"modify\",\n \"delete\",\n \"duplicate\",\n \"move\",\n \"rename\",\n \"search\",\n \"get_info\",\n \"create_folder\",\n \"get_components\",\n };\n\n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Check if the action is valid before switching\n if (!ValidActions.Contains(action))\n {\n string validActionsList = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsList}\"\n );\n }\n\n // Common parameters\n string path = @params[\"path\"]?.ToString();\n\n try\n {\n switch (action)\n {\n case \"import\":\n // Note: Unity typically auto-imports. This might re-import or configure import settings.\n return ReimportAsset(path, @params[\"properties\"] as JObject);\n case \"create\":\n return CreateAsset(@params);\n case \"modify\":\n return ModifyAsset(path, @params[\"properties\"] as JObject);\n case \"delete\":\n return DeleteAsset(path);\n case \"duplicate\":\n return DuplicateAsset(path, @params[\"destination\"]?.ToString());\n case \"move\": // Often same as rename if within Assets/\n case \"rename\":\n return MoveOrRenameAsset(path, @params[\"destination\"]?.ToString());\n case \"search\":\n return SearchAssets(@params);\n case \"get_info\":\n return GetAssetInfo(\n path,\n @params[\"generatePreview\"]?.ToObject() ?? false\n );\n case \"create_folder\": // Added specific action for clarity\n return CreateFolder(path);\n case \"get_components\":\n return GetComponentsFromAsset(path);\n\n default:\n // This error message is less likely to be hit now, but kept here as a fallback or for potential future modifications.\n string validActionsListDefault = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsListDefault}\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageAsset] Action '{action}' failed for path '{path}': {e}\");\n return Response.Error(\n $\"Internal error processing action '{action}' on '{path}': {e.Message}\"\n );\n }\n }\n\n // --- Action Implementations ---\n\n private static object ReimportAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for reimport.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // TODO: Apply importer properties before reimporting?\n // This is complex as it requires getting the AssetImporter, casting it,\n // applying properties via reflection or specific methods, saving, then reimporting.\n if (properties != null && properties.HasValues)\n {\n Debug.LogWarning(\n \"[ManageAsset.Reimport] Modifying importer properties before reimport is not fully implemented yet.\"\n );\n // AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n // if (importer != null) { /* Apply properties */ AssetDatabase.WriteImportSettingsIfDirty(fullPath); }\n }\n\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate);\n // AssetDatabase.Refresh(); // Usually ImportAsset handles refresh\n return Response.Success($\"Asset '{fullPath}' reimported.\", GetAssetData(fullPath));\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to reimport asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateAsset(JObject @params)\n {\n string path = @params[\"path\"]?.ToString();\n string assetType = @params[\"assetType\"]?.ToString();\n JObject properties = @params[\"properties\"] as JObject;\n\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create.\");\n if (string.IsNullOrEmpty(assetType))\n return Response.Error(\"'assetType' is required for create.\");\n\n string fullPath = SanitizeAssetPath(path);\n string directory = Path.GetDirectoryName(fullPath);\n\n // Ensure directory exists\n if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), directory)))\n {\n Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), directory));\n AssetDatabase.Refresh(); // Make sure Unity knows about the new folder\n }\n\n if (AssetExists(fullPath))\n return Response.Error($\"Asset already exists at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object newAsset = null;\n string lowerAssetType = assetType.ToLowerInvariant();\n\n // Handle common asset types\n if (lowerAssetType == \"folder\")\n {\n return CreateFolder(path); // Use dedicated method\n }\n else if (lowerAssetType == \"material\")\n {\n Material mat = new Material(Shader.Find(\"Standard\")); // Default shader\n // TODO: Apply properties from JObject (e.g., shader name, color, texture assignments)\n if (properties != null)\n ApplyMaterialProperties(mat, properties);\n AssetDatabase.CreateAsset(mat, fullPath);\n newAsset = mat;\n }\n else if (lowerAssetType == \"physicsmaterial\")\n {\n PhysicsMaterialType pmat = new PhysicsMaterialType();\n if (properties != null)\n ApplyPhysicsMaterialProperties(pmat, properties);\n AssetDatabase.CreateAsset(pmat, fullPath);\n newAsset = pmat;\n }\n else if (lowerAssetType == \"scriptableobject\")\n {\n string scriptClassName = properties?[\"scriptClass\"]?.ToString();\n if (string.IsNullOrEmpty(scriptClassName))\n return Response.Error(\n \"'scriptClass' property required when creating ScriptableObject asset.\"\n );\n\n Type scriptType = FindType(scriptClassName);\n if (\n scriptType == null\n || !typeof(ScriptableObject).IsAssignableFrom(scriptType)\n )\n {\n return Response.Error(\n $\"Script class '{scriptClassName}' not found or does not inherit from ScriptableObject.\"\n );\n }\n\n ScriptableObject so = ScriptableObject.CreateInstance(scriptType);\n // TODO: Apply properties from JObject to the ScriptableObject instance?\n AssetDatabase.CreateAsset(so, fullPath);\n newAsset = so;\n }\n else if (lowerAssetType == \"prefab\")\n {\n // Creating prefabs usually involves saving an existing GameObject hierarchy.\n // A common pattern is to create an empty GameObject, configure it, and then save it.\n return Response.Error(\n \"Creating prefabs programmatically usually requires a source GameObject. Use manage_gameobject to create/configure, then save as prefab via a separate mechanism or future enhancement.\"\n );\n // Example (conceptual):\n // GameObject source = GameObject.Find(properties[\"sourceGameObject\"].ToString());\n // if(source != null) PrefabUtility.SaveAsPrefabAsset(source, fullPath);\n }\n // TODO: Add more asset types (Animation Controller, Scene, etc.)\n else\n {\n // Generic creation attempt (might fail or create empty files)\n // For some types, just creating the file might be enough if Unity imports it.\n // File.Create(Path.Combine(Directory.GetCurrentDirectory(), fullPath)).Close();\n // AssetDatabase.ImportAsset(fullPath); // Let Unity try to import it\n // newAsset = AssetDatabase.LoadAssetAtPath(fullPath);\n return Response.Error(\n $\"Creation for asset type '{assetType}' is not explicitly supported yet. Supported: Folder, Material, ScriptableObject.\"\n );\n }\n\n if (\n newAsset == null\n && !Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), fullPath))\n ) // Check if it wasn't a folder and asset wasn't created\n {\n return Response.Error(\n $\"Failed to create asset '{assetType}' at '{fullPath}'. See logs for details.\"\n );\n }\n\n AssetDatabase.SaveAssets();\n // AssetDatabase.Refresh(); // CreateAsset often handles refresh\n return Response.Success(\n $\"Asset '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create asset at '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateFolder(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create_folder.\");\n string fullPath = SanitizeAssetPath(path);\n string parentDir = Path.GetDirectoryName(fullPath);\n string folderName = Path.GetFileName(fullPath);\n\n if (AssetExists(fullPath))\n {\n // Check if it's actually a folder already\n if (AssetDatabase.IsValidFolder(fullPath))\n {\n return Response.Success(\n $\"Folder already exists at path: {fullPath}\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n return Response.Error(\n $\"An asset (not a folder) already exists at path: {fullPath}\"\n );\n }\n }\n\n try\n {\n // Ensure parent exists\n if (!string.IsNullOrEmpty(parentDir) && !AssetDatabase.IsValidFolder(parentDir))\n {\n // Recursively create parent folders if needed (AssetDatabase handles this internally)\n // Or we can do it manually: Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), parentDir)); AssetDatabase.Refresh();\n }\n\n string guid = AssetDatabase.CreateFolder(parentDir, folderName);\n if (string.IsNullOrEmpty(guid))\n {\n return Response.Error(\n $\"Failed to create folder '{fullPath}'. Check logs and permissions.\"\n );\n }\n\n // AssetDatabase.Refresh(); // CreateFolder usually handles refresh\n return Response.Success(\n $\"Folder '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create folder '{fullPath}': {e.Message}\");\n }\n }\n\n private static object ModifyAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for modify.\");\n if (properties == null || !properties.HasValues)\n return Response.Error(\"'properties' are required for modify.\");\n\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n bool modified = false; // Flag to track if any changes were made\n\n // --- NEW: Handle GameObject / Prefab Component Modification ---\n if (asset is GameObject gameObject)\n {\n // Iterate through the properties JSON: keys are component names, values are properties objects for that component\n foreach (var prop in properties.Properties())\n {\n string componentName = prop.Name; // e.g., \"Collectible\"\n // Check if the value associated with the component name is actually an object containing properties\n if (\n prop.Value is JObject componentProperties\n && componentProperties.HasValues\n ) // e.g., {\"bobSpeed\": 2.0}\n {\n // Find the component on the GameObject using the name from the JSON key\n // Using GetComponent(string) is convenient but might require exact type name or be ambiguous.\n // Consider using FindType helper if needed for more complex scenarios.\n Component targetComponent = gameObject.GetComponent(componentName);\n\n if (targetComponent != null)\n {\n // Apply the nested properties (e.g., bobSpeed) to the found component instance\n // Use |= to ensure 'modified' becomes true if any component is successfully modified\n modified |= ApplyObjectProperties(\n targetComponent,\n componentProperties\n );\n }\n else\n {\n // Log a warning if a specified component couldn't be found\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Component '{componentName}' not found on GameObject '{gameObject.name}' in asset '{fullPath}'. Skipping modification for this component.\"\n );\n }\n }\n else\n {\n // Log a warning if the structure isn't {\"ComponentName\": {\"prop\": value}}\n // We could potentially try to apply this property directly to the GameObject here if needed,\n // but the primary goal is component modification.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Property '{prop.Name}' for GameObject modification should have a JSON object value containing component properties. Value was: {prop.Value.Type}. Skipping.\"\n );\n }\n }\n // Note: 'modified' is now true if ANY component property was successfully changed.\n }\n // --- End NEW ---\n\n // --- Existing logic for other asset types (now as else-if) ---\n // Example: Modifying a Material\n else if (asset is Material material)\n {\n // Apply properties directly to the material. If this modifies, it sets modified=true.\n // Use |= in case the asset was already marked modified by previous logic (though unlikely here)\n modified |= ApplyMaterialProperties(material, properties);\n }\n // Example: Modifying a ScriptableObject\n else if (asset is ScriptableObject so)\n {\n // Apply properties directly to the ScriptableObject.\n modified |= ApplyObjectProperties(so, properties); // General helper\n }\n // Example: Modifying TextureImporter settings\n else if (asset is Texture)\n {\n AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n if (importer is TextureImporter textureImporter)\n {\n bool importerModified = ApplyObjectProperties(textureImporter, properties);\n if (importerModified)\n {\n // Importer settings need saving and reimporting\n AssetDatabase.WriteImportSettingsIfDirty(fullPath);\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate); // Reimport to apply changes\n modified = true; // Mark overall operation as modified\n }\n }\n else\n {\n Debug.LogWarning($\"Could not get TextureImporter for {fullPath}.\");\n }\n }\n // TODO: Add modification logic for other common asset types (Models, AudioClips importers, etc.)\n else // Fallback for other asset types OR direct properties on non-GameObject assets\n {\n // This block handles non-GameObject/Material/ScriptableObject/Texture assets.\n // Attempts to apply properties directly to the asset itself.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Asset type '{asset.GetType().Name}' at '{fullPath}' is not explicitly handled for component modification. Attempting generic property setting on the asset itself.\"\n );\n modified |= ApplyObjectProperties(asset, properties);\n }\n // --- End Existing Logic ---\n\n // Check if any modification happened (either component or direct asset modification)\n if (modified)\n {\n // Mark the asset as dirty (important for prefabs/SOs) so Unity knows to save it.\n EditorUtility.SetDirty(asset);\n // Save all modified assets to disk.\n AssetDatabase.SaveAssets();\n // Refresh might be needed in some edge cases, but SaveAssets usually covers it.\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{fullPath}' modified successfully.\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n // If no changes were made (e.g., component not found, property names incorrect, value unchanged), return a success message indicating nothing changed.\n return Response.Success(\n $\"No applicable or modifiable properties found for asset '{fullPath}'. Check component names, property names, and values.\",\n GetAssetData(fullPath)\n );\n // Previous message: return Response.Success($\"No applicable properties found to modify for asset '{fullPath}'.\", GetAssetData(fullPath));\n }\n }\n catch (Exception e)\n {\n // Log the detailed error internally\n Debug.LogError($\"[ManageAsset] Action 'modify' failed for path '{path}': {e}\");\n // Return a user-friendly error message\n return Response.Error($\"Failed to modify asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DeleteAsset(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for delete.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n bool success = AssetDatabase.DeleteAsset(fullPath);\n if (success)\n {\n // AssetDatabase.Refresh(); // DeleteAsset usually handles refresh\n return Response.Success($\"Asset '{fullPath}' deleted successfully.\");\n }\n else\n {\n // This might happen if the file couldn't be deleted (e.g., locked)\n return Response.Error(\n $\"Failed to delete asset '{fullPath}'. Check logs or if the file is locked.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DuplicateAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for duplicate.\");\n\n string sourcePath = SanitizeAssetPath(path);\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n\n string destPath;\n if (string.IsNullOrEmpty(destinationPath))\n {\n // Generate a unique path if destination is not provided\n destPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath);\n }\n else\n {\n destPath = SanitizeAssetPath(destinationPath);\n if (AssetExists(destPath))\n return Response.Error($\"Asset already exists at destination path: {destPath}\");\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n }\n\n try\n {\n bool success = AssetDatabase.CopyAsset(sourcePath, destPath);\n if (success)\n {\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{sourcePath}' duplicated to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n return Response.Error(\n $\"Failed to duplicate asset from '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error duplicating asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object MoveOrRenameAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for move/rename.\");\n if (string.IsNullOrEmpty(destinationPath))\n return Response.Error(\"'destination' path is required for move/rename.\");\n\n string sourcePath = SanitizeAssetPath(path);\n string destPath = SanitizeAssetPath(destinationPath);\n\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n if (AssetExists(destPath))\n return Response.Error(\n $\"An asset already exists at the destination path: {destPath}\"\n );\n\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n\n try\n {\n // Validate will return an error string if failed, null if successful\n string error = AssetDatabase.ValidateMoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(error))\n {\n return Response.Error(\n $\"Failed to move/rename asset from '{sourcePath}' to '{destPath}': {error}\"\n );\n }\n\n string guid = AssetDatabase.MoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(guid)) // MoveAsset returns the new GUID on success\n {\n // AssetDatabase.Refresh(); // MoveAsset usually handles refresh\n return Response.Success(\n $\"Asset moved/renamed from '{sourcePath}' to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n // This case might not be reachable if ValidateMoveAsset passes, but good to have\n return Response.Error(\n $\"MoveAsset call failed unexpectedly for '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error moving/renaming asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object SearchAssets(JObject @params)\n {\n string searchPattern = @params[\"searchPattern\"]?.ToString();\n string filterType = @params[\"filterType\"]?.ToString();\n string pathScope = @params[\"path\"]?.ToString(); // Use path as folder scope\n string filterDateAfterStr = @params[\"filterDateAfter\"]?.ToString();\n int pageSize = @params[\"pageSize\"]?.ToObject() ?? 50; // Default page size\n int pageNumber = @params[\"pageNumber\"]?.ToObject() ?? 1; // Default page number (1-based)\n bool generatePreview = @params[\"generatePreview\"]?.ToObject() ?? false;\n\n List searchFilters = new List();\n if (!string.IsNullOrEmpty(searchPattern))\n searchFilters.Add(searchPattern);\n if (!string.IsNullOrEmpty(filterType))\n searchFilters.Add($\"t:{filterType}\");\n\n string[] folderScope = null;\n if (!string.IsNullOrEmpty(pathScope))\n {\n folderScope = new string[] { SanitizeAssetPath(pathScope) };\n if (!AssetDatabase.IsValidFolder(folderScope[0]))\n {\n // Maybe the user provided a file path instead of a folder?\n // We could search in the containing folder, or return an error.\n Debug.LogWarning(\n $\"Search path '{folderScope[0]}' is not a valid folder. Searching entire project.\"\n );\n folderScope = null; // Search everywhere if path isn't a folder\n }\n }\n\n DateTime? filterDateAfter = null;\n if (!string.IsNullOrEmpty(filterDateAfterStr))\n {\n if (\n DateTime.TryParse(\n filterDateAfterStr,\n CultureInfo.InvariantCulture,\n DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,\n out DateTime parsedDate\n )\n )\n {\n filterDateAfter = parsedDate;\n }\n else\n {\n Debug.LogWarning(\n $\"Could not parse filterDateAfter: '{filterDateAfterStr}'. Expected ISO 8601 format.\"\n );\n }\n }\n\n try\n {\n string[] guids = AssetDatabase.FindAssets(\n string.Join(\" \", searchFilters),\n folderScope\n );\n List results = new List();\n int totalFound = 0;\n\n foreach (string guid in guids)\n {\n string assetPath = AssetDatabase.GUIDToAssetPath(guid);\n if (string.IsNullOrEmpty(assetPath))\n continue;\n\n // Apply date filter if present\n if (filterDateAfter.HasValue)\n {\n DateTime lastWriteTime = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), assetPath)\n );\n if (lastWriteTime <= filterDateAfter.Value)\n {\n continue; // Skip assets older than or equal to the filter date\n }\n }\n\n totalFound++; // Count matching assets before pagination\n results.Add(GetAssetData(assetPath, generatePreview));\n }\n\n // Apply pagination\n int startIndex = (pageNumber - 1) * pageSize;\n var pagedResults = results.Skip(startIndex).Take(pageSize).ToList();\n\n return Response.Success(\n $\"Found {totalFound} asset(s). Returning page {pageNumber} ({pagedResults.Count} assets).\",\n new\n {\n totalAssets = totalFound,\n pageSize = pageSize,\n pageNumber = pageNumber,\n assets = pagedResults,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error searching assets: {e.Message}\");\n }\n }\n\n private static object GetAssetInfo(string path, bool generatePreview)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_info.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n return Response.Success(\n \"Asset info retrieved.\",\n GetAssetData(fullPath, generatePreview)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting info for asset '{fullPath}': {e.Message}\");\n }\n }\n\n /// \n /// Retrieves components attached to a GameObject asset (like a Prefab).\n /// \n /// The asset path of the GameObject or Prefab.\n /// A response object containing a list of component type names or an error.\n private static object GetComponentsFromAsset(string path)\n {\n // 1. Validate input path\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_components.\");\n\n // 2. Sanitize and check existence\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // 3. Load the asset\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n // 4. Check if it's a GameObject (Prefabs load as GameObjects)\n GameObject gameObject = asset as GameObject;\n if (gameObject == null)\n {\n // Also check if it's *directly* a Component type (less common for primary assets)\n Component componentAsset = asset as Component;\n if (componentAsset != null)\n {\n // If the asset itself *is* a component, maybe return just its info?\n // This is an edge case. Let's stick to GameObjects for now.\n return Response.Error(\n $\"Asset at '{fullPath}' is a Component ({asset.GetType().FullName}), not a GameObject. Components are typically retrieved *from* a GameObject.\"\n );\n }\n return Response.Error(\n $\"Asset at '{fullPath}' is not a GameObject (Type: {asset.GetType().FullName}). Cannot get components from this asset type.\"\n );\n }\n\n // 5. Get components\n Component[] components = gameObject.GetComponents();\n\n // 6. Format component data\n List componentList = components\n .Select(comp => new\n {\n typeName = comp.GetType().FullName,\n instanceID = comp.GetInstanceID(),\n // TODO: Add more component-specific details here if needed in the future?\n // Requires reflection or specific handling per component type.\n })\n .ToList(); // Explicit cast for clarity if needed\n\n // 7. Return success response\n return Response.Success(\n $\"Found {componentList.Count} component(s) on asset '{fullPath}'.\",\n componentList\n );\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageAsset.GetComponentsFromAsset] Error getting components for '{fullPath}': {e}\"\n );\n return Response.Error(\n $\"Error getting components for asset '{fullPath}': {e.Message}\"\n );\n }\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Ensures the asset path starts with \"Assets/\".\n /// \n private static string SanitizeAssetPath(string path)\n {\n if (string.IsNullOrEmpty(path))\n return path;\n path = path.Replace('\\\\', '/'); // Normalize separators\n if (!path.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n return \"Assets/\" + path.TrimStart('/');\n }\n return path;\n }\n\n /// \n /// Checks if an asset exists at the given path (file or folder).\n /// \n private static bool AssetExists(string sanitizedPath)\n {\n // AssetDatabase APIs are generally preferred over raw File/Directory checks for assets.\n // Check if it's a known asset GUID.\n if (!string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath)))\n {\n return true;\n }\n // AssetPathToGUID might not work for newly created folders not yet refreshed.\n // Check directory explicitly for folders.\n if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n // Check if it's considered a *valid* folder by Unity\n return AssetDatabase.IsValidFolder(sanitizedPath);\n }\n // Check file existence for non-folder assets.\n if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n return true; // Assume if file exists, it's an asset or will be imported\n }\n\n return false;\n // Alternative: return !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath));\n }\n\n /// \n /// Ensures the directory for a given asset path exists, creating it if necessary.\n /// \n private static void EnsureDirectoryExists(string directoryPath)\n {\n if (string.IsNullOrEmpty(directoryPath))\n return;\n string fullDirPath = Path.Combine(Directory.GetCurrentDirectory(), directoryPath);\n if (!Directory.Exists(fullDirPath))\n {\n Directory.CreateDirectory(fullDirPath);\n AssetDatabase.Refresh(); // Let Unity know about the new folder\n }\n }\n\n /// \n /// Applies properties from JObject to a Material.\n /// \n private static bool ApplyMaterialProperties(Material mat, JObject properties)\n {\n if (mat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set shader\n if (properties[\"shader\"]?.Type == JTokenType.String)\n {\n Shader newShader = Shader.Find(properties[\"shader\"].ToString());\n if (newShader != null && mat.shader != newShader)\n {\n mat.shader = newShader;\n modified = true;\n }\n }\n // Example: Set color property\n if (properties[\"color\"] is JObject colorProps)\n {\n string propName = colorProps[\"name\"]?.ToString() ?? \"_Color\"; // Default main color\n if (colorProps[\"value\"] is JArray colArr && colArr.Count >= 3)\n {\n try\n {\n Color newColor = new Color(\n colArr[0].ToObject(),\n colArr[1].ToObject(),\n colArr[2].ToObject(),\n colArr.Count > 3 ? colArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n } else if (properties[\"color\"] is JArray colorArr) //Use color now with examples set in manage_asset.py\n {\n string propName = \"_Color\"; \n try {\n if (colorArr.Count >= 3)\n {\n Color newColor = new Color(\n colorArr[0].ToObject(),\n colorArr[1].ToObject(), \n colorArr[2].ToObject(), \n colorArr.Count > 3 ? colorArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n } \n catch (Exception ex) {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n // Example: Set float property\n if (properties[\"float\"] is JObject floatProps)\n {\n string propName = floatProps[\"name\"]?.ToString();\n if (\n !string.IsNullOrEmpty(propName) && floatProps[\"value\"]?.Type == JTokenType.Float\n || floatProps[\"value\"]?.Type == JTokenType.Integer\n )\n {\n try\n {\n float newVal = floatProps[\"value\"].ToObject();\n if (mat.HasProperty(propName) && mat.GetFloat(propName) != newVal)\n {\n mat.SetFloat(propName, newVal);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing float property '{propName}': {ex.Message}\"\n );\n }\n }\n }\n // Example: Set texture property\n if (properties[\"texture\"] is JObject texProps)\n {\n string propName = texProps[\"name\"]?.ToString() ?? \"_MainTex\"; // Default main texture\n string texPath = texProps[\"path\"]?.ToString();\n if (!string.IsNullOrEmpty(texPath))\n {\n Texture newTex = AssetDatabase.LoadAssetAtPath(\n SanitizeAssetPath(texPath)\n );\n if (\n newTex != null\n && mat.HasProperty(propName)\n && mat.GetTexture(propName) != newTex\n )\n {\n mat.SetTexture(propName, newTex);\n modified = true;\n }\n else if (newTex == null)\n {\n Debug.LogWarning($\"Texture not found at path: {texPath}\");\n }\n }\n }\n\n // TODO: Add handlers for other property types (Vectors, Ints, Keywords, RenderQueue, etc.)\n return modified;\n }\n\n /// \n /// Applies properties from JObject to a PhysicsMaterial.\n /// \n private static bool ApplyPhysicsMaterialProperties(PhysicsMaterialType pmat, JObject properties)\n {\n if (pmat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set dynamic friction\n if (properties[\"dynamicFriction\"]?.Type == JTokenType.Float)\n {\n float dynamicFriction = properties[\"dynamicFriction\"].ToObject();\n pmat.dynamicFriction = dynamicFriction;\n modified = true;\n }\n\n // Example: Set static friction\n if (properties[\"staticFriction\"]?.Type == JTokenType.Float)\n {\n float staticFriction = properties[\"staticFriction\"].ToObject();\n pmat.staticFriction = staticFriction;\n modified = true;\n }\n\n // Example: Set bounciness\n if (properties[\"bounciness\"]?.Type == JTokenType.Float)\n {\n float bounciness = properties[\"bounciness\"].ToObject();\n pmat.bounciness = bounciness;\n modified = true;\n }\n\n List averageList = new List { \"ave\", \"Ave\", \"average\", \"Average\" };\n List multiplyList = new List { \"mul\", \"Mul\", \"mult\", \"Mult\", \"multiply\", \"Multiply\" };\n List minimumList = new List { \"min\", \"Min\", \"minimum\", \"Minimum\" };\n List maximumList = new List { \"max\", \"Max\", \"maximum\", \"Maximum\" };\n\n // Example: Set friction combine\n if (properties[\"frictionCombine\"]?.Type == JTokenType.String)\n {\n string frictionCombine = properties[\"frictionCombine\"].ToString();\n if (averageList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n // Example: Set bounce combine\n if (properties[\"bounceCombine\"]?.Type == JTokenType.String)\n {\n string bounceCombine = properties[\"bounceCombine\"].ToString();\n if (averageList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n return modified;\n }\n\n /// \n /// Generic helper to set properties on any UnityEngine.Object using reflection.\n /// \n private static bool ApplyObjectProperties(UnityEngine.Object target, JObject properties)\n {\n if (target == null || properties == null)\n return false;\n bool modified = false;\n Type type = target.GetType();\n\n foreach (var prop in properties.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n if (SetPropertyOrField(target, propName, propValue, type))\n {\n modified = true;\n }\n }\n return modified;\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types and Unity objects.\n /// \n private static bool SetPropertyOrField(\n object target,\n string memberName,\n JToken value,\n Type type = null\n )\n {\n type = type ?? target.GetType();\n System.Reflection.BindingFlags flags =\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.Instance\n | System.Reflection.BindingFlags.IgnoreCase;\n\n try\n {\n System.Reflection.PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType);\n if (\n convertedValue != null\n && !object.Equals(propInfo.GetValue(target), convertedValue)\n )\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n else\n {\n System.Reflection.FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null)\n {\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType);\n if (\n convertedValue != null\n && !object.Equals(fieldInfo.GetValue(target), convertedValue)\n )\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[SetPropertyOrField] Failed to set '{memberName}' on {type.Name}: {ex.Message}\"\n );\n }\n return false;\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types and primitives.\n /// \n private static object ConvertJTokenToType(JToken token, Type targetType)\n {\n try\n {\n if (token == null || token.Type == JTokenType.Null)\n return null;\n\n if (targetType == typeof(string))\n return token.ToObject();\n if (targetType == typeof(int))\n return token.ToObject();\n if (targetType == typeof(float))\n return token.ToObject();\n if (targetType == typeof(bool))\n return token.ToObject();\n if (targetType == typeof(Vector2) && token is JArray arrV2 && arrV2.Count == 2)\n return new Vector2(arrV2[0].ToObject(), arrV2[1].ToObject());\n if (targetType == typeof(Vector3) && token is JArray arrV3 && arrV3.Count == 3)\n return new Vector3(\n arrV3[0].ToObject(),\n arrV3[1].ToObject(),\n arrV3[2].ToObject()\n );\n if (targetType == typeof(Vector4) && token is JArray arrV4 && arrV4.Count == 4)\n return new Vector4(\n arrV4[0].ToObject(),\n arrV4[1].ToObject(),\n arrV4[2].ToObject(),\n arrV4[3].ToObject()\n );\n if (targetType == typeof(Quaternion) && token is JArray arrQ && arrQ.Count == 4)\n return new Quaternion(\n arrQ[0].ToObject(),\n arrQ[1].ToObject(),\n arrQ[2].ToObject(),\n arrQ[3].ToObject()\n );\n if (targetType == typeof(Color) && token is JArray arrC && arrC.Count >= 3) // Allow RGB or RGBA\n return new Color(\n arrC[0].ToObject(),\n arrC[1].ToObject(),\n arrC[2].ToObject(),\n arrC.Count > 3 ? arrC[3].ToObject() : 1.0f\n );\n if (targetType.IsEnum)\n return Enum.Parse(targetType, token.ToString(), true); // Case-insensitive enum parsing\n\n // Handle loading Unity Objects (Materials, Textures, etc.) by path\n if (\n typeof(UnityEngine.Object).IsAssignableFrom(targetType)\n && token.Type == JTokenType.String\n )\n {\n string assetPath = SanitizeAssetPath(token.ToString());\n UnityEngine.Object loadedAsset = AssetDatabase.LoadAssetAtPath(\n assetPath,\n targetType\n );\n if (loadedAsset == null)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not load asset of type {targetType.Name} from path: {assetPath}\"\n );\n }\n return loadedAsset;\n }\n\n // Fallback: Try direct conversion (might work for other simple value types)\n return token.ToObject(targetType);\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not convert JToken '{token}' (type {token.Type}) to type '{targetType.Name}': {ex.Message}\"\n );\n return null;\n }\n }\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// Needed for creating ScriptableObjects or finding component types by name.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Try direct lookup first (common Unity types often don't need assembly qualified name)\n var type =\n Type.GetType(typeName)\n ?? Type.GetType($\"UnityEngine.{typeName}, UnityEngine.CoreModule\")\n ?? Type.GetType($\"UnityEngine.UI.{typeName}, UnityEngine.UI\")\n ?? Type.GetType($\"UnityEditor.{typeName}, UnityEditor.CoreModule\");\n\n if (type != null)\n return type;\n\n // If not found, search loaded assemblies (slower but more robust for user scripts)\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n {\n // Look for non-namespaced first\n type = assembly.GetType(typeName, false, true); // throwOnError=false, ignoreCase=true\n if (type != null)\n return type;\n\n // Check common namespaces if simple name given\n type = assembly.GetType(\"UnityEngine.\" + typeName, false, true);\n if (type != null)\n return type;\n type = assembly.GetType(\"UnityEditor.\" + typeName, false, true);\n if (type != null)\n return type;\n // Add other likely namespaces if needed (e.g., specific plugins)\n }\n\n Debug.LogWarning($\"[FindType] Type '{typeName}' not found in any loaded assembly.\");\n return null; // Not found\n }\n\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of an asset.\n /// \n private static object GetAssetData(string path, bool generatePreview = false)\n {\n if (string.IsNullOrEmpty(path) || !AssetExists(path))\n return null;\n\n string guid = AssetDatabase.AssetPathToGUID(path);\n Type assetType = AssetDatabase.GetMainAssetTypeAtPath(path);\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(path);\n string previewBase64 = null;\n int previewWidth = 0;\n int previewHeight = 0;\n\n if (generatePreview && asset != null)\n {\n Texture2D preview = AssetPreview.GetAssetPreview(asset);\n\n if (preview != null)\n {\n try\n {\n // Ensure texture is readable for EncodeToPNG\n // Creating a temporary readable copy is safer\n RenderTexture rt = RenderTexture.GetTemporary(\n preview.width,\n preview.height\n );\n Graphics.Blit(preview, rt);\n RenderTexture previous = RenderTexture.active;\n RenderTexture.active = rt;\n Texture2D readablePreview = new Texture2D(preview.width, preview.height);\n readablePreview.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);\n readablePreview.Apply();\n RenderTexture.active = previous;\n RenderTexture.ReleaseTemporary(rt);\n\n byte[] pngData = readablePreview.EncodeToPNG();\n previewBase64 = Convert.ToBase64String(pngData);\n previewWidth = readablePreview.width;\n previewHeight = readablePreview.height;\n UnityEngine.Object.DestroyImmediate(readablePreview); // Clean up temp texture\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Failed to generate readable preview for '{path}': {ex.Message}. Preview might not be readable.\"\n );\n // Fallback: Try getting static preview if available?\n // Texture2D staticPreview = AssetPreview.GetMiniThumbnail(asset);\n }\n }\n else\n {\n Debug.LogWarning(\n $\"Could not get asset preview for {path} (Type: {assetType?.Name}). Is it supported?\"\n );\n }\n }\n\n return new\n {\n path = path,\n guid = guid,\n assetType = assetType?.FullName ?? \"Unknown\",\n name = Path.GetFileNameWithoutExtension(path),\n fileName = Path.GetFileName(path),\n isFolder = AssetDatabase.IsValidFolder(path),\n instanceID = asset?.GetInstanceID() ?? 0,\n lastWriteTimeUtc = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), path)\n )\n .ToString(\"o\"), // ISO 8601\n // --- Preview Data ---\n previewBase64 = previewBase64, // PNG data as Base64 string\n previewWidth = previewWidth,\n previewHeight = previewHeight,\n // TODO: Add more metadata? Importer settings? Dependencies?\n };\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageGameObject.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json; // Added for JsonSerializationException\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\nusing UnityMcpBridge.Runtime.Serialization;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles GameObject manipulation within the current scene (CRUD, find, components).\n /// \n public static class ManageGameObject\n {\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Parameters used by various actions\n JToken targetToken = @params[\"target\"]; // Can be string (name/path) or int (instanceID)\n string searchMethod = @params[\"searchMethod\"]?.ToString().ToLower();\n\n // Get common parameters (consolidated)\n string name = @params[\"name\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString();\n string layer = @params[\"layer\"]?.ToString();\n JToken parentToken = @params[\"parent\"];\n\n // --- Add parameter for controlling non-public field inclusion ---\n bool includeNonPublicSerialized = @params[\"includeNonPublicSerialized\"]?.ToObject() ?? true; // Default to true\n // --- End add parameter ---\n\n // --- Prefab Redirection Check ---\n string targetPath =\n targetToken?.Type == JTokenType.String ? targetToken.ToString() : null;\n if (\n !string.IsNullOrEmpty(targetPath)\n && targetPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n // Allow 'create' (instantiate), 'find' (?), 'get_components' (?)\n if (action == \"modify\" || action == \"set_component_property\")\n {\n Debug.Log(\n $\"[ManageGameObject->ManageAsset] Redirecting action '{action}' for prefab '{targetPath}' to ManageAsset.\"\n );\n // Prepare params for ManageAsset.ModifyAsset\n JObject assetParams = new JObject();\n assetParams[\"action\"] = \"modify\"; // ManageAsset uses \"modify\"\n assetParams[\"path\"] = targetPath;\n\n // Extract properties.\n // For 'set_component_property', combine componentName and componentProperties.\n // For 'modify', directly use componentProperties.\n JObject properties = null;\n if (action == \"set_component_property\")\n {\n string compName = @params[\"componentName\"]?.ToString();\n JObject compProps = @params[\"componentProperties\"]?[compName] as JObject; // Handle potential nesting\n if (string.IsNullOrEmpty(compName))\n return Response.Error(\n \"Missing 'componentName' for 'set_component_property' on prefab.\"\n );\n if (compProps == null)\n return Response.Error(\n $\"Missing or invalid 'componentProperties' for component '{compName}' for 'set_component_property' on prefab.\"\n );\n\n properties = new JObject();\n properties[compName] = compProps;\n }\n else // action == \"modify\"\n {\n properties = @params[\"componentProperties\"] as JObject;\n if (properties == null)\n return Response.Error(\n \"Missing 'componentProperties' for 'modify' action on prefab.\"\n );\n }\n\n assetParams[\"properties\"] = properties;\n\n // Call ManageAsset handler\n return ManageAsset.HandleCommand(assetParams);\n }\n else if (\n action == \"delete\"\n || action == \"add_component\"\n || action == \"remove_component\"\n || action == \"get_components\"\n ) // Added get_components here too\n {\n // Explicitly block other modifications on the prefab asset itself via manage_gameobject\n return Response.Error(\n $\"Action '{action}' on a prefab asset ('{targetPath}') should be performed using the 'manage_asset' command.\"\n );\n }\n // Allow 'create' (instantiation) and 'find' to proceed, although finding a prefab asset by path might be less common via manage_gameobject.\n // No specific handling needed here, the code below will run.\n }\n // --- End Prefab Redirection Check ---\n\n try\n {\n switch (action)\n {\n case \"create\":\n return CreateGameObject(@params);\n case \"modify\":\n return ModifyGameObject(@params, targetToken, searchMethod);\n case \"delete\":\n return DeleteGameObject(targetToken, searchMethod);\n case \"find\":\n return FindGameObjects(@params, targetToken, searchMethod);\n case \"get_components\":\n string getCompTarget = targetToken?.ToString(); // Expect name, path, or ID string\n if (getCompTarget == null)\n return Response.Error(\n \"'target' parameter required for get_components.\"\n );\n // Pass the includeNonPublicSerialized flag here\n return GetComponentsFromTarget(getCompTarget, searchMethod, includeNonPublicSerialized);\n case \"add_component\":\n return AddComponentToTarget(@params, targetToken, searchMethod);\n case \"remove_component\":\n return RemoveComponentFromTarget(@params, targetToken, searchMethod);\n case \"set_component_property\":\n return SetComponentPropertyOnTarget(@params, targetToken, searchMethod);\n\n default:\n return Response.Error($\"Unknown action: '{action}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageGameObject] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object CreateGameObject(JObject @params)\n {\n string name = @params[\"name\"]?.ToString();\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"'name' parameter is required for 'create' action.\");\n }\n\n // Get prefab creation parameters\n bool saveAsPrefab = @params[\"saveAsPrefab\"]?.ToObject() ?? false;\n string prefabPath = @params[\"prefabPath\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString(); // Get tag for creation\n string primitiveType = @params[\"primitiveType\"]?.ToString(); // Keep primitiveType check\n GameObject newGo = null; // Initialize as null\n\n // --- Try Instantiating Prefab First ---\n string originalPrefabPath = prefabPath; // Keep original for messages\n if (!string.IsNullOrEmpty(prefabPath))\n {\n // If no extension, search for the prefab by name\n if (\n !prefabPath.Contains(\"/\")\n && !prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n string prefabNameOnly = prefabPath;\n Debug.Log(\n $\"[ManageGameObject.Create] Searching for prefab named: '{prefabNameOnly}'\"\n );\n string[] guids = AssetDatabase.FindAssets($\"t:Prefab {prefabNameOnly}\");\n if (guids.Length == 0)\n {\n return Response.Error(\n $\"Prefab named '{prefabNameOnly}' not found anywhere in the project.\"\n );\n }\n else if (guids.Length > 1)\n {\n string foundPaths = string.Join(\n \", \",\n guids.Select(g => AssetDatabase.GUIDToAssetPath(g))\n );\n return Response.Error(\n $\"Multiple prefabs found matching name '{prefabNameOnly}': {foundPaths}. Please provide a more specific path.\"\n );\n }\n else // Exactly one found\n {\n prefabPath = AssetDatabase.GUIDToAssetPath(guids[0]); // Update prefabPath with the full path\n Debug.Log(\n $\"[ManageGameObject.Create] Found unique prefab at path: '{prefabPath}'\"\n );\n }\n }\n else if (!prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n // If it looks like a path but doesn't end with .prefab, assume user forgot it and append it.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Provided prefabPath '{prefabPath}' does not end with .prefab. Assuming it's missing and appending.\"\n );\n prefabPath += \".prefab\";\n // Note: This path might still not exist, AssetDatabase.LoadAssetAtPath will handle that.\n }\n // The logic above now handles finding or assuming the .prefab extension.\n\n GameObject prefabAsset = AssetDatabase.LoadAssetAtPath(prefabPath);\n if (prefabAsset != null)\n {\n try\n {\n // Instantiate the prefab, initially place it at the root\n // Parent will be set later if specified\n newGo = PrefabUtility.InstantiatePrefab(prefabAsset) as GameObject;\n\n if (newGo == null)\n {\n // This might happen if the asset exists but isn't a valid GameObject prefab somehow\n Debug.LogError(\n $\"[ManageGameObject.Create] Failed to instantiate prefab at '{prefabPath}', asset might be corrupted or not a GameObject.\"\n );\n return Response.Error(\n $\"Failed to instantiate prefab at '{prefabPath}'.\"\n );\n }\n // Name the instance based on the 'name' parameter, not the prefab's default name\n if (!string.IsNullOrEmpty(name))\n {\n newGo.name = name;\n }\n // Register Undo for prefab instantiation\n Undo.RegisterCreatedObjectUndo(\n newGo,\n $\"Instantiate Prefab '{prefabAsset.name}' as '{newGo.name}'\"\n );\n Debug.Log(\n $\"[ManageGameObject.Create] Instantiated prefab '{prefabAsset.name}' from path '{prefabPath}' as '{newGo.name}'.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error instantiating prefab '{prefabPath}': {e.Message}\"\n );\n }\n }\n else\n {\n // Only return error if prefabPath was specified but not found.\n // If prefabPath was empty/null, we proceed to create primitive/empty.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Prefab asset not found at path: '{prefabPath}'. Will proceed to create new object if specified.\"\n );\n // Do not return error here, allow fallback to primitive/empty creation\n }\n }\n\n // --- Fallback: Create Primitive or Empty GameObject ---\n bool createdNewObject = false; // Flag to track if we created (not instantiated)\n if (newGo == null) // Only proceed if prefab instantiation didn't happen\n {\n if (!string.IsNullOrEmpty(primitiveType))\n {\n try\n {\n PrimitiveType type = (PrimitiveType)\n Enum.Parse(typeof(PrimitiveType), primitiveType, true);\n newGo = GameObject.CreatePrimitive(type);\n // Set name *after* creation for primitives\n if (!string.IsNullOrEmpty(name))\n newGo.name = name;\n else\n return Response.Error(\n \"'name' parameter is required when creating a primitive.\"\n ); // Name is essential\n createdNewObject = true;\n }\n catch (ArgumentException)\n {\n return Response.Error(\n $\"Invalid primitive type: '{primitiveType}'. Valid types: {string.Join(\", \", Enum.GetNames(typeof(PrimitiveType)))}\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Failed to create primitive '{primitiveType}': {e.Message}\"\n );\n }\n }\n else // Create empty GameObject\n {\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\n \"'name' parameter is required for 'create' action when not instantiating a prefab or creating a primitive.\"\n );\n }\n newGo = new GameObject(name);\n createdNewObject = true;\n }\n // Record creation for Undo *only* if we created a new object\n if (createdNewObject)\n {\n Undo.RegisterCreatedObjectUndo(newGo, $\"Create GameObject '{newGo.name}'\");\n }\n }\n // --- Common Setup (Parent, Transform, Tag, Components) - Applied AFTER object exists ---\n if (newGo == null)\n {\n // Should theoretically not happen if logic above is correct, but safety check.\n return Response.Error(\"Failed to create or instantiate the GameObject.\");\n }\n\n // Record potential changes to the existing prefab instance or the new GO\n // Record transform separately in case parent changes affect it\n Undo.RecordObject(newGo.transform, \"Set GameObject Transform\");\n Undo.RecordObject(newGo, \"Set GameObject Properties\");\n\n // Set Parent\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject parentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\"); // Flexible parent finding\n if (parentGo == null)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up created object\n return Response.Error($\"Parent specified ('{parentToken}') but not found.\");\n }\n newGo.transform.SetParent(parentGo.transform, true); // worldPositionStays = true\n }\n\n // Set Transform\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue)\n newGo.transform.localPosition = position.Value;\n if (rotation.HasValue)\n newGo.transform.localEulerAngles = rotation.Value;\n if (scale.HasValue)\n newGo.transform.localScale = scale.Value;\n\n // Set Tag (added for create action)\n if (!string.IsNullOrEmpty(tag))\n {\n // Similar logic as in ModifyGameObject for setting/creating tags\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n newGo.tag = tagToSet;\n }\n catch (UnityException ex)\n {\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n InternalEditorUtility.AddTag(tagToSet);\n newGo.tag = tagToSet; // Retry\n Debug.Log(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}' during creation: {innerEx.Message}.\"\n );\n }\n }\n else\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to set tag to '{tagToSet}' during creation: {ex.Message}.\"\n );\n }\n }\n }\n\n // Set Layer (new for create action)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId != -1)\n {\n newGo.layer = layerId;\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Layer '{layerName}' not found. Using default layer.\"\n );\n }\n }\n\n // Add Components\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArray)\n {\n foreach (var compToken in componentsToAddArray)\n {\n string typeName = null;\n JObject properties = null;\n\n if (compToken.Type == JTokenType.String)\n {\n typeName = compToken.ToString();\n }\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(newGo, typeName, properties);\n if (addResult != null) // Check if AddComponentInternal returned an error object\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return addResult; // Return the error response\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Invalid component format in componentsToAdd: {compToken}\"\n );\n }\n }\n }\n\n // Save as Prefab ONLY if we *created* a new object AND saveAsPrefab is true\n GameObject finalInstance = newGo; // Use this for selection and return data\n if (createdNewObject && saveAsPrefab)\n {\n string finalPrefabPath = prefabPath; // Use a separate variable for saving path\n // This check should now happen *before* attempting to save\n if (string.IsNullOrEmpty(finalPrefabPath))\n {\n // Clean up the created object before returning error\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n \"'prefabPath' is required when 'saveAsPrefab' is true and creating a new object.\"\n );\n }\n // Ensure the *saving* path ends with .prefab\n if (!finalPrefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n Debug.Log(\n $\"[ManageGameObject.Create] Appending .prefab extension to save path: '{finalPrefabPath}' -> '{finalPrefabPath}.prefab'\"\n );\n finalPrefabPath += \".prefab\";\n }\n\n try\n {\n // Ensure directory exists using the final saving path\n string directoryPath = System.IO.Path.GetDirectoryName(finalPrefabPath);\n if (\n !string.IsNullOrEmpty(directoryPath)\n && !System.IO.Directory.Exists(directoryPath)\n )\n {\n System.IO.Directory.CreateDirectory(directoryPath);\n AssetDatabase.Refresh(); // Refresh asset database to recognize the new folder\n Debug.Log(\n $\"[ManageGameObject.Create] Created directory for prefab: {directoryPath}\"\n );\n }\n // Use SaveAsPrefabAssetAndConnect with the final saving path\n finalInstance = PrefabUtility.SaveAsPrefabAssetAndConnect(\n newGo,\n finalPrefabPath,\n InteractionMode.UserAction\n );\n\n if (finalInstance == null)\n {\n // Destroy the original if saving failed somehow (shouldn't usually happen if path is valid)\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n $\"Failed to save GameObject '{name}' as prefab at '{finalPrefabPath}'. Check path and permissions.\"\n );\n }\n Debug.Log(\n $\"[ManageGameObject.Create] GameObject '{name}' saved as prefab to '{finalPrefabPath}' and instance connected.\"\n );\n // Mark the new prefab asset as dirty? Not usually necessary, SaveAsPrefabAsset handles it.\n // EditorUtility.SetDirty(finalInstance); // Instance is handled by SaveAsPrefabAssetAndConnect\n }\n catch (Exception e)\n {\n // Clean up the instance if prefab saving fails\n UnityEngine.Object.DestroyImmediate(newGo); // Destroy the original attempt\n return Response.Error($\"Error saving prefab '{finalPrefabPath}': {e.Message}\");\n }\n }\n\n // Select the instance in the scene (either prefab instance or newly created/saved one)\n Selection.activeGameObject = finalInstance;\n\n // Determine appropriate success message using the potentially updated or original path\n string messagePrefabPath =\n finalInstance == null\n ? originalPrefabPath\n : AssetDatabase.GetAssetPath(\n PrefabUtility.GetCorrespondingObjectFromSource(finalInstance)\n ?? (UnityEngine.Object)finalInstance\n );\n string successMessage;\n if (!createdNewObject && !string.IsNullOrEmpty(messagePrefabPath)) // Instantiated existing prefab\n {\n successMessage =\n $\"Prefab '{messagePrefabPath}' instantiated successfully as '{finalInstance.name}'.\";\n }\n else if (createdNewObject && saveAsPrefab && !string.IsNullOrEmpty(messagePrefabPath)) // Created new and saved as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created and saved as prefab to '{messagePrefabPath}'.\";\n }\n else // Created new primitive or empty GO, didn't save as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created successfully in scene.\";\n }\n\n // Use the new serializer helper\n //return Response.Success(successMessage, GetGameObjectData(finalInstance));\n return Response.Success(successMessage, Helpers.GameObjectSerializer.GetGameObjectData(finalInstance));\n }\n\n private static object ModifyGameObject(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n // Record state for Undo *before* modifications\n Undo.RecordObject(targetGo.transform, \"Modify GameObject Transform\");\n Undo.RecordObject(targetGo, \"Modify GameObject Properties\");\n\n bool modified = false;\n\n // Rename (using consolidated 'name' parameter)\n string name = @params[\"name\"]?.ToString();\n if (!string.IsNullOrEmpty(name) && targetGo.name != name)\n {\n targetGo.name = name;\n modified = true;\n }\n\n // Change Parent (using consolidated 'parent' parameter)\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject newParentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\");\n // Check for hierarchy loops\n if (\n newParentGo == null\n && !(\n parentToken.Type == JTokenType.Null\n || (\n parentToken.Type == JTokenType.String\n && string.IsNullOrEmpty(parentToken.ToString())\n )\n )\n )\n {\n return Response.Error($\"New parent ('{parentToken}') not found.\");\n }\n if (newParentGo != null && newParentGo.transform.IsChildOf(targetGo.transform))\n {\n return Response.Error(\n $\"Cannot parent '{targetGo.name}' to '{newParentGo.name}', as it would create a hierarchy loop.\"\n );\n }\n if (targetGo.transform.parent != (newParentGo?.transform))\n {\n targetGo.transform.SetParent(newParentGo?.transform, true); // worldPositionStays = true\n modified = true;\n }\n }\n\n // Set Active State\n bool? setActive = @params[\"setActive\"]?.ToObject();\n if (setActive.HasValue && targetGo.activeSelf != setActive.Value)\n {\n targetGo.SetActive(setActive.Value);\n modified = true;\n }\n\n // Change Tag (using consolidated 'tag' parameter)\n string tag = @params[\"tag\"]?.ToString();\n // Only attempt to change tag if a non-null tag is provided and it's different from the current one.\n // Allow setting an empty string to remove the tag (Unity uses \"Untagged\").\n if (tag != null && targetGo.tag != tag)\n {\n // Ensure the tag is not empty, if empty, it means \"Untagged\" implicitly\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n targetGo.tag = tagToSet;\n modified = true;\n }\n catch (UnityException ex)\n {\n // Check if the error is specifically because the tag doesn't exist\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n // Attempt to create the tag using internal utility\n InternalEditorUtility.AddTag(tagToSet);\n // Wait a frame maybe? Not strictly necessary but sometimes helps editor updates.\n // yield return null; // Cannot yield here, editor script limitation\n\n // Retry setting the tag immediately after creation\n targetGo.tag = tagToSet;\n modified = true;\n Debug.Log(\n $\"[ManageGameObject] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n // Handle failure during tag creation or the second assignment attempt\n Debug.LogError(\n $\"[ManageGameObject] Failed to create or assign tag '{tagToSet}' after attempting creation: {innerEx.Message}\"\n );\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}': {innerEx.Message}. Check Tag Manager and permissions.\"\n );\n }\n }\n else\n {\n // If the exception was for a different reason, return the original error\n return Response.Error($\"Failed to set tag to '{tagToSet}': {ex.Message}.\");\n }\n }\n }\n\n // Change Layer (using consolidated 'layer' parameter)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId == -1 && layerName != \"Default\")\n {\n return Response.Error(\n $\"Invalid layer specified: '{layerName}'. Use a valid layer name.\"\n );\n }\n if (layerId != -1 && targetGo.layer != layerId)\n {\n targetGo.layer = layerId;\n modified = true;\n }\n }\n\n // Transform Modifications\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue && targetGo.transform.localPosition != position.Value)\n {\n targetGo.transform.localPosition = position.Value;\n modified = true;\n }\n if (rotation.HasValue && targetGo.transform.localEulerAngles != rotation.Value)\n {\n targetGo.transform.localEulerAngles = rotation.Value;\n modified = true;\n }\n if (scale.HasValue && targetGo.transform.localScale != scale.Value)\n {\n targetGo.transform.localScale = scale.Value;\n modified = true;\n }\n\n // --- Component Modifications ---\n // Note: These might need more specific Undo recording per component\n\n // Remove Components\n if (@params[\"componentsToRemove\"] is JArray componentsToRemoveArray)\n {\n foreach (var compToken in componentsToRemoveArray)\n {\n // ... (parsing logic as in CreateGameObject) ...\n string typeName = compToken.ToString();\n if (!string.IsNullOrEmpty(typeName))\n {\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error if removal failed\n modified = true;\n }\n }\n }\n\n // Add Components (similar to create)\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArrayModify)\n {\n foreach (var compToken in componentsToAddArrayModify)\n {\n string typeName = null;\n JObject properties = null;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult;\n modified = true;\n }\n }\n }\n\n // Set Component Properties\n if (@params[\"componentProperties\"] is JObject componentPropertiesObj)\n {\n foreach (var prop in componentPropertiesObj.Properties())\n {\n string compName = prop.Name;\n JObject propertiesToSet = prop.Value as JObject;\n if (propertiesToSet != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n compName,\n propertiesToSet\n );\n if (setResult != null)\n return setResult;\n modified = true;\n }\n }\n }\n\n if (!modified)\n {\n // Use the new serializer helper\n // return Response.Success(\n // $\"No modifications applied to GameObject '{targetGo.name}'.\",\n // GetGameObjectData(targetGo));\n\n return Response.Success(\n $\"No modifications applied to GameObject '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n EditorUtility.SetDirty(targetGo); // Mark scene as dirty\n // Use the new serializer helper\n return Response.Success(\n $\"GameObject '{targetGo.name}' modified successfully.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n // return Response.Success(\n // $\"GameObject '{targetGo.name}' modified successfully.\",\n // GetGameObjectData(targetGo));\n \n }\n\n private static object DeleteGameObject(JToken targetToken, string searchMethod)\n {\n // Find potentially multiple objects if name/tag search is used without find_all=false implicitly\n List targets = FindObjectsInternal(targetToken, searchMethod, true); // find_all=true for delete safety\n\n if (targets.Count == 0)\n {\n return Response.Error(\n $\"Target GameObject(s) ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n List deletedObjects = new List();\n foreach (var targetGo in targets)\n {\n if (targetGo != null)\n {\n string goName = targetGo.name;\n int goId = targetGo.GetInstanceID();\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(targetGo);\n deletedObjects.Add(new { name = goName, instanceID = goId });\n }\n }\n\n if (deletedObjects.Count > 0)\n {\n string message =\n targets.Count == 1\n ? $\"GameObject '{deletedObjects[0].GetType().GetProperty(\"name\").GetValue(deletedObjects[0])}' deleted successfully.\"\n : $\"{deletedObjects.Count} GameObjects deleted successfully.\";\n return Response.Success(message, deletedObjects);\n }\n else\n {\n // Should not happen if targets.Count > 0 initially, but defensive check\n return Response.Error(\"Failed to delete target GameObject(s).\");\n }\n }\n\n private static object FindGameObjects(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n bool findAll = @params[\"findAll\"]?.ToObject() ?? false;\n List foundObjects = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n @params\n );\n\n if (foundObjects.Count == 0)\n {\n return Response.Success(\"No matching GameObjects found.\", new List());\n }\n\n // Use the new serializer helper\n //var results = foundObjects.Select(go => GetGameObjectData(go)).ToList();\n var results = foundObjects.Select(go => Helpers.GameObjectSerializer.GetGameObjectData(go)).ToList();\n return Response.Success($\"Found {results.Count} GameObject(s).\", results);\n }\n\n private static object GetComponentsFromTarget(string target, string searchMethod, bool includeNonPublicSerialized = true)\n {\n GameObject targetGo = FindObjectInternal(target, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{target}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n try\n {\n // --- Get components, immediately copy to list, and null original array --- \n Component[] originalComponents = targetGo.GetComponents();\n List componentsToIterate = new List(originalComponents ?? Array.Empty()); // Copy immediately, handle null case\n int componentCount = componentsToIterate.Count; \n originalComponents = null; // Null the original reference\n // Debug.Log($\"[GetComponentsFromTarget] Found {componentCount} components on {targetGo.name}. Copied to list, nulled original. Starting REVERSE for loop...\");\n // --- End Copy and Null --- \n \n var componentData = new List();\n \n for (int i = componentCount - 1; i >= 0; i--) // Iterate backwards over the COPY\n {\n Component c = componentsToIterate[i]; // Use the copy\n if (c == null) \n {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] Encountered a null component at index {i} on {targetGo.name}. Skipping.\");\n continue; // Safety check\n }\n // Debug.Log($\"[GetComponentsFromTarget REVERSE for] Processing component: {c.GetType()?.FullName ?? \"null\"} (ID: {c.GetInstanceID()}) at index {i} on {targetGo.name}\");\n try \n {\n var data = Helpers.GameObjectSerializer.GetComponentData(c, includeNonPublicSerialized);\n if (data != null) // Ensure GetComponentData didn't return null\n {\n componentData.Insert(0, data); // Insert at beginning to maintain original order in final list\n }\n // else\n // {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] GetComponentData returned null for component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}. Skipping addition.\");\n // }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"[GetComponentsFromTarget REVERSE for] Error processing component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}: {ex.Message}\\n{ex.StackTrace}\");\n // Optionally add placeholder data or just skip\n componentData.Insert(0, new JObject( // Insert error marker at beginning\n new JProperty(\"typeName\", c.GetType().FullName + \" (Serialization Error)\"),\n new JProperty(\"instanceID\", c.GetInstanceID()),\n new JProperty(\"error\", ex.Message)\n ));\n }\n }\n // Debug.Log($\"[GetComponentsFromTarget] Finished REVERSE for loop.\");\n \n // Cleanup the list we created\n componentsToIterate.Clear();\n componentsToIterate = null;\n\n return Response.Success(\n $\"Retrieved {componentData.Count} components from '{targetGo.name}'.\",\n componentData // List was built in original order\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error getting components from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n private static object AddComponentToTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n JObject properties = null;\n\n // Allow adding component specified directly or via componentsToAdd array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n properties = @params[\"componentProperties\"]?[typeName] as JObject; // Check if props are nested under name\n }\n else if (\n @params[\"componentsToAdd\"] is JArray componentsToAddArray\n && componentsToAddArray.Count > 0\n )\n {\n var compToken = componentsToAddArray.First;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToAdd') is required.\"\n );\n }\n\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' added to '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n ); // Return updated GO data\n }\n\n private static object RemoveComponentFromTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n // Allow removing component specified directly or via componentsToRemove array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n }\n else if (\n @params[\"componentsToRemove\"] is JArray componentsToRemoveArray\n && componentsToRemoveArray.Count > 0\n )\n {\n typeName = componentsToRemoveArray.First?.ToString();\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToRemove') is required.\"\n );\n }\n\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' removed from '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n private static object SetComponentPropertyOnTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string compName = @params[\"componentName\"]?.ToString();\n JObject propertiesToSet = null;\n\n if (!string.IsNullOrEmpty(compName))\n {\n // Properties might be directly under componentProperties or nested under the component name\n if (@params[\"componentProperties\"] is JObject compProps)\n {\n propertiesToSet = compProps[compName] as JObject ?? compProps; // Allow flat or nested structure\n }\n }\n else\n {\n return Response.Error(\"'componentName' parameter is required.\");\n }\n\n if (propertiesToSet == null || !propertiesToSet.HasValues)\n {\n return Response.Error(\n \"'componentProperties' dictionary for the specified component is required and cannot be empty.\"\n );\n }\n\n var setResult = SetComponentPropertiesInternal(targetGo, compName, propertiesToSet);\n if (setResult != null)\n return setResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Properties set for component '{compName}' on '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Finds a single GameObject based on token (ID, name, path) and search method.\n /// \n private static GameObject FindObjectInternal(\n JToken targetToken,\n string searchMethod,\n JObject findParams = null\n )\n {\n // If find_all is not explicitly false, we still want only one for most single-target operations.\n bool findAll = findParams?[\"findAll\"]?.ToObject() ?? false;\n // If a specific target ID is given, always find just that one.\n if (\n targetToken?.Type == JTokenType.Integer\n || (searchMethod == \"by_id\" && int.TryParse(targetToken?.ToString(), out _))\n )\n {\n findAll = false;\n }\n List results = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n findParams\n );\n return results.Count > 0 ? results[0] : null;\n }\n\n /// \n /// Core logic for finding GameObjects based on various criteria.\n /// \n private static List FindObjectsInternal(\n JToken targetToken,\n string searchMethod,\n bool findAll,\n JObject findParams = null\n )\n {\n List results = new List();\n string searchTerm = findParams?[\"searchTerm\"]?.ToString() ?? targetToken?.ToString(); // Use searchTerm if provided, else the target itself\n bool searchInChildren = findParams?[\"searchInChildren\"]?.ToObject() ?? false;\n bool searchInactive = findParams?[\"searchInactive\"]?.ToObject() ?? false;\n\n // Default search method if not specified\n if (string.IsNullOrEmpty(searchMethod))\n {\n if (targetToken?.Type == JTokenType.Integer)\n searchMethod = \"by_id\";\n else if (!string.IsNullOrEmpty(searchTerm) && searchTerm.Contains('/'))\n searchMethod = \"by_path\";\n else\n searchMethod = \"by_name\"; // Default fallback\n }\n\n GameObject rootSearchObject = null;\n // If searching in children, find the initial target first\n if (searchInChildren && targetToken != null)\n {\n rootSearchObject = FindObjectInternal(targetToken, \"by_id_or_name_or_path\"); // Find the root for child search\n if (rootSearchObject == null)\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Root object '{targetToken}' for child search not found.\"\n );\n return results; // Return empty if root not found\n }\n }\n\n switch (searchMethod)\n {\n case \"by_id\":\n if (int.TryParse(searchTerm, out int instanceId))\n {\n // EditorUtility.InstanceIDToObject is slow, iterate manually if possible\n // GameObject obj = EditorUtility.InstanceIDToObject(instanceId) as GameObject;\n var allObjects = GetAllSceneObjects(searchInactive); // More efficient\n GameObject obj = allObjects.FirstOrDefault(go =>\n go.GetInstanceID() == instanceId\n );\n if (obj != null)\n results.Add(obj);\n }\n break;\n case \"by_name\":\n var searchPoolName = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolName.Where(go => go.name == searchTerm));\n break;\n case \"by_path\":\n // Path is relative to scene root or rootSearchObject\n Transform foundTransform = rootSearchObject\n ? rootSearchObject.transform.Find(searchTerm)\n : GameObject.Find(searchTerm)?.transform;\n if (foundTransform != null)\n results.Add(foundTransform.gameObject);\n break;\n case \"by_tag\":\n var searchPoolTag = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolTag.Where(go => go.CompareTag(searchTerm)));\n break;\n case \"by_layer\":\n var searchPoolLayer = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n if (int.TryParse(searchTerm, out int layerIndex))\n {\n results.AddRange(searchPoolLayer.Where(go => go.layer == layerIndex));\n }\n else\n {\n int namedLayer = LayerMask.NameToLayer(searchTerm);\n if (namedLayer != -1)\n results.AddRange(searchPoolLayer.Where(go => go.layer == namedLayer));\n }\n break;\n case \"by_component\":\n Type componentType = FindType(searchTerm);\n if (componentType != null)\n {\n // Determine FindObjectsInactive based on the searchInactive flag\n FindObjectsInactive findInactive = searchInactive\n ? FindObjectsInactive.Include\n : FindObjectsInactive.Exclude;\n // Replace FindObjectsOfType with FindObjectsByType, specifying the sorting mode and inactive state\n var searchPoolComp = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(componentType, searchInactive)\n .Select(c => (c as Component).gameObject)\n : UnityEngine\n .Object.FindObjectsByType(\n componentType,\n findInactive,\n FindObjectsSortMode.None\n )\n .Select(c => (c as Component).gameObject);\n results.AddRange(searchPoolComp.Where(go => go != null)); // Ensure GO is valid\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Component type not found: {searchTerm}\"\n );\n }\n break;\n case \"by_id_or_name_or_path\": // Helper method used internally\n if (int.TryParse(searchTerm, out int id))\n {\n var allObjectsId = GetAllSceneObjects(true); // Search inactive for internal lookup\n GameObject objById = allObjectsId.FirstOrDefault(go =>\n go.GetInstanceID() == id\n );\n if (objById != null)\n {\n results.Add(objById);\n break;\n }\n }\n GameObject objByPath = GameObject.Find(searchTerm);\n if (objByPath != null)\n {\n results.Add(objByPath);\n break;\n }\n\n var allObjectsName = GetAllSceneObjects(true);\n results.AddRange(allObjectsName.Where(go => go.name == searchTerm));\n break;\n default:\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Unknown search method: {searchMethod}\"\n );\n break;\n }\n\n // If only one result is needed, return just the first one found.\n if (!findAll && results.Count > 1)\n {\n return new List { results[0] };\n }\n\n return results.Distinct().ToList(); // Ensure uniqueness\n }\n\n // Helper to get all scene objects efficiently\n private static IEnumerable GetAllSceneObjects(bool includeInactive)\n {\n // SceneManager.GetActiveScene().GetRootGameObjects() is faster than FindObjectsOfType()\n var rootObjects = SceneManager.GetActiveScene().GetRootGameObjects();\n var allObjects = new List();\n foreach (var root in rootObjects)\n {\n allObjects.AddRange(\n root.GetComponentsInChildren(includeInactive)\n .Select(t => t.gameObject)\n );\n }\n return allObjects;\n }\n\n /// \n /// Adds a component by type name and optionally sets properties.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object AddComponentInternal(\n GameObject targetGo,\n string typeName,\n JObject properties\n )\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error(\n $\"Component type '{typeName}' not found or is not a valid Component.\"\n );\n }\n if (!typeof(Component).IsAssignableFrom(componentType))\n {\n return Response.Error($\"Type '{typeName}' is not a Component.\");\n }\n\n // Prevent adding Transform again\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot add another Transform component.\");\n }\n\n // Check for 2D/3D physics component conflicts\n bool isAdding2DPhysics =\n typeof(Rigidbody2D).IsAssignableFrom(componentType)\n || typeof(Collider2D).IsAssignableFrom(componentType);\n bool isAdding3DPhysics =\n typeof(Rigidbody).IsAssignableFrom(componentType)\n || typeof(Collider).IsAssignableFrom(componentType);\n\n if (isAdding2DPhysics)\n {\n // Check if the GameObject already has any 3D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 2D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 3D Rigidbody or Collider.\"\n );\n }\n }\n else if (isAdding3DPhysics)\n {\n // Check if the GameObject already has any 2D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 3D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 2D Rigidbody or Collider.\"\n );\n }\n }\n\n try\n {\n // Use Undo.AddComponent for undo support\n Component newComponent = Undo.AddComponent(targetGo, componentType);\n if (newComponent == null)\n {\n return Response.Error(\n $\"Failed to add component '{typeName}' to '{targetGo.name}'. It might be disallowed (e.g., adding script twice).\"\n );\n }\n\n // Set default values for specific component types\n if (newComponent is Light light)\n {\n // Default newly added lights to directional\n light.type = LightType.Directional;\n }\n\n // Set properties if provided\n if (properties != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n typeName,\n properties,\n newComponent\n ); // Pass the new component instance\n if (setResult != null)\n {\n // If setting properties failed, maybe remove the added component?\n Undo.DestroyObjectImmediate(newComponent);\n return setResult; // Return the error from setting properties\n }\n }\n\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error adding component '{typeName}' to '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Removes a component by type name.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object RemoveComponentInternal(GameObject targetGo, string typeName)\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error($\"Component type '{typeName}' not found for removal.\");\n }\n\n // Prevent removing essential components\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot remove the Transform component.\");\n }\n\n Component componentToRemove = targetGo.GetComponent(componentType);\n if (componentToRemove == null)\n {\n return Response.Error(\n $\"Component '{typeName}' not found on '{targetGo.name}' to remove.\"\n );\n }\n\n try\n {\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(componentToRemove);\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error removing component '{typeName}' from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Sets properties on a component.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object SetComponentPropertiesInternal(\n GameObject targetGo,\n string compName,\n JObject propertiesToSet,\n Component targetComponentInstance = null\n )\n {\n Component targetComponent = targetComponentInstance ?? targetGo.GetComponent(compName);\n if (targetComponent == null)\n {\n return Response.Error(\n $\"Component '{compName}' not found on '{targetGo.name}' to set properties.\"\n );\n }\n\n Undo.RecordObject(targetComponent, \"Set Component Properties\");\n\n foreach (var prop in propertiesToSet.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n\n try\n {\n if (!SetProperty(targetComponent, propName, propValue))\n {\n // Log warning if property could not be set\n Debug.LogWarning(\n $\"[ManageGameObject] Could not set property '{propName}' on component '{compName}' ('{targetComponent.GetType().Name}'). Property might not exist, be read-only, or type mismatch.\"\n );\n // Optionally return an error here instead of just logging\n // return Response.Error($\"Could not set property '{propName}' on component '{compName}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageGameObject] Error setting property '{propName}' on '{compName}': {e.Message}\"\n );\n // Optionally return an error here\n // return Response.Error($\"Error setting property '{propName}' on '{compName}': {e.Message}\");\n }\n }\n EditorUtility.SetDirty(targetComponent);\n return null; // Success (or partial success if warnings were logged)\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types.\n /// \n private static bool SetProperty(object target, string memberName, JToken value)\n {\n Type type = target.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // --- Use a dedicated serializer for input conversion ---\n // Define this somewhere accessible, maybe static readonly field\n JsonSerializerSettings inputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n // Add specific converters needed for INPUT deserialization if different from output\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Crucial for finding references from instructions\n }\n // No ReferenceLoopHandling needed typically for input\n };\n JsonSerializer inputSerializer = JsonSerializer.Create(inputSerializerSettings);\n // --- End Serializer Setup ---\n\n try\n {\n // Handle special case for materials with dot notation (material.property)\n // Examples: material.color, sharedMaterial.color, materials[0].color\n if (memberName.Contains('.') || memberName.Contains('['))\n {\n // Pass the inputSerializer down for nested conversions\n return SetNestedProperty(target, memberName, value, inputSerializer);\n }\n\n PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for property '{memberName}' (Type: {propInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null) // Check if !IsLiteral?\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for field '{memberName}' (Type: {fieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetProperty] Failed to set '{memberName}' on {type.Name}: {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n return false;\n }\n\n /// \n /// Sets a nested property using dot notation (e.g., \"material.color\") or array access (e.g., \"materials[0]\")\n /// \n // Pass the input serializer for conversions\n //Using the serializer helper\n private static bool SetNestedProperty(object target, string path, JToken value, JsonSerializer inputSerializer)\n {\n try\n {\n // Split the path into parts (handling both dot notation and array indexing)\n string[] pathParts = SplitPropertyPath(path);\n if (pathParts.Length == 0)\n return false;\n\n object currentObject = target;\n Type currentType = currentObject.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // Traverse the path until we reach the final property\n for (int i = 0; i < pathParts.Length - 1; i++)\n {\n string part = pathParts[i];\n bool isArray = false;\n int arrayIndex = -1;\n\n // Check if this part contains array indexing\n if (part.Contains(\"[\"))\n {\n int startBracket = part.IndexOf('[');\n int endBracket = part.IndexOf(']');\n if (startBracket > 0 && endBracket > startBracket)\n {\n string indexStr = part.Substring(\n startBracket + 1,\n endBracket - startBracket - 1\n );\n if (int.TryParse(indexStr, out arrayIndex))\n {\n isArray = true;\n part = part.Substring(0, startBracket);\n }\n }\n }\n // Get the property/field\n PropertyInfo propInfo = currentType.GetProperty(part, flags);\n FieldInfo fieldInfo = null;\n if (propInfo == null)\n {\n fieldInfo = currentType.GetField(part, flags);\n if (fieldInfo == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find property or field '{part}' on type '{currentType.Name}'\"\n );\n return false;\n }\n }\n\n // Get the value\n currentObject =\n propInfo != null\n ? propInfo.GetValue(currentObject)\n : fieldInfo.GetValue(currentObject);\n //Need to stop if current property is null\n if (currentObject == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is null, cannot access nested properties.\"\n );\n return false;\n }\n // If this part was an array or list, access the specific index\n if (isArray)\n {\n if (currentObject is Material[])\n {\n var materials = currentObject as Material[];\n if (arrayIndex < 0 || arrayIndex >= materials.Length)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Material index {arrayIndex} out of range (0-{materials.Length - 1})\"\n );\n return false;\n }\n currentObject = materials[arrayIndex];\n }\n else if (currentObject is System.Collections.IList)\n {\n var list = currentObject as System.Collections.IList;\n if (arrayIndex < 0 || arrayIndex >= list.Count)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Index {arrayIndex} out of range (0-{list.Count - 1})\"\n );\n return false;\n }\n currentObject = list[arrayIndex];\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is not an array or list, cannot access by index.\"\n );\n return false;\n }\n }\n currentType = currentObject.GetType();\n }\n\n // Set the final property\n string finalPart = pathParts[pathParts.Length - 1];\n\n // Special handling for Material properties (shader properties)\n if (currentObject is Material material && finalPart.StartsWith(\"_\"))\n {\n // Use the serializer to convert the JToken value first\n if (value is JArray jArray)\n {\n // Try converting to known types that SetColor/SetVector accept\n if (jArray.Count == 4) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { }\n try { Vector4 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n } else if (jArray.Count == 3) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { } // ToObject handles conversion to Color\n } else if (jArray.Count == 2) {\n try { Vector2 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n }\n }\n else if (value.Type == JTokenType.Float || value.Type == JTokenType.Integer)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer)); return true; } catch { }\n }\n else if (value.Type == JTokenType.Boolean)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer) ? 1f : 0f); return true; } catch { }\n }\n else if (value.Type == JTokenType.String)\n {\n // Try converting to Texture using the serializer/converter\n try {\n Texture texture = value.ToObject(inputSerializer);\n if (texture != null) {\n material.SetTexture(finalPart, texture);\n return true;\n }\n } catch { }\n }\n\n Debug.LogWarning(\n $\"[SetNestedProperty] Unsupported or failed conversion for material property '{finalPart}' from value: {value.ToString(Formatting.None)}\"\n );\n return false;\n }\n\n // For standard properties (not shader specific)\n PropertyInfo finalPropInfo = currentType.GetProperty(finalPart, flags);\n if (finalPropInfo != null && finalPropInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalPropInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalPropInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for property '{finalPart}' (Type: {finalPropInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo finalFieldInfo = currentType.GetField(finalPart, flags);\n if (finalFieldInfo != null)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalFieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalFieldInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for field '{finalPart}' (Type: {finalFieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find final writable property or field '{finalPart}' on type '{currentType.Name}'\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetNestedProperty] Error setting nested property '{path}': {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n\n return false;\n }\n\n\n /// \n /// Split a property path into parts, handling both dot notation and array indexers\n /// \n private static string[] SplitPropertyPath(string path)\n {\n // Handle complex paths with both dots and array indexers\n List parts = new List();\n int startIndex = 0;\n bool inBrackets = false;\n\n for (int i = 0; i < path.Length; i++)\n {\n char c = path[i];\n\n if (c == '[')\n {\n inBrackets = true;\n }\n else if (c == ']')\n {\n inBrackets = false;\n }\n else if (c == '.' && !inBrackets)\n {\n // Found a dot separator outside of brackets\n parts.Add(path.Substring(startIndex, i - startIndex));\n startIndex = i + 1;\n }\n }\n if (startIndex < path.Length)\n {\n parts.Add(path.Substring(startIndex));\n }\n return parts.ToArray();\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types, using JsonSerializer.\n /// \n // Pass the input serializer\n private static object ConvertJTokenToType(JToken token, Type targetType, JsonSerializer inputSerializer)\n {\n if (token == null || token.Type == JTokenType.Null)\n {\n if (targetType.IsValueType && Nullable.GetUnderlyingType(targetType) == null)\n {\n Debug.LogWarning($\"Cannot assign null to non-nullable value type {targetType.Name}. Returning default value.\");\n return Activator.CreateInstance(targetType);\n }\n return null;\n }\n\n try\n {\n // Use the provided serializer instance which includes our custom converters\n return token.ToObject(targetType, inputSerializer);\n }\n catch (JsonSerializationException jsonEx)\n {\n Debug.LogError($\"JSON Deserialization Error converting token to {targetType.FullName}: {jsonEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n // Optionally re-throw or return null/default\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n throw; // Re-throw to indicate failure higher up\n }\n catch (ArgumentException argEx)\n {\n Debug.LogError($\"Argument Error converting token to {targetType.FullName}: {argEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Unexpected error converting token to {targetType.FullName}: {ex}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n // If ToObject succeeded, it would have returned. If it threw, we wouldn't reach here.\n // This fallback logic is likely unreachable if ToObject covers all cases or throws on failure.\n // Debug.LogWarning($\"Conversion failed for token to {targetType.FullName}. Token: {token.ToString(Formatting.None)}\");\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n }\n\n // --- ParseJTokenTo... helpers are likely redundant now with the serializer approach ---\n // Keep them temporarily for reference or if specific fallback logic is ever needed.\n\n private static Vector3 ParseJTokenToVector3(JToken token)\n {\n // ... (implementation - likely replaced by Vector3Converter) ...\n // Consider removing these if the serializer handles them reliably.\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\"))\n {\n return new Vector3(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 3)\n {\n return new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector3 using fallback. Returning Vector3.zero.\");\n return Vector3.zero;\n\n }\n private static Vector2 ParseJTokenToVector2(JToken token)\n {\n // ... (implementation - likely replaced by Vector2Converter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\"))\n {\n return new Vector2(obj[\"x\"].ToObject(), obj[\"y\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 2)\n {\n return new Vector2(arr[0].ToObject(), arr[1].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector2 using fallback. Returning Vector2.zero.\");\n return Vector2.zero;\n }\n private static Quaternion ParseJTokenToQuaternion(JToken token)\n {\n // ... (implementation - likely replaced by QuaternionConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\") && obj.ContainsKey(\"w\"))\n {\n return new Quaternion(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject(), obj[\"w\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Quaternion(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Quaternion using fallback. Returning Quaternion.identity.\");\n return Quaternion.identity;\n }\n private static Color ParseJTokenToColor(JToken token)\n {\n // ... (implementation - likely replaced by ColorConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"r\") && obj.ContainsKey(\"g\") && obj.ContainsKey(\"b\") && obj.ContainsKey(\"a\"))\n {\n return new Color(obj[\"r\"].ToObject(), obj[\"g\"].ToObject(), obj[\"b\"].ToObject(), obj[\"a\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Color(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Color using fallback. Returning Color.white.\");\n return Color.white;\n }\n private static Rect ParseJTokenToRect(JToken token)\n {\n // ... (implementation - likely replaced by RectConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"width\") && obj.ContainsKey(\"height\"))\n {\n return new Rect(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"width\"].ToObject(), obj[\"height\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Rect(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Rect using fallback. Returning Rect.zero.\");\n return Rect.zero;\n }\n private static Bounds ParseJTokenToBounds(JToken token)\n {\n // ... (implementation - likely replaced by BoundsConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"center\") && obj.ContainsKey(\"size\"))\n {\n // Requires Vector3 conversion, which should ideally use the serializer too\n Vector3 center = ParseJTokenToVector3(obj[\"center\"]); // Or use obj[\"center\"].ToObject(inputSerializer)\n Vector3 size = ParseJTokenToVector3(obj[\"size\"]); // Or use obj[\"size\"].ToObject(inputSerializer)\n return new Bounds(center, size);\n }\n // Array fallback for Bounds is less intuitive, maybe remove?\n // if (token is JArray arr && arr.Count >= 6)\n // {\n // return new Bounds(new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject()), new Vector3(arr[3].ToObject(), arr[4].ToObject(), arr[5].ToObject()));\n // }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Bounds using fallback. Returning new Bounds(Vector3.zero, Vector3.zero).\");\n return new Bounds(Vector3.zero, Vector3.zero);\n }\n // --- End Redundant Parse Helpers ---\n\n /// \n /// Finds a specific UnityEngine.Object based on a find instruction JObject.\n /// Primarily used by UnityEngineObjectConverter during deserialization.\n /// \n // Made public static so UnityEngineObjectConverter can call it. Moved from ConvertJTokenToType.\n public static UnityEngine.Object FindObjectByInstruction(JObject instruction, Type targetType)\n {\n string findTerm = instruction[\"find\"]?.ToString();\n string method = instruction[\"method\"]?.ToString()?.ToLower();\n string componentName = instruction[\"component\"]?.ToString(); // Specific component to get\n\n if (string.IsNullOrEmpty(findTerm))\n {\n Debug.LogWarning(\"Find instruction missing 'find' term.\");\n return null;\n }\n\n // Use a flexible default search method if none provided\n string searchMethodToUse = string.IsNullOrEmpty(method) ? \"by_id_or_name_or_path\" : method;\n\n // If the target is an asset (Material, Texture, ScriptableObject etc.) try AssetDatabase first\n if (typeof(Material).IsAssignableFrom(targetType) ||\n typeof(Texture).IsAssignableFrom(targetType) ||\n typeof(ScriptableObject).IsAssignableFrom(targetType) ||\n targetType.FullName.StartsWith(\"UnityEngine.U2D\") || // Sprites etc.\n typeof(AudioClip).IsAssignableFrom(targetType) ||\n typeof(AnimationClip).IsAssignableFrom(targetType) ||\n typeof(Font).IsAssignableFrom(targetType) ||\n typeof(Shader).IsAssignableFrom(targetType) ||\n typeof(ComputeShader).IsAssignableFrom(targetType) ||\n typeof(GameObject).IsAssignableFrom(targetType) && findTerm.StartsWith(\"Assets/\")) // Prefab check\n {\n // Try loading directly by path/GUID first\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(findTerm, targetType);\n if (asset != null) return asset;\n asset = AssetDatabase.LoadAssetAtPath(findTerm); // Try generic if type specific failed\n if (asset != null && targetType.IsAssignableFrom(asset.GetType())) return asset;\n\n\n // If direct path failed, try finding by name/type using FindAssets\n string searchFilter = $\"t:{targetType.Name} {System.IO.Path.GetFileNameWithoutExtension(findTerm)}\"; // Search by type and name\n string[] guids = AssetDatabase.FindAssets(searchFilter);\n\n if (guids.Length == 1)\n {\n asset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]), targetType);\n if (asset != null) return asset;\n }\n else if (guids.Length > 1)\n {\n Debug.LogWarning($\"[FindObjectByInstruction] Ambiguous asset find: Found {guids.Length} assets matching filter '{searchFilter}'. Provide a full path or unique name.\");\n // Optionally return the first one? Or null? Returning null is safer.\n return null;\n }\n // If still not found, fall through to scene search (though unlikely for assets)\n }\n\n\n // --- Scene Object Search ---\n // Find the GameObject using the internal finder\n GameObject foundGo = FindObjectInternal(new JValue(findTerm), searchMethodToUse);\n\n if (foundGo == null)\n {\n // Don't warn yet, could still be an asset not found above\n // Debug.LogWarning($\"Could not find GameObject using instruction: {instruction}\");\n return null;\n }\n\n // Now, get the target object/component from the found GameObject\n if (targetType == typeof(GameObject))\n {\n return foundGo; // We were looking for a GameObject\n }\n else if (typeof(Component).IsAssignableFrom(targetType))\n {\n Type componentToGetType = targetType;\n if (!string.IsNullOrEmpty(componentName))\n {\n Type specificCompType = FindType(componentName);\n if (specificCompType != null && typeof(Component).IsAssignableFrom(specificCompType))\n {\n componentToGetType = specificCompType;\n }\n else\n {\n Debug.LogWarning($\"Could not find component type '{componentName}' specified in find instruction. Falling back to target type '{targetType.Name}'.\");\n }\n }\n\n Component foundComp = foundGo.GetComponent(componentToGetType);\n if (foundComp == null)\n {\n Debug.LogWarning($\"Found GameObject '{foundGo.name}' but could not find component of type '{componentToGetType.Name}'.\");\n }\n return foundComp;\n }\n else\n {\n Debug.LogWarning($\"Find instruction handling not implemented for target type: {targetType.Name}\");\n return null;\n }\n }\n\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Handle fully qualified names first\n Type type = Type.GetType(typeName);\n if (type != null) return type;\n\n // Handle common namespaces implicitly (add more as needed)\n string[] namespaces = { \"UnityEngine\", \"UnityEngine.UI\", \"UnityEngine.AI\", \"UnityEngine.Animations\", \"UnityEngine.Audio\", \"UnityEngine.EventSystems\", \"UnityEngine.InputSystem\", \"UnityEngine.Networking\", \"UnityEngine.Rendering\", \"UnityEngine.SceneManagement\", \"UnityEngine.Tilemaps\", \"UnityEngine.U2D\", \"UnityEngine.Video\", \"UnityEditor\", \"UnityEditor.AI\", \"UnityEditor.Animations\", \"UnityEditor.Experimental.GraphView\", \"UnityEditor.IMGUI.Controls\", \"UnityEditor.PackageManager.UI\", \"UnityEditor.SceneManagement\", \"UnityEditor.UI\", \"UnityEditor.U2D\", \"UnityEditor.VersionControl\" }; // Add more relevant namespaces\n\n foreach (string ns in namespaces) {\n type = Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}.CoreModule\") ?? // Heuristic: Check CoreModule first for UnityEngine/UnityEditor\n Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}\"); // Try assembly matching namespace root\n if (type != null) return type;\n }\n\n\n // If not found, search all loaded assemblies (slower, last resort)\n // Prioritize assemblies likely to contain game/editor types\n Assembly[] priorityAssemblies = {\n Assembly.Load(\"Assembly-CSharp\"), // Main game scripts\n Assembly.Load(\"Assembly-CSharp-Editor\"), // Main editor scripts\n // Add other important project assemblies if known\n };\n foreach (var assembly in priorityAssemblies.Where(a => a != null))\n {\n type = assembly.GetType(typeName) ?? assembly.GetType(\"UnityEngine.\" + typeName) ?? assembly.GetType(\"UnityEditor.\" + typeName);\n if (type != null) return type;\n }\n\n // Search remaining assemblies\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Except(priorityAssemblies))\n {\n try { // Protect against assembly loading errors\n type = assembly.GetType(typeName);\n if (type != null) return type;\n // Also check with common namespaces if simple name given\n foreach (string ns in namespaces) {\n type = assembly.GetType($\"{ns}.{typeName}\");\n if (type != null) return type;\n }\n } catch (Exception ex) {\n Debug.LogWarning($\"[FindType] Error searching assembly {assembly.FullName}: {ex.Message}\");\n }\n }\n\n Debug.LogWarning($\"[FindType] Type not found after extensive search: '{typeName}'\");\n return null; // Not found\n }\n\n /// \n /// Parses a JArray like [x, y, z] into a Vector3.\n /// \n private static Vector3? ParseVector3(JArray array)\n {\n if (array != null && array.Count == 3)\n {\n try\n {\n // Use ToObject for potentially better handling than direct indexing\n return new Vector3(\n array[0].ToObject(),\n array[1].ToObject(),\n array[2].ToObject()\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Failed to parse JArray as Vector3: {array}. Error: {ex.Message}\");\n }\n }\n return null;\n }\n\n // Removed GetGameObjectData, GetComponentData, and related private helpers/caching/serializer setup.\n // They are now in Helpers.GameObjectSerializer\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/UnityMcpBridge.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\nusing UnityMcpBridge.Editor.Tools;\n\nnamespace UnityMcpBridge.Editor\n{\n [InitializeOnLoad]\n public static partial class UnityMcpBridge\n {\n private static TcpListener listener;\n private static bool isRunning = false;\n private static readonly object lockObj = new();\n private static Dictionary<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > commandQueue = new();\n private static readonly int unityPort = 6400; // Hardcoded port\n\n public static bool IsRunning => isRunning;\n\n public static bool FolderExists(string path)\n {\n if (string.IsNullOrEmpty(path))\n {\n return false;\n }\n\n if (path.Equals(\"Assets\", StringComparison.OrdinalIgnoreCase))\n {\n return true;\n }\n\n string fullPath = Path.Combine(\n Application.dataPath,\n path.StartsWith(\"Assets/\") ? path[7..] : path\n );\n return Directory.Exists(fullPath);\n }\n\n static UnityMcpBridge()\n {\n Start();\n EditorApplication.quitting += Stop;\n }\n\n public static void Start()\n {\n Stop();\n\n try\n {\n ServerInstaller.EnsureServerInstalled();\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure UnityMcpServer is installed: {ex.Message}\");\n }\n\n if (isRunning)\n {\n return;\n }\n\n try\n {\n listener = new TcpListener(IPAddress.Loopback, unityPort);\n listener.Start();\n isRunning = true;\n Debug.Log($\"UnityMcpBridge started on port {unityPort}.\");\n // Assuming ListenerLoop and ProcessCommands are defined elsewhere\n Task.Run(ListenerLoop);\n EditorApplication.update += ProcessCommands;\n }\n catch (SocketException ex)\n {\n if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)\n {\n Debug.LogError(\n $\"Port {unityPort} is already in use. Ensure no other instances are running or change the port.\"\n );\n }\n else\n {\n Debug.LogError($\"Failed to start TCP listener: {ex.Message}\");\n }\n }\n }\n\n public static void Stop()\n {\n if (!isRunning)\n {\n return;\n }\n\n try\n {\n listener?.Stop();\n listener = null;\n isRunning = false;\n EditorApplication.update -= ProcessCommands;\n Debug.Log(\"UnityMcpBridge stopped.\");\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error stopping UnityMcpBridge: {ex.Message}\");\n }\n }\n\n private static async Task ListenerLoop()\n {\n while (isRunning)\n {\n try\n {\n TcpClient client = await listener.AcceptTcpClientAsync();\n // Enable basic socket keepalive\n client.Client.SetSocketOption(\n SocketOptionLevel.Socket,\n SocketOptionName.KeepAlive,\n true\n );\n\n // Set longer receive timeout to prevent quick disconnections\n client.ReceiveTimeout = 60000; // 60 seconds\n\n // Fire and forget each client connection\n _ = HandleClientAsync(client);\n }\n catch (Exception ex)\n {\n if (isRunning)\n {\n Debug.LogError($\"Listener error: {ex.Message}\");\n }\n }\n }\n }\n\n private static async Task HandleClientAsync(TcpClient client)\n {\n using (client)\n using (NetworkStream stream = client.GetStream())\n {\n byte[] buffer = new byte[8192];\n while (isRunning)\n {\n try\n {\n int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);\n if (bytesRead == 0)\n {\n break; // Client disconnected\n }\n\n string commandText = System.Text.Encoding.UTF8.GetString(\n buffer,\n 0,\n bytesRead\n );\n string commandId = Guid.NewGuid().ToString();\n TaskCompletionSource tcs = new();\n\n // Special handling for ping command to avoid JSON parsing\n if (commandText.Trim() == \"ping\")\n {\n // Direct response to ping without going through JSON parsing\n byte[] pingResponseBytes = System.Text.Encoding.UTF8.GetBytes(\n /*lang=json,strict*/\n \"{\\\"status\\\":\\\"success\\\",\\\"result\\\":{\\\"message\\\":\\\"pong\\\"}}\"\n );\n await stream.WriteAsync(pingResponseBytes, 0, pingResponseBytes.Length);\n continue;\n }\n\n lock (lockObj)\n {\n commandQueue[commandId] = (commandText, tcs);\n }\n\n string response = await tcs.Task;\n byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);\n await stream.WriteAsync(responseBytes, 0, responseBytes.Length);\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Client handler error: {ex.Message}\");\n break;\n }\n }\n }\n }\n\n private static void ProcessCommands()\n {\n List processedIds = new();\n lock (lockObj)\n {\n foreach (\n KeyValuePair<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > kvp in commandQueue.ToList()\n )\n {\n string id = kvp.Key;\n string commandText = kvp.Value.commandJson;\n TaskCompletionSource tcs = kvp.Value.tcs;\n\n try\n {\n // Special case handling\n if (string.IsNullOrEmpty(commandText))\n {\n var emptyResponse = new\n {\n status = \"error\",\n error = \"Empty command received\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(emptyResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Trim the command text to remove any whitespace\n commandText = commandText.Trim();\n\n // Non-JSON direct commands handling (like ping)\n if (commandText == \"ping\")\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n tcs.SetResult(JsonConvert.SerializeObject(pingResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Check if the command is valid JSON before attempting to deserialize\n if (!IsValidJson(commandText))\n {\n var invalidJsonResponse = new\n {\n status = \"error\",\n error = \"Invalid JSON format\",\n receivedText = commandText.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n tcs.SetResult(JsonConvert.SerializeObject(invalidJsonResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Normal JSON command processing\n Command command = JsonConvert.DeserializeObject(commandText);\n \n if (command == null)\n {\n var nullCommandResponse = new\n {\n status = \"error\",\n error = \"Command deserialized to null\",\n details = \"The command was valid JSON but could not be deserialized to a Command object\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(nullCommandResponse));\n }\n else\n {\n string responseJson = ExecuteCommand(command);\n tcs.SetResult(responseJson);\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error processing command: {ex.Message}\\n{ex.StackTrace}\");\n\n var response = new\n {\n status = \"error\",\n error = ex.Message,\n commandType = \"Unknown (error during processing)\",\n receivedText = commandText?.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n string responseJson = JsonConvert.SerializeObject(response);\n tcs.SetResult(responseJson);\n }\n\n processedIds.Add(id);\n }\n\n foreach (string id in processedIds)\n {\n commandQueue.Remove(id);\n }\n }\n }\n\n // Helper method to check if a string is valid JSON\n private static bool IsValidJson(string text)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n return false;\n }\n\n text = text.Trim();\n if (\n (text.StartsWith(\"{\") && text.EndsWith(\"}\"))\n || // Object\n (text.StartsWith(\"[\") && text.EndsWith(\"]\"))\n ) // Array\n {\n try\n {\n JToken.Parse(text);\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n return false;\n }\n\n private static string ExecuteCommand(Command command)\n {\n try\n {\n if (string.IsNullOrEmpty(command.type))\n {\n var errorResponse = new\n {\n status = \"error\",\n error = \"Command type cannot be empty\",\n details = \"A valid command type is required for processing\",\n };\n return JsonConvert.SerializeObject(errorResponse);\n }\n\n // Handle ping command for connection verification\n if (command.type.Equals(\"ping\", StringComparison.OrdinalIgnoreCase))\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n return JsonConvert.SerializeObject(pingResponse);\n }\n\n // Use JObject for parameters as the new handlers likely expect this\n JObject paramsObject = command.@params ?? new JObject();\n\n // Route command based on the new tool structure from the refactor plan\n object result = command.type switch\n {\n // Maps the command type (tool name) to the corresponding handler's static HandleCommand method\n // Assumes each handler class has a static method named 'HandleCommand' that takes JObject parameters\n \"manage_script\" => ManageScript.HandleCommand(paramsObject),\n \"manage_scene\" => ManageScene.HandleCommand(paramsObject),\n \"manage_editor\" => ManageEditor.HandleCommand(paramsObject),\n \"manage_gameobject\" => ManageGameObject.HandleCommand(paramsObject),\n \"manage_asset\" => ManageAsset.HandleCommand(paramsObject),\n \"manage_shader\" => ManageShader.HandleCommand(paramsObject),\n \"read_console\" => ReadConsole.HandleCommand(paramsObject),\n \"execute_menu_item\" => ExecuteMenuItem.HandleCommand(paramsObject),\n _ => throw new ArgumentException(\n $\"Unknown or unsupported command type: {command.type}\"\n ),\n };\n\n // Standard success response format\n var response = new { status = \"success\", result };\n return JsonConvert.SerializeObject(response);\n }\n catch (Exception ex)\n {\n // Log the detailed error in Unity for debugging\n Debug.LogError(\n $\"Error executing command '{command?.type ?? \"Unknown\"}': {ex.Message}\\n{ex.StackTrace}\"\n );\n\n // Standard error response format\n var response = new\n {\n status = \"error\",\n error = ex.Message, // Provide the specific error message\n command = command?.type ?? \"Unknown\", // Include the command type if available\n stackTrace = ex.StackTrace, // Include stack trace for detailed debugging\n paramsSummary = command?.@params != null\n ? GetParamsSummary(command.@params)\n : \"No parameters\", // Summarize parameters for context\n };\n return JsonConvert.SerializeObject(response);\n }\n }\n\n // Helper method to get a summary of parameters for error reporting\n private static string GetParamsSummary(JObject @params)\n {\n try\n {\n return @params == null || !@params.HasValues\n ? \"No parameters\"\n : string.Join(\n \", \",\n @params\n .Properties()\n .Select(static p =>\n $\"{p.Name}: {p.Value?.ToString()?[..Math.Min(20, p.Value?.ToString()?.Length ?? 0)]}\"\n )\n );\n }\n catch\n {\n return \"Could not summarize parameters\";\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScript.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\n#if USE_ROSLYN\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\n#endif\n\n#if UNITY_EDITOR\nusing UnityEditor.Compilation;\n#endif\n\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for C# scripts within the Unity project.\n /// \n /// ROSLYN INSTALLATION GUIDE:\n /// To enable advanced syntax validation with Roslyn compiler services:\n /// \n /// 1. Install Microsoft.CodeAnalysis.CSharp NuGet package:\n /// - Open Package Manager in Unity\n /// - Follow the instruction on https://github.com/GlitchEnzo/NuGetForUnity\n /// \n /// 2. Open NuGet Package Manager and Install Microsoft.CodeAnalysis.CSharp:\n /// \n /// 3. Alternative: Manual DLL installation:\n /// - Download Microsoft.CodeAnalysis.CSharp.dll and dependencies\n /// - Place in Assets/Plugins/ folder\n /// - Ensure .NET compatibility settings are correct\n /// \n /// 4. Define USE_ROSLYN symbol:\n /// - Go to Player Settings > Scripting Define Symbols\n /// - Add \"USE_ROSLYN\" to enable Roslyn-based validation\n /// \n /// 5. Restart Unity after installation\n /// \n /// Note: Without Roslyn, the system falls back to basic structural validation.\n /// Roslyn provides full C# compiler diagnostics with line numbers and detailed error messages.\n /// \n public static class ManageScript\n {\n /// \n /// Main handler for script management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode script contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n string scriptType = @params[\"scriptType\"]?.ToString(); // For templates/validation\n string namespaceName = @params[\"namespace\"]?.ToString(); // For organizing code\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid script name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Scripts\" if path is not provided\n string relativeDir = path ?? \"Scripts\"; // Default to \"Scripts\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Scripts\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string scriptFileName = $\"{name}.cs\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Application.dataPath ends in \"Assets\"\n string fullPath = Path.Combine(fullPathDir, scriptFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, scriptFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateScript(\n fullPath,\n relativePath,\n name,\n contents,\n scriptType,\n namespaceName\n );\n case \"read\":\n return ReadScript(fullPath, relativePath);\n case \"update\":\n return UpdateScript(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteScript(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents,\n string scriptType,\n string namespaceName\n )\n {\n // Check if script already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultScriptContent(name, scriptType, namespaceName);\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block creation\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new script\n return Response.Success(\n $\"Script '{name}.cs' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script not found at '{relativePath}'. Use 'create' action to add a new script.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block update\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath); // Re-import to reflect changes\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{name}.cs' updated successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'. Cannot delete.\");\n }\n\n try\n {\n // Use AssetDatabase.MoveAssetToTrash for safer deletion (allows undo)\n bool deleted = AssetDatabase.MoveAssetToTrash(relativePath);\n if (deleted)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' moved to trash successfully.\"\n );\n }\n else\n {\n // Fallback or error if MoveAssetToTrash fails\n return Response.Error(\n $\"Failed to move script '{relativePath}' to trash. It might be locked or in use.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting script '{relativePath}': {e.Message}\");\n }\n }\n\n /// \n /// Generates basic C# script content based on name and type.\n /// \n private static string GenerateDefaultScriptContent(\n string name,\n string scriptType,\n string namespaceName\n )\n {\n string usingStatements = \"using UnityEngine;\\nusing System.Collections;\\n\";\n string classDeclaration;\n string body =\n \"\\n // Use this for initialization\\n void Start() {\\n\\n }\\n\\n // Update is called once per frame\\n void Update() {\\n\\n }\\n\";\n\n string baseClass = \"\";\n if (!string.IsNullOrEmpty(scriptType))\n {\n if (scriptType.Equals(\"MonoBehaviour\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : MonoBehaviour\";\n else if (scriptType.Equals(\"ScriptableObject\", StringComparison.OrdinalIgnoreCase))\n {\n baseClass = \" : ScriptableObject\";\n body = \"\"; // ScriptableObjects don't usually need Start/Update\n }\n else if (\n scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase)\n || scriptType.Equals(\"EditorWindow\", StringComparison.OrdinalIgnoreCase)\n )\n {\n usingStatements += \"using UnityEditor;\\n\";\n if (scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : Editor\";\n else\n baseClass = \" : EditorWindow\";\n body = \"\"; // Editor scripts have different structures\n }\n // Add more types as needed\n }\n\n classDeclaration = $\"public class {name}{baseClass}\";\n\n string fullContent = $\"{usingStatements}\\n\";\n bool useNamespace = !string.IsNullOrEmpty(namespaceName);\n\n if (useNamespace)\n {\n fullContent += $\"namespace {namespaceName}\\n{{\\n\";\n // Indent class and body if using namespace\n classDeclaration = \" \" + classDeclaration;\n body = string.Join(\"\\n\", body.Split('\\n').Select(line => \" \" + line));\n }\n\n fullContent += $\"{classDeclaration}\\n{{\\n{body}\\n}}\";\n\n if (useNamespace)\n {\n fullContent += \"\\n}\"; // Close namespace\n }\n\n return fullContent.Trim() + \"\\n\"; // Ensure a trailing newline\n }\n\n /// \n /// Gets the validation level from the GUI settings\n /// \n private static ValidationLevel GetValidationLevelFromGUI()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel.ToLower() switch\n {\n \"basic\" => ValidationLevel.Basic,\n \"standard\" => ValidationLevel.Standard,\n \"comprehensive\" => ValidationLevel.Comprehensive,\n \"strict\" => ValidationLevel.Strict,\n _ => ValidationLevel.Standard // Default fallback\n };\n }\n\n /// \n /// Validates C# script syntax using multiple validation layers.\n /// \n private static bool ValidateScriptSyntax(string contents)\n {\n return ValidateScriptSyntax(contents, ValidationLevel.Standard, out _);\n }\n\n /// \n /// Advanced syntax validation with detailed diagnostics and configurable strictness.\n /// \n private static bool ValidateScriptSyntax(string contents, ValidationLevel level, out string[] errors)\n {\n var errorList = new System.Collections.Generic.List();\n errors = null;\n\n if (string.IsNullOrEmpty(contents))\n {\n return true; // Empty content is valid\n }\n\n // Basic structural validation\n if (!ValidateBasicStructure(contents, errorList))\n {\n errors = errorList.ToArray();\n return false;\n }\n\n#if USE_ROSLYN\n // Advanced Roslyn-based validation\n if (!ValidateScriptSyntaxRoslyn(contents, level, errorList))\n {\n errors = errorList.ToArray();\n return level != ValidationLevel.Standard; //TODO: Allow standard to run roslyn right now, might formalize it in the future\n }\n#endif\n\n // Unity-specific validation\n if (level >= ValidationLevel.Standard)\n {\n ValidateScriptSyntaxUnity(contents, errorList);\n }\n\n // Semantic analysis for common issues\n if (level >= ValidationLevel.Comprehensive)\n {\n ValidateSemanticRules(contents, errorList);\n }\n\n#if USE_ROSLYN\n // Full semantic compilation validation for Strict level\n if (level == ValidationLevel.Strict)\n {\n if (!ValidateScriptSemantics(contents, errorList))\n {\n errors = errorList.ToArray();\n return false; // Strict level fails on any semantic errors\n }\n }\n#endif\n\n errors = errorList.ToArray();\n return errorList.Count == 0 || (level != ValidationLevel.Strict && !errorList.Any(e => e.StartsWith(\"ERROR:\")));\n }\n\n /// \n /// Validation strictness levels\n /// \n private enum ValidationLevel\n {\n Basic, // Only syntax errors\n Standard, // Syntax + Unity best practices\n Comprehensive, // All checks + semantic analysis\n Strict // Treat all issues as errors\n }\n\n /// \n /// Validates basic code structure (braces, quotes, comments)\n /// \n private static bool ValidateBasicStructure(string contents, System.Collections.Generic.List errors)\n {\n bool isValid = true;\n int braceBalance = 0;\n int parenBalance = 0;\n int bracketBalance = 0;\n bool inStringLiteral = false;\n bool inCharLiteral = false;\n bool inSingleLineComment = false;\n bool inMultiLineComment = false;\n bool escaped = false;\n\n for (int i = 0; i < contents.Length; i++)\n {\n char c = contents[i];\n char next = i + 1 < contents.Length ? contents[i + 1] : '\\0';\n\n // Handle escape sequences\n if (escaped)\n {\n escaped = false;\n continue;\n }\n\n if (c == '\\\\' && (inStringLiteral || inCharLiteral))\n {\n escaped = true;\n continue;\n }\n\n // Handle comments\n if (!inStringLiteral && !inCharLiteral)\n {\n if (c == '/' && next == '/' && !inMultiLineComment)\n {\n inSingleLineComment = true;\n continue;\n }\n if (c == '/' && next == '*' && !inSingleLineComment)\n {\n inMultiLineComment = true;\n i++; // Skip next character\n continue;\n }\n if (c == '*' && next == '/' && inMultiLineComment)\n {\n inMultiLineComment = false;\n i++; // Skip next character\n continue;\n }\n }\n\n if (c == '\\n')\n {\n inSingleLineComment = false;\n continue;\n }\n\n if (inSingleLineComment || inMultiLineComment)\n continue;\n\n // Handle string and character literals\n if (c == '\"' && !inCharLiteral)\n {\n inStringLiteral = !inStringLiteral;\n continue;\n }\n if (c == '\\'' && !inStringLiteral)\n {\n inCharLiteral = !inCharLiteral;\n continue;\n }\n\n if (inStringLiteral || inCharLiteral)\n continue;\n\n // Count brackets and braces\n switch (c)\n {\n case '{': braceBalance++; break;\n case '}': braceBalance--; break;\n case '(': parenBalance++; break;\n case ')': parenBalance--; break;\n case '[': bracketBalance++; break;\n case ']': bracketBalance--; break;\n }\n\n // Check for negative balances (closing without opening)\n if (braceBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing brace '}'\");\n isValid = false;\n }\n if (parenBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing parenthesis ')'\");\n isValid = false;\n }\n if (bracketBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing bracket ']'\");\n isValid = false;\n }\n }\n\n // Check final balances\n if (braceBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced braces (difference: {braceBalance})\");\n isValid = false;\n }\n if (parenBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced parentheses (difference: {parenBalance})\");\n isValid = false;\n }\n if (bracketBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced brackets (difference: {bracketBalance})\");\n isValid = false;\n }\n if (inStringLiteral)\n {\n errors.Add(\"ERROR: Unterminated string literal\");\n isValid = false;\n }\n if (inCharLiteral)\n {\n errors.Add(\"ERROR: Unterminated character literal\");\n isValid = false;\n }\n if (inMultiLineComment)\n {\n errors.Add(\"WARNING: Unterminated multi-line comment\");\n }\n\n return isValid;\n }\n\n#if USE_ROSLYN\n /// \n /// Cached compilation references for performance\n /// \n private static System.Collections.Generic.List _cachedReferences = null;\n private static DateTime _cacheTime = DateTime.MinValue;\n private static readonly TimeSpan CacheExpiry = TimeSpan.FromMinutes(5);\n\n /// \n /// Validates syntax using Roslyn compiler services\n /// \n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n try\n {\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n var diagnostics = syntaxTree.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n string severity = diagnostic.Severity.ToString().ToUpper();\n string message = $\"{severity}: {diagnostic.GetMessage()}\";\n \n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n }\n \n // Include warnings in comprehensive mode\n if (level >= ValidationLevel.Standard || diagnostic.Severity == DiagnosticSeverity.Error) //Also use Standard for now\n {\n var location = diagnostic.Location.GetLineSpan();\n if (location.IsValid)\n {\n message += $\" (Line {location.StartLinePosition.Line + 1})\";\n }\n errors.Add(message);\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Roslyn validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Validates script semantics using full compilation context to catch namespace, type, and method resolution errors\n /// \n private static bool ValidateScriptSemantics(string contents, System.Collections.Generic.List errors)\n {\n try\n {\n // Get compilation references with caching\n var references = GetCompilationReferences();\n if (references == null || references.Count == 0)\n {\n errors.Add(\"WARNING: Could not load compilation references for semantic validation\");\n return true; // Don't fail if we can't get references\n }\n\n // Create syntax tree\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n\n // Create compilation with full context\n var compilation = CSharpCompilation.Create(\n \"TempValidation\",\n new[] { syntaxTree },\n references,\n new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)\n );\n\n // Get semantic diagnostics - this catches all the issues you mentioned!\n var diagnostics = compilation.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n // Include diagnostic ID for better error identification\n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"ERROR: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n else if (diagnostic.Severity == DiagnosticSeverity.Warning)\n {\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"WARNING: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Semantic validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets compilation references with caching for performance\n /// \n private static System.Collections.Generic.List GetCompilationReferences()\n {\n // Check cache validity\n if (_cachedReferences != null && DateTime.Now - _cacheTime < CacheExpiry)\n {\n return _cachedReferences;\n }\n\n try\n {\n var references = new System.Collections.Generic.List();\n\n // Core .NET assemblies\n references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); // mscorlib/System.Private.CoreLib\n references.Add(MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location)); // System.Linq\n references.Add(MetadataReference.CreateFromFile(typeof(System.Collections.Generic.List<>).Assembly.Location)); // System.Collections\n\n // Unity assemblies\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEngine.Debug).Assembly.Location)); // UnityEngine\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEngine assembly: {ex.Message}\");\n }\n\n#if UNITY_EDITOR\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEditor.Editor).Assembly.Location)); // UnityEditor\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEditor assembly: {ex.Message}\");\n }\n\n // Get Unity project assemblies\n try\n {\n var assemblies = CompilationPipeline.GetAssemblies();\n foreach (var assembly in assemblies)\n {\n if (File.Exists(assembly.outputPath))\n {\n references.Add(MetadataReference.CreateFromFile(assembly.outputPath));\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load Unity project assemblies: {ex.Message}\");\n }\n#endif\n\n // Cache the results\n _cachedReferences = references;\n _cacheTime = DateTime.Now;\n\n return references;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to get compilation references: {ex.Message}\");\n return new System.Collections.Generic.List();\n }\n }\n#else\n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n // Fallback when Roslyn is not available\n return true;\n }\n#endif\n\n /// \n /// Validates Unity-specific coding rules and best practices\n /// //TODO: Naive Unity Checks and not really yield any results, need to be improved\n /// \n private static void ValidateScriptSyntaxUnity(string contents, System.Collections.Generic.List errors)\n {\n // Check for common Unity anti-patterns\n if (contents.Contains(\"FindObjectOfType\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: FindObjectOfType in Update() can cause performance issues\");\n }\n\n if (contents.Contains(\"GameObject.Find\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: GameObject.Find in Update() can cause performance issues\");\n }\n\n // Check for proper MonoBehaviour usage\n if (contents.Contains(\": MonoBehaviour\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: MonoBehaviour requires 'using UnityEngine;'\");\n }\n\n // Check for SerializeField usage\n if (contents.Contains(\"[SerializeField]\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: SerializeField requires 'using UnityEngine;'\");\n }\n\n // Check for proper coroutine usage\n if (contents.Contains(\"StartCoroutine\") && !contents.Contains(\"IEnumerator\"))\n {\n errors.Add(\"WARNING: StartCoroutine typically requires IEnumerator methods\");\n }\n\n // Check for Update without FixedUpdate for physics\n if (contents.Contains(\"Rigidbody\") && contents.Contains(\"Update()\") && !contents.Contains(\"FixedUpdate()\"))\n {\n errors.Add(\"WARNING: Consider using FixedUpdate() for Rigidbody operations\");\n }\n\n // Check for missing null checks on Unity objects\n if (contents.Contains(\"GetComponent<\") && !contents.Contains(\"!= null\"))\n {\n errors.Add(\"WARNING: Consider null checking GetComponent results\");\n }\n\n // Check for proper event function signatures\n if (contents.Contains(\"void Start(\") && !contents.Contains(\"void Start()\"))\n {\n errors.Add(\"WARNING: Start() should not have parameters\");\n }\n\n if (contents.Contains(\"void Update(\") && !contents.Contains(\"void Update()\"))\n {\n errors.Add(\"WARNING: Update() should not have parameters\");\n }\n\n // Check for inefficient string operations\n if (contents.Contains(\"Update()\") && contents.Contains(\"\\\"\") && contents.Contains(\"+\"))\n {\n errors.Add(\"WARNING: String concatenation in Update() can cause garbage collection issues\");\n }\n }\n\n /// \n /// Validates semantic rules and common coding issues\n /// \n private static void ValidateSemanticRules(string contents, System.Collections.Generic.List errors)\n {\n // Check for potential memory leaks\n if (contents.Contains(\"new \") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: Creating objects in Update() may cause memory issues\");\n }\n\n // Check for magic numbers\n var magicNumberPattern = new Regex(@\"\\b\\d+\\.?\\d*f?\\b(?!\\s*[;})\\]])\");\n var matches = magicNumberPattern.Matches(contents);\n if (matches.Count > 5)\n {\n errors.Add(\"WARNING: Consider using named constants instead of magic numbers\");\n }\n\n // Check for long methods (simple line count check)\n var methodPattern = new Regex(@\"(public|private|protected|internal)?\\s*(static)?\\s*\\w+\\s+\\w+\\s*\\([^)]*\\)\\s*{\");\n var methodMatches = methodPattern.Matches(contents);\n foreach (Match match in methodMatches)\n {\n int startIndex = match.Index;\n int braceCount = 0;\n int lineCount = 0;\n bool inMethod = false;\n\n for (int i = startIndex; i < contents.Length; i++)\n {\n if (contents[i] == '{')\n {\n braceCount++;\n inMethod = true;\n }\n else if (contents[i] == '}')\n {\n braceCount--;\n if (braceCount == 0 && inMethod)\n break;\n }\n else if (contents[i] == '\\n' && inMethod)\n {\n lineCount++;\n }\n }\n\n if (lineCount > 50)\n {\n errors.Add(\"WARNING: Method is very long, consider breaking it into smaller methods\");\n break; // Only report once\n }\n }\n\n // Check for proper exception handling\n if (contents.Contains(\"catch\") && contents.Contains(\"catch()\"))\n {\n errors.Add(\"WARNING: Empty catch blocks should be avoided\");\n }\n\n // Check for proper async/await usage\n if (contents.Contains(\"async \") && !contents.Contains(\"await\"))\n {\n errors.Add(\"WARNING: Async method should contain await or return Task\");\n }\n\n // Check for hardcoded tags and layers\n if (contents.Contains(\"\\\"Player\\\"\") || contents.Contains(\"\\\"Enemy\\\"\"))\n {\n errors.Add(\"WARNING: Consider using constants for tags instead of hardcoded strings\");\n }\n }\n\n //TODO: A easier way for users to update incorrect scripts (now duplicated with the updateScript method and need to also update server side, put aside for now)\n /// \n /// Public method to validate script syntax with configurable validation level\n /// Returns detailed validation results including errors and warnings\n /// \n // public static object ValidateScript(JObject @params)\n // {\n // string contents = @params[\"contents\"]?.ToString();\n // string validationLevel = @params[\"validationLevel\"]?.ToString() ?? \"standard\";\n\n // if (string.IsNullOrEmpty(contents))\n // {\n // return Response.Error(\"Contents parameter is required for validation.\");\n // }\n\n // // Parse validation level\n // ValidationLevel level = ValidationLevel.Standard;\n // switch (validationLevel.ToLower())\n // {\n // case \"basic\": level = ValidationLevel.Basic; break;\n // case \"standard\": level = ValidationLevel.Standard; break;\n // case \"comprehensive\": level = ValidationLevel.Comprehensive; break;\n // case \"strict\": level = ValidationLevel.Strict; break;\n // default:\n // return Response.Error($\"Invalid validation level: '{validationLevel}'. Valid levels are: basic, standard, comprehensive, strict.\");\n // }\n\n // // Perform validation\n // bool isValid = ValidateScriptSyntax(contents, level, out string[] validationErrors);\n\n // var errors = validationErrors?.Where(e => e.StartsWith(\"ERROR:\")).ToArray() ?? new string[0];\n // var warnings = validationErrors?.Where(e => e.StartsWith(\"WARNING:\")).ToArray() ?? new string[0];\n\n // var result = new\n // {\n // isValid = isValid,\n // validationLevel = validationLevel,\n // errorCount = errors.Length,\n // warningCount = warnings.Length,\n // errors = errors,\n // warnings = warnings,\n // summary = isValid \n // ? (warnings.Length > 0 ? $\"Validation passed with {warnings.Length} warnings\" : \"Validation passed with no issues\")\n // : $\"Validation failed with {errors.Length} errors and {warnings.Length} warnings\"\n // };\n\n // if (isValid)\n // {\n // return Response.Success(\"Script validation completed successfully.\", result);\n // }\n // else\n // {\n // return Response.Error(\"Script validation failed.\", result);\n // }\n // }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/ServerInstaller.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Runtime.InteropServices;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n public static class ServerInstaller\n {\n private const string RootFolder = \"UnityMCP\";\n private const string ServerFolder = \"UnityMcpServer\";\n private const string BranchName = \"master\";\n private const string GitUrl = \"https://github.com/justinpbarnett/unity-mcp.git\";\n private const string PyprojectUrl =\n \"https://raw.githubusercontent.com/justinpbarnett/unity-mcp/refs/heads/\"\n + BranchName\n + \"/UnityMcpServer/src/pyproject.toml\";\n\n /// \n /// Ensures the unity-mcp-server is installed and up to date.\n /// \n public static void EnsureServerInstalled()\n {\n try\n {\n string saveLocation = GetSaveLocation();\n\n if (!IsServerInstalled(saveLocation))\n {\n InstallServer(saveLocation);\n }\n else\n {\n string installedVersion = GetInstalledVersion();\n string latestVersion = GetLatestVersion();\n\n if (IsNewerVersion(latestVersion, installedVersion))\n {\n UpdateServer(saveLocation);\n }\n else { }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure server installation: {ex.Message}\");\n }\n }\n\n public static string GetServerPath()\n {\n return Path.Combine(GetSaveLocation(), ServerFolder, \"src\");\n }\n\n /// \n /// Gets the platform-specific save location for the server.\n /// \n private static string GetSaveLocation()\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"AppData\",\n \"Local\",\n \"Programs\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"bin\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n string path = \"/usr/local/bin\";\n return !Directory.Exists(path) || !IsDirectoryWritable(path)\n ? Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Applications\",\n RootFolder\n )\n : Path.Combine(path, RootFolder);\n }\n throw new Exception(\"Unsupported operating system.\");\n }\n\n private static bool IsDirectoryWritable(string path)\n {\n try\n {\n File.Create(Path.Combine(path, \"test.txt\")).Dispose();\n File.Delete(Path.Combine(path, \"test.txt\"));\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Checks if the server is installed at the specified location.\n /// \n private static bool IsServerInstalled(string location)\n {\n return Directory.Exists(location)\n && File.Exists(Path.Combine(location, ServerFolder, \"src\", \"pyproject.toml\"));\n }\n\n /// \n /// Installs the server by cloning only the UnityMcpServer folder from the repository and setting up dependencies.\n /// \n private static void InstallServer(string location)\n {\n // Create the src directory where the server code will reside\n Directory.CreateDirectory(location);\n\n // Initialize git repo in the src directory\n RunCommand(\"git\", $\"init\", workingDirectory: location);\n\n // Add remote\n RunCommand(\"git\", $\"remote add origin {GitUrl}\", workingDirectory: location);\n\n // Configure sparse checkout\n RunCommand(\"git\", \"config core.sparseCheckout true\", workingDirectory: location);\n\n // Set sparse checkout path to only include UnityMcpServer folder\n string sparseCheckoutPath = Path.Combine(location, \".git\", \"info\", \"sparse-checkout\");\n File.WriteAllText(sparseCheckoutPath, $\"{ServerFolder}/\");\n\n // Fetch and checkout the branch\n RunCommand(\"git\", $\"fetch --depth=1 origin {BranchName}\", workingDirectory: location);\n RunCommand(\"git\", $\"checkout {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Fetches the currently installed version from the local pyproject.toml file.\n /// \n public static string GetInstalledVersion()\n {\n string pyprojectPath = Path.Combine(\n GetSaveLocation(),\n ServerFolder,\n \"src\",\n \"pyproject.toml\"\n );\n return ParseVersionFromPyproject(File.ReadAllText(pyprojectPath));\n }\n\n /// \n /// Fetches the latest version from the GitHub pyproject.toml file.\n /// \n public static string GetLatestVersion()\n {\n using WebClient webClient = new();\n string pyprojectContent = webClient.DownloadString(PyprojectUrl);\n return ParseVersionFromPyproject(pyprojectContent);\n }\n\n /// \n /// Updates the server by pulling the latest changes for the UnityMcpServer folder only.\n /// \n private static void UpdateServer(string location)\n {\n RunCommand(\"git\", $\"pull origin {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Parses the version number from pyproject.toml content.\n /// \n private static string ParseVersionFromPyproject(string content)\n {\n foreach (string line in content.Split('\\n'))\n {\n if (line.Trim().StartsWith(\"version =\"))\n {\n string[] parts = line.Split('=');\n if (parts.Length == 2)\n {\n return parts[1].Trim().Trim('\"');\n }\n }\n }\n throw new Exception(\"Version not found in pyproject.toml\");\n }\n\n /// \n /// Compares two version strings to determine if the latest is newer.\n /// \n public static bool IsNewerVersion(string latest, string installed)\n {\n int[] latestParts = latest.Split('.').Select(int.Parse).ToArray();\n int[] installedParts = installed.Split('.').Select(int.Parse).ToArray();\n for (int i = 0; i < Math.Min(latestParts.Length, installedParts.Length); i++)\n {\n if (latestParts[i] > installedParts[i])\n {\n return true;\n }\n\n if (latestParts[i] < installedParts[i])\n {\n return false;\n }\n }\n return latestParts.Length > installedParts.Length;\n }\n\n /// \n /// Runs a command-line process and handles output/errors.\n /// \n private static void RunCommand(\n string command,\n string arguments,\n string workingDirectory = null\n )\n {\n System.Diagnostics.Process process = new()\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = command,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n WorkingDirectory = workingDirectory ?? string.Empty,\n },\n };\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n if (process.ExitCode != 0)\n {\n throw new Exception(\n $\"Command failed: {command} {arguments}\\nOutput: {output}\\nError: {error}\"\n );\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ReadConsole.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles reading and clearing Unity Editor console log entries.\n /// Uses reflection to access internal LogEntry methods/properties.\n /// \n public static class ReadConsole\n {\n // Reflection members for accessing internal LogEntry data\n // private static MethodInfo _getEntriesMethod; // Removed as it's unused and fails reflection\n private static MethodInfo _startGettingEntriesMethod;\n private static MethodInfo _endGettingEntriesMethod; // Renamed from _stopGettingEntriesMethod, trying End...\n private static MethodInfo _clearMethod;\n private static MethodInfo _getCountMethod;\n private static MethodInfo _getEntryMethod;\n private static FieldInfo _modeField;\n private static FieldInfo _messageField;\n private static FieldInfo _fileField;\n private static FieldInfo _lineField;\n private static FieldInfo _instanceIdField;\n\n // Note: Timestamp is not directly available in LogEntry; need to parse message or find alternative?\n\n // Static constructor for reflection setup\n static ReadConsole()\n {\n try\n {\n Type logEntriesType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntries\"\n );\n if (logEntriesType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntries\");\n\n // Include NonPublic binding flags as internal APIs might change accessibility\n BindingFlags staticFlags =\n BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;\n BindingFlags instanceFlags =\n BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\n\n _startGettingEntriesMethod = logEntriesType.GetMethod(\n \"StartGettingEntries\",\n staticFlags\n );\n if (_startGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.StartGettingEntries\");\n\n // Try reflecting EndGettingEntries based on warning message\n _endGettingEntriesMethod = logEntriesType.GetMethod(\n \"EndGettingEntries\",\n staticFlags\n );\n if (_endGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.EndGettingEntries\");\n\n _clearMethod = logEntriesType.GetMethod(\"Clear\", staticFlags);\n if (_clearMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.Clear\");\n\n _getCountMethod = logEntriesType.GetMethod(\"GetCount\", staticFlags);\n if (_getCountMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetCount\");\n\n _getEntryMethod = logEntriesType.GetMethod(\"GetEntryInternal\", staticFlags);\n if (_getEntryMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetEntryInternal\");\n\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntry\");\n\n _modeField = logEntryType.GetField(\"mode\", instanceFlags);\n if (_modeField == null)\n throw new Exception(\"Failed to reflect LogEntry.mode\");\n\n _messageField = logEntryType.GetField(\"message\", instanceFlags);\n if (_messageField == null)\n throw new Exception(\"Failed to reflect LogEntry.message\");\n\n _fileField = logEntryType.GetField(\"file\", instanceFlags);\n if (_fileField == null)\n throw new Exception(\"Failed to reflect LogEntry.file\");\n\n _lineField = logEntryType.GetField(\"line\", instanceFlags);\n if (_lineField == null)\n throw new Exception(\"Failed to reflect LogEntry.line\");\n\n _instanceIdField = logEntryType.GetField(\"instanceID\", instanceFlags);\n if (_instanceIdField == null)\n throw new Exception(\"Failed to reflect LogEntry.instanceID\");\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ReadConsole] Static Initialization Failed: Could not setup reflection for LogEntries/LogEntry. Console reading/clearing will likely fail. Specific Error: {e.Message}\"\n );\n // Set members to null to prevent NullReferenceExceptions later, HandleCommand should check this.\n _startGettingEntriesMethod =\n _endGettingEntriesMethod =\n _clearMethod =\n _getCountMethod =\n _getEntryMethod =\n null;\n _modeField = _messageField = _fileField = _lineField = _instanceIdField = null;\n }\n }\n\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n // Check if ALL required reflection members were successfully initialized.\n if (\n _startGettingEntriesMethod == null\n || _endGettingEntriesMethod == null\n || _clearMethod == null\n || _getCountMethod == null\n || _getEntryMethod == null\n || _modeField == null\n || _messageField == null\n || _fileField == null\n || _lineField == null\n || _instanceIdField == null\n )\n {\n // Log the error here as well for easier debugging in Unity Console\n Debug.LogError(\n \"[ReadConsole] HandleCommand called but reflection members are not initialized. Static constructor might have failed silently or there's an issue.\"\n );\n return Response.Error(\n \"ReadConsole handler failed to initialize due to reflection errors. Cannot access console logs.\"\n );\n }\n\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"get\";\n\n try\n {\n if (action == \"clear\")\n {\n return ClearConsole();\n }\n else if (action == \"get\")\n {\n // Extract parameters for 'get'\n var types =\n (@params[\"types\"] as JArray)?.Select(t => t.ToString().ToLower()).ToList()\n ?? new List { \"error\", \"warning\", \"log\" };\n int? count = @params[\"count\"]?.ToObject();\n string filterText = @params[\"filterText\"]?.ToString();\n string sinceTimestampStr = @params[\"sinceTimestamp\"]?.ToString(); // TODO: Implement timestamp filtering\n string format = (@params[\"format\"]?.ToString() ?? \"detailed\").ToLower();\n bool includeStacktrace =\n @params[\"includeStacktrace\"]?.ToObject() ?? true;\n\n if (types.Contains(\"all\"))\n {\n types = new List { \"error\", \"warning\", \"log\" }; // Expand 'all'\n }\n\n if (!string.IsNullOrEmpty(sinceTimestampStr))\n {\n Debug.LogWarning(\n \"[ReadConsole] Filtering by 'since_timestamp' is not currently implemented.\"\n );\n // Need a way to get timestamp per log entry.\n }\n\n return GetConsoleEntries(types, count, filterText, format, includeStacktrace);\n }\n else\n {\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'get' or 'clear'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object ClearConsole()\n {\n try\n {\n _clearMethod.Invoke(null, null); // Static method, no instance, no parameters\n return Response.Success(\"Console cleared successfully.\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to clear console: {e}\");\n return Response.Error($\"Failed to clear console: {e.Message}\");\n }\n }\n\n private static object GetConsoleEntries(\n List types,\n int? count,\n string filterText,\n string format,\n bool includeStacktrace\n )\n {\n List formattedEntries = new List();\n int retrievedCount = 0;\n\n try\n {\n // LogEntries requires calling Start/Stop around GetEntries/GetEntryInternal\n _startGettingEntriesMethod.Invoke(null, null);\n\n int totalEntries = (int)_getCountMethod.Invoke(null, null);\n // Create instance to pass to GetEntryInternal - Ensure the type is correct\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\n \"Could not find internal type UnityEditor.LogEntry during GetConsoleEntries.\"\n );\n object logEntryInstance = Activator.CreateInstance(logEntryType);\n\n for (int i = 0; i < totalEntries; i++)\n {\n // Get the entry data into our instance using reflection\n _getEntryMethod.Invoke(null, new object[] { i, logEntryInstance });\n\n // Extract data using reflection\n int mode = (int)_modeField.GetValue(logEntryInstance);\n string message = (string)_messageField.GetValue(logEntryInstance);\n string file = (string)_fileField.GetValue(logEntryInstance);\n\n int line = (int)_lineField.GetValue(logEntryInstance);\n // int instanceId = (int)_instanceIdField.GetValue(logEntryInstance);\n\n if (string.IsNullOrEmpty(message))\n continue; // Skip empty messages\n\n // --- Filtering ---\n // Filter by type\n LogType currentType = GetLogTypeFromMode(mode);\n if (!types.Contains(currentType.ToString().ToLowerInvariant()))\n {\n continue;\n }\n\n // Filter by text (case-insensitive)\n if (\n !string.IsNullOrEmpty(filterText)\n && message.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) < 0\n )\n {\n continue;\n }\n\n // TODO: Filter by timestamp (requires timestamp data)\n\n // --- Formatting ---\n string stackTrace = includeStacktrace ? ExtractStackTrace(message) : null;\n // Get first line if stack is present and requested, otherwise use full message\n string messageOnly =\n (includeStacktrace && !string.IsNullOrEmpty(stackTrace))\n ? message.Split(\n new[] { '\\n', '\\r' },\n StringSplitOptions.RemoveEmptyEntries\n )[0]\n : message;\n\n object formattedEntry = null;\n switch (format)\n {\n case \"plain\":\n formattedEntry = messageOnly;\n break;\n case \"json\":\n case \"detailed\": // Treat detailed as json for structured return\n default:\n formattedEntry = new\n {\n type = currentType.ToString(),\n message = messageOnly,\n file = file,\n line = line,\n // timestamp = \"\", // TODO\n stackTrace = stackTrace, // Will be null if includeStacktrace is false or no stack found\n };\n break;\n }\n\n formattedEntries.Add(formattedEntry);\n retrievedCount++;\n\n // Apply count limit (after filtering)\n if (count.HasValue && retrievedCount >= count.Value)\n {\n break;\n }\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Error while retrieving log entries: {e}\");\n // Ensure EndGettingEntries is called even if there's an error during iteration\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch\n { /* Ignore nested exception */\n }\n return Response.Error($\"Error retrieving log entries: {e.Message}\");\n }\n finally\n {\n // Ensure we always call EndGettingEntries\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to call EndGettingEntries: {e}\");\n // Don't return error here as we might have valid data, but log it.\n }\n }\n\n // Return the filtered and formatted list (might be empty)\n return Response.Success(\n $\"Retrieved {formattedEntries.Count} log entries.\",\n formattedEntries\n );\n }\n\n // --- Internal Helpers ---\n\n // Mapping from LogEntry.mode bits to LogType enum\n // Based on decompiled UnityEditor code or common patterns. Precise bits might change between Unity versions.\n // See comments below for LogEntry mode bits exploration.\n // Note: This mapping is simplified and might not cover all edge cases or future Unity versions perfectly.\n private const int ModeBitError = 1 << 0;\n private const int ModeBitAssert = 1 << 1;\n private const int ModeBitWarning = 1 << 2;\n private const int ModeBitLog = 1 << 3;\n private const int ModeBitException = 1 << 4; // Often combined with Error bits\n private const int ModeBitScriptingError = 1 << 9;\n private const int ModeBitScriptingWarning = 1 << 10;\n private const int ModeBitScriptingLog = 1 << 11;\n private const int ModeBitScriptingException = 1 << 18;\n private const int ModeBitScriptingAssertion = 1 << 22;\n\n private static LogType GetLogTypeFromMode(int mode)\n {\n // First, determine the type based on the original logic (most severe first)\n LogType initialType;\n if (\n (\n mode\n & (\n ModeBitError\n | ModeBitScriptingError\n | ModeBitException\n | ModeBitScriptingException\n )\n ) != 0\n )\n {\n initialType = LogType.Error;\n }\n else if ((mode & (ModeBitAssert | ModeBitScriptingAssertion)) != 0)\n {\n initialType = LogType.Assert;\n }\n else if ((mode & (ModeBitWarning | ModeBitScriptingWarning)) != 0)\n {\n initialType = LogType.Warning;\n }\n else\n {\n initialType = LogType.Log;\n }\n\n // Apply the observed \"one level lower\" correction\n switch (initialType)\n {\n case LogType.Error:\n return LogType.Warning; // Error becomes Warning\n case LogType.Warning:\n return LogType.Log; // Warning becomes Log\n case LogType.Assert:\n return LogType.Assert; // Assert remains Assert (no lower level defined)\n case LogType.Log:\n return LogType.Log; // Log remains Log\n default:\n return LogType.Log; // Default fallback\n }\n }\n\n /// \n /// Attempts to extract the stack trace part from a log message.\n /// Unity log messages often have the stack trace appended after the main message,\n /// starting on a new line and typically indented or beginning with \"at \".\n /// \n /// The complete log message including potential stack trace.\n /// The extracted stack trace string, or null if none is found.\n private static string ExtractStackTrace(string fullMessage)\n {\n if (string.IsNullOrEmpty(fullMessage))\n return null;\n\n // Split into lines, removing empty ones to handle different line endings gracefully.\n // Using StringSplitOptions.None might be better if empty lines matter within stack trace, but RemoveEmptyEntries is usually safer here.\n string[] lines = fullMessage.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n // If there's only one line or less, there's no separate stack trace.\n if (lines.Length <= 1)\n return null;\n\n int stackStartIndex = -1;\n\n // Start checking from the second line onwards.\n for (int i = 1; i < lines.Length; ++i)\n {\n // Performance: TrimStart creates a new string. Consider using IsWhiteSpace check if performance critical.\n string trimmedLine = lines[i].TrimStart();\n\n // Check for common stack trace patterns.\n if (\n trimmedLine.StartsWith(\"at \")\n || trimmedLine.StartsWith(\"UnityEngine.\")\n || trimmedLine.StartsWith(\"UnityEditor.\")\n || trimmedLine.Contains(\"(at \")\n || // Covers \"(at Assets/...\" pattern\n // Heuristic: Check if line starts with likely namespace/class pattern (Uppercase.Something)\n (\n trimmedLine.Length > 0\n && char.IsUpper(trimmedLine[0])\n && trimmedLine.Contains('.')\n )\n )\n {\n stackStartIndex = i;\n break; // Found the likely start of the stack trace\n }\n }\n\n // If a potential start index was found...\n if (stackStartIndex > 0)\n {\n // Join the lines from the stack start index onwards using standard newline characters.\n // This reconstructs the stack trace part of the message.\n return string.Join(\"\\n\", lines.Skip(stackStartIndex));\n }\n\n // No clear stack trace found based on the patterns.\n return null;\n }\n\n /* LogEntry.mode bits exploration (based on Unity decompilation/observation):\n May change between versions.\n\n Basic Types:\n kError = 1 << 0 (1)\n kAssert = 1 << 1 (2)\n kWarning = 1 << 2 (4)\n kLog = 1 << 3 (8)\n kFatal = 1 << 4 (16) - Often treated as Exception/Error\n\n Modifiers/Context:\n kAssetImportError = 1 << 7 (128)\n kAssetImportWarning = 1 << 8 (256)\n kScriptingError = 1 << 9 (512)\n kScriptingWarning = 1 << 10 (1024)\n kScriptingLog = 1 << 11 (2048)\n kScriptCompileError = 1 << 12 (4096)\n kScriptCompileWarning = 1 << 13 (8192)\n kStickyError = 1 << 14 (16384) - Stays visible even after Clear On Play\n kMayIgnoreLineNumber = 1 << 15 (32768)\n kReportBug = 1 << 16 (65536) - Shows the \"Report Bug\" button\n kDisplayPreviousErrorInStatusBar = 1 << 17 (131072)\n kScriptingException = 1 << 18 (262144)\n kDontExtractStacktrace = 1 << 19 (524288) - Hint to the console UI\n kShouldClearOnPlay = 1 << 20 (1048576) - Default behavior\n kGraphCompileError = 1 << 21 (2097152)\n kScriptingAssertion = 1 << 22 (4194304)\n kVisualScriptingError = 1 << 23 (8388608)\n\n Example observed values:\n Log: 2048 (ScriptingLog) or 8 (Log)\n Warning: 1028 (ScriptingWarning | Warning) or 4 (Warning)\n Error: 513 (ScriptingError | Error) or 1 (Error)\n Exception: 262161 (ScriptingException | Error | kFatal?) - Complex combination\n Assertion: 4194306 (ScriptingAssertion | Assert) or 2 (Assert)\n */\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageEditor.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal; // Required for tag management\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles operations related to controlling and querying the Unity Editor state,\n /// including managing Tags and Layers.\n /// \n public static class ManageEditor\n {\n // Constant for starting user layer index\n private const int FirstUserLayerIndex = 8;\n\n // Constant for total layer count\n private const int TotalLayerCount = 32;\n\n /// \n /// Main handler for editor management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n // Parameters for specific actions\n string tagName = @params[\"tagName\"]?.ToString();\n string layerName = @params[\"layerName\"]?.ToString();\n bool waitForCompletion = @params[\"waitForCompletion\"]?.ToObject() ?? false; // Example - not used everywhere\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Route action\n switch (action)\n {\n // Play Mode Control\n case \"play\":\n try\n {\n if (!EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = true;\n return Response.Success(\"Entered play mode.\");\n }\n return Response.Success(\"Already in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error entering play mode: {e.Message}\");\n }\n case \"pause\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPaused = !EditorApplication.isPaused;\n return Response.Success(\n EditorApplication.isPaused ? \"Game paused.\" : \"Game resumed.\"\n );\n }\n return Response.Error(\"Cannot pause/resume: Not in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error pausing/resuming game: {e.Message}\");\n }\n case \"stop\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = false;\n return Response.Success(\"Exited play mode.\");\n }\n return Response.Success(\"Already stopped (not in play mode).\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error stopping play mode: {e.Message}\");\n }\n\n // Editor State/Info\n case \"get_state\":\n return GetEditorState();\n case \"get_windows\":\n return GetEditorWindows();\n case \"get_active_tool\":\n return GetActiveTool();\n case \"get_selection\":\n return GetSelection();\n case \"set_active_tool\":\n string toolName = @params[\"toolName\"]?.ToString();\n if (string.IsNullOrEmpty(toolName))\n return Response.Error(\"'toolName' parameter required for set_active_tool.\");\n return SetActiveTool(toolName);\n\n // Tag Management\n case \"add_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for add_tag.\");\n return AddTag(tagName);\n case \"remove_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for remove_tag.\");\n return RemoveTag(tagName);\n case \"get_tags\":\n return GetTags(); // Helper to list current tags\n\n // Layer Management\n case \"add_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for add_layer.\");\n return AddLayer(layerName);\n case \"remove_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for remove_layer.\");\n return RemoveLayer(layerName);\n case \"get_layers\":\n return GetLayers(); // Helper to list current layers\n\n // --- Settings (Example) ---\n // case \"set_resolution\":\n // int? width = @params[\"width\"]?.ToObject();\n // int? height = @params[\"height\"]?.ToObject();\n // if (!width.HasValue || !height.HasValue) return Response.Error(\"'width' and 'height' parameters required.\");\n // return SetGameViewResolution(width.Value, height.Value);\n // case \"set_quality\":\n // // Handle string name or int index\n // return SetQualityLevel(@params[\"qualityLevel\"]);\n\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Supported actions include play, pause, stop, get_state, get_windows, get_active_tool, get_selection, set_active_tool, add_tag, remove_tag, get_tags, add_layer, remove_layer, get_layers.\"\n );\n }\n }\n\n // --- Editor State/Info Methods ---\n private static object GetEditorState()\n {\n try\n {\n var state = new\n {\n isPlaying = EditorApplication.isPlaying,\n isPaused = EditorApplication.isPaused,\n isCompiling = EditorApplication.isCompiling,\n isUpdating = EditorApplication.isUpdating,\n applicationPath = EditorApplication.applicationPath,\n applicationContentsPath = EditorApplication.applicationContentsPath,\n timeSinceStartup = EditorApplication.timeSinceStartup,\n };\n return Response.Success(\"Retrieved editor state.\", state);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor state: {e.Message}\");\n }\n }\n\n private static object GetEditorWindows()\n {\n try\n {\n // Get all types deriving from EditorWindow\n var windowTypes = AppDomain\n .CurrentDomain.GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => type.IsSubclassOf(typeof(EditorWindow)))\n .ToList();\n\n var openWindows = new List();\n\n // Find currently open instances\n // Resources.FindObjectsOfTypeAll seems more reliable than GetWindow for finding *all* open windows\n EditorWindow[] allWindows = Resources.FindObjectsOfTypeAll();\n\n foreach (EditorWindow window in allWindows)\n {\n if (window == null)\n continue; // Skip potentially destroyed windows\n\n try\n {\n openWindows.Add(\n new\n {\n title = window.titleContent.text,\n typeName = window.GetType().FullName,\n isFocused = EditorWindow.focusedWindow == window,\n position = new\n {\n x = window.position.x,\n y = window.position.y,\n width = window.position.width,\n height = window.position.height,\n },\n instanceID = window.GetInstanceID(),\n }\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Could not get info for window {window.GetType().Name}: {ex.Message}\"\n );\n }\n }\n\n return Response.Success(\"Retrieved list of open editor windows.\", openWindows);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor windows: {e.Message}\");\n }\n }\n\n private static object GetActiveTool()\n {\n try\n {\n Tool currentTool = UnityEditor.Tools.current;\n string toolName = currentTool.ToString(); // Enum to string\n bool customToolActive = UnityEditor.Tools.current == Tool.Custom; // Check if a custom tool is active\n string activeToolName = customToolActive\n ? EditorTools.GetActiveToolName()\n : toolName; // Get custom name if needed\n\n var toolInfo = new\n {\n activeTool = activeToolName,\n isCustom = customToolActive,\n pivotMode = UnityEditor.Tools.pivotMode.ToString(),\n pivotRotation = UnityEditor.Tools.pivotRotation.ToString(),\n handleRotation = UnityEditor.Tools.handleRotation.eulerAngles, // Euler for simplicity\n handlePosition = UnityEditor.Tools.handlePosition,\n };\n\n return Response.Success(\"Retrieved active tool information.\", toolInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active tool: {e.Message}\");\n }\n }\n\n private static object SetActiveTool(string toolName)\n {\n try\n {\n Tool targetTool;\n if (Enum.TryParse(toolName, true, out targetTool)) // Case-insensitive parse\n {\n // Check if it's a valid built-in tool\n if (targetTool != Tool.None && targetTool <= Tool.Custom) // Tool.Custom is the last standard tool\n {\n UnityEditor.Tools.current = targetTool;\n return Response.Success($\"Set active tool to '{targetTool}'.\");\n }\n else\n {\n return Response.Error(\n $\"Cannot directly set tool to '{toolName}'. It might be None, Custom, or invalid.\"\n );\n }\n }\n else\n {\n // Potentially try activating a custom tool by name here if needed\n // This often requires specific editor scripting knowledge for that tool.\n return Response.Error(\n $\"Could not parse '{toolName}' as a standard Unity Tool (View, Move, Rotate, Scale, Rect, Transform, Custom).\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error setting active tool: {e.Message}\");\n }\n }\n\n private static object GetSelection()\n {\n try\n {\n var selectionInfo = new\n {\n activeObject = Selection.activeObject?.name,\n activeGameObject = Selection.activeGameObject?.name,\n activeTransform = Selection.activeTransform?.name,\n activeInstanceID = Selection.activeInstanceID,\n count = Selection.count,\n objects = Selection\n .objects.Select(obj => new\n {\n name = obj?.name,\n type = obj?.GetType().FullName,\n instanceID = obj?.GetInstanceID(),\n })\n .ToList(),\n gameObjects = Selection\n .gameObjects.Select(go => new\n {\n name = go?.name,\n instanceID = go?.GetInstanceID(),\n })\n .ToList(),\n assetGUIDs = Selection.assetGUIDs, // GUIDs for selected assets in Project view\n };\n\n return Response.Success(\"Retrieved current selection details.\", selectionInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting selection: {e.Message}\");\n }\n }\n\n // --- Tag Management Methods ---\n\n private static object AddTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n\n // Check if tag already exists\n if (InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' already exists.\");\n }\n\n try\n {\n // Add the tag using the internal utility\n InternalEditorUtility.AddTag(tagName);\n // Force save assets to ensure the change persists in the TagManager asset\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' added successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object RemoveTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n if (tagName.Equals(\"Untagged\", StringComparison.OrdinalIgnoreCase))\n return Response.Error(\"Cannot remove the built-in 'Untagged' tag.\");\n\n // Check if tag exists before attempting removal\n if (!InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' does not exist.\");\n }\n\n try\n {\n // Remove the tag using the internal utility\n InternalEditorUtility.RemoveTag(tagName);\n // Force save assets\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' removed successfully.\");\n }\n catch (Exception e)\n {\n // Catch potential issues if the tag is somehow in use or removal fails\n return Response.Error($\"Failed to remove tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object GetTags()\n {\n try\n {\n string[] tags = InternalEditorUtility.tags;\n return Response.Success(\"Retrieved current tags.\", tags);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve tags: {e.Message}\");\n }\n }\n\n // --- Layer Management Methods ---\n\n private static object AddLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Check if layer name already exists (case-insensitive check recommended)\n for (int i = 0; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n return Response.Error($\"Layer '{layerName}' already exists at index {i}.\");\n }\n }\n\n // Find the first empty user layer slot (indices 8 to 31)\n int firstEmptyUserLayer = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (layerSP != null && string.IsNullOrEmpty(layerSP.stringValue))\n {\n firstEmptyUserLayer = i;\n break;\n }\n }\n\n if (firstEmptyUserLayer == -1)\n {\n return Response.Error(\"No empty User Layer slots available (8-31 are full).\");\n }\n\n // Assign the name to the found slot\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n firstEmptyUserLayer\n );\n targetLayerSP.stringValue = layerName;\n // Apply the changes to the TagManager asset\n tagManager.ApplyModifiedProperties();\n // Save assets to make sure it's written to disk\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' added successfully to slot {firstEmptyUserLayer}.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object RemoveLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Find the layer by name (must be user layer)\n int layerIndexToRemove = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++) // Start from user layers\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n // Case-insensitive comparison is safer\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n layerIndexToRemove = i;\n break;\n }\n }\n\n if (layerIndexToRemove == -1)\n {\n return Response.Error($\"User layer '{layerName}' not found.\");\n }\n\n // Clear the name for that index\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n layerIndexToRemove\n );\n targetLayerSP.stringValue = string.Empty; // Set to empty string to remove\n // Apply the changes\n tagManager.ApplyModifiedProperties();\n // Save assets\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' (slot {layerIndexToRemove}) removed successfully.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to remove layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object GetLayers()\n {\n try\n {\n var layers = new Dictionary();\n for (int i = 0; i < TotalLayerCount; i++)\n {\n string layerName = LayerMask.LayerToName(i);\n if (!string.IsNullOrEmpty(layerName)) // Only include layers that have names\n {\n layers.Add(i, layerName);\n }\n }\n return Response.Success(\"Retrieved current named layers.\", layers);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve layers: {e.Message}\");\n }\n }\n\n // --- Helper Methods ---\n\n /// \n /// Gets the SerializedObject for the TagManager asset.\n /// \n private static SerializedObject GetTagManager()\n {\n try\n {\n // Load the TagManager asset from the ProjectSettings folder\n UnityEngine.Object[] tagManagerAssets = AssetDatabase.LoadAllAssetsAtPath(\n \"ProjectSettings/TagManager.asset\"\n );\n if (tagManagerAssets == null || tagManagerAssets.Length == 0)\n {\n Debug.LogError(\"[ManageEditor] TagManager.asset not found in ProjectSettings.\");\n return null;\n }\n // The first object in the asset file should be the TagManager\n return new SerializedObject(tagManagerAssets[0]);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageEditor] Error accessing TagManager.asset: {e.Message}\");\n return null;\n }\n }\n\n // --- Example Implementations for Settings ---\n /*\n private static object SetGameViewResolution(int width, int height) { ... }\n private static object SetQualityLevel(JToken qualityLevelToken) { ... }\n */\n }\n\n // Helper class to get custom tool names (remains the same)\n internal static class EditorTools\n {\n public static string GetActiveToolName()\n {\n // This is a placeholder. Real implementation depends on how custom tools\n // are registered and tracked in the specific Unity project setup.\n // It might involve checking static variables, calling methods on specific tool managers, etc.\n if (UnityEditor.Tools.current == Tool.Custom)\n {\n // Example: Check a known custom tool manager\n // if (MyCustomToolManager.IsActive) return MyCustomToolManager.ActiveToolName;\n return \"Unknown Custom Tool\";\n }\n return UnityEditor.Tools.current.ToString();\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageShader.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for shader files within the Unity project.\n /// \n public static class ManageShader\n {\n /// \n /// Main handler for shader management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode shader contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid shader name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Shaders\" if path is not provided\n string relativeDir = path ?? \"Shaders\"; // Default to \"Shaders\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Shaders\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string shaderFileName = $\"{name}.shader\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir);\n string fullPath = Path.Combine(fullPathDir, shaderFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, shaderFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n if (!Directory.Exists(fullPathDir))\n {\n Directory.CreateDirectory(fullPathDir);\n // Refresh AssetDatabase to recognize new folders\n AssetDatabase.Refresh();\n }\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateShader(fullPath, relativePath, name, contents);\n case \"read\":\n return ReadShader(fullPath, relativePath);\n case \"update\":\n return UpdateShader(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteShader(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n // Check if shader already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Add validation for shader name conflicts in Unity\n if (Shader.Find(name) != null)\n {\n return Response.Error(\n $\"A shader with name '{name}' already exists in the project. Choose a different name.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultShaderContent(name);\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new shader\n return Response.Success(\n $\"Shader '{name}.shader' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n //TODO: Consider a threshold for large files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader not found at '{relativePath}'. Use 'create' action to add a new shader.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' updated successfully.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n // Delete the asset through Unity's AssetDatabase first\n bool success = AssetDatabase.DeleteAsset(relativePath);\n if (!success)\n {\n return Response.Error($\"Failed to delete shader through Unity's AssetDatabase: '{relativePath}'\");\n }\n\n // If the file still exists (rare case), try direct deletion\n if (File.Exists(fullPath))\n {\n File.Delete(fullPath);\n }\n\n return Response.Success($\"Shader '{Path.GetFileName(relativePath)}' deleted successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to delete shader '{relativePath}': {e.Message}\");\n }\n }\n\n //This is a CGProgram template\n //TODO: making a HLSL template as well?\n private static string GenerateDefaultShaderContent(string name)\n {\n return @\"Shader \"\"\" + name + @\"\"\"\n {\n Properties\n {\n _MainTex (\"\"Texture\"\", 2D) = \"\"white\"\" {}\n }\n SubShader\n {\n Tags { \"\"RenderType\"\"=\"\"Opaque\"\" }\n LOD 100\n\n Pass\n {\n CGPROGRAM\n #pragma vertex vert\n #pragma fragment frag\n #include \"\"UnityCG.cginc\"\"\n\n struct appdata\n {\n float4 vertex : POSITION;\n float2 uv : TEXCOORD0;\n };\n\n struct v2f\n {\n float2 uv : TEXCOORD0;\n float4 vertex : SV_POSITION;\n };\n\n sampler2D _MainTex;\n float4 _MainTex_ST;\n\n v2f vert (appdata v)\n {\n v2f o;\n o.vertex = UnityObjectToClipPos(v.vertex);\n o.uv = TRANSFORM_TEX(v.uv, _MainTex);\n return o;\n }\n\n fixed4 frag (v2f i) : SV_Target\n {\n fixed4 col = tex2D(_MainTex, i.uv);\n return col;\n }\n ENDCG\n }\n }\n }\";\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScene.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles scene management operations like loading, saving, creating, and querying hierarchy.\n /// \n public static class ManageScene\n {\n /// \n /// Main handler for scene management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n int? buildIndex = @params[\"buildIndex\"]?.ToObject();\n // bool loadAdditive = @params[\"loadAdditive\"]?.ToObject() ?? false; // Example for future extension\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n string relativeDir = path ?? string.Empty;\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n\n // Apply default *after* sanitizing, using the original path variable for the check\n if (string.IsNullOrEmpty(path) && action == \"create\") // Check original path for emptiness\n {\n relativeDir = \"Scenes\"; // Default relative directory\n }\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n string sceneFileName = string.IsNullOrEmpty(name) ? null : $\"{name}.unity\";\n // Construct full system path correctly: ProjectRoot/Assets/relativeDir/sceneFileName\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Combine with Assets path (Application.dataPath ends in Assets)\n string fullPath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(fullPathDir, sceneFileName);\n // Ensure relativePath always starts with \"Assets/\" and uses forward slashes\n string relativePath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(\"Assets\", relativeDir, sceneFileName).Replace('\\\\', '/');\n\n // Ensure directory exists for 'create'\n if (action == \"create\" && !string.IsNullOrEmpty(fullPathDir))\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route action\n switch (action)\n {\n case \"create\":\n if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(relativePath))\n return Response.Error(\n \"'name' and 'path' parameters are required for 'create' action.\"\n );\n return CreateScene(fullPath, relativePath);\n case \"load\":\n // Loading can be done by path/name or build index\n if (!string.IsNullOrEmpty(relativePath))\n return LoadScene(relativePath);\n else if (buildIndex.HasValue)\n return LoadScene(buildIndex.Value);\n else\n return Response.Error(\n \"Either 'name'/'path' or 'buildIndex' must be provided for 'load' action.\"\n );\n case \"save\":\n // Save current scene, optionally to a new path\n return SaveScene(fullPath, relativePath);\n case \"get_hierarchy\":\n return GetSceneHierarchy();\n case \"get_active\":\n return GetActiveSceneInfo();\n case \"get_build_settings\":\n return GetBuildSettingsScenes();\n // Add cases for modifying build settings, additive loading, unloading etc.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions: create, load, save, get_hierarchy, get_active, get_build_settings.\"\n );\n }\n }\n\n private static object CreateScene(string fullPath, string relativePath)\n {\n if (File.Exists(fullPath))\n {\n return Response.Error($\"Scene already exists at '{relativePath}'.\");\n }\n\n try\n {\n // Create a new empty scene\n Scene newScene = EditorSceneManager.NewScene(\n NewSceneSetup.EmptyScene,\n NewSceneMode.Single\n );\n // Save it to the specified path\n bool saved = EditorSceneManager.SaveScene(newScene, relativePath);\n\n if (saved)\n {\n AssetDatabase.Refresh(); // Ensure Unity sees the new scene file\n return Response.Success(\n $\"Scene '{Path.GetFileName(relativePath)}' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n else\n {\n // If SaveScene fails, it might leave an untitled scene open.\n // Optionally try to close it, but be cautious.\n return Response.Error($\"Failed to save new scene to '{relativePath}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error creating scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(string relativePath)\n {\n if (\n !File.Exists(\n Path.Combine(\n Application.dataPath.Substring(\n 0,\n Application.dataPath.Length - \"Assets\".Length\n ),\n relativePath\n )\n )\n )\n {\n return Response.Error($\"Scene file not found at '{relativePath}'.\");\n }\n\n // Check for unsaved changes in the current scene\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n // Optionally prompt the user or save automatically before loading\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n // Example: bool saveOK = EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();\n // if (!saveOK) return Response.Error(\"Load cancelled by user.\");\n }\n\n try\n {\n EditorSceneManager.OpenScene(relativePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene '{relativePath}' loaded successfully.\",\n new\n {\n path = relativePath,\n name = Path.GetFileNameWithoutExtension(relativePath),\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error loading scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(int buildIndex)\n {\n if (buildIndex < 0 || buildIndex >= SceneManager.sceneCountInBuildSettings)\n {\n return Response.Error(\n $\"Invalid build index: {buildIndex}. Must be between 0 and {SceneManager.sceneCountInBuildSettings - 1}.\"\n );\n }\n\n // Check for unsaved changes\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n }\n\n try\n {\n string scenePath = SceneUtility.GetScenePathByBuildIndex(buildIndex);\n EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene at build index {buildIndex} ('{scenePath}') loaded successfully.\",\n new\n {\n path = scenePath,\n name = Path.GetFileNameWithoutExtension(scenePath),\n buildIndex = buildIndex,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error loading scene with build index {buildIndex}: {e.Message}\"\n );\n }\n }\n\n private static object SaveScene(string fullPath, string relativePath)\n {\n try\n {\n Scene currentScene = EditorSceneManager.GetActiveScene();\n if (!currentScene.IsValid())\n {\n return Response.Error(\"No valid scene is currently active to save.\");\n }\n\n bool saved;\n string finalPath = currentScene.path; // Path where it was last saved or will be saved\n\n if (!string.IsNullOrEmpty(relativePath) && currentScene.path != relativePath)\n {\n // Save As...\n // Ensure directory exists\n string dir = Path.GetDirectoryName(fullPath);\n if (!Directory.Exists(dir))\n Directory.CreateDirectory(dir);\n\n saved = EditorSceneManager.SaveScene(currentScene, relativePath);\n finalPath = relativePath;\n }\n else\n {\n // Save (overwrite existing or save untitled)\n if (string.IsNullOrEmpty(currentScene.path))\n {\n // Scene is untitled, needs a path\n return Response.Error(\n \"Cannot save an untitled scene without providing a 'name' and 'path'. Use Save As functionality.\"\n );\n }\n saved = EditorSceneManager.SaveScene(currentScene);\n }\n\n if (saved)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Scene '{currentScene.name}' saved successfully to '{finalPath}'.\",\n new { path = finalPath, name = currentScene.name }\n );\n }\n else\n {\n return Response.Error($\"Failed to save scene '{currentScene.name}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error saving scene: {e.Message}\");\n }\n }\n\n private static object GetActiveSceneInfo()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid())\n {\n return Response.Error(\"No active scene found.\");\n }\n\n var sceneInfo = new\n {\n name = activeScene.name,\n path = activeScene.path,\n buildIndex = activeScene.buildIndex, // -1 if not in build settings\n isDirty = activeScene.isDirty,\n isLoaded = activeScene.isLoaded,\n rootCount = activeScene.rootCount,\n };\n\n return Response.Success(\"Retrieved active scene information.\", sceneInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active scene info: {e.Message}\");\n }\n }\n\n private static object GetBuildSettingsScenes()\n {\n try\n {\n var scenes = new List();\n for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)\n {\n var scene = EditorBuildSettings.scenes[i];\n scenes.Add(\n new\n {\n path = scene.path,\n guid = scene.guid.ToString(),\n enabled = scene.enabled,\n buildIndex = i, // Actual build index considering only enabled scenes might differ\n }\n );\n }\n return Response.Success(\"Retrieved scenes from Build Settings.\", scenes);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scenes from Build Settings: {e.Message}\");\n }\n }\n\n private static object GetSceneHierarchy()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid() || !activeScene.isLoaded)\n {\n return Response.Error(\n \"No valid and loaded scene is active to get hierarchy from.\"\n );\n }\n\n GameObject[] rootObjects = activeScene.GetRootGameObjects();\n var hierarchy = rootObjects.Select(go => GetGameObjectDataRecursive(go)).ToList();\n\n return Response.Success(\n $\"Retrieved hierarchy for scene '{activeScene.name}'.\",\n hierarchy\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scene hierarchy: {e.Message}\");\n }\n }\n\n /// \n /// Recursively builds a data representation of a GameObject and its children.\n /// \n private static object GetGameObjectDataRecursive(GameObject go)\n {\n if (go == null)\n return null;\n\n var childrenData = new List();\n foreach (Transform child in go.transform)\n {\n childrenData.Add(GetGameObjectDataRecursive(child.gameObject));\n }\n\n var gameObjectData = new Dictionary\n {\n { \"name\", go.name },\n { \"activeSelf\", go.activeSelf },\n { \"activeInHierarchy\", go.activeInHierarchy },\n { \"tag\", go.tag },\n { \"layer\", go.layer },\n { \"isStatic\", go.isStatic },\n { \"instanceID\", go.GetInstanceID() }, // Useful unique identifier\n {\n \"transform\",\n new\n {\n position = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n }, // Euler for simplicity\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n }\n },\n { \"children\", childrenData },\n };\n\n return gameObjectData;\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Runtime/Serialization/UnityTypeConverters.cs", "using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing UnityEngine;\n#if UNITY_EDITOR\nusing UnityEditor; // Required for AssetDatabase and EditorUtility\n#endif\n\nnamespace UnityMcpBridge.Runtime.Serialization\n{\n public class Vector3Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector3 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WriteEndObject();\n }\n\n public override Vector3 ReadJson(JsonReader reader, Type objectType, Vector3 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector3(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"]\n );\n }\n }\n\n public class Vector2Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WriteEndObject();\n }\n\n public override Vector2 ReadJson(JsonReader reader, Type objectType, Vector2 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector2(\n (float)jo[\"x\"],\n (float)jo[\"y\"]\n );\n }\n }\n\n public class QuaternionConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Quaternion value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WritePropertyName(\"w\");\n writer.WriteValue(value.w);\n writer.WriteEndObject();\n }\n\n public override Quaternion ReadJson(JsonReader reader, Type objectType, Quaternion existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Quaternion(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"],\n (float)jo[\"w\"]\n );\n }\n }\n\n public class ColorConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Color value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"r\");\n writer.WriteValue(value.r);\n writer.WritePropertyName(\"g\");\n writer.WriteValue(value.g);\n writer.WritePropertyName(\"b\");\n writer.WriteValue(value.b);\n writer.WritePropertyName(\"a\");\n writer.WriteValue(value.a);\n writer.WriteEndObject();\n }\n\n public override Color ReadJson(JsonReader reader, Type objectType, Color existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Color(\n (float)jo[\"r\"],\n (float)jo[\"g\"],\n (float)jo[\"b\"],\n (float)jo[\"a\"]\n );\n }\n }\n \n public class RectConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Rect value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"width\");\n writer.WriteValue(value.width);\n writer.WritePropertyName(\"height\");\n writer.WriteValue(value.height);\n writer.WriteEndObject();\n }\n\n public override Rect ReadJson(JsonReader reader, Type objectType, Rect existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Rect(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"width\"],\n (float)jo[\"height\"]\n );\n }\n }\n \n public class BoundsConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Bounds value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"center\");\n serializer.Serialize(writer, value.center); // Use serializer to handle nested Vector3\n writer.WritePropertyName(\"size\");\n serializer.Serialize(writer, value.size); // Use serializer to handle nested Vector3\n writer.WriteEndObject();\n }\n\n public override Bounds ReadJson(JsonReader reader, Type objectType, Bounds existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n Vector3 center = jo[\"center\"].ToObject(serializer); // Use serializer to handle nested Vector3\n Vector3 size = jo[\"size\"].ToObject(serializer); // Use serializer to handle nested Vector3\n return new Bounds(center, size);\n }\n }\n\n // Converter for UnityEngine.Object references (GameObjects, Components, Materials, Textures, etc.)\n public class UnityEngineObjectConverter : JsonConverter\n {\n public override bool CanRead => true; // We need to implement ReadJson\n public override bool CanWrite => true;\n\n public override void WriteJson(JsonWriter writer, UnityEngine.Object value, JsonSerializer serializer)\n {\n if (value == null)\n {\n writer.WriteNull();\n return;\n }\n\n#if UNITY_EDITOR // AssetDatabase and EditorUtility are Editor-only\n if (UnityEditor.AssetDatabase.Contains(value))\n {\n // It's an asset (Material, Texture, Prefab, etc.)\n string path = UnityEditor.AssetDatabase.GetAssetPath(value);\n if (!string.IsNullOrEmpty(path))\n {\n writer.WriteValue(path);\n }\n else\n {\n // Asset exists but path couldn't be found? Write minimal info.\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"isAssetWithoutPath\");\n writer.WriteValue(true);\n writer.WriteEndObject();\n }\n }\n else\n {\n // It's a scene object (GameObject, Component, etc.)\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WriteEndObject();\n }\n#else\n // Runtime fallback: Write basic info without AssetDatabase\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"warning\");\n writer.WriteValue(\"UnityEngineObjectConverter running in non-Editor mode, asset path unavailable.\");\n writer.WriteEndObject();\n#endif\n }\n\n public override UnityEngine.Object ReadJson(JsonReader reader, Type objectType, UnityEngine.Object existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n if (reader.TokenType == JsonToken.Null)\n {\n return null;\n }\n\n#if UNITY_EDITOR\n if (reader.TokenType == JsonToken.String)\n {\n // Assume it's an asset path\n string path = reader.Value.ToString();\n return UnityEditor.AssetDatabase.LoadAssetAtPath(path, objectType);\n }\n\n if (reader.TokenType == JsonToken.StartObject)\n {\n JObject jo = JObject.Load(reader);\n if (jo.TryGetValue(\"instanceID\", out JToken idToken) && idToken.Type == JTokenType.Integer)\n {\n int instanceId = idToken.ToObject();\n UnityEngine.Object obj = UnityEditor.EditorUtility.InstanceIDToObject(instanceId);\n if (obj != null && objectType.IsAssignableFrom(obj.GetType()))\n {\n return obj;\n }\n }\n // Could potentially try finding by name as a fallback if ID lookup fails/isn't present\n // but that's less reliable.\n }\n#else\n // Runtime deserialization is tricky without AssetDatabase/EditorUtility\n // Maybe log a warning and return null or existingValue?\n Debug.LogWarning(\"UnityEngineObjectConverter cannot deserialize complex objects in non-Editor mode.\");\n // Skip the token to avoid breaking the reader\n if (reader.TokenType == JsonToken.StartObject) JObject.Load(reader);\n else if (reader.TokenType == JsonToken.String) reader.ReadAsString(); \n // Return null or existing value, depending on desired behavior\n return existingValue; \n#endif\n\n throw new JsonSerializationException($\"Unexpected token type '{reader.TokenType}' when deserializing UnityEngine.Object\");\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/GameObjectSerializer.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Runtime.Serialization; // For Converters\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Handles serialization of GameObjects and Components for MCP responses.\n /// Includes reflection helpers and caching for performance.\n /// \n public static class GameObjectSerializer\n {\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of a GameObject.\n /// \n public static object GetGameObjectData(GameObject go)\n {\n if (go == null)\n return null;\n return new\n {\n name = go.name,\n instanceID = go.GetInstanceID(),\n tag = go.tag,\n layer = go.layer,\n activeSelf = go.activeSelf,\n activeInHierarchy = go.activeInHierarchy,\n isStatic = go.isStatic,\n scenePath = go.scene.path, // Identify which scene it belongs to\n transform = new // Serialize transform components carefully to avoid JSON issues\n {\n // Serialize Vector3 components individually to prevent self-referencing loops.\n // The default serializer can struggle with properties like Vector3.normalized.\n position = new\n {\n x = go.transform.position.x,\n y = go.transform.position.y,\n z = go.transform.position.z,\n },\n localPosition = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.rotation.eulerAngles.x,\n y = go.transform.rotation.eulerAngles.y,\n z = go.transform.rotation.eulerAngles.z,\n },\n localRotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n },\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n forward = new\n {\n x = go.transform.forward.x,\n y = go.transform.forward.y,\n z = go.transform.forward.z,\n },\n up = new\n {\n x = go.transform.up.x,\n y = go.transform.up.y,\n z = go.transform.up.z,\n },\n right = new\n {\n x = go.transform.right.x,\n y = go.transform.right.y,\n z = go.transform.right.z,\n },\n },\n parentInstanceID = go.transform.parent?.gameObject.GetInstanceID() ?? 0, // 0 if no parent\n // Optionally include components, but can be large\n // components = go.GetComponents().Select(c => GetComponentData(c)).ToList()\n // Or just component names:\n componentNames = go.GetComponents()\n .Select(c => c.GetType().FullName)\n .ToList(),\n };\n }\n\n // --- Metadata Caching for Reflection ---\n private class CachedMetadata\n {\n public readonly List SerializableProperties;\n public readonly List SerializableFields;\n\n public CachedMetadata(List properties, List fields)\n {\n SerializableProperties = properties;\n SerializableFields = fields;\n }\n }\n // Key becomes Tuple\n private static readonly Dictionary, CachedMetadata> _metadataCache = new Dictionary, CachedMetadata>();\n // --- End Metadata Caching ---\n\n /// \n /// Creates a serializable representation of a Component, attempting to serialize\n /// public properties and fields using reflection, with caching and control over non-public fields.\n /// \n // Add the flag parameter here\n public static object GetComponentData(Component c, bool includeNonPublicSerializedFields = true)\n {\n // --- Add Early Logging --- \n // Debug.Log($\"[GetComponentData] Starting for component: {c?.GetType()?.FullName ?? \"null\"} (ID: {c?.GetInstanceID() ?? 0})\");\n // --- End Early Logging ---\n \n if (c == null) return null;\n Type componentType = c.GetType();\n\n // --- Special handling for Transform to avoid reflection crashes and problematic properties --- \n if (componentType == typeof(Transform))\n {\n Transform tr = c as Transform;\n // Debug.Log($\"[GetComponentData] Manually serializing Transform (ID: {tr.GetInstanceID()})\");\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", tr.GetInstanceID() },\n // Manually extract known-safe properties. Avoid Quaternion 'rotation' and 'lossyScale'.\n { \"position\", CreateTokenFromValue(tr.position, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localPosition\", CreateTokenFromValue(tr.localPosition, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"eulerAngles\", CreateTokenFromValue(tr.eulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() }, // Use Euler angles\n { \"localEulerAngles\", CreateTokenFromValue(tr.localEulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localScale\", CreateTokenFromValue(tr.localScale, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"right\", CreateTokenFromValue(tr.right, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"up\", CreateTokenFromValue(tr.up, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"forward\", CreateTokenFromValue(tr.forward, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"parentInstanceID\", tr.parent?.gameObject.GetInstanceID() ?? 0 },\n { \"rootInstanceID\", tr.root?.gameObject.GetInstanceID() ?? 0 },\n { \"childCount\", tr.childCount },\n // Include standard Object/Component properties\n { \"name\", tr.name }, \n { \"tag\", tr.tag }, \n { \"gameObjectInstanceID\", tr.gameObject?.GetInstanceID() ?? 0 }\n };\n }\n // --- End Special handling for Transform --- \n\n // --- Special handling for Camera to avoid matrix-related crashes ---\n if (componentType == typeof(Camera))\n {\n Camera cam = c as Camera;\n var cameraProperties = new Dictionary();\n\n // List of safe properties to serialize\n var safeProperties = new Dictionary>\n {\n { \"nearClipPlane\", () => cam.nearClipPlane },\n { \"farClipPlane\", () => cam.farClipPlane },\n { \"fieldOfView\", () => cam.fieldOfView },\n { \"renderingPath\", () => (int)cam.renderingPath },\n { \"actualRenderingPath\", () => (int)cam.actualRenderingPath },\n { \"allowHDR\", () => cam.allowHDR },\n { \"allowMSAA\", () => cam.allowMSAA },\n { \"allowDynamicResolution\", () => cam.allowDynamicResolution },\n { \"forceIntoRenderTexture\", () => cam.forceIntoRenderTexture },\n { \"orthographicSize\", () => cam.orthographicSize },\n { \"orthographic\", () => cam.orthographic },\n { \"opaqueSortMode\", () => (int)cam.opaqueSortMode },\n { \"transparencySortMode\", () => (int)cam.transparencySortMode },\n { \"depth\", () => cam.depth },\n { \"aspect\", () => cam.aspect },\n { \"cullingMask\", () => cam.cullingMask },\n { \"eventMask\", () => cam.eventMask },\n { \"backgroundColor\", () => cam.backgroundColor },\n { \"clearFlags\", () => (int)cam.clearFlags },\n { \"stereoEnabled\", () => cam.stereoEnabled },\n { \"stereoSeparation\", () => cam.stereoSeparation },\n { \"stereoConvergence\", () => cam.stereoConvergence },\n { \"enabled\", () => cam.enabled },\n { \"name\", () => cam.name },\n { \"tag\", () => cam.tag },\n { \"gameObject\", () => new { name = cam.gameObject.name, instanceID = cam.gameObject.GetInstanceID() } }\n };\n\n foreach (var prop in safeProperties)\n {\n try\n {\n var value = prop.Value();\n if (value != null)\n {\n AddSerializableValue(cameraProperties, prop.Key, value.GetType(), value);\n }\n }\n catch (Exception)\n {\n // Silently skip any property that fails\n continue;\n }\n }\n\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", cam.GetInstanceID() },\n { \"properties\", cameraProperties }\n };\n }\n // --- End Special handling for Camera ---\n\n var data = new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", c.GetInstanceID() }\n };\n\n // --- Get Cached or Generate Metadata (using new cache key) ---\n Tuple cacheKey = new Tuple(componentType, includeNonPublicSerializedFields);\n if (!_metadataCache.TryGetValue(cacheKey, out CachedMetadata cachedData))\n {\n var propertiesToCache = new List();\n var fieldsToCache = new List();\n\n // Traverse the hierarchy from the component type up to MonoBehaviour\n Type currentType = componentType;\n while (currentType != null && currentType != typeof(MonoBehaviour) && currentType != typeof(object))\n {\n // Get properties declared only at the current type level\n BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n foreach (var propInfo in currentType.GetProperties(propFlags))\n {\n // Basic filtering (readable, not indexer, not transform which is handled elsewhere)\n if (!propInfo.CanRead || propInfo.GetIndexParameters().Length > 0 || propInfo.Name == \"transform\") continue;\n // Add if not already added (handles overrides - keep the most derived version)\n if (!propertiesToCache.Any(p => p.Name == propInfo.Name)) {\n propertiesToCache.Add(propInfo);\n }\n }\n\n // Get fields declared only at the current type level (both public and non-public)\n BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n var declaredFields = currentType.GetFields(fieldFlags);\n\n // Process the declared Fields for caching\n foreach (var fieldInfo in declaredFields)\n {\n if (fieldInfo.Name.EndsWith(\"k__BackingField\")) continue; // Skip backing fields\n\n // Add if not already added (handles hiding - keep the most derived version)\n if (fieldsToCache.Any(f => f.Name == fieldInfo.Name)) continue;\n\n bool shouldInclude = false;\n if (includeNonPublicSerializedFields)\n {\n // If TRUE, include Public OR NonPublic with [SerializeField]\n shouldInclude = fieldInfo.IsPublic || (fieldInfo.IsPrivate && fieldInfo.IsDefined(typeof(SerializeField), inherit: false));\n }\n else // includeNonPublicSerializedFields is FALSE\n {\n // If FALSE, include ONLY if it is explicitly Public.\n shouldInclude = fieldInfo.IsPublic;\n }\n\n if (shouldInclude)\n {\n fieldsToCache.Add(fieldInfo);\n }\n }\n\n // Move to the base type\n currentType = currentType.BaseType;\n }\n // --- End Hierarchy Traversal ---\n\n cachedData = new CachedMetadata(propertiesToCache, fieldsToCache);\n _metadataCache[cacheKey] = cachedData; // Add to cache with combined key\n }\n // --- End Get Cached or Generate Metadata ---\n\n // --- Use cached metadata ---\n var serializablePropertiesOutput = new Dictionary();\n \n // --- Add Logging Before Property Loop ---\n // Debug.Log($\"[GetComponentData] Starting property loop for {componentType.Name}...\");\n // --- End Logging Before Property Loop ---\n\n // Use cached properties\n foreach (var propInfo in cachedData.SerializableProperties)\n {\n string propName = propInfo.Name;\n\n // --- Skip known obsolete/problematic Component shortcut properties ---\n bool skipProperty = false;\n if (propName == \"rigidbody\" || propName == \"rigidbody2D\" || propName == \"camera\" ||\n propName == \"light\" || propName == \"animation\" || propName == \"constantForce\" ||\n propName == \"renderer\" || propName == \"audio\" || propName == \"networkView\" ||\n propName == \"collider\" || propName == \"collider2D\" || propName == \"hingeJoint\" ||\n propName == \"particleSystem\" ||\n // Also skip potentially problematic Matrix properties prone to cycles/errors\n propName == \"worldToLocalMatrix\" || propName == \"localToWorldMatrix\")\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping generic property: {propName}\"); // Optional log\n skipProperty = true;\n }\n // --- End Skip Generic Properties ---\n\n // --- Skip specific potentially problematic Camera properties ---\n if (componentType == typeof(Camera) && \n (propName == \"pixelRect\" || \n propName == \"rect\" || \n propName == \"cullingMatrix\" ||\n propName == \"useOcclusionCulling\" ||\n propName == \"worldToCameraMatrix\" ||\n propName == \"projectionMatrix\" ||\n propName == \"nonJitteredProjectionMatrix\" ||\n propName == \"previousViewProjectionMatrix\" ||\n propName == \"cameraToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Camera property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Camera Properties ---\n\n // --- Skip specific potentially problematic Transform properties ---\n if (componentType == typeof(Transform) && \n (propName == \"lossyScale\" || \n propName == \"rotation\" ||\n propName == \"worldToLocalMatrix\" ||\n propName == \"localToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Transform property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Transform Properties ---\n\n // Skip if flagged\n if (skipProperty)\n {\n continue;\n }\n\n try\n {\n // --- Add detailed logging --- \n // Debug.Log($\"[GetComponentData] Accessing: {componentType.Name}.{propName}\");\n // --- End detailed logging ---\n object value = propInfo.GetValue(c);\n Type propType = propInfo.PropertyType;\n AddSerializableValue(serializablePropertiesOutput, propName, propType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read property {propName} on {componentType.Name}: {ex.Message}\");\n }\n }\n\n // --- Add Logging Before Field Loop ---\n // Debug.Log($\"[GetComponentData] Starting field loop for {componentType.Name}...\");\n // --- End Logging Before Field Loop ---\n\n // Use cached fields\n foreach (var fieldInfo in cachedData.SerializableFields)\n {\n try\n {\n // --- Add detailed logging for fields --- \n // Debug.Log($\"[GetComponentData] Accessing Field: {componentType.Name}.{fieldInfo.Name}\");\n // --- End detailed logging for fields ---\n object value = fieldInfo.GetValue(c);\n string fieldName = fieldInfo.Name;\n Type fieldType = fieldInfo.FieldType;\n AddSerializableValue(serializablePropertiesOutput, fieldName, fieldType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read field {fieldInfo.Name} on {componentType.Name}: {ex.Message}\");\n }\n }\n // --- End Use cached metadata ---\n\n if (serializablePropertiesOutput.Count > 0)\n {\n data[\"properties\"] = serializablePropertiesOutput;\n }\n\n return data;\n }\n\n // Helper function to decide how to serialize different types\n private static void AddSerializableValue(Dictionary dict, string name, Type type, object value)\n {\n // Simplified: Directly use CreateTokenFromValue which uses the serializer\n if (value == null)\n {\n dict[name] = null;\n return;\n }\n\n try\n {\n // Use the helper that employs our custom serializer settings\n JToken token = CreateTokenFromValue(value, type);\n if (token != null) // Check if serialization succeeded in the helper\n {\n // Convert JToken back to a basic object structure for the dictionary\n dict[name] = ConvertJTokenToPlainObject(token);\n }\n // If token is null, it means serialization failed and a warning was logged.\n }\n catch (Exception e)\n {\n // Catch potential errors during JToken conversion or addition to dictionary\n Debug.LogWarning($\"[AddSerializableValue] Error processing value for '{name}' (Type: {type.FullName}): {e.Message}. Skipping.\");\n }\n }\n\n // Helper to convert JToken back to basic object structure\n private static object ConvertJTokenToPlainObject(JToken token)\n {\n if (token == null) return null;\n\n switch (token.Type)\n {\n case JTokenType.Object:\n var objDict = new Dictionary();\n foreach (var prop in ((JObject)token).Properties())\n {\n objDict[prop.Name] = ConvertJTokenToPlainObject(prop.Value);\n }\n return objDict;\n\n case JTokenType.Array:\n var list = new List();\n foreach (var item in (JArray)token)\n {\n list.Add(ConvertJTokenToPlainObject(item));\n }\n return list;\n\n case JTokenType.Integer:\n return token.ToObject(); // Use long for safety\n case JTokenType.Float:\n return token.ToObject(); // Use double for safety\n case JTokenType.String:\n return token.ToObject();\n case JTokenType.Boolean:\n return token.ToObject();\n case JTokenType.Date:\n return token.ToObject();\n case JTokenType.Guid:\n return token.ToObject();\n case JTokenType.Uri:\n return token.ToObject();\n case JTokenType.TimeSpan:\n return token.ToObject();\n case JTokenType.Bytes:\n return token.ToObject();\n case JTokenType.Null:\n return null;\n case JTokenType.Undefined:\n return null; // Treat undefined as null\n\n default:\n // Fallback for simple value types not explicitly listed\n if (token is JValue jValue && jValue.Value != null)\n {\n return jValue.Value;\n }\n // Debug.LogWarning($\"Unsupported JTokenType encountered: {token.Type}. Returning null.\");\n return null;\n }\n }\n\n // --- Define custom JsonSerializerSettings for OUTPUT ---\n private static readonly JsonSerializerSettings _outputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Handles serialization of references\n },\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore,\n // ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } // Example if needed\n };\n private static readonly JsonSerializer _outputSerializer = JsonSerializer.Create(_outputSerializerSettings);\n // --- End Define custom JsonSerializerSettings ---\n\n // Helper to create JToken using the output serializer\n private static JToken CreateTokenFromValue(object value, Type type)\n {\n if (value == null) return JValue.CreateNull();\n\n try\n {\n // Use the pre-configured OUTPUT serializer instance\n return JToken.FromObject(value, _outputSerializer);\n }\n catch (JsonSerializationException e)\n {\n Debug.LogWarning($\"[GameObjectSerializer] Newtonsoft.Json Error serializing value of type {type.FullName}: {e.Message}. Skipping property/field.\");\n return null; // Indicate serialization failure\n }\n catch (Exception e) // Catch other unexpected errors\n {\n Debug.LogWarning($\"[GameObjectSerializer] Unexpected error serializing value of type {type.FullName}: {e}. Skipping property/field.\");\n return null; // Indicate serialization failure\n }\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Data/McpClients.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class McpClients\n {\n public List clients = new()\n {\n new()\n {\n name = \"Claude Desktop\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n mcpType = McpTypes.ClaudeDesktop,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"Cursor\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n mcpType = McpTypes.Cursor,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"VSCode GitHub Copilot\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n mcpType = McpTypes.VSCode,\n configStatus = \"Not Configured\",\n },\n };\n\n // Initialize status enums after construction\n public McpClients()\n {\n foreach (var client in clients)\n {\n if (client.configStatus == \"Not Configured\")\n {\n client.status = McpStatus.NotConfigured;\n }\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpClient.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public class McpClient\n {\n public string name;\n public string windowsConfigPath;\n public string linuxConfigPath;\n public McpTypes mcpType;\n public string configStatus;\n public McpStatus status = McpStatus.NotConfigured;\n\n // Helper method to convert the enum to a display string\n public string GetStatusDisplayString()\n {\n return status switch\n {\n McpStatus.NotConfigured => \"Not Configured\",\n McpStatus.Configured => \"Configured\",\n McpStatus.Running => \"Running\",\n McpStatus.Connected => \"Connected\",\n McpStatus.IncorrectPath => \"Incorrect Path\",\n McpStatus.CommunicationError => \"Communication Error\",\n McpStatus.NoResponse => \"No Response\",\n McpStatus.UnsupportedOS => \"Unsupported OS\",\n McpStatus.MissingConfig => \"Missing UnityMCP Config\",\n McpStatus.Error => configStatus.StartsWith(\"Error:\") ? configStatus : \"Error\",\n _ => \"Unknown\",\n };\n }\n\n // Helper method to set both status enum and string for backward compatibility\n public void SetStatus(McpStatus newStatus, string errorDetails = null)\n {\n status = newStatus;\n\n if (newStatus == McpStatus.Error && !string.IsNullOrEmpty(errorDetails))\n {\n configStatus = $\"Error: {errorDetails}\";\n }\n else\n {\n configStatus = GetStatusDisplayString();\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ExecuteMenuItem.cs", "using System;\nusing System.Collections.Generic; // Added for HashSet\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles executing Unity Editor menu items by path.\n /// \n public static class ExecuteMenuItem\n {\n // Basic blacklist to prevent accidental execution of potentially disruptive menu items.\n // This can be expanded based on needs.\n private static readonly HashSet _menuPathBlacklist = new HashSet(\n StringComparer.OrdinalIgnoreCase\n )\n {\n \"File/Quit\",\n // Add other potentially dangerous items like \"Edit/Preferences...\", \"File/Build Settings...\" if needed\n };\n\n /// \n /// Main handler for executing menu items or getting available ones.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"execute\"; // Default action\n\n try\n {\n switch (action)\n {\n case \"execute\":\n return ExecuteItem(@params);\n case \"get_available_menus\":\n // Getting a comprehensive list of *all* menu items dynamically is very difficult\n // and often requires complex reflection or maintaining a manual list.\n // Returning a placeholder/acknowledgement for now.\n Debug.LogWarning(\n \"[ExecuteMenuItem] 'get_available_menus' action is not fully implemented. Dynamically listing all menu items is complex.\"\n );\n // Returning an empty list as per the refactor plan's requirements.\n return Response.Success(\n \"'get_available_menus' action is not fully implemented. Returning empty list.\",\n new List()\n );\n // TODO: Consider implementing a basic list of common/known menu items or exploring reflection techniques if this feature becomes critical.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'execute', 'get_available_menus'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ExecuteMenuItem] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n /// \n /// Executes a specific menu item.\n /// \n private static object ExecuteItem(JObject @params)\n {\n // Try both naming conventions: snake_case and camelCase\n string menuPath = @params[\"menu_path\"]?.ToString() ?? @params[\"menuPath\"]?.ToString();\n\n // string alias = @params[\"alias\"]?.ToString(); // TODO: Implement alias mapping based on refactor plan requirements.\n // JObject parameters = @params[\"parameters\"] as JObject; // TODO: Investigate parameter passing (often not directly supported by ExecuteMenuItem).\n\n if (string.IsNullOrWhiteSpace(menuPath))\n {\n return Response.Error(\"Required parameter 'menu_path' or 'menuPath' is missing or empty.\");\n }\n\n // Validate against blacklist\n if (_menuPathBlacklist.Contains(menuPath))\n {\n return Response.Error(\n $\"Execution of menu item '{menuPath}' is blocked for safety reasons.\"\n );\n }\n\n // TODO: Implement alias lookup here if needed (Map alias to actual menuPath).\n // if (!string.IsNullOrEmpty(alias)) { menuPath = LookupAlias(alias); if(menuPath == null) return Response.Error(...); }\n\n // TODO: Handle parameters ('parameters' object) if a viable method is found.\n // This is complex as EditorApplication.ExecuteMenuItem doesn't take arguments directly.\n // It might require finding the underlying EditorWindow or command if parameters are needed.\n\n try\n {\n // Attempt to execute the menu item on the main thread using delayCall for safety.\n EditorApplication.delayCall += () =>\n {\n try\n {\n bool executed = EditorApplication.ExecuteMenuItem(menuPath);\n // Log potential failure inside the delayed call.\n if (!executed)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to find or execute menu item via delayCall: '{menuPath}'. It might be invalid, disabled, or context-dependent.\"\n );\n }\n }\n catch (Exception delayEx)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Exception during delayed execution of '{menuPath}': {delayEx}\"\n );\n }\n };\n\n // Report attempt immediately, as execution is delayed.\n return Response.Success(\n $\"Attempted to execute menu item: '{menuPath}'. Check Unity logs for confirmation or errors.\"\n );\n }\n catch (Exception e)\n {\n // Catch errors during setup phase.\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to setup execution for '{menuPath}': {e}\"\n );\n return Response.Error(\n $\"Error setting up execution for menu item '{menuPath}': {e.Message}\"\n );\n }\n }\n\n // TODO: Add helper for alias lookup if implementing aliases.\n // private static string LookupAlias(string alias) { ... return actualMenuPath or null ... }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Data/DefaultServerConfig.cs", "using UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class DefaultServerConfig : ServerConfig\n {\n public new string unityHost = \"localhost\";\n public new int unityPort = 6400;\n public new int mcpPort = 6500;\n public new float connectionTimeout = 15.0f;\n public new int bufferSize = 32768;\n public new string logLevel = \"INFO\";\n public new string logFormat = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\";\n public new int maxRetries = 3;\n public new float retryDelay = 1.0f;\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Response.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Provides static methods for creating standardized success and error response objects.\n /// Ensures consistent JSON structure for communication back to the Python server.\n /// \n public static class Response\n {\n /// \n /// Creates a standardized success response object.\n /// \n /// A message describing the successful operation.\n /// Optional additional data to include in the response.\n /// An object representing the success response.\n public static object Success(string message, object data = null)\n {\n if (data != null)\n {\n return new\n {\n success = true,\n message = message,\n data = data,\n };\n }\n else\n {\n return new { success = true, message = message };\n }\n }\n\n /// \n /// Creates a standardized error response object.\n /// \n /// A message describing the error.\n /// Optional additional data (e.g., error details) to include.\n /// An object representing the error response.\n public static object Error(string errorMessage, object data = null)\n {\n if (data != null)\n {\n // Note: The key is \"error\" for error messages, not \"message\"\n return new\n {\n success = false,\n error = errorMessage,\n data = data,\n };\n }\n else\n {\n return new { success = false, error = errorMessage };\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Vector3Helper.cs", "using Newtonsoft.Json.Linq;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Helper class for Vector3 operations\n /// \n public static class Vector3Helper\n {\n /// \n /// Parses a JArray into a Vector3\n /// \n /// The array containing x, y, z coordinates\n /// A Vector3 with the parsed coordinates\n /// Thrown when array is invalid\n public static Vector3 ParseVector3(JArray array)\n {\n if (array == null || array.Count != 3)\n throw new System.Exception(\"Vector3 must be an array of 3 floats [x, y, z].\");\n return new Vector3((float)array[0], (float)array[1], (float)array[2]);\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/CommandRegistry.cs", "using System;\nusing System.Collections.Generic;\nusing Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Registry for all MCP command handlers (Refactored Version)\n /// \n public static class CommandRegistry\n {\n // Maps command names (matching those called from Python via ctx.bridge.unity_editor.HandlerName)\n // to the corresponding static HandleCommand method in the appropriate tool class.\n private static readonly Dictionary> _handlers = new()\n {\n { \"HandleManageScript\", ManageScript.HandleCommand },\n { \"HandleManageScene\", ManageScene.HandleCommand },\n { \"HandleManageEditor\", ManageEditor.HandleCommand },\n { \"HandleManageGameObject\", ManageGameObject.HandleCommand },\n { \"HandleManageAsset\", ManageAsset.HandleCommand },\n { \"HandleReadConsole\", ReadConsole.HandleCommand },\n { \"HandleExecuteMenuItem\", ExecuteMenuItem.HandleCommand },\n { \"HandleManageShader\", ManageShader.HandleCommand},\n };\n\n /// \n /// Gets a command handler by name.\n /// \n /// Name of the command handler (e.g., \"HandleManageAsset\").\n /// The command handler function if found, null otherwise.\n public static Func GetHandler(string commandName)\n {\n // Use case-insensitive comparison for flexibility, although Python side should be consistent\n return _handlers.TryGetValue(commandName, out var handler) ? handler : null;\n // Consider adding logging here if a handler is not found\n /*\n if (_handlers.TryGetValue(commandName, out var handler)) {\n return handler;\n } else {\n UnityEngine.Debug.LogError($\\\"[CommandRegistry] No handler found for command: {commandName}\\\");\n return null;\n }\n */\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpStatus.cs", "namespace UnityMcpBridge.Editor.Models\n{\n // Enum representing the various status states for MCP clients\n public enum McpStatus\n {\n NotConfigured, // Not set up yet\n Configured, // Successfully configured\n Running, // Service is running\n Connected, // Successfully connected\n IncorrectPath, // Configuration has incorrect paths\n CommunicationError, // Connected but communication issues\n NoResponse, // Connected but not responding\n MissingConfig, // Config file exists but missing required elements\n UnsupportedOS, // OS is not supported\n Error, // General error state\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/ServerConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class ServerConfig\n {\n [JsonProperty(\"unity_host\")]\n public string unityHost = \"localhost\";\n\n [JsonProperty(\"unity_port\")]\n public int unityPort;\n\n [JsonProperty(\"mcp_port\")]\n public int mcpPort;\n\n [JsonProperty(\"connection_timeout\")]\n public float connectionTimeout;\n\n [JsonProperty(\"buffer_size\")]\n public int bufferSize;\n\n [JsonProperty(\"log_level\")]\n public string logLevel;\n\n [JsonProperty(\"log_format\")]\n public string logFormat;\n\n [JsonProperty(\"max_retries\")]\n public int maxRetries;\n\n [JsonProperty(\"retry_delay\")]\n public float retryDelay;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfig\n {\n [JsonProperty(\"mcpServers\")]\n public McpConfigServers mcpServers;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpTypes.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public enum McpTypes\n {\n ClaudeDesktop,\n Cursor,\n VSCode,\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServer.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServer\n {\n [JsonProperty(\"command\")]\n public string command;\n\n [JsonProperty(\"args\")]\n public string[] args;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServers.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServers\n {\n [JsonProperty(\"unityMCP\")]\n public McpConfigServer unityMCP;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/Command.cs", "using Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n /// \n /// Represents a command received from the MCP client\n /// \n public class Command\n {\n /// \n /// The type of command to execute\n /// \n public string type { get; set; }\n\n /// \n /// The parameters for the command\n /// \n public JObject @params { get; set; }\n }\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-20 19:14:42", "created_task_model": "DeepSeek-R1", "function_skeleton": "protected virtual void OnGUI () {}", "code_description": "This code segment functions to: Render a graphical interface with step-by-step configuration instructions, display platform-specific file paths, provide copy functionality for configuration data, and enable direct file access through interactive buttons while managing user feedback states."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\nprotected virtual void OnGUI()\n{\n using (var scroll = new EditorGUILayout.ScrollViewScope(scrollPos))\n {\n scrollPos = scroll.scrollPosition;\n \n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\"Configuration File Path\", EditorStyles.boldLabel);\n \n using (new EditorGUILayout.HorizontalScope())\n {\n EditorGUILayout.TextField(configPath, GUILayout.ExpandWidth(true));\n if (GUILayout.Button(\"Copy\", GUILayout.Width(60)))\n {\n GUIUtility.systemCopyBuffer = configPath;\n pathCopied = true;\n copyFeedbackTimer = 2;\n }\n }\n \n EditorGUILayout.Space(20);\n EditorGUILayout.LabelField(\"Configuration JSON\", EditorStyles.boldLabel);\n \n EditorGUILayout.BeginVertical(GUI.skin.box);\n configJson = EditorGUILayout.TextArea(configJson, GUILayout.Height(200));\n EditorGUILayout.EndVertical();\n \n using (new EditorGUILayout.HorizontalScope())\n {\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Copy JSON\", GUILayout.Width(100)))\n {\n GUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2;\n }\n }\n\n if (pathCopied)\n {\n EditorGUILayout.HelpBox(\"Path copied to clipboard!\", MessageType.Info);\n }\n \n if (jsonCopied)\n {\n EditorGUILayout.HelpBox(\"JSON copied to clipboard!\", MessageType.Info);\n }\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 19-15-13"}, "editdistance_info": {"edit_distance": 11.3435, "calculate_time": "2025-08-20 19:15:13", "true_code_clean": "protected virtual void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n mcpClient.name + \" Manual Configuration\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"The automatic configuration failed. Please follow these steps:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n EditorGUILayout.LabelField(\n \"1. Open \" + mcpClient.name + \" config file by either:\",\n instructionStyle\n );\n if (mcpClient.mcpType == McpTypes.ClaudeDesktop)\n {\n EditorGUILayout.LabelField(\n \" a) Going to Settings > Developer > Edit Config\",\n instructionStyle\n );\n }\n else if (mcpClient.mcpType == McpTypes.Cursor)\n {\n EditorGUILayout.LabelField(\n \" a) Going to File > Preferences > Cursor Settings > MCP > Add new global MCP server\",\n instructionStyle\n );\n }\n EditorGUILayout.LabelField(\" OR\", instructionStyle);\n EditorGUILayout.LabelField(\n \" b) Opening the configuration file at:\",\n instructionStyle\n );\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n displayPath = mcpClient.linuxConfigPath;\n }\n else\n {\n displayPath = configPath;\n }\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"2. Paste the following JSON configuration:\",\n instructionStyle\n );\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); \n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"3. Save the file and restart \" + mcpClient.name,\n instructionStyle\n );\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndScrollView();\n }", "predict_code_clean": "protected virtual void OnGUI()\n{\n using (var scroll = new EditorGUILayout.ScrollViewScope(scrollPos))\n {\n scrollPos = scroll.scrollPosition;\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\"Configuration File Path\", EditorStyles.boldLabel);\n using (new EditorGUILayout.HorizontalScope())\n {\n EditorGUILayout.TextField(configPath, GUILayout.ExpandWidth(true));\n if (GUILayout.Button(\"Copy\", GUILayout.Width(60)))\n {\n GUIUtility.systemCopyBuffer = configPath;\n pathCopied = true;\n copyFeedbackTimer = 2;\n }\n }\n EditorGUILayout.Space(20);\n EditorGUILayout.LabelField(\"Configuration JSON\", EditorStyles.boldLabel);\n EditorGUILayout.BeginVertical(GUI.skin.box);\n configJson = EditorGUILayout.TextArea(configJson, GUILayout.Height(200));\n EditorGUILayout.EndVertical();\n using (new EditorGUILayout.HorizontalScope())\n {\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Copy JSON\", GUILayout.Width(100)))\n {\n GUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2;\n }\n }\n if (pathCopied)\n {\n EditorGUILayout.HelpBox(\"Path copied to clipboard!\", MessageType.Info);\n }\n if (jsonCopied)\n {\n EditorGUILayout.HelpBox(\"JSON copied to clipboard!\", MessageType.Info);\n }\n }\n}"}} {"repo_name": "unity-mcp", "file_name": "/unity-mcp/UnityMcpBridge/Editor/Data/McpClients.cs", "inference_info": {"prefix_code": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class McpClients\n {\n public List clients = new()\n {\n new()\n {\n name = \"Claude Desktop\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Claude\",\n \"claude_desktop_config.json\"\n ),\n mcpType = McpTypes.ClaudeDesktop,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"Cursor\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \".cursor\",\n \"mcp.json\"\n ),\n mcpType = McpTypes.Cursor,\n configStatus = \"Not Configured\",\n },\n new()\n {\n name = \"VSCode GitHub Copilot\",\n windowsConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n linuxConfigPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n ),\n mcpType = McpTypes.VSCode,\n configStatus = \"Not Configured\",\n },\n };\n\n // Initialize status enums after construction\n ", "suffix_code": "\n }\n}\n\n", "middle_code": "public McpClients()\n {\n foreach (var client in clients)\n {\n if (client.configStatus == \"Not Configured\")\n {\n client.status = McpStatus.NotConfigured;\n }\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/unity-mcp/UnityMcpBridge/Editor/Windows/VSCodeManualSetupWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class VSCodeManualSetupWindow : ManualConfigEditorWindow\n {\n public static new void ShowWindow(string configPath, string configJson)\n {\n var window = GetWindow(\"VSCode GitHub Copilot Setup\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.minSize = new Vector2(550, 500);\n \n // Create a McpClient for VSCode\n window.mcpClient = new McpClient\n {\n name = \"VSCode GitHub Copilot\",\n mcpType = McpTypes.VSCode\n };\n \n window.Show();\n }\n\n protected override void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n \"VSCode GitHub Copilot MCP Setup\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"Setting up GitHub Copilot in VSCode with Unity MCP\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Prerequisites\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have VSCode installed\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have GitHub Copilot extension installed in VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Ensure you have a valid GitHub Copilot subscription\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"2. Steps to Configure\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"a) Open VSCode Settings (File > Preferences > Settings)\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"b) Click on the 'Open Settings (JSON)' button in the top right\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"c) Add the MCP configuration shown below to your settings.json file\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"d) Save the file and restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.Space(5);\n \n EditorGUILayout.LabelField(\n \"3. VSCode settings.json location:\",\n EditorStyles.boldLabel\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n else \n {\n displayPath = System.IO.Path.Combine(\n System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile),\n \"Library\",\n \"Application Support\",\n \"Code\",\n \"User\",\n \"settings.json\"\n );\n }\n\n // Store the path in the base class config path\n if (string.IsNullOrEmpty(configPath))\n {\n configPath = displayPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"4. Add this configuration to your settings.json:\",\n EditorStyles.boldLabel\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"5. After configuration:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.LabelField(\n \"• Restart VSCode\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• GitHub Copilot will now be able to interact with your Unity project through the MCP protocol\",\n instructionStyle\n );\n EditorGUILayout.LabelField(\n \"• Remember to have the Unity MCP Bridge running in Unity Editor\",\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected override void Update()\n {\n // Call the base implementation which handles the copy feedback timer\n base.Update();\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Windows/UnityMcpEditorWindow.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing Newtonsoft.Json;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Data;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n public class UnityMcpEditorWindow : EditorWindow\n {\n private bool isUnityBridgeRunning = false;\n private Vector2 scrollPosition;\n private string pythonServerInstallationStatus = \"Not Installed\";\n private Color pythonServerInstallationStatusColor = Color.red;\n private const int unityPort = 6400; // Hardcoded Unity port\n private const int mcpPort = 6500; // Hardcoded MCP port\n private readonly McpClients mcpClients = new();\n \n // Script validation settings\n private int validationLevelIndex = 1; // Default to Standard\n private readonly string[] validationLevelOptions = new string[]\n {\n \"Basic - Only syntax checks\",\n \"Standard - Syntax + Unity practices\", \n \"Comprehensive - All checks + semantic analysis\",\n \"Strict - Full semantic validation (requires Roslyn)\"\n };\n \n // UI state\n private int selectedClientIndex = 0;\n\n [MenuItem(\"Window/Unity MCP\")]\n public static void ShowWindow()\n {\n GetWindow(\"MCP Editor\");\n }\n\n private void OnEnable()\n {\n UpdatePythonServerInstallationStatus();\n\n isUnityBridgeRunning = UnityMcpBridge.IsRunning;\n foreach (McpClient mcpClient in mcpClients.clients)\n {\n CheckMcpConfiguration(mcpClient);\n }\n \n // Load validation level setting\n LoadValidationLevelSetting();\n }\n\n private Color GetStatusColor(McpStatus status)\n {\n // Return appropriate color based on the status enum\n return status switch\n {\n McpStatus.Configured => Color.green,\n McpStatus.Running => Color.green,\n McpStatus.Connected => Color.green,\n McpStatus.IncorrectPath => Color.yellow,\n McpStatus.CommunicationError => Color.yellow,\n McpStatus.NoResponse => Color.yellow,\n _ => Color.red, // Default to red for error states or not configured\n };\n }\n\n private void UpdatePythonServerInstallationStatus()\n {\n string serverPath = ServerInstaller.GetServerPath();\n\n if (File.Exists(Path.Combine(serverPath, \"server.py\")))\n {\n string installedVersion = ServerInstaller.GetInstalledVersion();\n string latestVersion = ServerInstaller.GetLatestVersion();\n\n if (ServerInstaller.IsNewerVersion(latestVersion, installedVersion))\n {\n pythonServerInstallationStatus = \"Newer Version Available\";\n pythonServerInstallationStatusColor = Color.yellow;\n }\n else\n {\n pythonServerInstallationStatus = \"Up to Date\";\n pythonServerInstallationStatusColor = Color.green;\n }\n }\n else\n {\n pythonServerInstallationStatus = \"Not Installed\";\n pythonServerInstallationStatusColor = Color.red;\n }\n }\n\n\n private void DrawStatusDot(Rect statusRect, Color statusColor, float size = 12)\n {\n float offsetX = (statusRect.width - size) / 2;\n float offsetY = (statusRect.height - size) / 2;\n Rect dotRect = new(statusRect.x + offsetX, statusRect.y + offsetY, size, size);\n Vector3 center = new(\n dotRect.x + (dotRect.width / 2),\n dotRect.y + (dotRect.height / 2),\n 0\n );\n float radius = size / 2;\n\n // Draw the main dot\n Handles.color = statusColor;\n Handles.DrawSolidDisc(center, Vector3.forward, radius);\n\n // Draw the border\n Color borderColor = new(\n statusColor.r * 0.7f,\n statusColor.g * 0.7f,\n statusColor.b * 0.7f\n );\n Handles.color = borderColor;\n Handles.DrawWireDisc(center, Vector3.forward, radius);\n }\n\n private void OnGUI()\n {\n scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);\n\n // Header\n DrawHeader();\n \n // Main sections in a more compact layout\n EditorGUILayout.BeginHorizontal();\n \n // Left column - Status and Bridge\n EditorGUILayout.BeginVertical(GUILayout.Width(position.width * 0.5f));\n DrawServerStatusSection();\n EditorGUILayout.Space(5);\n DrawBridgeSection();\n EditorGUILayout.EndVertical();\n \n // Right column - Validation Settings\n EditorGUILayout.BeginVertical();\n DrawValidationSection();\n EditorGUILayout.EndVertical();\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Unified MCP Client Configuration\n DrawUnifiedClientConfiguration();\n\n EditorGUILayout.EndScrollView();\n }\n\n private void DrawHeader()\n {\n EditorGUILayout.Space(15);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 40);\n EditorGUI.DrawRect(titleRect, new Color(0.2f, 0.2f, 0.2f, 0.1f));\n \n GUIStyle titleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 16,\n alignment = TextAnchor.MiddleLeft\n };\n \n GUI.Label(\n new Rect(titleRect.x + 15, titleRect.y + 8, titleRect.width - 30, titleRect.height),\n \"Unity MCP Editor\",\n titleStyle\n );\n EditorGUILayout.Space(15);\n }\n\n private void DrawServerStatusSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Server Status\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(statusRect, pythonServerInstallationStatusColor, 16);\n \n GUIStyle statusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(pythonServerInstallationStatus, statusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(5);\n GUIStyle portStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 11\n };\n EditorGUILayout.LabelField($\"Ports: Unity {unityPort}, MCP {mcpPort}\", portStyle);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawBridgeSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Unity Bridge\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUILayout.BeginHorizontal();\n Color bridgeColor = isUnityBridgeRunning ? Color.green : Color.red;\n Rect bridgeStatusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n DrawStatusDot(bridgeStatusRect, bridgeColor, 16);\n \n GUIStyle bridgeStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(isUnityBridgeRunning ? \"Running\" : \"Stopped\", bridgeStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.Space(8);\n if (GUILayout.Button(isUnityBridgeRunning ? \"Stop Bridge\" : \"Start Bridge\", GUILayout.Height(32)))\n {\n ToggleUnityBridge();\n }\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawValidationSection()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"Script Validation\", sectionTitleStyle);\n EditorGUILayout.Space(8);\n \n EditorGUI.BeginChangeCheck();\n validationLevelIndex = EditorGUILayout.Popup(\"Validation Level\", validationLevelIndex, validationLevelOptions, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n SaveValidationLevelSetting();\n }\n \n EditorGUILayout.Space(8);\n string description = GetValidationLevelDescription(validationLevelIndex);\n EditorGUILayout.HelpBox(description, MessageType.Info);\n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawUnifiedClientConfiguration()\n {\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n \n GUIStyle sectionTitleStyle = new GUIStyle(EditorStyles.boldLabel)\n {\n fontSize = 14\n };\n EditorGUILayout.LabelField(\"MCP Client Configuration\", sectionTitleStyle);\n EditorGUILayout.Space(10);\n \n // Client selector\n string[] clientNames = mcpClients.clients.Select(c => c.name).ToArray();\n EditorGUI.BeginChangeCheck();\n selectedClientIndex = EditorGUILayout.Popup(\"Select Client\", selectedClientIndex, clientNames, GUILayout.Height(20));\n if (EditorGUI.EndChangeCheck())\n {\n selectedClientIndex = Mathf.Clamp(selectedClientIndex, 0, mcpClients.clients.Count - 1);\n }\n \n EditorGUILayout.Space(10);\n \n if (mcpClients.clients.Count > 0 && selectedClientIndex < mcpClients.clients.Count)\n {\n McpClient selectedClient = mcpClients.clients[selectedClientIndex];\n DrawClientConfigurationCompact(selectedClient);\n }\n \n EditorGUILayout.Space(5);\n EditorGUILayout.EndVertical();\n }\n\n private void DrawClientConfigurationCompact(McpClient mcpClient)\n {\n // Status display\n EditorGUILayout.BeginHorizontal();\n Rect statusRect = GUILayoutUtility.GetRect(0, 28, GUILayout.Width(24));\n Color statusColor = GetStatusColor(mcpClient.status);\n DrawStatusDot(statusRect, statusColor, 16);\n \n GUIStyle clientStatusStyle = new GUIStyle(EditorStyles.label)\n {\n fontSize = 12,\n fontStyle = FontStyle.Bold\n };\n EditorGUILayout.LabelField(mcpClient.configStatus, clientStatusStyle, GUILayout.Height(28));\n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(10);\n \n // Action buttons in horizontal layout\n EditorGUILayout.BeginHorizontal();\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n if (GUILayout.Button(\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n else\n {\n if (GUILayout.Button($\"Auto Configure\", GUILayout.Height(32)))\n {\n ConfigureMcpClient(mcpClient);\n }\n }\n \n if (GUILayout.Button(\"Manual Setup\", GUILayout.Height(32)))\n {\n string configPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)\n ? mcpClient.windowsConfigPath\n : mcpClient.linuxConfigPath;\n \n if (mcpClient.mcpType == McpTypes.VSCode)\n {\n string pythonDir = FindPackagePythonDirectory();\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n VSCodeManualSetupWindow.ShowWindow(configPath, manualConfigJson);\n }\n else\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n }\n \n EditorGUILayout.EndHorizontal();\n \n EditorGUILayout.Space(8);\n // Quick info\n GUIStyle configInfoStyle = new GUIStyle(EditorStyles.miniLabel)\n {\n fontSize = 10\n };\n EditorGUILayout.LabelField($\"Config: {Path.GetFileName(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? mcpClient.windowsConfigPath : mcpClient.linuxConfigPath)}\", configInfoStyle);\n }\n\n private void ToggleUnityBridge()\n {\n if (isUnityBridgeRunning)\n {\n UnityMcpBridge.Stop();\n }\n else\n {\n UnityMcpBridge.Start();\n }\n\n isUnityBridgeRunning = !isUnityBridgeRunning;\n }\n\n private string WriteToConfig(string pythonDir, string configPath, McpClient mcpClient = null)\n {\n // Create configuration object for unityMCP\n McpConfigServer unityMCPConfig = new()\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n\n // Read existing config if it exists\n string existingJson = \"{}\";\n if (File.Exists(configPath))\n {\n try\n {\n existingJson = File.ReadAllText(configPath);\n }\n catch (Exception e)\n {\n Debug.LogWarning($\"Error reading existing config: {e.Message}.\");\n }\n }\n\n // Parse the existing JSON while preserving all properties\n dynamic existingConfig = JsonConvert.DeserializeObject(existingJson);\n existingConfig ??= new Newtonsoft.Json.Linq.JObject();\n\n // Handle different client types with a switch statement\n //Comments: Interestingly, VSCode has mcp.servers.unityMCP while others have mcpServers.unityMCP, which is why we need to prevent this\n switch (mcpClient?.mcpType)\n {\n case McpTypes.VSCode:\n // VSCode specific configuration\n // Ensure mcp object exists\n if (existingConfig.mcp == null)\n {\n existingConfig.mcp = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Ensure mcp.servers object exists\n if (existingConfig.mcp.servers == null)\n {\n existingConfig.mcp.servers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in VSCode settings\n existingConfig.mcp.servers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n\n default:\n // Standard MCP configuration (Claude Desktop, Cursor, etc.)\n // Ensure mcpServers object exists\n if (existingConfig.mcpServers == null)\n {\n existingConfig.mcpServers = new Newtonsoft.Json.Linq.JObject();\n }\n\n // Add/update UnityMCP server in standard MCP settings\n existingConfig.mcpServers.unityMCP =\n JsonConvert.DeserializeObject(\n JsonConvert.SerializeObject(unityMCPConfig)\n );\n break;\n }\n\n // Write the merged configuration back to file\n string mergedJson = JsonConvert.SerializeObject(existingConfig, jsonSettings);\n File.WriteAllText(configPath, mergedJson);\n\n return \"Configured successfully\";\n }\n\n private void ShowManualConfigurationInstructions(string configPath, McpClient mcpClient)\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n }\n\n // New method to show manual instructions without changing status\n private void ShowManualInstructionsWindow(string configPath, McpClient mcpClient)\n {\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n string manualConfigJson;\n \n // Create common JsonSerializerSettings\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n \n // Use switch statement to handle different client types\n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n // Create VSCode-specific configuration with proper format\n var vscodeConfig = new\n {\n mcp = new\n {\n servers = new\n {\n unityMCP = new\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" }\n }\n }\n }\n };\n manualConfigJson = JsonConvert.SerializeObject(vscodeConfig, jsonSettings);\n break;\n \n default:\n // Create standard MCP configuration for other clients\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n break;\n }\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private string FindPackagePythonDirectory()\n {\n string pythonDir = ServerInstaller.GetServerPath();\n\n try\n {\n // Try to find the package using Package Manager API\n UnityEditor.PackageManager.Requests.ListRequest request =\n UnityEditor.PackageManager.Client.List();\n while (!request.IsCompleted) { } // Wait for the request to complete\n\n if (request.Status == UnityEditor.PackageManager.StatusCode.Success)\n {\n foreach (UnityEditor.PackageManager.PackageInfo package in request.Result)\n {\n if (package.name == \"com.justinpbarnett.unity-mcp\")\n {\n string packagePath = package.resolvedPath;\n string potentialPythonDir = Path.Combine(packagePath, \"Python\");\n\n if (\n Directory.Exists(potentialPythonDir)\n && File.Exists(Path.Combine(potentialPythonDir, \"server.py\"))\n )\n {\n return potentialPythonDir;\n }\n }\n }\n }\n else if (request.Error != null)\n {\n Debug.LogError(\"Failed to list packages: \" + request.Error.message);\n }\n\n // If not found via Package Manager, try manual approaches\n // First check for local installation\n string[] possibleDirs =\n {\n Path.GetFullPath(Path.Combine(Application.dataPath, \"unity-mcp\", \"Python\")),\n };\n\n foreach (string dir in possibleDirs)\n {\n if (Directory.Exists(dir) && File.Exists(Path.Combine(dir, \"server.py\")))\n {\n return dir;\n }\n }\n\n // If still not found, return the placeholder path\n Debug.LogWarning(\"Could not find Python directory, using placeholder path\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"Error finding package path: {e.Message}\");\n }\n\n return pythonDir;\n }\n\n private string ConfigureMcpClient(McpClient mcpClient)\n {\n try\n {\n // Determine the config file path based on OS\n string configPath;\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n return \"Unsupported OS\";\n }\n\n // Create directory if it doesn't exist\n Directory.CreateDirectory(Path.GetDirectoryName(configPath));\n\n // Find the server.py file location\n string pythonDir = ServerInstaller.GetServerPath();\n\n if (pythonDir == null || !File.Exists(Path.Combine(pythonDir, \"server.py\")))\n {\n ShowManualInstructionsWindow(configPath, mcpClient);\n return \"Manual Configuration Required\";\n }\n\n string result = WriteToConfig(pythonDir, configPath, mcpClient);\n\n // Update the client status after successful configuration\n if (result == \"Configured successfully\")\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n\n return result;\n }\n catch (Exception e)\n {\n // Determine the config file path based on OS for error message\n string configPath = \"\";\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n\n ShowManualInstructionsWindow(configPath, mcpClient);\n Debug.LogError(\n $\"Failed to configure {mcpClient.name}: {e.Message}\\n{e.StackTrace}\"\n );\n return $\"Failed to configure {mcpClient.name}\";\n }\n }\n\n private void ShowCursorManualConfigurationInstructions(\n string configPath,\n McpClient mcpClient\n )\n {\n mcpClient.SetStatus(McpStatus.Error, \"Manual configuration required\");\n\n // Get the Python directory path using Package Manager API\n string pythonDir = FindPackagePythonDirectory();\n\n // Create the manual configuration message\n McpConfig jsonConfig = new()\n {\n mcpServers = new McpConfigServers\n {\n unityMCP = new McpConfigServer\n {\n command = \"uv\",\n args = new[] { \"--directory\", pythonDir, \"run\", \"server.py\" },\n },\n },\n };\n\n JsonSerializerSettings jsonSettings = new() { Formatting = Formatting.Indented };\n string manualConfigJson = JsonConvert.SerializeObject(jsonConfig, jsonSettings);\n\n ManualConfigEditorWindow.ShowWindow(configPath, manualConfigJson, mcpClient);\n }\n\n private void LoadValidationLevelSetting()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n validationLevelIndex = savedLevel.ToLower() switch\n {\n \"basic\" => 0,\n \"standard\" => 1,\n \"comprehensive\" => 2,\n \"strict\" => 3,\n _ => 1 // Default to Standard\n };\n }\n\n private void SaveValidationLevelSetting()\n {\n string levelString = validationLevelIndex switch\n {\n 0 => \"basic\",\n 1 => \"standard\",\n 2 => \"comprehensive\",\n 3 => \"strict\",\n _ => \"standard\"\n };\n EditorPrefs.SetString(\"UnityMCP_ScriptValidationLevel\", levelString);\n }\n\n private string GetValidationLevelDescription(int index)\n {\n return index switch\n {\n 0 => \"Only basic syntax checks (braces, quotes, comments)\",\n 1 => \"Syntax checks + Unity best practices and warnings\",\n 2 => \"All checks + semantic analysis and performance warnings\",\n 3 => \"Full semantic validation with namespace/type resolution (requires Roslyn)\",\n _ => \"Standard validation\"\n };\n }\n\n public static string GetCurrentValidationLevel()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel;\n }\n\n private void CheckMcpConfiguration(McpClient mcpClient)\n {\n try\n {\n string configPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n configPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n configPath = mcpClient.linuxConfigPath;\n }\n else\n {\n mcpClient.SetStatus(McpStatus.UnsupportedOS);\n return;\n }\n\n if (!File.Exists(configPath))\n {\n mcpClient.SetStatus(McpStatus.NotConfigured);\n return;\n }\n\n string configJson = File.ReadAllText(configPath);\n string pythonDir = ServerInstaller.GetServerPath();\n \n // Use switch statement to handle different client types, extracting common logic\n string[] args = null;\n bool configExists = false;\n \n switch (mcpClient.mcpType)\n {\n case McpTypes.VSCode:\n dynamic config = JsonConvert.DeserializeObject(configJson);\n \n if (config?.mcp?.servers?.unityMCP != null)\n {\n // Extract args from VSCode config format\n args = config.mcp.servers.unityMCP.args.ToObject();\n configExists = true;\n }\n break;\n \n default:\n // Standard MCP configuration check for Claude Desktop, Cursor, etc.\n McpConfig standardConfig = JsonConvert.DeserializeObject(configJson);\n \n if (standardConfig?.mcpServers?.unityMCP != null)\n {\n args = standardConfig.mcpServers.unityMCP.args;\n configExists = true;\n }\n break;\n }\n \n // Common logic for checking configuration status\n if (configExists)\n {\n if (pythonDir != null && \n Array.Exists(args, arg => arg.Contains(pythonDir, StringComparison.Ordinal)))\n {\n mcpClient.SetStatus(McpStatus.Configured);\n }\n else\n {\n mcpClient.SetStatus(McpStatus.IncorrectPath);\n }\n }\n else\n {\n mcpClient.SetStatus(McpStatus.MissingConfig);\n }\n }\n catch (Exception e)\n {\n mcpClient.SetStatus(McpStatus.Error, e.Message);\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/ServerInstaller.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Runtime.InteropServices;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n public static class ServerInstaller\n {\n private const string RootFolder = \"UnityMCP\";\n private const string ServerFolder = \"UnityMcpServer\";\n private const string BranchName = \"master\";\n private const string GitUrl = \"https://github.com/justinpbarnett/unity-mcp.git\";\n private const string PyprojectUrl =\n \"https://raw.githubusercontent.com/justinpbarnett/unity-mcp/refs/heads/\"\n + BranchName\n + \"/UnityMcpServer/src/pyproject.toml\";\n\n /// \n /// Ensures the unity-mcp-server is installed and up to date.\n /// \n public static void EnsureServerInstalled()\n {\n try\n {\n string saveLocation = GetSaveLocation();\n\n if (!IsServerInstalled(saveLocation))\n {\n InstallServer(saveLocation);\n }\n else\n {\n string installedVersion = GetInstalledVersion();\n string latestVersion = GetLatestVersion();\n\n if (IsNewerVersion(latestVersion, installedVersion))\n {\n UpdateServer(saveLocation);\n }\n else { }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure server installation: {ex.Message}\");\n }\n }\n\n public static string GetServerPath()\n {\n return Path.Combine(GetSaveLocation(), ServerFolder, \"src\");\n }\n\n /// \n /// Gets the platform-specific save location for the server.\n /// \n private static string GetSaveLocation()\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"AppData\",\n \"Local\",\n \"Programs\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n return Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"bin\",\n RootFolder\n );\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n string path = \"/usr/local/bin\";\n return !Directory.Exists(path) || !IsDirectoryWritable(path)\n ? Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),\n \"Applications\",\n RootFolder\n )\n : Path.Combine(path, RootFolder);\n }\n throw new Exception(\"Unsupported operating system.\");\n }\n\n private static bool IsDirectoryWritable(string path)\n {\n try\n {\n File.Create(Path.Combine(path, \"test.txt\")).Dispose();\n File.Delete(Path.Combine(path, \"test.txt\"));\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Checks if the server is installed at the specified location.\n /// \n private static bool IsServerInstalled(string location)\n {\n return Directory.Exists(location)\n && File.Exists(Path.Combine(location, ServerFolder, \"src\", \"pyproject.toml\"));\n }\n\n /// \n /// Installs the server by cloning only the UnityMcpServer folder from the repository and setting up dependencies.\n /// \n private static void InstallServer(string location)\n {\n // Create the src directory where the server code will reside\n Directory.CreateDirectory(location);\n\n // Initialize git repo in the src directory\n RunCommand(\"git\", $\"init\", workingDirectory: location);\n\n // Add remote\n RunCommand(\"git\", $\"remote add origin {GitUrl}\", workingDirectory: location);\n\n // Configure sparse checkout\n RunCommand(\"git\", \"config core.sparseCheckout true\", workingDirectory: location);\n\n // Set sparse checkout path to only include UnityMcpServer folder\n string sparseCheckoutPath = Path.Combine(location, \".git\", \"info\", \"sparse-checkout\");\n File.WriteAllText(sparseCheckoutPath, $\"{ServerFolder}/\");\n\n // Fetch and checkout the branch\n RunCommand(\"git\", $\"fetch --depth=1 origin {BranchName}\", workingDirectory: location);\n RunCommand(\"git\", $\"checkout {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Fetches the currently installed version from the local pyproject.toml file.\n /// \n public static string GetInstalledVersion()\n {\n string pyprojectPath = Path.Combine(\n GetSaveLocation(),\n ServerFolder,\n \"src\",\n \"pyproject.toml\"\n );\n return ParseVersionFromPyproject(File.ReadAllText(pyprojectPath));\n }\n\n /// \n /// Fetches the latest version from the GitHub pyproject.toml file.\n /// \n public static string GetLatestVersion()\n {\n using WebClient webClient = new();\n string pyprojectContent = webClient.DownloadString(PyprojectUrl);\n return ParseVersionFromPyproject(pyprojectContent);\n }\n\n /// \n /// Updates the server by pulling the latest changes for the UnityMcpServer folder only.\n /// \n private static void UpdateServer(string location)\n {\n RunCommand(\"git\", $\"pull origin {BranchName}\", workingDirectory: location);\n }\n\n /// \n /// Parses the version number from pyproject.toml content.\n /// \n private static string ParseVersionFromPyproject(string content)\n {\n foreach (string line in content.Split('\\n'))\n {\n if (line.Trim().StartsWith(\"version =\"))\n {\n string[] parts = line.Split('=');\n if (parts.Length == 2)\n {\n return parts[1].Trim().Trim('\"');\n }\n }\n }\n throw new Exception(\"Version not found in pyproject.toml\");\n }\n\n /// \n /// Compares two version strings to determine if the latest is newer.\n /// \n public static bool IsNewerVersion(string latest, string installed)\n {\n int[] latestParts = latest.Split('.').Select(int.Parse).ToArray();\n int[] installedParts = installed.Split('.').Select(int.Parse).ToArray();\n for (int i = 0; i < Math.Min(latestParts.Length, installedParts.Length); i++)\n {\n if (latestParts[i] > installedParts[i])\n {\n return true;\n }\n\n if (latestParts[i] < installedParts[i])\n {\n return false;\n }\n }\n return latestParts.Length > installedParts.Length;\n }\n\n /// \n /// Runs a command-line process and handles output/errors.\n /// \n private static void RunCommand(\n string command,\n string arguments,\n string workingDirectory = null\n )\n {\n System.Diagnostics.Process process = new()\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = command,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n WorkingDirectory = workingDirectory ?? string.Empty,\n },\n };\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n if (process.ExitCode != 0)\n {\n throw new Exception(\n $\"Command failed: {command} {arguments}\\nOutput: {output}\\nError: {error}\"\n );\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Windows/ManualConfigEditorWindow.cs", "using System.Runtime.InteropServices;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Windows\n{\n // Editor window to display manual configuration instructions\n public class ManualConfigEditorWindow : EditorWindow\n {\n protected string configPath;\n protected string configJson;\n protected Vector2 scrollPos;\n protected bool pathCopied = false;\n protected bool jsonCopied = false;\n protected float copyFeedbackTimer = 0;\n protected McpClient mcpClient;\n\n public static void ShowWindow(string configPath, string configJson, McpClient mcpClient)\n {\n var window = GetWindow(\"Manual Configuration\");\n window.configPath = configPath;\n window.configJson = configJson;\n window.mcpClient = mcpClient;\n window.minSize = new Vector2(500, 400);\n window.Show();\n }\n\n protected virtual void OnGUI()\n {\n scrollPos = EditorGUILayout.BeginScrollView(scrollPos);\n\n // Header with improved styling\n EditorGUILayout.Space(10);\n Rect titleRect = EditorGUILayout.GetControlRect(false, 30);\n EditorGUI.DrawRect(\n new Rect(titleRect.x, titleRect.y, titleRect.width, titleRect.height),\n new Color(0.2f, 0.2f, 0.2f, 0.1f)\n );\n GUI.Label(\n new Rect(titleRect.x + 10, titleRect.y + 6, titleRect.width - 20, titleRect.height),\n mcpClient.name + \" Manual Configuration\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n // Instructions with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n Rect headerRect = EditorGUILayout.GetControlRect(false, 24);\n EditorGUI.DrawRect(\n new Rect(headerRect.x, headerRect.y, headerRect.width, headerRect.height),\n new Color(0.1f, 0.1f, 0.1f, 0.2f)\n );\n GUI.Label(\n new Rect(\n headerRect.x + 8,\n headerRect.y + 4,\n headerRect.width - 16,\n headerRect.height\n ),\n \"The automatic configuration failed. Please follow these steps:\",\n EditorStyles.boldLabel\n );\n EditorGUILayout.Space(10);\n\n GUIStyle instructionStyle = new(EditorStyles.wordWrappedLabel)\n {\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n EditorGUILayout.LabelField(\n \"1. Open \" + mcpClient.name + \" config file by either:\",\n instructionStyle\n );\n if (mcpClient.mcpType == McpTypes.ClaudeDesktop)\n {\n EditorGUILayout.LabelField(\n \" a) Going to Settings > Developer > Edit Config\",\n instructionStyle\n );\n }\n else if (mcpClient.mcpType == McpTypes.Cursor)\n {\n EditorGUILayout.LabelField(\n \" a) Going to File > Preferences > Cursor Settings > MCP > Add new global MCP server\",\n instructionStyle\n );\n }\n EditorGUILayout.LabelField(\" OR\", instructionStyle);\n EditorGUILayout.LabelField(\n \" b) Opening the configuration file at:\",\n instructionStyle\n );\n\n // Path section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n string displayPath;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n displayPath = mcpClient.windowsConfigPath;\n }\n else if (\n RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\n || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)\n )\n {\n displayPath = mcpClient.linuxConfigPath;\n }\n else\n {\n displayPath = configPath;\n }\n\n // Prevent text overflow by allowing the text field to wrap\n GUIStyle pathStyle = new(EditorStyles.textField) { wordWrap = true };\n\n EditorGUILayout.TextField(\n displayPath,\n pathStyle,\n GUILayout.Height(EditorGUIUtility.singleLineHeight)\n );\n\n // Copy button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n GUIStyle copyButtonStyle = new(GUI.skin.button)\n {\n padding = new RectOffset(15, 15, 5, 5),\n margin = new RectOffset(10, 10, 5, 5),\n };\n\n if (\n GUILayout.Button(\n \"Copy Path\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = displayPath;\n pathCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (\n GUILayout.Button(\n \"Open File\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n // Open the file using the system's default application\n System.Diagnostics.Process.Start(\n new System.Diagnostics.ProcessStartInfo\n {\n FileName = displayPath,\n UseShellExecute = true,\n }\n );\n }\n\n if (pathCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n EditorGUILayout.LabelField(\n \"2. Paste the following JSON configuration:\",\n instructionStyle\n );\n\n // JSON section with improved styling\n EditorGUILayout.BeginVertical(EditorStyles.helpBox);\n\n // Improved text area for JSON with syntax highlighting colors\n GUIStyle jsonStyle = new(EditorStyles.textArea)\n {\n font = EditorStyles.boldFont,\n wordWrap = true,\n };\n jsonStyle.normal.textColor = new Color(0.3f, 0.6f, 0.9f); // Syntax highlighting blue\n\n // Draw the JSON in a text area with a taller height for better readability\n EditorGUILayout.TextArea(configJson, jsonStyle, GUILayout.Height(200));\n\n // Copy JSON button with improved styling\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n\n if (\n GUILayout.Button(\n \"Copy JSON\",\n copyButtonStyle,\n GUILayout.Height(25),\n GUILayout.Width(100)\n )\n )\n {\n EditorGUIUtility.systemCopyBuffer = configJson;\n jsonCopied = true;\n copyFeedbackTimer = 2f;\n }\n\n if (jsonCopied)\n {\n GUIStyle feedbackStyle = new(EditorStyles.label);\n feedbackStyle.normal.textColor = Color.green;\n EditorGUILayout.LabelField(\"Copied!\", feedbackStyle, GUILayout.Width(60));\n }\n\n EditorGUILayout.EndHorizontal();\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n EditorGUILayout.LabelField(\n \"3. Save the file and restart \" + mcpClient.name,\n instructionStyle\n );\n\n EditorGUILayout.EndVertical();\n\n EditorGUILayout.Space(10);\n\n // Close button at the bottom\n EditorGUILayout.BeginHorizontal();\n GUILayout.FlexibleSpace();\n if (GUILayout.Button(\"Close\", GUILayout.Height(30), GUILayout.Width(100)))\n {\n Close();\n }\n GUILayout.FlexibleSpace();\n EditorGUILayout.EndHorizontal();\n\n EditorGUILayout.EndScrollView();\n }\n\n protected virtual void Update()\n {\n // Handle the feedback message timer\n if (copyFeedbackTimer > 0)\n {\n copyFeedbackTimer -= Time.deltaTime;\n if (copyFeedbackTimer <= 0)\n {\n pathCopied = false;\n jsonCopied = false;\n Repaint();\n }\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpClient.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public class McpClient\n {\n public string name;\n public string windowsConfigPath;\n public string linuxConfigPath;\n public McpTypes mcpType;\n public string configStatus;\n public McpStatus status = McpStatus.NotConfigured;\n\n // Helper method to convert the enum to a display string\n public string GetStatusDisplayString()\n {\n return status switch\n {\n McpStatus.NotConfigured => \"Not Configured\",\n McpStatus.Configured => \"Configured\",\n McpStatus.Running => \"Running\",\n McpStatus.Connected => \"Connected\",\n McpStatus.IncorrectPath => \"Incorrect Path\",\n McpStatus.CommunicationError => \"Communication Error\",\n McpStatus.NoResponse => \"No Response\",\n McpStatus.UnsupportedOS => \"Unsupported OS\",\n McpStatus.MissingConfig => \"Missing UnityMCP Config\",\n McpStatus.Error => configStatus.StartsWith(\"Error:\") ? configStatus : \"Error\",\n _ => \"Unknown\",\n };\n }\n\n // Helper method to set both status enum and string for backward compatibility\n public void SetStatus(McpStatus newStatus, string errorDetails = null)\n {\n status = newStatus;\n\n if (newStatus == McpStatus.Error && !string.IsNullOrEmpty(errorDetails))\n {\n configStatus = $\"Error: {errorDetails}\";\n }\n else\n {\n configStatus = GetStatusDisplayString();\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/UnityMcpBridge.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\nusing UnityMcpBridge.Editor.Models;\nusing UnityMcpBridge.Editor.Tools;\n\nnamespace UnityMcpBridge.Editor\n{\n [InitializeOnLoad]\n public static partial class UnityMcpBridge\n {\n private static TcpListener listener;\n private static bool isRunning = false;\n private static readonly object lockObj = new();\n private static Dictionary<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > commandQueue = new();\n private static readonly int unityPort = 6400; // Hardcoded port\n\n public static bool IsRunning => isRunning;\n\n public static bool FolderExists(string path)\n {\n if (string.IsNullOrEmpty(path))\n {\n return false;\n }\n\n if (path.Equals(\"Assets\", StringComparison.OrdinalIgnoreCase))\n {\n return true;\n }\n\n string fullPath = Path.Combine(\n Application.dataPath,\n path.StartsWith(\"Assets/\") ? path[7..] : path\n );\n return Directory.Exists(fullPath);\n }\n\n static UnityMcpBridge()\n {\n Start();\n EditorApplication.quitting += Stop;\n }\n\n public static void Start()\n {\n Stop();\n\n try\n {\n ServerInstaller.EnsureServerInstalled();\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to ensure UnityMcpServer is installed: {ex.Message}\");\n }\n\n if (isRunning)\n {\n return;\n }\n\n try\n {\n listener = new TcpListener(IPAddress.Loopback, unityPort);\n listener.Start();\n isRunning = true;\n Debug.Log($\"UnityMcpBridge started on port {unityPort}.\");\n // Assuming ListenerLoop and ProcessCommands are defined elsewhere\n Task.Run(ListenerLoop);\n EditorApplication.update += ProcessCommands;\n }\n catch (SocketException ex)\n {\n if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)\n {\n Debug.LogError(\n $\"Port {unityPort} is already in use. Ensure no other instances are running or change the port.\"\n );\n }\n else\n {\n Debug.LogError($\"Failed to start TCP listener: {ex.Message}\");\n }\n }\n }\n\n public static void Stop()\n {\n if (!isRunning)\n {\n return;\n }\n\n try\n {\n listener?.Stop();\n listener = null;\n isRunning = false;\n EditorApplication.update -= ProcessCommands;\n Debug.Log(\"UnityMcpBridge stopped.\");\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error stopping UnityMcpBridge: {ex.Message}\");\n }\n }\n\n private static async Task ListenerLoop()\n {\n while (isRunning)\n {\n try\n {\n TcpClient client = await listener.AcceptTcpClientAsync();\n // Enable basic socket keepalive\n client.Client.SetSocketOption(\n SocketOptionLevel.Socket,\n SocketOptionName.KeepAlive,\n true\n );\n\n // Set longer receive timeout to prevent quick disconnections\n client.ReceiveTimeout = 60000; // 60 seconds\n\n // Fire and forget each client connection\n _ = HandleClientAsync(client);\n }\n catch (Exception ex)\n {\n if (isRunning)\n {\n Debug.LogError($\"Listener error: {ex.Message}\");\n }\n }\n }\n }\n\n private static async Task HandleClientAsync(TcpClient client)\n {\n using (client)\n using (NetworkStream stream = client.GetStream())\n {\n byte[] buffer = new byte[8192];\n while (isRunning)\n {\n try\n {\n int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);\n if (bytesRead == 0)\n {\n break; // Client disconnected\n }\n\n string commandText = System.Text.Encoding.UTF8.GetString(\n buffer,\n 0,\n bytesRead\n );\n string commandId = Guid.NewGuid().ToString();\n TaskCompletionSource tcs = new();\n\n // Special handling for ping command to avoid JSON parsing\n if (commandText.Trim() == \"ping\")\n {\n // Direct response to ping without going through JSON parsing\n byte[] pingResponseBytes = System.Text.Encoding.UTF8.GetBytes(\n /*lang=json,strict*/\n \"{\\\"status\\\":\\\"success\\\",\\\"result\\\":{\\\"message\\\":\\\"pong\\\"}}\"\n );\n await stream.WriteAsync(pingResponseBytes, 0, pingResponseBytes.Length);\n continue;\n }\n\n lock (lockObj)\n {\n commandQueue[commandId] = (commandText, tcs);\n }\n\n string response = await tcs.Task;\n byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);\n await stream.WriteAsync(responseBytes, 0, responseBytes.Length);\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Client handler error: {ex.Message}\");\n break;\n }\n }\n }\n }\n\n private static void ProcessCommands()\n {\n List processedIds = new();\n lock (lockObj)\n {\n foreach (\n KeyValuePair<\n string,\n (string commandJson, TaskCompletionSource tcs)\n > kvp in commandQueue.ToList()\n )\n {\n string id = kvp.Key;\n string commandText = kvp.Value.commandJson;\n TaskCompletionSource tcs = kvp.Value.tcs;\n\n try\n {\n // Special case handling\n if (string.IsNullOrEmpty(commandText))\n {\n var emptyResponse = new\n {\n status = \"error\",\n error = \"Empty command received\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(emptyResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Trim the command text to remove any whitespace\n commandText = commandText.Trim();\n\n // Non-JSON direct commands handling (like ping)\n if (commandText == \"ping\")\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n tcs.SetResult(JsonConvert.SerializeObject(pingResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Check if the command is valid JSON before attempting to deserialize\n if (!IsValidJson(commandText))\n {\n var invalidJsonResponse = new\n {\n status = \"error\",\n error = \"Invalid JSON format\",\n receivedText = commandText.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n tcs.SetResult(JsonConvert.SerializeObject(invalidJsonResponse));\n processedIds.Add(id);\n continue;\n }\n\n // Normal JSON command processing\n Command command = JsonConvert.DeserializeObject(commandText);\n \n if (command == null)\n {\n var nullCommandResponse = new\n {\n status = \"error\",\n error = \"Command deserialized to null\",\n details = \"The command was valid JSON but could not be deserialized to a Command object\",\n };\n tcs.SetResult(JsonConvert.SerializeObject(nullCommandResponse));\n }\n else\n {\n string responseJson = ExecuteCommand(command);\n tcs.SetResult(responseJson);\n }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Error processing command: {ex.Message}\\n{ex.StackTrace}\");\n\n var response = new\n {\n status = \"error\",\n error = ex.Message,\n commandType = \"Unknown (error during processing)\",\n receivedText = commandText?.Length > 50\n ? commandText[..50] + \"...\"\n : commandText,\n };\n string responseJson = JsonConvert.SerializeObject(response);\n tcs.SetResult(responseJson);\n }\n\n processedIds.Add(id);\n }\n\n foreach (string id in processedIds)\n {\n commandQueue.Remove(id);\n }\n }\n }\n\n // Helper method to check if a string is valid JSON\n private static bool IsValidJson(string text)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n return false;\n }\n\n text = text.Trim();\n if (\n (text.StartsWith(\"{\") && text.EndsWith(\"}\"))\n || // Object\n (text.StartsWith(\"[\") && text.EndsWith(\"]\"))\n ) // Array\n {\n try\n {\n JToken.Parse(text);\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n return false;\n }\n\n private static string ExecuteCommand(Command command)\n {\n try\n {\n if (string.IsNullOrEmpty(command.type))\n {\n var errorResponse = new\n {\n status = \"error\",\n error = \"Command type cannot be empty\",\n details = \"A valid command type is required for processing\",\n };\n return JsonConvert.SerializeObject(errorResponse);\n }\n\n // Handle ping command for connection verification\n if (command.type.Equals(\"ping\", StringComparison.OrdinalIgnoreCase))\n {\n var pingResponse = new\n {\n status = \"success\",\n result = new { message = \"pong\" },\n };\n return JsonConvert.SerializeObject(pingResponse);\n }\n\n // Use JObject for parameters as the new handlers likely expect this\n JObject paramsObject = command.@params ?? new JObject();\n\n // Route command based on the new tool structure from the refactor plan\n object result = command.type switch\n {\n // Maps the command type (tool name) to the corresponding handler's static HandleCommand method\n // Assumes each handler class has a static method named 'HandleCommand' that takes JObject parameters\n \"manage_script\" => ManageScript.HandleCommand(paramsObject),\n \"manage_scene\" => ManageScene.HandleCommand(paramsObject),\n \"manage_editor\" => ManageEditor.HandleCommand(paramsObject),\n \"manage_gameobject\" => ManageGameObject.HandleCommand(paramsObject),\n \"manage_asset\" => ManageAsset.HandleCommand(paramsObject),\n \"manage_shader\" => ManageShader.HandleCommand(paramsObject),\n \"read_console\" => ReadConsole.HandleCommand(paramsObject),\n \"execute_menu_item\" => ExecuteMenuItem.HandleCommand(paramsObject),\n _ => throw new ArgumentException(\n $\"Unknown or unsupported command type: {command.type}\"\n ),\n };\n\n // Standard success response format\n var response = new { status = \"success\", result };\n return JsonConvert.SerializeObject(response);\n }\n catch (Exception ex)\n {\n // Log the detailed error in Unity for debugging\n Debug.LogError(\n $\"Error executing command '{command?.type ?? \"Unknown\"}': {ex.Message}\\n{ex.StackTrace}\"\n );\n\n // Standard error response format\n var response = new\n {\n status = \"error\",\n error = ex.Message, // Provide the specific error message\n command = command?.type ?? \"Unknown\", // Include the command type if available\n stackTrace = ex.StackTrace, // Include stack trace for detailed debugging\n paramsSummary = command?.@params != null\n ? GetParamsSummary(command.@params)\n : \"No parameters\", // Summarize parameters for context\n };\n return JsonConvert.SerializeObject(response);\n }\n }\n\n // Helper method to get a summary of parameters for error reporting\n private static string GetParamsSummary(JObject @params)\n {\n try\n {\n return @params == null || !@params.HasValues\n ? \"No parameters\"\n : string.Join(\n \", \",\n @params\n .Properties()\n .Select(static p =>\n $\"{p.Name}: {p.Value?.ToString()?[..Math.Min(20, p.Value?.ToString()?.Length ?? 0)]}\"\n )\n );\n }\n catch\n {\n return \"Could not summarize parameters\";\n }\n }\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScene.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles scene management operations like loading, saving, creating, and querying hierarchy.\n /// \n public static class ManageScene\n {\n /// \n /// Main handler for scene management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n int? buildIndex = @params[\"buildIndex\"]?.ToObject();\n // bool loadAdditive = @params[\"loadAdditive\"]?.ToObject() ?? false; // Example for future extension\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n string relativeDir = path ?? string.Empty;\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n\n // Apply default *after* sanitizing, using the original path variable for the check\n if (string.IsNullOrEmpty(path) && action == \"create\") // Check original path for emptiness\n {\n relativeDir = \"Scenes\"; // Default relative directory\n }\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n string sceneFileName = string.IsNullOrEmpty(name) ? null : $\"{name}.unity\";\n // Construct full system path correctly: ProjectRoot/Assets/relativeDir/sceneFileName\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Combine with Assets path (Application.dataPath ends in Assets)\n string fullPath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(fullPathDir, sceneFileName);\n // Ensure relativePath always starts with \"Assets/\" and uses forward slashes\n string relativePath = string.IsNullOrEmpty(sceneFileName)\n ? null\n : Path.Combine(\"Assets\", relativeDir, sceneFileName).Replace('\\\\', '/');\n\n // Ensure directory exists for 'create'\n if (action == \"create\" && !string.IsNullOrEmpty(fullPathDir))\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route action\n switch (action)\n {\n case \"create\":\n if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(relativePath))\n return Response.Error(\n \"'name' and 'path' parameters are required for 'create' action.\"\n );\n return CreateScene(fullPath, relativePath);\n case \"load\":\n // Loading can be done by path/name or build index\n if (!string.IsNullOrEmpty(relativePath))\n return LoadScene(relativePath);\n else if (buildIndex.HasValue)\n return LoadScene(buildIndex.Value);\n else\n return Response.Error(\n \"Either 'name'/'path' or 'buildIndex' must be provided for 'load' action.\"\n );\n case \"save\":\n // Save current scene, optionally to a new path\n return SaveScene(fullPath, relativePath);\n case \"get_hierarchy\":\n return GetSceneHierarchy();\n case \"get_active\":\n return GetActiveSceneInfo();\n case \"get_build_settings\":\n return GetBuildSettingsScenes();\n // Add cases for modifying build settings, additive loading, unloading etc.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions: create, load, save, get_hierarchy, get_active, get_build_settings.\"\n );\n }\n }\n\n private static object CreateScene(string fullPath, string relativePath)\n {\n if (File.Exists(fullPath))\n {\n return Response.Error($\"Scene already exists at '{relativePath}'.\");\n }\n\n try\n {\n // Create a new empty scene\n Scene newScene = EditorSceneManager.NewScene(\n NewSceneSetup.EmptyScene,\n NewSceneMode.Single\n );\n // Save it to the specified path\n bool saved = EditorSceneManager.SaveScene(newScene, relativePath);\n\n if (saved)\n {\n AssetDatabase.Refresh(); // Ensure Unity sees the new scene file\n return Response.Success(\n $\"Scene '{Path.GetFileName(relativePath)}' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n else\n {\n // If SaveScene fails, it might leave an untitled scene open.\n // Optionally try to close it, but be cautious.\n return Response.Error($\"Failed to save new scene to '{relativePath}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error creating scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(string relativePath)\n {\n if (\n !File.Exists(\n Path.Combine(\n Application.dataPath.Substring(\n 0,\n Application.dataPath.Length - \"Assets\".Length\n ),\n relativePath\n )\n )\n )\n {\n return Response.Error($\"Scene file not found at '{relativePath}'.\");\n }\n\n // Check for unsaved changes in the current scene\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n // Optionally prompt the user or save automatically before loading\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n // Example: bool saveOK = EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();\n // if (!saveOK) return Response.Error(\"Load cancelled by user.\");\n }\n\n try\n {\n EditorSceneManager.OpenScene(relativePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene '{relativePath}' loaded successfully.\",\n new\n {\n path = relativePath,\n name = Path.GetFileNameWithoutExtension(relativePath),\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error loading scene '{relativePath}': {e.Message}\");\n }\n }\n\n private static object LoadScene(int buildIndex)\n {\n if (buildIndex < 0 || buildIndex >= SceneManager.sceneCountInBuildSettings)\n {\n return Response.Error(\n $\"Invalid build index: {buildIndex}. Must be between 0 and {SceneManager.sceneCountInBuildSettings - 1}.\"\n );\n }\n\n // Check for unsaved changes\n if (EditorSceneManager.GetActiveScene().isDirty)\n {\n return Response.Error(\n \"Current scene has unsaved changes. Please save or discard changes before loading a new scene.\"\n );\n }\n\n try\n {\n string scenePath = SceneUtility.GetScenePathByBuildIndex(buildIndex);\n EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);\n return Response.Success(\n $\"Scene at build index {buildIndex} ('{scenePath}') loaded successfully.\",\n new\n {\n path = scenePath,\n name = Path.GetFileNameWithoutExtension(scenePath),\n buildIndex = buildIndex,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error loading scene with build index {buildIndex}: {e.Message}\"\n );\n }\n }\n\n private static object SaveScene(string fullPath, string relativePath)\n {\n try\n {\n Scene currentScene = EditorSceneManager.GetActiveScene();\n if (!currentScene.IsValid())\n {\n return Response.Error(\"No valid scene is currently active to save.\");\n }\n\n bool saved;\n string finalPath = currentScene.path; // Path where it was last saved or will be saved\n\n if (!string.IsNullOrEmpty(relativePath) && currentScene.path != relativePath)\n {\n // Save As...\n // Ensure directory exists\n string dir = Path.GetDirectoryName(fullPath);\n if (!Directory.Exists(dir))\n Directory.CreateDirectory(dir);\n\n saved = EditorSceneManager.SaveScene(currentScene, relativePath);\n finalPath = relativePath;\n }\n else\n {\n // Save (overwrite existing or save untitled)\n if (string.IsNullOrEmpty(currentScene.path))\n {\n // Scene is untitled, needs a path\n return Response.Error(\n \"Cannot save an untitled scene without providing a 'name' and 'path'. Use Save As functionality.\"\n );\n }\n saved = EditorSceneManager.SaveScene(currentScene);\n }\n\n if (saved)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Scene '{currentScene.name}' saved successfully to '{finalPath}'.\",\n new { path = finalPath, name = currentScene.name }\n );\n }\n else\n {\n return Response.Error($\"Failed to save scene '{currentScene.name}'.\");\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error saving scene: {e.Message}\");\n }\n }\n\n private static object GetActiveSceneInfo()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid())\n {\n return Response.Error(\"No active scene found.\");\n }\n\n var sceneInfo = new\n {\n name = activeScene.name,\n path = activeScene.path,\n buildIndex = activeScene.buildIndex, // -1 if not in build settings\n isDirty = activeScene.isDirty,\n isLoaded = activeScene.isLoaded,\n rootCount = activeScene.rootCount,\n };\n\n return Response.Success(\"Retrieved active scene information.\", sceneInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active scene info: {e.Message}\");\n }\n }\n\n private static object GetBuildSettingsScenes()\n {\n try\n {\n var scenes = new List();\n for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)\n {\n var scene = EditorBuildSettings.scenes[i];\n scenes.Add(\n new\n {\n path = scene.path,\n guid = scene.guid.ToString(),\n enabled = scene.enabled,\n buildIndex = i, // Actual build index considering only enabled scenes might differ\n }\n );\n }\n return Response.Success(\"Retrieved scenes from Build Settings.\", scenes);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scenes from Build Settings: {e.Message}\");\n }\n }\n\n private static object GetSceneHierarchy()\n {\n try\n {\n Scene activeScene = EditorSceneManager.GetActiveScene();\n if (!activeScene.IsValid() || !activeScene.isLoaded)\n {\n return Response.Error(\n \"No valid and loaded scene is active to get hierarchy from.\"\n );\n }\n\n GameObject[] rootObjects = activeScene.GetRootGameObjects();\n var hierarchy = rootObjects.Select(go => GetGameObjectDataRecursive(go)).ToList();\n\n return Response.Success(\n $\"Retrieved hierarchy for scene '{activeScene.name}'.\",\n hierarchy\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting scene hierarchy: {e.Message}\");\n }\n }\n\n /// \n /// Recursively builds a data representation of a GameObject and its children.\n /// \n private static object GetGameObjectDataRecursive(GameObject go)\n {\n if (go == null)\n return null;\n\n var childrenData = new List();\n foreach (Transform child in go.transform)\n {\n childrenData.Add(GetGameObjectDataRecursive(child.gameObject));\n }\n\n var gameObjectData = new Dictionary\n {\n { \"name\", go.name },\n { \"activeSelf\", go.activeSelf },\n { \"activeInHierarchy\", go.activeInHierarchy },\n { \"tag\", go.tag },\n { \"layer\", go.layer },\n { \"isStatic\", go.isStatic },\n { \"instanceID\", go.GetInstanceID() }, // Useful unique identifier\n {\n \"transform\",\n new\n {\n position = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n }, // Euler for simplicity\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n }\n },\n { \"children\", childrenData },\n };\n\n return gameObjectData;\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageAsset.cs", "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\n#if UNITY_6000_0_OR_NEWER\nusing PhysicsMaterialType = UnityEngine.PhysicsMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicsMaterialCombine; \n#else\nusing PhysicsMaterialType = UnityEngine.PhysicMaterial;\nusing PhysicsMaterialCombine = UnityEngine.PhysicMaterialCombine;\n#endif\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles asset management operations within the Unity project.\n /// \n public static class ManageAsset\n {\n // --- Main Handler ---\n\n // Define the list of valid actions\n private static readonly List ValidActions = new List\n {\n \"import\",\n \"create\",\n \"modify\",\n \"delete\",\n \"duplicate\",\n \"move\",\n \"rename\",\n \"search\",\n \"get_info\",\n \"create_folder\",\n \"get_components\",\n };\n\n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Check if the action is valid before switching\n if (!ValidActions.Contains(action))\n {\n string validActionsList = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsList}\"\n );\n }\n\n // Common parameters\n string path = @params[\"path\"]?.ToString();\n\n try\n {\n switch (action)\n {\n case \"import\":\n // Note: Unity typically auto-imports. This might re-import or configure import settings.\n return ReimportAsset(path, @params[\"properties\"] as JObject);\n case \"create\":\n return CreateAsset(@params);\n case \"modify\":\n return ModifyAsset(path, @params[\"properties\"] as JObject);\n case \"delete\":\n return DeleteAsset(path);\n case \"duplicate\":\n return DuplicateAsset(path, @params[\"destination\"]?.ToString());\n case \"move\": // Often same as rename if within Assets/\n case \"rename\":\n return MoveOrRenameAsset(path, @params[\"destination\"]?.ToString());\n case \"search\":\n return SearchAssets(@params);\n case \"get_info\":\n return GetAssetInfo(\n path,\n @params[\"generatePreview\"]?.ToObject() ?? false\n );\n case \"create_folder\": // Added specific action for clarity\n return CreateFolder(path);\n case \"get_components\":\n return GetComponentsFromAsset(path);\n\n default:\n // This error message is less likely to be hit now, but kept here as a fallback or for potential future modifications.\n string validActionsListDefault = string.Join(\", \", ValidActions);\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: {validActionsListDefault}\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageAsset] Action '{action}' failed for path '{path}': {e}\");\n return Response.Error(\n $\"Internal error processing action '{action}' on '{path}': {e.Message}\"\n );\n }\n }\n\n // --- Action Implementations ---\n\n private static object ReimportAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for reimport.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // TODO: Apply importer properties before reimporting?\n // This is complex as it requires getting the AssetImporter, casting it,\n // applying properties via reflection or specific methods, saving, then reimporting.\n if (properties != null && properties.HasValues)\n {\n Debug.LogWarning(\n \"[ManageAsset.Reimport] Modifying importer properties before reimport is not fully implemented yet.\"\n );\n // AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n // if (importer != null) { /* Apply properties */ AssetDatabase.WriteImportSettingsIfDirty(fullPath); }\n }\n\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate);\n // AssetDatabase.Refresh(); // Usually ImportAsset handles refresh\n return Response.Success($\"Asset '{fullPath}' reimported.\", GetAssetData(fullPath));\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to reimport asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateAsset(JObject @params)\n {\n string path = @params[\"path\"]?.ToString();\n string assetType = @params[\"assetType\"]?.ToString();\n JObject properties = @params[\"properties\"] as JObject;\n\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create.\");\n if (string.IsNullOrEmpty(assetType))\n return Response.Error(\"'assetType' is required for create.\");\n\n string fullPath = SanitizeAssetPath(path);\n string directory = Path.GetDirectoryName(fullPath);\n\n // Ensure directory exists\n if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), directory)))\n {\n Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), directory));\n AssetDatabase.Refresh(); // Make sure Unity knows about the new folder\n }\n\n if (AssetExists(fullPath))\n return Response.Error($\"Asset already exists at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object newAsset = null;\n string lowerAssetType = assetType.ToLowerInvariant();\n\n // Handle common asset types\n if (lowerAssetType == \"folder\")\n {\n return CreateFolder(path); // Use dedicated method\n }\n else if (lowerAssetType == \"material\")\n {\n Material mat = new Material(Shader.Find(\"Standard\")); // Default shader\n // TODO: Apply properties from JObject (e.g., shader name, color, texture assignments)\n if (properties != null)\n ApplyMaterialProperties(mat, properties);\n AssetDatabase.CreateAsset(mat, fullPath);\n newAsset = mat;\n }\n else if (lowerAssetType == \"physicsmaterial\")\n {\n PhysicsMaterialType pmat = new PhysicsMaterialType();\n if (properties != null)\n ApplyPhysicsMaterialProperties(pmat, properties);\n AssetDatabase.CreateAsset(pmat, fullPath);\n newAsset = pmat;\n }\n else if (lowerAssetType == \"scriptableobject\")\n {\n string scriptClassName = properties?[\"scriptClass\"]?.ToString();\n if (string.IsNullOrEmpty(scriptClassName))\n return Response.Error(\n \"'scriptClass' property required when creating ScriptableObject asset.\"\n );\n\n Type scriptType = FindType(scriptClassName);\n if (\n scriptType == null\n || !typeof(ScriptableObject).IsAssignableFrom(scriptType)\n )\n {\n return Response.Error(\n $\"Script class '{scriptClassName}' not found or does not inherit from ScriptableObject.\"\n );\n }\n\n ScriptableObject so = ScriptableObject.CreateInstance(scriptType);\n // TODO: Apply properties from JObject to the ScriptableObject instance?\n AssetDatabase.CreateAsset(so, fullPath);\n newAsset = so;\n }\n else if (lowerAssetType == \"prefab\")\n {\n // Creating prefabs usually involves saving an existing GameObject hierarchy.\n // A common pattern is to create an empty GameObject, configure it, and then save it.\n return Response.Error(\n \"Creating prefabs programmatically usually requires a source GameObject. Use manage_gameobject to create/configure, then save as prefab via a separate mechanism or future enhancement.\"\n );\n // Example (conceptual):\n // GameObject source = GameObject.Find(properties[\"sourceGameObject\"].ToString());\n // if(source != null) PrefabUtility.SaveAsPrefabAsset(source, fullPath);\n }\n // TODO: Add more asset types (Animation Controller, Scene, etc.)\n else\n {\n // Generic creation attempt (might fail or create empty files)\n // For some types, just creating the file might be enough if Unity imports it.\n // File.Create(Path.Combine(Directory.GetCurrentDirectory(), fullPath)).Close();\n // AssetDatabase.ImportAsset(fullPath); // Let Unity try to import it\n // newAsset = AssetDatabase.LoadAssetAtPath(fullPath);\n return Response.Error(\n $\"Creation for asset type '{assetType}' is not explicitly supported yet. Supported: Folder, Material, ScriptableObject.\"\n );\n }\n\n if (\n newAsset == null\n && !Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), fullPath))\n ) // Check if it wasn't a folder and asset wasn't created\n {\n return Response.Error(\n $\"Failed to create asset '{assetType}' at '{fullPath}'. See logs for details.\"\n );\n }\n\n AssetDatabase.SaveAssets();\n // AssetDatabase.Refresh(); // CreateAsset often handles refresh\n return Response.Success(\n $\"Asset '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create asset at '{fullPath}': {e.Message}\");\n }\n }\n\n private static object CreateFolder(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for create_folder.\");\n string fullPath = SanitizeAssetPath(path);\n string parentDir = Path.GetDirectoryName(fullPath);\n string folderName = Path.GetFileName(fullPath);\n\n if (AssetExists(fullPath))\n {\n // Check if it's actually a folder already\n if (AssetDatabase.IsValidFolder(fullPath))\n {\n return Response.Success(\n $\"Folder already exists at path: {fullPath}\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n return Response.Error(\n $\"An asset (not a folder) already exists at path: {fullPath}\"\n );\n }\n }\n\n try\n {\n // Ensure parent exists\n if (!string.IsNullOrEmpty(parentDir) && !AssetDatabase.IsValidFolder(parentDir))\n {\n // Recursively create parent folders if needed (AssetDatabase handles this internally)\n // Or we can do it manually: Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), parentDir)); AssetDatabase.Refresh();\n }\n\n string guid = AssetDatabase.CreateFolder(parentDir, folderName);\n if (string.IsNullOrEmpty(guid))\n {\n return Response.Error(\n $\"Failed to create folder '{fullPath}'. Check logs and permissions.\"\n );\n }\n\n // AssetDatabase.Refresh(); // CreateFolder usually handles refresh\n return Response.Success(\n $\"Folder '{fullPath}' created successfully.\",\n GetAssetData(fullPath)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create folder '{fullPath}': {e.Message}\");\n }\n }\n\n private static object ModifyAsset(string path, JObject properties)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for modify.\");\n if (properties == null || !properties.HasValues)\n return Response.Error(\"'properties' are required for modify.\");\n\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n bool modified = false; // Flag to track if any changes were made\n\n // --- NEW: Handle GameObject / Prefab Component Modification ---\n if (asset is GameObject gameObject)\n {\n // Iterate through the properties JSON: keys are component names, values are properties objects for that component\n foreach (var prop in properties.Properties())\n {\n string componentName = prop.Name; // e.g., \"Collectible\"\n // Check if the value associated with the component name is actually an object containing properties\n if (\n prop.Value is JObject componentProperties\n && componentProperties.HasValues\n ) // e.g., {\"bobSpeed\": 2.0}\n {\n // Find the component on the GameObject using the name from the JSON key\n // Using GetComponent(string) is convenient but might require exact type name or be ambiguous.\n // Consider using FindType helper if needed for more complex scenarios.\n Component targetComponent = gameObject.GetComponent(componentName);\n\n if (targetComponent != null)\n {\n // Apply the nested properties (e.g., bobSpeed) to the found component instance\n // Use |= to ensure 'modified' becomes true if any component is successfully modified\n modified |= ApplyObjectProperties(\n targetComponent,\n componentProperties\n );\n }\n else\n {\n // Log a warning if a specified component couldn't be found\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Component '{componentName}' not found on GameObject '{gameObject.name}' in asset '{fullPath}'. Skipping modification for this component.\"\n );\n }\n }\n else\n {\n // Log a warning if the structure isn't {\"ComponentName\": {\"prop\": value}}\n // We could potentially try to apply this property directly to the GameObject here if needed,\n // but the primary goal is component modification.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Property '{prop.Name}' for GameObject modification should have a JSON object value containing component properties. Value was: {prop.Value.Type}. Skipping.\"\n );\n }\n }\n // Note: 'modified' is now true if ANY component property was successfully changed.\n }\n // --- End NEW ---\n\n // --- Existing logic for other asset types (now as else-if) ---\n // Example: Modifying a Material\n else if (asset is Material material)\n {\n // Apply properties directly to the material. If this modifies, it sets modified=true.\n // Use |= in case the asset was already marked modified by previous logic (though unlikely here)\n modified |= ApplyMaterialProperties(material, properties);\n }\n // Example: Modifying a ScriptableObject\n else if (asset is ScriptableObject so)\n {\n // Apply properties directly to the ScriptableObject.\n modified |= ApplyObjectProperties(so, properties); // General helper\n }\n // Example: Modifying TextureImporter settings\n else if (asset is Texture)\n {\n AssetImporter importer = AssetImporter.GetAtPath(fullPath);\n if (importer is TextureImporter textureImporter)\n {\n bool importerModified = ApplyObjectProperties(textureImporter, properties);\n if (importerModified)\n {\n // Importer settings need saving and reimporting\n AssetDatabase.WriteImportSettingsIfDirty(fullPath);\n AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate); // Reimport to apply changes\n modified = true; // Mark overall operation as modified\n }\n }\n else\n {\n Debug.LogWarning($\"Could not get TextureImporter for {fullPath}.\");\n }\n }\n // TODO: Add modification logic for other common asset types (Models, AudioClips importers, etc.)\n else // Fallback for other asset types OR direct properties on non-GameObject assets\n {\n // This block handles non-GameObject/Material/ScriptableObject/Texture assets.\n // Attempts to apply properties directly to the asset itself.\n Debug.LogWarning(\n $\"[ManageAsset.ModifyAsset] Asset type '{asset.GetType().Name}' at '{fullPath}' is not explicitly handled for component modification. Attempting generic property setting on the asset itself.\"\n );\n modified |= ApplyObjectProperties(asset, properties);\n }\n // --- End Existing Logic ---\n\n // Check if any modification happened (either component or direct asset modification)\n if (modified)\n {\n // Mark the asset as dirty (important for prefabs/SOs) so Unity knows to save it.\n EditorUtility.SetDirty(asset);\n // Save all modified assets to disk.\n AssetDatabase.SaveAssets();\n // Refresh might be needed in some edge cases, but SaveAssets usually covers it.\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{fullPath}' modified successfully.\",\n GetAssetData(fullPath)\n );\n }\n else\n {\n // If no changes were made (e.g., component not found, property names incorrect, value unchanged), return a success message indicating nothing changed.\n return Response.Success(\n $\"No applicable or modifiable properties found for asset '{fullPath}'. Check component names, property names, and values.\",\n GetAssetData(fullPath)\n );\n // Previous message: return Response.Success($\"No applicable properties found to modify for asset '{fullPath}'.\", GetAssetData(fullPath));\n }\n }\n catch (Exception e)\n {\n // Log the detailed error internally\n Debug.LogError($\"[ManageAsset] Action 'modify' failed for path '{path}': {e}\");\n // Return a user-friendly error message\n return Response.Error($\"Failed to modify asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DeleteAsset(string path)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for delete.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n bool success = AssetDatabase.DeleteAsset(fullPath);\n if (success)\n {\n // AssetDatabase.Refresh(); // DeleteAsset usually handles refresh\n return Response.Success($\"Asset '{fullPath}' deleted successfully.\");\n }\n else\n {\n // This might happen if the file couldn't be deleted (e.g., locked)\n return Response.Error(\n $\"Failed to delete asset '{fullPath}'. Check logs or if the file is locked.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting asset '{fullPath}': {e.Message}\");\n }\n }\n\n private static object DuplicateAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for duplicate.\");\n\n string sourcePath = SanitizeAssetPath(path);\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n\n string destPath;\n if (string.IsNullOrEmpty(destinationPath))\n {\n // Generate a unique path if destination is not provided\n destPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath);\n }\n else\n {\n destPath = SanitizeAssetPath(destinationPath);\n if (AssetExists(destPath))\n return Response.Error($\"Asset already exists at destination path: {destPath}\");\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n }\n\n try\n {\n bool success = AssetDatabase.CopyAsset(sourcePath, destPath);\n if (success)\n {\n // AssetDatabase.Refresh();\n return Response.Success(\n $\"Asset '{sourcePath}' duplicated to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n return Response.Error(\n $\"Failed to duplicate asset from '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error duplicating asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object MoveOrRenameAsset(string path, string destinationPath)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for move/rename.\");\n if (string.IsNullOrEmpty(destinationPath))\n return Response.Error(\"'destination' path is required for move/rename.\");\n\n string sourcePath = SanitizeAssetPath(path);\n string destPath = SanitizeAssetPath(destinationPath);\n\n if (!AssetExists(sourcePath))\n return Response.Error($\"Source asset not found at path: {sourcePath}\");\n if (AssetExists(destPath))\n return Response.Error(\n $\"An asset already exists at the destination path: {destPath}\"\n );\n\n // Ensure destination directory exists\n EnsureDirectoryExists(Path.GetDirectoryName(destPath));\n\n try\n {\n // Validate will return an error string if failed, null if successful\n string error = AssetDatabase.ValidateMoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(error))\n {\n return Response.Error(\n $\"Failed to move/rename asset from '{sourcePath}' to '{destPath}': {error}\"\n );\n }\n\n string guid = AssetDatabase.MoveAsset(sourcePath, destPath);\n if (!string.IsNullOrEmpty(guid)) // MoveAsset returns the new GUID on success\n {\n // AssetDatabase.Refresh(); // MoveAsset usually handles refresh\n return Response.Success(\n $\"Asset moved/renamed from '{sourcePath}' to '{destPath}'.\",\n GetAssetData(destPath)\n );\n }\n else\n {\n // This case might not be reachable if ValidateMoveAsset passes, but good to have\n return Response.Error(\n $\"MoveAsset call failed unexpectedly for '{sourcePath}' to '{destPath}'.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error moving/renaming asset '{sourcePath}': {e.Message}\");\n }\n }\n\n private static object SearchAssets(JObject @params)\n {\n string searchPattern = @params[\"searchPattern\"]?.ToString();\n string filterType = @params[\"filterType\"]?.ToString();\n string pathScope = @params[\"path\"]?.ToString(); // Use path as folder scope\n string filterDateAfterStr = @params[\"filterDateAfter\"]?.ToString();\n int pageSize = @params[\"pageSize\"]?.ToObject() ?? 50; // Default page size\n int pageNumber = @params[\"pageNumber\"]?.ToObject() ?? 1; // Default page number (1-based)\n bool generatePreview = @params[\"generatePreview\"]?.ToObject() ?? false;\n\n List searchFilters = new List();\n if (!string.IsNullOrEmpty(searchPattern))\n searchFilters.Add(searchPattern);\n if (!string.IsNullOrEmpty(filterType))\n searchFilters.Add($\"t:{filterType}\");\n\n string[] folderScope = null;\n if (!string.IsNullOrEmpty(pathScope))\n {\n folderScope = new string[] { SanitizeAssetPath(pathScope) };\n if (!AssetDatabase.IsValidFolder(folderScope[0]))\n {\n // Maybe the user provided a file path instead of a folder?\n // We could search in the containing folder, or return an error.\n Debug.LogWarning(\n $\"Search path '{folderScope[0]}' is not a valid folder. Searching entire project.\"\n );\n folderScope = null; // Search everywhere if path isn't a folder\n }\n }\n\n DateTime? filterDateAfter = null;\n if (!string.IsNullOrEmpty(filterDateAfterStr))\n {\n if (\n DateTime.TryParse(\n filterDateAfterStr,\n CultureInfo.InvariantCulture,\n DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,\n out DateTime parsedDate\n )\n )\n {\n filterDateAfter = parsedDate;\n }\n else\n {\n Debug.LogWarning(\n $\"Could not parse filterDateAfter: '{filterDateAfterStr}'. Expected ISO 8601 format.\"\n );\n }\n }\n\n try\n {\n string[] guids = AssetDatabase.FindAssets(\n string.Join(\" \", searchFilters),\n folderScope\n );\n List results = new List();\n int totalFound = 0;\n\n foreach (string guid in guids)\n {\n string assetPath = AssetDatabase.GUIDToAssetPath(guid);\n if (string.IsNullOrEmpty(assetPath))\n continue;\n\n // Apply date filter if present\n if (filterDateAfter.HasValue)\n {\n DateTime lastWriteTime = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), assetPath)\n );\n if (lastWriteTime <= filterDateAfter.Value)\n {\n continue; // Skip assets older than or equal to the filter date\n }\n }\n\n totalFound++; // Count matching assets before pagination\n results.Add(GetAssetData(assetPath, generatePreview));\n }\n\n // Apply pagination\n int startIndex = (pageNumber - 1) * pageSize;\n var pagedResults = results.Skip(startIndex).Take(pageSize).ToList();\n\n return Response.Success(\n $\"Found {totalFound} asset(s). Returning page {pageNumber} ({pagedResults.Count} assets).\",\n new\n {\n totalAssets = totalFound,\n pageSize = pageSize,\n pageNumber = pageNumber,\n assets = pagedResults,\n }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error searching assets: {e.Message}\");\n }\n }\n\n private static object GetAssetInfo(string path, bool generatePreview)\n {\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_info.\");\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n return Response.Success(\n \"Asset info retrieved.\",\n GetAssetData(fullPath, generatePreview)\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting info for asset '{fullPath}': {e.Message}\");\n }\n }\n\n /// \n /// Retrieves components attached to a GameObject asset (like a Prefab).\n /// \n /// The asset path of the GameObject or Prefab.\n /// A response object containing a list of component type names or an error.\n private static object GetComponentsFromAsset(string path)\n {\n // 1. Validate input path\n if (string.IsNullOrEmpty(path))\n return Response.Error(\"'path' is required for get_components.\");\n\n // 2. Sanitize and check existence\n string fullPath = SanitizeAssetPath(path);\n if (!AssetExists(fullPath))\n return Response.Error($\"Asset not found at path: {fullPath}\");\n\n try\n {\n // 3. Load the asset\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(\n fullPath\n );\n if (asset == null)\n return Response.Error($\"Failed to load asset at path: {fullPath}\");\n\n // 4. Check if it's a GameObject (Prefabs load as GameObjects)\n GameObject gameObject = asset as GameObject;\n if (gameObject == null)\n {\n // Also check if it's *directly* a Component type (less common for primary assets)\n Component componentAsset = asset as Component;\n if (componentAsset != null)\n {\n // If the asset itself *is* a component, maybe return just its info?\n // This is an edge case. Let's stick to GameObjects for now.\n return Response.Error(\n $\"Asset at '{fullPath}' is a Component ({asset.GetType().FullName}), not a GameObject. Components are typically retrieved *from* a GameObject.\"\n );\n }\n return Response.Error(\n $\"Asset at '{fullPath}' is not a GameObject (Type: {asset.GetType().FullName}). Cannot get components from this asset type.\"\n );\n }\n\n // 5. Get components\n Component[] components = gameObject.GetComponents();\n\n // 6. Format component data\n List componentList = components\n .Select(comp => new\n {\n typeName = comp.GetType().FullName,\n instanceID = comp.GetInstanceID(),\n // TODO: Add more component-specific details here if needed in the future?\n // Requires reflection or specific handling per component type.\n })\n .ToList(); // Explicit cast for clarity if needed\n\n // 7. Return success response\n return Response.Success(\n $\"Found {componentList.Count} component(s) on asset '{fullPath}'.\",\n componentList\n );\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageAsset.GetComponentsFromAsset] Error getting components for '{fullPath}': {e}\"\n );\n return Response.Error(\n $\"Error getting components for asset '{fullPath}': {e.Message}\"\n );\n }\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Ensures the asset path starts with \"Assets/\".\n /// \n private static string SanitizeAssetPath(string path)\n {\n if (string.IsNullOrEmpty(path))\n return path;\n path = path.Replace('\\\\', '/'); // Normalize separators\n if (!path.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n return \"Assets/\" + path.TrimStart('/');\n }\n return path;\n }\n\n /// \n /// Checks if an asset exists at the given path (file or folder).\n /// \n private static bool AssetExists(string sanitizedPath)\n {\n // AssetDatabase APIs are generally preferred over raw File/Directory checks for assets.\n // Check if it's a known asset GUID.\n if (!string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath)))\n {\n return true;\n }\n // AssetPathToGUID might not work for newly created folders not yet refreshed.\n // Check directory explicitly for folders.\n if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n // Check if it's considered a *valid* folder by Unity\n return AssetDatabase.IsValidFolder(sanitizedPath);\n }\n // Check file existence for non-folder assets.\n if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), sanitizedPath)))\n {\n return true; // Assume if file exists, it's an asset or will be imported\n }\n\n return false;\n // Alternative: return !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(sanitizedPath));\n }\n\n /// \n /// Ensures the directory for a given asset path exists, creating it if necessary.\n /// \n private static void EnsureDirectoryExists(string directoryPath)\n {\n if (string.IsNullOrEmpty(directoryPath))\n return;\n string fullDirPath = Path.Combine(Directory.GetCurrentDirectory(), directoryPath);\n if (!Directory.Exists(fullDirPath))\n {\n Directory.CreateDirectory(fullDirPath);\n AssetDatabase.Refresh(); // Let Unity know about the new folder\n }\n }\n\n /// \n /// Applies properties from JObject to a Material.\n /// \n private static bool ApplyMaterialProperties(Material mat, JObject properties)\n {\n if (mat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set shader\n if (properties[\"shader\"]?.Type == JTokenType.String)\n {\n Shader newShader = Shader.Find(properties[\"shader\"].ToString());\n if (newShader != null && mat.shader != newShader)\n {\n mat.shader = newShader;\n modified = true;\n }\n }\n // Example: Set color property\n if (properties[\"color\"] is JObject colorProps)\n {\n string propName = colorProps[\"name\"]?.ToString() ?? \"_Color\"; // Default main color\n if (colorProps[\"value\"] is JArray colArr && colArr.Count >= 3)\n {\n try\n {\n Color newColor = new Color(\n colArr[0].ToObject(),\n colArr[1].ToObject(),\n colArr[2].ToObject(),\n colArr.Count > 3 ? colArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n } else if (properties[\"color\"] is JArray colorArr) //Use color now with examples set in manage_asset.py\n {\n string propName = \"_Color\"; \n try {\n if (colorArr.Count >= 3)\n {\n Color newColor = new Color(\n colorArr[0].ToObject(),\n colorArr[1].ToObject(), \n colorArr[2].ToObject(), \n colorArr.Count > 3 ? colorArr[3].ToObject() : 1.0f\n );\n if (mat.HasProperty(propName) && mat.GetColor(propName) != newColor)\n {\n mat.SetColor(propName, newColor);\n modified = true;\n }\n }\n } \n catch (Exception ex) {\n Debug.LogWarning(\n $\"Error parsing color property '{propName}': {ex.Message}\"\n );\n }\n }\n // Example: Set float property\n if (properties[\"float\"] is JObject floatProps)\n {\n string propName = floatProps[\"name\"]?.ToString();\n if (\n !string.IsNullOrEmpty(propName) && floatProps[\"value\"]?.Type == JTokenType.Float\n || floatProps[\"value\"]?.Type == JTokenType.Integer\n )\n {\n try\n {\n float newVal = floatProps[\"value\"].ToObject();\n if (mat.HasProperty(propName) && mat.GetFloat(propName) != newVal)\n {\n mat.SetFloat(propName, newVal);\n modified = true;\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Error parsing float property '{propName}': {ex.Message}\"\n );\n }\n }\n }\n // Example: Set texture property\n if (properties[\"texture\"] is JObject texProps)\n {\n string propName = texProps[\"name\"]?.ToString() ?? \"_MainTex\"; // Default main texture\n string texPath = texProps[\"path\"]?.ToString();\n if (!string.IsNullOrEmpty(texPath))\n {\n Texture newTex = AssetDatabase.LoadAssetAtPath(\n SanitizeAssetPath(texPath)\n );\n if (\n newTex != null\n && mat.HasProperty(propName)\n && mat.GetTexture(propName) != newTex\n )\n {\n mat.SetTexture(propName, newTex);\n modified = true;\n }\n else if (newTex == null)\n {\n Debug.LogWarning($\"Texture not found at path: {texPath}\");\n }\n }\n }\n\n // TODO: Add handlers for other property types (Vectors, Ints, Keywords, RenderQueue, etc.)\n return modified;\n }\n\n /// \n /// Applies properties from JObject to a PhysicsMaterial.\n /// \n private static bool ApplyPhysicsMaterialProperties(PhysicsMaterialType pmat, JObject properties)\n {\n if (pmat == null || properties == null)\n return false;\n bool modified = false;\n\n // Example: Set dynamic friction\n if (properties[\"dynamicFriction\"]?.Type == JTokenType.Float)\n {\n float dynamicFriction = properties[\"dynamicFriction\"].ToObject();\n pmat.dynamicFriction = dynamicFriction;\n modified = true;\n }\n\n // Example: Set static friction\n if (properties[\"staticFriction\"]?.Type == JTokenType.Float)\n {\n float staticFriction = properties[\"staticFriction\"].ToObject();\n pmat.staticFriction = staticFriction;\n modified = true;\n }\n\n // Example: Set bounciness\n if (properties[\"bounciness\"]?.Type == JTokenType.Float)\n {\n float bounciness = properties[\"bounciness\"].ToObject();\n pmat.bounciness = bounciness;\n modified = true;\n }\n\n List averageList = new List { \"ave\", \"Ave\", \"average\", \"Average\" };\n List multiplyList = new List { \"mul\", \"Mul\", \"mult\", \"Mult\", \"multiply\", \"Multiply\" };\n List minimumList = new List { \"min\", \"Min\", \"minimum\", \"Minimum\" };\n List maximumList = new List { \"max\", \"Max\", \"maximum\", \"Maximum\" };\n\n // Example: Set friction combine\n if (properties[\"frictionCombine\"]?.Type == JTokenType.String)\n {\n string frictionCombine = properties[\"frictionCombine\"].ToString();\n if (averageList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(frictionCombine))\n pmat.frictionCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n // Example: Set bounce combine\n if (properties[\"bounceCombine\"]?.Type == JTokenType.String)\n {\n string bounceCombine = properties[\"bounceCombine\"].ToString();\n if (averageList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Average;\n else if (multiplyList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Multiply;\n else if (minimumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Minimum;\n else if (maximumList.Contains(bounceCombine))\n pmat.bounceCombine = PhysicsMaterialCombine.Maximum;\n modified = true;\n }\n\n return modified;\n }\n\n /// \n /// Generic helper to set properties on any UnityEngine.Object using reflection.\n /// \n private static bool ApplyObjectProperties(UnityEngine.Object target, JObject properties)\n {\n if (target == null || properties == null)\n return false;\n bool modified = false;\n Type type = target.GetType();\n\n foreach (var prop in properties.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n if (SetPropertyOrField(target, propName, propValue, type))\n {\n modified = true;\n }\n }\n return modified;\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types and Unity objects.\n /// \n private static bool SetPropertyOrField(\n object target,\n string memberName,\n JToken value,\n Type type = null\n )\n {\n type = type ?? target.GetType();\n System.Reflection.BindingFlags flags =\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.Instance\n | System.Reflection.BindingFlags.IgnoreCase;\n\n try\n {\n System.Reflection.PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType);\n if (\n convertedValue != null\n && !object.Equals(propInfo.GetValue(target), convertedValue)\n )\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n else\n {\n System.Reflection.FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null)\n {\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType);\n if (\n convertedValue != null\n && !object.Equals(fieldInfo.GetValue(target), convertedValue)\n )\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[SetPropertyOrField] Failed to set '{memberName}' on {type.Name}: {ex.Message}\"\n );\n }\n return false;\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types and primitives.\n /// \n private static object ConvertJTokenToType(JToken token, Type targetType)\n {\n try\n {\n if (token == null || token.Type == JTokenType.Null)\n return null;\n\n if (targetType == typeof(string))\n return token.ToObject();\n if (targetType == typeof(int))\n return token.ToObject();\n if (targetType == typeof(float))\n return token.ToObject();\n if (targetType == typeof(bool))\n return token.ToObject();\n if (targetType == typeof(Vector2) && token is JArray arrV2 && arrV2.Count == 2)\n return new Vector2(arrV2[0].ToObject(), arrV2[1].ToObject());\n if (targetType == typeof(Vector3) && token is JArray arrV3 && arrV3.Count == 3)\n return new Vector3(\n arrV3[0].ToObject(),\n arrV3[1].ToObject(),\n arrV3[2].ToObject()\n );\n if (targetType == typeof(Vector4) && token is JArray arrV4 && arrV4.Count == 4)\n return new Vector4(\n arrV4[0].ToObject(),\n arrV4[1].ToObject(),\n arrV4[2].ToObject(),\n arrV4[3].ToObject()\n );\n if (targetType == typeof(Quaternion) && token is JArray arrQ && arrQ.Count == 4)\n return new Quaternion(\n arrQ[0].ToObject(),\n arrQ[1].ToObject(),\n arrQ[2].ToObject(),\n arrQ[3].ToObject()\n );\n if (targetType == typeof(Color) && token is JArray arrC && arrC.Count >= 3) // Allow RGB or RGBA\n return new Color(\n arrC[0].ToObject(),\n arrC[1].ToObject(),\n arrC[2].ToObject(),\n arrC.Count > 3 ? arrC[3].ToObject() : 1.0f\n );\n if (targetType.IsEnum)\n return Enum.Parse(targetType, token.ToString(), true); // Case-insensitive enum parsing\n\n // Handle loading Unity Objects (Materials, Textures, etc.) by path\n if (\n typeof(UnityEngine.Object).IsAssignableFrom(targetType)\n && token.Type == JTokenType.String\n )\n {\n string assetPath = SanitizeAssetPath(token.ToString());\n UnityEngine.Object loadedAsset = AssetDatabase.LoadAssetAtPath(\n assetPath,\n targetType\n );\n if (loadedAsset == null)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not load asset of type {targetType.Name} from path: {assetPath}\"\n );\n }\n return loadedAsset;\n }\n\n // Fallback: Try direct conversion (might work for other simple value types)\n return token.ToObject(targetType);\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"[ConvertJTokenToType] Could not convert JToken '{token}' (type {token.Type}) to type '{targetType.Name}': {ex.Message}\"\n );\n return null;\n }\n }\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// Needed for creating ScriptableObjects or finding component types by name.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Try direct lookup first (common Unity types often don't need assembly qualified name)\n var type =\n Type.GetType(typeName)\n ?? Type.GetType($\"UnityEngine.{typeName}, UnityEngine.CoreModule\")\n ?? Type.GetType($\"UnityEngine.UI.{typeName}, UnityEngine.UI\")\n ?? Type.GetType($\"UnityEditor.{typeName}, UnityEditor.CoreModule\");\n\n if (type != null)\n return type;\n\n // If not found, search loaded assemblies (slower but more robust for user scripts)\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n {\n // Look for non-namespaced first\n type = assembly.GetType(typeName, false, true); // throwOnError=false, ignoreCase=true\n if (type != null)\n return type;\n\n // Check common namespaces if simple name given\n type = assembly.GetType(\"UnityEngine.\" + typeName, false, true);\n if (type != null)\n return type;\n type = assembly.GetType(\"UnityEditor.\" + typeName, false, true);\n if (type != null)\n return type;\n // Add other likely namespaces if needed (e.g., specific plugins)\n }\n\n Debug.LogWarning($\"[FindType] Type '{typeName}' not found in any loaded assembly.\");\n return null; // Not found\n }\n\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of an asset.\n /// \n private static object GetAssetData(string path, bool generatePreview = false)\n {\n if (string.IsNullOrEmpty(path) || !AssetExists(path))\n return null;\n\n string guid = AssetDatabase.AssetPathToGUID(path);\n Type assetType = AssetDatabase.GetMainAssetTypeAtPath(path);\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(path);\n string previewBase64 = null;\n int previewWidth = 0;\n int previewHeight = 0;\n\n if (generatePreview && asset != null)\n {\n Texture2D preview = AssetPreview.GetAssetPreview(asset);\n\n if (preview != null)\n {\n try\n {\n // Ensure texture is readable for EncodeToPNG\n // Creating a temporary readable copy is safer\n RenderTexture rt = RenderTexture.GetTemporary(\n preview.width,\n preview.height\n );\n Graphics.Blit(preview, rt);\n RenderTexture previous = RenderTexture.active;\n RenderTexture.active = rt;\n Texture2D readablePreview = new Texture2D(preview.width, preview.height);\n readablePreview.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);\n readablePreview.Apply();\n RenderTexture.active = previous;\n RenderTexture.ReleaseTemporary(rt);\n\n byte[] pngData = readablePreview.EncodeToPNG();\n previewBase64 = Convert.ToBase64String(pngData);\n previewWidth = readablePreview.width;\n previewHeight = readablePreview.height;\n UnityEngine.Object.DestroyImmediate(readablePreview); // Clean up temp texture\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Failed to generate readable preview for '{path}': {ex.Message}. Preview might not be readable.\"\n );\n // Fallback: Try getting static preview if available?\n // Texture2D staticPreview = AssetPreview.GetMiniThumbnail(asset);\n }\n }\n else\n {\n Debug.LogWarning(\n $\"Could not get asset preview for {path} (Type: {assetType?.Name}). Is it supported?\"\n );\n }\n }\n\n return new\n {\n path = path,\n guid = guid,\n assetType = assetType?.FullName ?? \"Unknown\",\n name = Path.GetFileNameWithoutExtension(path),\n fileName = Path.GetFileName(path),\n isFolder = AssetDatabase.IsValidFolder(path),\n instanceID = asset?.GetInstanceID() ?? 0,\n lastWriteTimeUtc = File.GetLastWriteTimeUtc(\n Path.Combine(Directory.GetCurrentDirectory(), path)\n )\n .ToString(\"o\"), // ISO 8601\n // --- Preview Data ---\n previewBase64 = previewBase64, // PNG data as Base64 string\n previewWidth = previewWidth,\n previewHeight = previewHeight,\n // TODO: Add more metadata? Importer settings? Dependencies?\n };\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageScript.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\n#if USE_ROSLYN\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\n#endif\n\n#if UNITY_EDITOR\nusing UnityEditor.Compilation;\n#endif\n\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for C# scripts within the Unity project.\n /// \n /// ROSLYN INSTALLATION GUIDE:\n /// To enable advanced syntax validation with Roslyn compiler services:\n /// \n /// 1. Install Microsoft.CodeAnalysis.CSharp NuGet package:\n /// - Open Package Manager in Unity\n /// - Follow the instruction on https://github.com/GlitchEnzo/NuGetForUnity\n /// \n /// 2. Open NuGet Package Manager and Install Microsoft.CodeAnalysis.CSharp:\n /// \n /// 3. Alternative: Manual DLL installation:\n /// - Download Microsoft.CodeAnalysis.CSharp.dll and dependencies\n /// - Place in Assets/Plugins/ folder\n /// - Ensure .NET compatibility settings are correct\n /// \n /// 4. Define USE_ROSLYN symbol:\n /// - Go to Player Settings > Scripting Define Symbols\n /// - Add \"USE_ROSLYN\" to enable Roslyn-based validation\n /// \n /// 5. Restart Unity after installation\n /// \n /// Note: Without Roslyn, the system falls back to basic structural validation.\n /// Roslyn provides full C# compiler diagnostics with line numbers and detailed error messages.\n /// \n public static class ManageScript\n {\n /// \n /// Main handler for script management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode script contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n string scriptType = @params[\"scriptType\"]?.ToString(); // For templates/validation\n string namespaceName = @params[\"namespace\"]?.ToString(); // For organizing code\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid script name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Scripts\" if path is not provided\n string relativeDir = path ?? \"Scripts\"; // Default to \"Scripts\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Scripts\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string scriptFileName = $\"{name}.cs\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir); // Application.dataPath ends in \"Assets\"\n string fullPath = Path.Combine(fullPathDir, scriptFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, scriptFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n Directory.CreateDirectory(fullPathDir);\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateScript(\n fullPath,\n relativePath,\n name,\n contents,\n scriptType,\n namespaceName\n );\n case \"read\":\n return ReadScript(fullPath, relativePath);\n case \"update\":\n return UpdateScript(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteScript(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents,\n string scriptType,\n string namespaceName\n )\n {\n // Check if script already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultScriptContent(name, scriptType, namespaceName);\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block creation\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new script\n return Response.Success(\n $\"Script '{name}.cs' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateScript(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Script not found at '{relativePath}'. Use 'create' action to add a new script.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n // Validate syntax with detailed error reporting using GUI setting\n ValidationLevel validationLevel = GetValidationLevelFromGUI();\n bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);\n if (!isValid)\n {\n string errorMessage = \"Script validation failed:\\n\" + string.Join(\"\\n\", validationErrors);\n return Response.Error(errorMessage);\n }\n else if (validationErrors != null && validationErrors.Length > 0)\n {\n // Log warnings but don't block update\n Debug.LogWarning($\"Script validation warnings for {name}:\\n\" + string.Join(\"\\n\", validationErrors));\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath); // Re-import to reflect changes\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{name}.cs' updated successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update script '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteScript(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Script not found at '{relativePath}'. Cannot delete.\");\n }\n\n try\n {\n // Use AssetDatabase.MoveAssetToTrash for safer deletion (allows undo)\n bool deleted = AssetDatabase.MoveAssetToTrash(relativePath);\n if (deleted)\n {\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Script '{Path.GetFileName(relativePath)}' moved to trash successfully.\"\n );\n }\n else\n {\n // Fallback or error if MoveAssetToTrash fails\n return Response.Error(\n $\"Failed to move script '{relativePath}' to trash. It might be locked or in use.\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error deleting script '{relativePath}': {e.Message}\");\n }\n }\n\n /// \n /// Generates basic C# script content based on name and type.\n /// \n private static string GenerateDefaultScriptContent(\n string name,\n string scriptType,\n string namespaceName\n )\n {\n string usingStatements = \"using UnityEngine;\\nusing System.Collections;\\n\";\n string classDeclaration;\n string body =\n \"\\n // Use this for initialization\\n void Start() {\\n\\n }\\n\\n // Update is called once per frame\\n void Update() {\\n\\n }\\n\";\n\n string baseClass = \"\";\n if (!string.IsNullOrEmpty(scriptType))\n {\n if (scriptType.Equals(\"MonoBehaviour\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : MonoBehaviour\";\n else if (scriptType.Equals(\"ScriptableObject\", StringComparison.OrdinalIgnoreCase))\n {\n baseClass = \" : ScriptableObject\";\n body = \"\"; // ScriptableObjects don't usually need Start/Update\n }\n else if (\n scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase)\n || scriptType.Equals(\"EditorWindow\", StringComparison.OrdinalIgnoreCase)\n )\n {\n usingStatements += \"using UnityEditor;\\n\";\n if (scriptType.Equals(\"Editor\", StringComparison.OrdinalIgnoreCase))\n baseClass = \" : Editor\";\n else\n baseClass = \" : EditorWindow\";\n body = \"\"; // Editor scripts have different structures\n }\n // Add more types as needed\n }\n\n classDeclaration = $\"public class {name}{baseClass}\";\n\n string fullContent = $\"{usingStatements}\\n\";\n bool useNamespace = !string.IsNullOrEmpty(namespaceName);\n\n if (useNamespace)\n {\n fullContent += $\"namespace {namespaceName}\\n{{\\n\";\n // Indent class and body if using namespace\n classDeclaration = \" \" + classDeclaration;\n body = string.Join(\"\\n\", body.Split('\\n').Select(line => \" \" + line));\n }\n\n fullContent += $\"{classDeclaration}\\n{{\\n{body}\\n}}\";\n\n if (useNamespace)\n {\n fullContent += \"\\n}\"; // Close namespace\n }\n\n return fullContent.Trim() + \"\\n\"; // Ensure a trailing newline\n }\n\n /// \n /// Gets the validation level from the GUI settings\n /// \n private static ValidationLevel GetValidationLevelFromGUI()\n {\n string savedLevel = EditorPrefs.GetString(\"UnityMCP_ScriptValidationLevel\", \"standard\");\n return savedLevel.ToLower() switch\n {\n \"basic\" => ValidationLevel.Basic,\n \"standard\" => ValidationLevel.Standard,\n \"comprehensive\" => ValidationLevel.Comprehensive,\n \"strict\" => ValidationLevel.Strict,\n _ => ValidationLevel.Standard // Default fallback\n };\n }\n\n /// \n /// Validates C# script syntax using multiple validation layers.\n /// \n private static bool ValidateScriptSyntax(string contents)\n {\n return ValidateScriptSyntax(contents, ValidationLevel.Standard, out _);\n }\n\n /// \n /// Advanced syntax validation with detailed diagnostics and configurable strictness.\n /// \n private static bool ValidateScriptSyntax(string contents, ValidationLevel level, out string[] errors)\n {\n var errorList = new System.Collections.Generic.List();\n errors = null;\n\n if (string.IsNullOrEmpty(contents))\n {\n return true; // Empty content is valid\n }\n\n // Basic structural validation\n if (!ValidateBasicStructure(contents, errorList))\n {\n errors = errorList.ToArray();\n return false;\n }\n\n#if USE_ROSLYN\n // Advanced Roslyn-based validation\n if (!ValidateScriptSyntaxRoslyn(contents, level, errorList))\n {\n errors = errorList.ToArray();\n return level != ValidationLevel.Standard; //TODO: Allow standard to run roslyn right now, might formalize it in the future\n }\n#endif\n\n // Unity-specific validation\n if (level >= ValidationLevel.Standard)\n {\n ValidateScriptSyntaxUnity(contents, errorList);\n }\n\n // Semantic analysis for common issues\n if (level >= ValidationLevel.Comprehensive)\n {\n ValidateSemanticRules(contents, errorList);\n }\n\n#if USE_ROSLYN\n // Full semantic compilation validation for Strict level\n if (level == ValidationLevel.Strict)\n {\n if (!ValidateScriptSemantics(contents, errorList))\n {\n errors = errorList.ToArray();\n return false; // Strict level fails on any semantic errors\n }\n }\n#endif\n\n errors = errorList.ToArray();\n return errorList.Count == 0 || (level != ValidationLevel.Strict && !errorList.Any(e => e.StartsWith(\"ERROR:\")));\n }\n\n /// \n /// Validation strictness levels\n /// \n private enum ValidationLevel\n {\n Basic, // Only syntax errors\n Standard, // Syntax + Unity best practices\n Comprehensive, // All checks + semantic analysis\n Strict // Treat all issues as errors\n }\n\n /// \n /// Validates basic code structure (braces, quotes, comments)\n /// \n private static bool ValidateBasicStructure(string contents, System.Collections.Generic.List errors)\n {\n bool isValid = true;\n int braceBalance = 0;\n int parenBalance = 0;\n int bracketBalance = 0;\n bool inStringLiteral = false;\n bool inCharLiteral = false;\n bool inSingleLineComment = false;\n bool inMultiLineComment = false;\n bool escaped = false;\n\n for (int i = 0; i < contents.Length; i++)\n {\n char c = contents[i];\n char next = i + 1 < contents.Length ? contents[i + 1] : '\\0';\n\n // Handle escape sequences\n if (escaped)\n {\n escaped = false;\n continue;\n }\n\n if (c == '\\\\' && (inStringLiteral || inCharLiteral))\n {\n escaped = true;\n continue;\n }\n\n // Handle comments\n if (!inStringLiteral && !inCharLiteral)\n {\n if (c == '/' && next == '/' && !inMultiLineComment)\n {\n inSingleLineComment = true;\n continue;\n }\n if (c == '/' && next == '*' && !inSingleLineComment)\n {\n inMultiLineComment = true;\n i++; // Skip next character\n continue;\n }\n if (c == '*' && next == '/' && inMultiLineComment)\n {\n inMultiLineComment = false;\n i++; // Skip next character\n continue;\n }\n }\n\n if (c == '\\n')\n {\n inSingleLineComment = false;\n continue;\n }\n\n if (inSingleLineComment || inMultiLineComment)\n continue;\n\n // Handle string and character literals\n if (c == '\"' && !inCharLiteral)\n {\n inStringLiteral = !inStringLiteral;\n continue;\n }\n if (c == '\\'' && !inStringLiteral)\n {\n inCharLiteral = !inCharLiteral;\n continue;\n }\n\n if (inStringLiteral || inCharLiteral)\n continue;\n\n // Count brackets and braces\n switch (c)\n {\n case '{': braceBalance++; break;\n case '}': braceBalance--; break;\n case '(': parenBalance++; break;\n case ')': parenBalance--; break;\n case '[': bracketBalance++; break;\n case ']': bracketBalance--; break;\n }\n\n // Check for negative balances (closing without opening)\n if (braceBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing brace '}'\");\n isValid = false;\n }\n if (parenBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing parenthesis ')'\");\n isValid = false;\n }\n if (bracketBalance < 0)\n {\n errors.Add(\"ERROR: Unmatched closing bracket ']'\");\n isValid = false;\n }\n }\n\n // Check final balances\n if (braceBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced braces (difference: {braceBalance})\");\n isValid = false;\n }\n if (parenBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced parentheses (difference: {parenBalance})\");\n isValid = false;\n }\n if (bracketBalance != 0)\n {\n errors.Add($\"ERROR: Unbalanced brackets (difference: {bracketBalance})\");\n isValid = false;\n }\n if (inStringLiteral)\n {\n errors.Add(\"ERROR: Unterminated string literal\");\n isValid = false;\n }\n if (inCharLiteral)\n {\n errors.Add(\"ERROR: Unterminated character literal\");\n isValid = false;\n }\n if (inMultiLineComment)\n {\n errors.Add(\"WARNING: Unterminated multi-line comment\");\n }\n\n return isValid;\n }\n\n#if USE_ROSLYN\n /// \n /// Cached compilation references for performance\n /// \n private static System.Collections.Generic.List _cachedReferences = null;\n private static DateTime _cacheTime = DateTime.MinValue;\n private static readonly TimeSpan CacheExpiry = TimeSpan.FromMinutes(5);\n\n /// \n /// Validates syntax using Roslyn compiler services\n /// \n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n try\n {\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n var diagnostics = syntaxTree.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n string severity = diagnostic.Severity.ToString().ToUpper();\n string message = $\"{severity}: {diagnostic.GetMessage()}\";\n \n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n }\n \n // Include warnings in comprehensive mode\n if (level >= ValidationLevel.Standard || diagnostic.Severity == DiagnosticSeverity.Error) //Also use Standard for now\n {\n var location = diagnostic.Location.GetLineSpan();\n if (location.IsValid)\n {\n message += $\" (Line {location.StartLinePosition.Line + 1})\";\n }\n errors.Add(message);\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Roslyn validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Validates script semantics using full compilation context to catch namespace, type, and method resolution errors\n /// \n private static bool ValidateScriptSemantics(string contents, System.Collections.Generic.List errors)\n {\n try\n {\n // Get compilation references with caching\n var references = GetCompilationReferences();\n if (references == null || references.Count == 0)\n {\n errors.Add(\"WARNING: Could not load compilation references for semantic validation\");\n return true; // Don't fail if we can't get references\n }\n\n // Create syntax tree\n var syntaxTree = CSharpSyntaxTree.ParseText(contents);\n\n // Create compilation with full context\n var compilation = CSharpCompilation.Create(\n \"TempValidation\",\n new[] { syntaxTree },\n references,\n new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)\n );\n\n // Get semantic diagnostics - this catches all the issues you mentioned!\n var diagnostics = compilation.GetDiagnostics();\n \n bool hasErrors = false;\n foreach (var diagnostic in diagnostics)\n {\n if (diagnostic.Severity == DiagnosticSeverity.Error)\n {\n hasErrors = true;\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n // Include diagnostic ID for better error identification\n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"ERROR: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n else if (diagnostic.Severity == DiagnosticSeverity.Warning)\n {\n var location = diagnostic.Location.GetLineSpan();\n string locationInfo = location.IsValid ? \n $\" (Line {location.StartLinePosition.Line + 1}, Column {location.StartLinePosition.Character + 1})\" : \"\";\n \n string diagnosticId = !string.IsNullOrEmpty(diagnostic.Id) ? $\" [{diagnostic.Id}]\" : \"\";\n errors.Add($\"WARNING: {diagnostic.GetMessage()}{diagnosticId}{locationInfo}\");\n }\n }\n \n return !hasErrors;\n }\n catch (Exception ex)\n {\n errors.Add($\"ERROR: Semantic validation failed: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets compilation references with caching for performance\n /// \n private static System.Collections.Generic.List GetCompilationReferences()\n {\n // Check cache validity\n if (_cachedReferences != null && DateTime.Now - _cacheTime < CacheExpiry)\n {\n return _cachedReferences;\n }\n\n try\n {\n var references = new System.Collections.Generic.List();\n\n // Core .NET assemblies\n references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); // mscorlib/System.Private.CoreLib\n references.Add(MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location)); // System.Linq\n references.Add(MetadataReference.CreateFromFile(typeof(System.Collections.Generic.List<>).Assembly.Location)); // System.Collections\n\n // Unity assemblies\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEngine.Debug).Assembly.Location)); // UnityEngine\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEngine assembly: {ex.Message}\");\n }\n\n#if UNITY_EDITOR\n try\n {\n references.Add(MetadataReference.CreateFromFile(typeof(UnityEditor.Editor).Assembly.Location)); // UnityEditor\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load UnityEditor assembly: {ex.Message}\");\n }\n\n // Get Unity project assemblies\n try\n {\n var assemblies = CompilationPipeline.GetAssemblies();\n foreach (var assembly in assemblies)\n {\n if (File.Exists(assembly.outputPath))\n {\n references.Add(MetadataReference.CreateFromFile(assembly.outputPath));\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Could not load Unity project assemblies: {ex.Message}\");\n }\n#endif\n\n // Cache the results\n _cachedReferences = references;\n _cacheTime = DateTime.Now;\n\n return references;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Failed to get compilation references: {ex.Message}\");\n return new System.Collections.Generic.List();\n }\n }\n#else\n private static bool ValidateScriptSyntaxRoslyn(string contents, ValidationLevel level, System.Collections.Generic.List errors)\n {\n // Fallback when Roslyn is not available\n return true;\n }\n#endif\n\n /// \n /// Validates Unity-specific coding rules and best practices\n /// //TODO: Naive Unity Checks and not really yield any results, need to be improved\n /// \n private static void ValidateScriptSyntaxUnity(string contents, System.Collections.Generic.List errors)\n {\n // Check for common Unity anti-patterns\n if (contents.Contains(\"FindObjectOfType\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: FindObjectOfType in Update() can cause performance issues\");\n }\n\n if (contents.Contains(\"GameObject.Find\") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: GameObject.Find in Update() can cause performance issues\");\n }\n\n // Check for proper MonoBehaviour usage\n if (contents.Contains(\": MonoBehaviour\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: MonoBehaviour requires 'using UnityEngine;'\");\n }\n\n // Check for SerializeField usage\n if (contents.Contains(\"[SerializeField]\") && !contents.Contains(\"using UnityEngine\"))\n {\n errors.Add(\"WARNING: SerializeField requires 'using UnityEngine;'\");\n }\n\n // Check for proper coroutine usage\n if (contents.Contains(\"StartCoroutine\") && !contents.Contains(\"IEnumerator\"))\n {\n errors.Add(\"WARNING: StartCoroutine typically requires IEnumerator methods\");\n }\n\n // Check for Update without FixedUpdate for physics\n if (contents.Contains(\"Rigidbody\") && contents.Contains(\"Update()\") && !contents.Contains(\"FixedUpdate()\"))\n {\n errors.Add(\"WARNING: Consider using FixedUpdate() for Rigidbody operations\");\n }\n\n // Check for missing null checks on Unity objects\n if (contents.Contains(\"GetComponent<\") && !contents.Contains(\"!= null\"))\n {\n errors.Add(\"WARNING: Consider null checking GetComponent results\");\n }\n\n // Check for proper event function signatures\n if (contents.Contains(\"void Start(\") && !contents.Contains(\"void Start()\"))\n {\n errors.Add(\"WARNING: Start() should not have parameters\");\n }\n\n if (contents.Contains(\"void Update(\") && !contents.Contains(\"void Update()\"))\n {\n errors.Add(\"WARNING: Update() should not have parameters\");\n }\n\n // Check for inefficient string operations\n if (contents.Contains(\"Update()\") && contents.Contains(\"\\\"\") && contents.Contains(\"+\"))\n {\n errors.Add(\"WARNING: String concatenation in Update() can cause garbage collection issues\");\n }\n }\n\n /// \n /// Validates semantic rules and common coding issues\n /// \n private static void ValidateSemanticRules(string contents, System.Collections.Generic.List errors)\n {\n // Check for potential memory leaks\n if (contents.Contains(\"new \") && contents.Contains(\"Update()\"))\n {\n errors.Add(\"WARNING: Creating objects in Update() may cause memory issues\");\n }\n\n // Check for magic numbers\n var magicNumberPattern = new Regex(@\"\\b\\d+\\.?\\d*f?\\b(?!\\s*[;})\\]])\");\n var matches = magicNumberPattern.Matches(contents);\n if (matches.Count > 5)\n {\n errors.Add(\"WARNING: Consider using named constants instead of magic numbers\");\n }\n\n // Check for long methods (simple line count check)\n var methodPattern = new Regex(@\"(public|private|protected|internal)?\\s*(static)?\\s*\\w+\\s+\\w+\\s*\\([^)]*\\)\\s*{\");\n var methodMatches = methodPattern.Matches(contents);\n foreach (Match match in methodMatches)\n {\n int startIndex = match.Index;\n int braceCount = 0;\n int lineCount = 0;\n bool inMethod = false;\n\n for (int i = startIndex; i < contents.Length; i++)\n {\n if (contents[i] == '{')\n {\n braceCount++;\n inMethod = true;\n }\n else if (contents[i] == '}')\n {\n braceCount--;\n if (braceCount == 0 && inMethod)\n break;\n }\n else if (contents[i] == '\\n' && inMethod)\n {\n lineCount++;\n }\n }\n\n if (lineCount > 50)\n {\n errors.Add(\"WARNING: Method is very long, consider breaking it into smaller methods\");\n break; // Only report once\n }\n }\n\n // Check for proper exception handling\n if (contents.Contains(\"catch\") && contents.Contains(\"catch()\"))\n {\n errors.Add(\"WARNING: Empty catch blocks should be avoided\");\n }\n\n // Check for proper async/await usage\n if (contents.Contains(\"async \") && !contents.Contains(\"await\"))\n {\n errors.Add(\"WARNING: Async method should contain await or return Task\");\n }\n\n // Check for hardcoded tags and layers\n if (contents.Contains(\"\\\"Player\\\"\") || contents.Contains(\"\\\"Enemy\\\"\"))\n {\n errors.Add(\"WARNING: Consider using constants for tags instead of hardcoded strings\");\n }\n }\n\n //TODO: A easier way for users to update incorrect scripts (now duplicated with the updateScript method and need to also update server side, put aside for now)\n /// \n /// Public method to validate script syntax with configurable validation level\n /// Returns detailed validation results including errors and warnings\n /// \n // public static object ValidateScript(JObject @params)\n // {\n // string contents = @params[\"contents\"]?.ToString();\n // string validationLevel = @params[\"validationLevel\"]?.ToString() ?? \"standard\";\n\n // if (string.IsNullOrEmpty(contents))\n // {\n // return Response.Error(\"Contents parameter is required for validation.\");\n // }\n\n // // Parse validation level\n // ValidationLevel level = ValidationLevel.Standard;\n // switch (validationLevel.ToLower())\n // {\n // case \"basic\": level = ValidationLevel.Basic; break;\n // case \"standard\": level = ValidationLevel.Standard; break;\n // case \"comprehensive\": level = ValidationLevel.Comprehensive; break;\n // case \"strict\": level = ValidationLevel.Strict; break;\n // default:\n // return Response.Error($\"Invalid validation level: '{validationLevel}'. Valid levels are: basic, standard, comprehensive, strict.\");\n // }\n\n // // Perform validation\n // bool isValid = ValidateScriptSyntax(contents, level, out string[] validationErrors);\n\n // var errors = validationErrors?.Where(e => e.StartsWith(\"ERROR:\")).ToArray() ?? new string[0];\n // var warnings = validationErrors?.Where(e => e.StartsWith(\"WARNING:\")).ToArray() ?? new string[0];\n\n // var result = new\n // {\n // isValid = isValid,\n // validationLevel = validationLevel,\n // errorCount = errors.Length,\n // warningCount = warnings.Length,\n // errors = errors,\n // warnings = warnings,\n // summary = isValid \n // ? (warnings.Length > 0 ? $\"Validation passed with {warnings.Length} warnings\" : \"Validation passed with no issues\")\n // : $\"Validation failed with {errors.Length} errors and {warnings.Length} warnings\"\n // };\n\n // if (isValid)\n // {\n // return Response.Success(\"Script validation completed successfully.\", result);\n // }\n // else\n // {\n // return Response.Error(\"Script validation failed.\", result);\n // }\n // }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageGameObject.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json; // Added for JsonSerializationException\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditor.SceneManagement;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\nusing UnityMcpBridge.Runtime.Serialization;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles GameObject manipulation within the current scene (CRUD, find, components).\n /// \n public static class ManageGameObject\n {\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n\n string action = @params[\"action\"]?.ToString().ToLower();\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Parameters used by various actions\n JToken targetToken = @params[\"target\"]; // Can be string (name/path) or int (instanceID)\n string searchMethod = @params[\"searchMethod\"]?.ToString().ToLower();\n\n // Get common parameters (consolidated)\n string name = @params[\"name\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString();\n string layer = @params[\"layer\"]?.ToString();\n JToken parentToken = @params[\"parent\"];\n\n // --- Add parameter for controlling non-public field inclusion ---\n bool includeNonPublicSerialized = @params[\"includeNonPublicSerialized\"]?.ToObject() ?? true; // Default to true\n // --- End add parameter ---\n\n // --- Prefab Redirection Check ---\n string targetPath =\n targetToken?.Type == JTokenType.String ? targetToken.ToString() : null;\n if (\n !string.IsNullOrEmpty(targetPath)\n && targetPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n // Allow 'create' (instantiate), 'find' (?), 'get_components' (?)\n if (action == \"modify\" || action == \"set_component_property\")\n {\n Debug.Log(\n $\"[ManageGameObject->ManageAsset] Redirecting action '{action}' for prefab '{targetPath}' to ManageAsset.\"\n );\n // Prepare params for ManageAsset.ModifyAsset\n JObject assetParams = new JObject();\n assetParams[\"action\"] = \"modify\"; // ManageAsset uses \"modify\"\n assetParams[\"path\"] = targetPath;\n\n // Extract properties.\n // For 'set_component_property', combine componentName and componentProperties.\n // For 'modify', directly use componentProperties.\n JObject properties = null;\n if (action == \"set_component_property\")\n {\n string compName = @params[\"componentName\"]?.ToString();\n JObject compProps = @params[\"componentProperties\"]?[compName] as JObject; // Handle potential nesting\n if (string.IsNullOrEmpty(compName))\n return Response.Error(\n \"Missing 'componentName' for 'set_component_property' on prefab.\"\n );\n if (compProps == null)\n return Response.Error(\n $\"Missing or invalid 'componentProperties' for component '{compName}' for 'set_component_property' on prefab.\"\n );\n\n properties = new JObject();\n properties[compName] = compProps;\n }\n else // action == \"modify\"\n {\n properties = @params[\"componentProperties\"] as JObject;\n if (properties == null)\n return Response.Error(\n \"Missing 'componentProperties' for 'modify' action on prefab.\"\n );\n }\n\n assetParams[\"properties\"] = properties;\n\n // Call ManageAsset handler\n return ManageAsset.HandleCommand(assetParams);\n }\n else if (\n action == \"delete\"\n || action == \"add_component\"\n || action == \"remove_component\"\n || action == \"get_components\"\n ) // Added get_components here too\n {\n // Explicitly block other modifications on the prefab asset itself via manage_gameobject\n return Response.Error(\n $\"Action '{action}' on a prefab asset ('{targetPath}') should be performed using the 'manage_asset' command.\"\n );\n }\n // Allow 'create' (instantiation) and 'find' to proceed, although finding a prefab asset by path might be less common via manage_gameobject.\n // No specific handling needed here, the code below will run.\n }\n // --- End Prefab Redirection Check ---\n\n try\n {\n switch (action)\n {\n case \"create\":\n return CreateGameObject(@params);\n case \"modify\":\n return ModifyGameObject(@params, targetToken, searchMethod);\n case \"delete\":\n return DeleteGameObject(targetToken, searchMethod);\n case \"find\":\n return FindGameObjects(@params, targetToken, searchMethod);\n case \"get_components\":\n string getCompTarget = targetToken?.ToString(); // Expect name, path, or ID string\n if (getCompTarget == null)\n return Response.Error(\n \"'target' parameter required for get_components.\"\n );\n // Pass the includeNonPublicSerialized flag here\n return GetComponentsFromTarget(getCompTarget, searchMethod, includeNonPublicSerialized);\n case \"add_component\":\n return AddComponentToTarget(@params, targetToken, searchMethod);\n case \"remove_component\":\n return RemoveComponentFromTarget(@params, targetToken, searchMethod);\n case \"set_component_property\":\n return SetComponentPropertyOnTarget(@params, targetToken, searchMethod);\n\n default:\n return Response.Error($\"Unknown action: '{action}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageGameObject] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object CreateGameObject(JObject @params)\n {\n string name = @params[\"name\"]?.ToString();\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"'name' parameter is required for 'create' action.\");\n }\n\n // Get prefab creation parameters\n bool saveAsPrefab = @params[\"saveAsPrefab\"]?.ToObject() ?? false;\n string prefabPath = @params[\"prefabPath\"]?.ToString();\n string tag = @params[\"tag\"]?.ToString(); // Get tag for creation\n string primitiveType = @params[\"primitiveType\"]?.ToString(); // Keep primitiveType check\n GameObject newGo = null; // Initialize as null\n\n // --- Try Instantiating Prefab First ---\n string originalPrefabPath = prefabPath; // Keep original for messages\n if (!string.IsNullOrEmpty(prefabPath))\n {\n // If no extension, search for the prefab by name\n if (\n !prefabPath.Contains(\"/\")\n && !prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase)\n )\n {\n string prefabNameOnly = prefabPath;\n Debug.Log(\n $\"[ManageGameObject.Create] Searching for prefab named: '{prefabNameOnly}'\"\n );\n string[] guids = AssetDatabase.FindAssets($\"t:Prefab {prefabNameOnly}\");\n if (guids.Length == 0)\n {\n return Response.Error(\n $\"Prefab named '{prefabNameOnly}' not found anywhere in the project.\"\n );\n }\n else if (guids.Length > 1)\n {\n string foundPaths = string.Join(\n \", \",\n guids.Select(g => AssetDatabase.GUIDToAssetPath(g))\n );\n return Response.Error(\n $\"Multiple prefabs found matching name '{prefabNameOnly}': {foundPaths}. Please provide a more specific path.\"\n );\n }\n else // Exactly one found\n {\n prefabPath = AssetDatabase.GUIDToAssetPath(guids[0]); // Update prefabPath with the full path\n Debug.Log(\n $\"[ManageGameObject.Create] Found unique prefab at path: '{prefabPath}'\"\n );\n }\n }\n else if (!prefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n // If it looks like a path but doesn't end with .prefab, assume user forgot it and append it.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Provided prefabPath '{prefabPath}' does not end with .prefab. Assuming it's missing and appending.\"\n );\n prefabPath += \".prefab\";\n // Note: This path might still not exist, AssetDatabase.LoadAssetAtPath will handle that.\n }\n // The logic above now handles finding or assuming the .prefab extension.\n\n GameObject prefabAsset = AssetDatabase.LoadAssetAtPath(prefabPath);\n if (prefabAsset != null)\n {\n try\n {\n // Instantiate the prefab, initially place it at the root\n // Parent will be set later if specified\n newGo = PrefabUtility.InstantiatePrefab(prefabAsset) as GameObject;\n\n if (newGo == null)\n {\n // This might happen if the asset exists but isn't a valid GameObject prefab somehow\n Debug.LogError(\n $\"[ManageGameObject.Create] Failed to instantiate prefab at '{prefabPath}', asset might be corrupted or not a GameObject.\"\n );\n return Response.Error(\n $\"Failed to instantiate prefab at '{prefabPath}'.\"\n );\n }\n // Name the instance based on the 'name' parameter, not the prefab's default name\n if (!string.IsNullOrEmpty(name))\n {\n newGo.name = name;\n }\n // Register Undo for prefab instantiation\n Undo.RegisterCreatedObjectUndo(\n newGo,\n $\"Instantiate Prefab '{prefabAsset.name}' as '{newGo.name}'\"\n );\n Debug.Log(\n $\"[ManageGameObject.Create] Instantiated prefab '{prefabAsset.name}' from path '{prefabPath}' as '{newGo.name}'.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error instantiating prefab '{prefabPath}': {e.Message}\"\n );\n }\n }\n else\n {\n // Only return error if prefabPath was specified but not found.\n // If prefabPath was empty/null, we proceed to create primitive/empty.\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Prefab asset not found at path: '{prefabPath}'. Will proceed to create new object if specified.\"\n );\n // Do not return error here, allow fallback to primitive/empty creation\n }\n }\n\n // --- Fallback: Create Primitive or Empty GameObject ---\n bool createdNewObject = false; // Flag to track if we created (not instantiated)\n if (newGo == null) // Only proceed if prefab instantiation didn't happen\n {\n if (!string.IsNullOrEmpty(primitiveType))\n {\n try\n {\n PrimitiveType type = (PrimitiveType)\n Enum.Parse(typeof(PrimitiveType), primitiveType, true);\n newGo = GameObject.CreatePrimitive(type);\n // Set name *after* creation for primitives\n if (!string.IsNullOrEmpty(name))\n newGo.name = name;\n else\n return Response.Error(\n \"'name' parameter is required when creating a primitive.\"\n ); // Name is essential\n createdNewObject = true;\n }\n catch (ArgumentException)\n {\n return Response.Error(\n $\"Invalid primitive type: '{primitiveType}'. Valid types: {string.Join(\", \", Enum.GetNames(typeof(PrimitiveType)))}\"\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Failed to create primitive '{primitiveType}': {e.Message}\"\n );\n }\n }\n else // Create empty GameObject\n {\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\n \"'name' parameter is required for 'create' action when not instantiating a prefab or creating a primitive.\"\n );\n }\n newGo = new GameObject(name);\n createdNewObject = true;\n }\n // Record creation for Undo *only* if we created a new object\n if (createdNewObject)\n {\n Undo.RegisterCreatedObjectUndo(newGo, $\"Create GameObject '{newGo.name}'\");\n }\n }\n // --- Common Setup (Parent, Transform, Tag, Components) - Applied AFTER object exists ---\n if (newGo == null)\n {\n // Should theoretically not happen if logic above is correct, but safety check.\n return Response.Error(\"Failed to create or instantiate the GameObject.\");\n }\n\n // Record potential changes to the existing prefab instance or the new GO\n // Record transform separately in case parent changes affect it\n Undo.RecordObject(newGo.transform, \"Set GameObject Transform\");\n Undo.RecordObject(newGo, \"Set GameObject Properties\");\n\n // Set Parent\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject parentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\"); // Flexible parent finding\n if (parentGo == null)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up created object\n return Response.Error($\"Parent specified ('{parentToken}') but not found.\");\n }\n newGo.transform.SetParent(parentGo.transform, true); // worldPositionStays = true\n }\n\n // Set Transform\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue)\n newGo.transform.localPosition = position.Value;\n if (rotation.HasValue)\n newGo.transform.localEulerAngles = rotation.Value;\n if (scale.HasValue)\n newGo.transform.localScale = scale.Value;\n\n // Set Tag (added for create action)\n if (!string.IsNullOrEmpty(tag))\n {\n // Similar logic as in ModifyGameObject for setting/creating tags\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n newGo.tag = tagToSet;\n }\n catch (UnityException ex)\n {\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n InternalEditorUtility.AddTag(tagToSet);\n newGo.tag = tagToSet; // Retry\n Debug.Log(\n $\"[ManageGameObject.Create] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}' during creation: {innerEx.Message}.\"\n );\n }\n }\n else\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return Response.Error(\n $\"Failed to set tag to '{tagToSet}' during creation: {ex.Message}.\"\n );\n }\n }\n }\n\n // Set Layer (new for create action)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId != -1)\n {\n newGo.layer = layerId;\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Create] Layer '{layerName}' not found. Using default layer.\"\n );\n }\n }\n\n // Add Components\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArray)\n {\n foreach (var compToken in componentsToAddArray)\n {\n string typeName = null;\n JObject properties = null;\n\n if (compToken.Type == JTokenType.String)\n {\n typeName = compToken.ToString();\n }\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(newGo, typeName, properties);\n if (addResult != null) // Check if AddComponentInternal returned an error object\n {\n UnityEngine.Object.DestroyImmediate(newGo); // Clean up\n return addResult; // Return the error response\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Invalid component format in componentsToAdd: {compToken}\"\n );\n }\n }\n }\n\n // Save as Prefab ONLY if we *created* a new object AND saveAsPrefab is true\n GameObject finalInstance = newGo; // Use this for selection and return data\n if (createdNewObject && saveAsPrefab)\n {\n string finalPrefabPath = prefabPath; // Use a separate variable for saving path\n // This check should now happen *before* attempting to save\n if (string.IsNullOrEmpty(finalPrefabPath))\n {\n // Clean up the created object before returning error\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n \"'prefabPath' is required when 'saveAsPrefab' is true and creating a new object.\"\n );\n }\n // Ensure the *saving* path ends with .prefab\n if (!finalPrefabPath.EndsWith(\".prefab\", StringComparison.OrdinalIgnoreCase))\n {\n Debug.Log(\n $\"[ManageGameObject.Create] Appending .prefab extension to save path: '{finalPrefabPath}' -> '{finalPrefabPath}.prefab'\"\n );\n finalPrefabPath += \".prefab\";\n }\n\n try\n {\n // Ensure directory exists using the final saving path\n string directoryPath = System.IO.Path.GetDirectoryName(finalPrefabPath);\n if (\n !string.IsNullOrEmpty(directoryPath)\n && !System.IO.Directory.Exists(directoryPath)\n )\n {\n System.IO.Directory.CreateDirectory(directoryPath);\n AssetDatabase.Refresh(); // Refresh asset database to recognize the new folder\n Debug.Log(\n $\"[ManageGameObject.Create] Created directory for prefab: {directoryPath}\"\n );\n }\n // Use SaveAsPrefabAssetAndConnect with the final saving path\n finalInstance = PrefabUtility.SaveAsPrefabAssetAndConnect(\n newGo,\n finalPrefabPath,\n InteractionMode.UserAction\n );\n\n if (finalInstance == null)\n {\n // Destroy the original if saving failed somehow (shouldn't usually happen if path is valid)\n UnityEngine.Object.DestroyImmediate(newGo);\n return Response.Error(\n $\"Failed to save GameObject '{name}' as prefab at '{finalPrefabPath}'. Check path and permissions.\"\n );\n }\n Debug.Log(\n $\"[ManageGameObject.Create] GameObject '{name}' saved as prefab to '{finalPrefabPath}' and instance connected.\"\n );\n // Mark the new prefab asset as dirty? Not usually necessary, SaveAsPrefabAsset handles it.\n // EditorUtility.SetDirty(finalInstance); // Instance is handled by SaveAsPrefabAssetAndConnect\n }\n catch (Exception e)\n {\n // Clean up the instance if prefab saving fails\n UnityEngine.Object.DestroyImmediate(newGo); // Destroy the original attempt\n return Response.Error($\"Error saving prefab '{finalPrefabPath}': {e.Message}\");\n }\n }\n\n // Select the instance in the scene (either prefab instance or newly created/saved one)\n Selection.activeGameObject = finalInstance;\n\n // Determine appropriate success message using the potentially updated or original path\n string messagePrefabPath =\n finalInstance == null\n ? originalPrefabPath\n : AssetDatabase.GetAssetPath(\n PrefabUtility.GetCorrespondingObjectFromSource(finalInstance)\n ?? (UnityEngine.Object)finalInstance\n );\n string successMessage;\n if (!createdNewObject && !string.IsNullOrEmpty(messagePrefabPath)) // Instantiated existing prefab\n {\n successMessage =\n $\"Prefab '{messagePrefabPath}' instantiated successfully as '{finalInstance.name}'.\";\n }\n else if (createdNewObject && saveAsPrefab && !string.IsNullOrEmpty(messagePrefabPath)) // Created new and saved as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created and saved as prefab to '{messagePrefabPath}'.\";\n }\n else // Created new primitive or empty GO, didn't save as prefab\n {\n successMessage =\n $\"GameObject '{finalInstance.name}' created successfully in scene.\";\n }\n\n // Use the new serializer helper\n //return Response.Success(successMessage, GetGameObjectData(finalInstance));\n return Response.Success(successMessage, Helpers.GameObjectSerializer.GetGameObjectData(finalInstance));\n }\n\n private static object ModifyGameObject(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n // Record state for Undo *before* modifications\n Undo.RecordObject(targetGo.transform, \"Modify GameObject Transform\");\n Undo.RecordObject(targetGo, \"Modify GameObject Properties\");\n\n bool modified = false;\n\n // Rename (using consolidated 'name' parameter)\n string name = @params[\"name\"]?.ToString();\n if (!string.IsNullOrEmpty(name) && targetGo.name != name)\n {\n targetGo.name = name;\n modified = true;\n }\n\n // Change Parent (using consolidated 'parent' parameter)\n JToken parentToken = @params[\"parent\"];\n if (parentToken != null)\n {\n GameObject newParentGo = FindObjectInternal(parentToken, \"by_id_or_name_or_path\");\n // Check for hierarchy loops\n if (\n newParentGo == null\n && !(\n parentToken.Type == JTokenType.Null\n || (\n parentToken.Type == JTokenType.String\n && string.IsNullOrEmpty(parentToken.ToString())\n )\n )\n )\n {\n return Response.Error($\"New parent ('{parentToken}') not found.\");\n }\n if (newParentGo != null && newParentGo.transform.IsChildOf(targetGo.transform))\n {\n return Response.Error(\n $\"Cannot parent '{targetGo.name}' to '{newParentGo.name}', as it would create a hierarchy loop.\"\n );\n }\n if (targetGo.transform.parent != (newParentGo?.transform))\n {\n targetGo.transform.SetParent(newParentGo?.transform, true); // worldPositionStays = true\n modified = true;\n }\n }\n\n // Set Active State\n bool? setActive = @params[\"setActive\"]?.ToObject();\n if (setActive.HasValue && targetGo.activeSelf != setActive.Value)\n {\n targetGo.SetActive(setActive.Value);\n modified = true;\n }\n\n // Change Tag (using consolidated 'tag' parameter)\n string tag = @params[\"tag\"]?.ToString();\n // Only attempt to change tag if a non-null tag is provided and it's different from the current one.\n // Allow setting an empty string to remove the tag (Unity uses \"Untagged\").\n if (tag != null && targetGo.tag != tag)\n {\n // Ensure the tag is not empty, if empty, it means \"Untagged\" implicitly\n string tagToSet = string.IsNullOrEmpty(tag) ? \"Untagged\" : tag;\n try\n {\n targetGo.tag = tagToSet;\n modified = true;\n }\n catch (UnityException ex)\n {\n // Check if the error is specifically because the tag doesn't exist\n if (ex.Message.Contains(\"is not defined\"))\n {\n Debug.LogWarning(\n $\"[ManageGameObject] Tag '{tagToSet}' not found. Attempting to create it.\"\n );\n try\n {\n // Attempt to create the tag using internal utility\n InternalEditorUtility.AddTag(tagToSet);\n // Wait a frame maybe? Not strictly necessary but sometimes helps editor updates.\n // yield return null; // Cannot yield here, editor script limitation\n\n // Retry setting the tag immediately after creation\n targetGo.tag = tagToSet;\n modified = true;\n Debug.Log(\n $\"[ManageGameObject] Tag '{tagToSet}' created and assigned successfully.\"\n );\n }\n catch (Exception innerEx)\n {\n // Handle failure during tag creation or the second assignment attempt\n Debug.LogError(\n $\"[ManageGameObject] Failed to create or assign tag '{tagToSet}' after attempting creation: {innerEx.Message}\"\n );\n return Response.Error(\n $\"Failed to create or assign tag '{tagToSet}': {innerEx.Message}. Check Tag Manager and permissions.\"\n );\n }\n }\n else\n {\n // If the exception was for a different reason, return the original error\n return Response.Error($\"Failed to set tag to '{tagToSet}': {ex.Message}.\");\n }\n }\n }\n\n // Change Layer (using consolidated 'layer' parameter)\n string layerName = @params[\"layer\"]?.ToString();\n if (!string.IsNullOrEmpty(layerName))\n {\n int layerId = LayerMask.NameToLayer(layerName);\n if (layerId == -1 && layerName != \"Default\")\n {\n return Response.Error(\n $\"Invalid layer specified: '{layerName}'. Use a valid layer name.\"\n );\n }\n if (layerId != -1 && targetGo.layer != layerId)\n {\n targetGo.layer = layerId;\n modified = true;\n }\n }\n\n // Transform Modifications\n Vector3? position = ParseVector3(@params[\"position\"] as JArray);\n Vector3? rotation = ParseVector3(@params[\"rotation\"] as JArray);\n Vector3? scale = ParseVector3(@params[\"scale\"] as JArray);\n\n if (position.HasValue && targetGo.transform.localPosition != position.Value)\n {\n targetGo.transform.localPosition = position.Value;\n modified = true;\n }\n if (rotation.HasValue && targetGo.transform.localEulerAngles != rotation.Value)\n {\n targetGo.transform.localEulerAngles = rotation.Value;\n modified = true;\n }\n if (scale.HasValue && targetGo.transform.localScale != scale.Value)\n {\n targetGo.transform.localScale = scale.Value;\n modified = true;\n }\n\n // --- Component Modifications ---\n // Note: These might need more specific Undo recording per component\n\n // Remove Components\n if (@params[\"componentsToRemove\"] is JArray componentsToRemoveArray)\n {\n foreach (var compToken in componentsToRemoveArray)\n {\n // ... (parsing logic as in CreateGameObject) ...\n string typeName = compToken.ToString();\n if (!string.IsNullOrEmpty(typeName))\n {\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error if removal failed\n modified = true;\n }\n }\n }\n\n // Add Components (similar to create)\n if (@params[\"componentsToAdd\"] is JArray componentsToAddArrayModify)\n {\n foreach (var compToken in componentsToAddArrayModify)\n {\n string typeName = null;\n JObject properties = null;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n\n if (!string.IsNullOrEmpty(typeName))\n {\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult;\n modified = true;\n }\n }\n }\n\n // Set Component Properties\n if (@params[\"componentProperties\"] is JObject componentPropertiesObj)\n {\n foreach (var prop in componentPropertiesObj.Properties())\n {\n string compName = prop.Name;\n JObject propertiesToSet = prop.Value as JObject;\n if (propertiesToSet != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n compName,\n propertiesToSet\n );\n if (setResult != null)\n return setResult;\n modified = true;\n }\n }\n }\n\n if (!modified)\n {\n // Use the new serializer helper\n // return Response.Success(\n // $\"No modifications applied to GameObject '{targetGo.name}'.\",\n // GetGameObjectData(targetGo));\n\n return Response.Success(\n $\"No modifications applied to GameObject '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n EditorUtility.SetDirty(targetGo); // Mark scene as dirty\n // Use the new serializer helper\n return Response.Success(\n $\"GameObject '{targetGo.name}' modified successfully.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n // return Response.Success(\n // $\"GameObject '{targetGo.name}' modified successfully.\",\n // GetGameObjectData(targetGo));\n \n }\n\n private static object DeleteGameObject(JToken targetToken, string searchMethod)\n {\n // Find potentially multiple objects if name/tag search is used without find_all=false implicitly\n List targets = FindObjectsInternal(targetToken, searchMethod, true); // find_all=true for delete safety\n\n if (targets.Count == 0)\n {\n return Response.Error(\n $\"Target GameObject(s) ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n List deletedObjects = new List();\n foreach (var targetGo in targets)\n {\n if (targetGo != null)\n {\n string goName = targetGo.name;\n int goId = targetGo.GetInstanceID();\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(targetGo);\n deletedObjects.Add(new { name = goName, instanceID = goId });\n }\n }\n\n if (deletedObjects.Count > 0)\n {\n string message =\n targets.Count == 1\n ? $\"GameObject '{deletedObjects[0].GetType().GetProperty(\"name\").GetValue(deletedObjects[0])}' deleted successfully.\"\n : $\"{deletedObjects.Count} GameObjects deleted successfully.\";\n return Response.Success(message, deletedObjects);\n }\n else\n {\n // Should not happen if targets.Count > 0 initially, but defensive check\n return Response.Error(\"Failed to delete target GameObject(s).\");\n }\n }\n\n private static object FindGameObjects(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n bool findAll = @params[\"findAll\"]?.ToObject() ?? false;\n List foundObjects = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n @params\n );\n\n if (foundObjects.Count == 0)\n {\n return Response.Success(\"No matching GameObjects found.\", new List());\n }\n\n // Use the new serializer helper\n //var results = foundObjects.Select(go => GetGameObjectData(go)).ToList();\n var results = foundObjects.Select(go => Helpers.GameObjectSerializer.GetGameObjectData(go)).ToList();\n return Response.Success($\"Found {results.Count} GameObject(s).\", results);\n }\n\n private static object GetComponentsFromTarget(string target, string searchMethod, bool includeNonPublicSerialized = true)\n {\n GameObject targetGo = FindObjectInternal(target, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{target}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n try\n {\n // --- Get components, immediately copy to list, and null original array --- \n Component[] originalComponents = targetGo.GetComponents();\n List componentsToIterate = new List(originalComponents ?? Array.Empty()); // Copy immediately, handle null case\n int componentCount = componentsToIterate.Count; \n originalComponents = null; // Null the original reference\n // Debug.Log($\"[GetComponentsFromTarget] Found {componentCount} components on {targetGo.name}. Copied to list, nulled original. Starting REVERSE for loop...\");\n // --- End Copy and Null --- \n \n var componentData = new List();\n \n for (int i = componentCount - 1; i >= 0; i--) // Iterate backwards over the COPY\n {\n Component c = componentsToIterate[i]; // Use the copy\n if (c == null) \n {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] Encountered a null component at index {i} on {targetGo.name}. Skipping.\");\n continue; // Safety check\n }\n // Debug.Log($\"[GetComponentsFromTarget REVERSE for] Processing component: {c.GetType()?.FullName ?? \"null\"} (ID: {c.GetInstanceID()}) at index {i} on {targetGo.name}\");\n try \n {\n var data = Helpers.GameObjectSerializer.GetComponentData(c, includeNonPublicSerialized);\n if (data != null) // Ensure GetComponentData didn't return null\n {\n componentData.Insert(0, data); // Insert at beginning to maintain original order in final list\n }\n // else\n // {\n // Debug.LogWarning($\"[GetComponentsFromTarget REVERSE for] GetComponentData returned null for component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}. Skipping addition.\");\n // }\n }\n catch (Exception ex)\n {\n Debug.LogError($\"[GetComponentsFromTarget REVERSE for] Error processing component {c.GetType().FullName} (ID: {c.GetInstanceID()}) on {targetGo.name}: {ex.Message}\\n{ex.StackTrace}\");\n // Optionally add placeholder data or just skip\n componentData.Insert(0, new JObject( // Insert error marker at beginning\n new JProperty(\"typeName\", c.GetType().FullName + \" (Serialization Error)\"),\n new JProperty(\"instanceID\", c.GetInstanceID()),\n new JProperty(\"error\", ex.Message)\n ));\n }\n }\n // Debug.Log($\"[GetComponentsFromTarget] Finished REVERSE for loop.\");\n \n // Cleanup the list we created\n componentsToIterate.Clear();\n componentsToIterate = null;\n\n return Response.Success(\n $\"Retrieved {componentData.Count} components from '{targetGo.name}'.\",\n componentData // List was built in original order\n );\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error getting components from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n private static object AddComponentToTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n JObject properties = null;\n\n // Allow adding component specified directly or via componentsToAdd array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n properties = @params[\"componentProperties\"]?[typeName] as JObject; // Check if props are nested under name\n }\n else if (\n @params[\"componentsToAdd\"] is JArray componentsToAddArray\n && componentsToAddArray.Count > 0\n )\n {\n var compToken = componentsToAddArray.First;\n if (compToken.Type == JTokenType.String)\n typeName = compToken.ToString();\n else if (compToken is JObject compObj)\n {\n typeName = compObj[\"typeName\"]?.ToString();\n properties = compObj[\"properties\"] as JObject;\n }\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToAdd') is required.\"\n );\n }\n\n var addResult = AddComponentInternal(targetGo, typeName, properties);\n if (addResult != null)\n return addResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' added to '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n ); // Return updated GO data\n }\n\n private static object RemoveComponentFromTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string typeName = null;\n // Allow removing component specified directly or via componentsToRemove array (take first)\n if (@params[\"componentName\"] != null)\n {\n typeName = @params[\"componentName\"]?.ToString();\n }\n else if (\n @params[\"componentsToRemove\"] is JArray componentsToRemoveArray\n && componentsToRemoveArray.Count > 0\n )\n {\n typeName = componentsToRemoveArray.First?.ToString();\n }\n\n if (string.IsNullOrEmpty(typeName))\n {\n return Response.Error(\n \"Component type name ('componentName' or first element in 'componentsToRemove') is required.\"\n );\n }\n\n var removeResult = RemoveComponentInternal(targetGo, typeName);\n if (removeResult != null)\n return removeResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Component '{typeName}' removed from '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n private static object SetComponentPropertyOnTarget(\n JObject @params,\n JToken targetToken,\n string searchMethod\n )\n {\n GameObject targetGo = FindObjectInternal(targetToken, searchMethod);\n if (targetGo == null)\n {\n return Response.Error(\n $\"Target GameObject ('{targetToken}') not found using method '{searchMethod ?? \"default\"}'.\"\n );\n }\n\n string compName = @params[\"componentName\"]?.ToString();\n JObject propertiesToSet = null;\n\n if (!string.IsNullOrEmpty(compName))\n {\n // Properties might be directly under componentProperties or nested under the component name\n if (@params[\"componentProperties\"] is JObject compProps)\n {\n propertiesToSet = compProps[compName] as JObject ?? compProps; // Allow flat or nested structure\n }\n }\n else\n {\n return Response.Error(\"'componentName' parameter is required.\");\n }\n\n if (propertiesToSet == null || !propertiesToSet.HasValues)\n {\n return Response.Error(\n \"'componentProperties' dictionary for the specified component is required and cannot be empty.\"\n );\n }\n\n var setResult = SetComponentPropertiesInternal(targetGo, compName, propertiesToSet);\n if (setResult != null)\n return setResult; // Return error\n\n EditorUtility.SetDirty(targetGo);\n // Use the new serializer helper\n return Response.Success(\n $\"Properties set for component '{compName}' on '{targetGo.name}'.\",\n Helpers.GameObjectSerializer.GetGameObjectData(targetGo)\n );\n }\n\n // --- Internal Helpers ---\n\n /// \n /// Finds a single GameObject based on token (ID, name, path) and search method.\n /// \n private static GameObject FindObjectInternal(\n JToken targetToken,\n string searchMethod,\n JObject findParams = null\n )\n {\n // If find_all is not explicitly false, we still want only one for most single-target operations.\n bool findAll = findParams?[\"findAll\"]?.ToObject() ?? false;\n // If a specific target ID is given, always find just that one.\n if (\n targetToken?.Type == JTokenType.Integer\n || (searchMethod == \"by_id\" && int.TryParse(targetToken?.ToString(), out _))\n )\n {\n findAll = false;\n }\n List results = FindObjectsInternal(\n targetToken,\n searchMethod,\n findAll,\n findParams\n );\n return results.Count > 0 ? results[0] : null;\n }\n\n /// \n /// Core logic for finding GameObjects based on various criteria.\n /// \n private static List FindObjectsInternal(\n JToken targetToken,\n string searchMethod,\n bool findAll,\n JObject findParams = null\n )\n {\n List results = new List();\n string searchTerm = findParams?[\"searchTerm\"]?.ToString() ?? targetToken?.ToString(); // Use searchTerm if provided, else the target itself\n bool searchInChildren = findParams?[\"searchInChildren\"]?.ToObject() ?? false;\n bool searchInactive = findParams?[\"searchInactive\"]?.ToObject() ?? false;\n\n // Default search method if not specified\n if (string.IsNullOrEmpty(searchMethod))\n {\n if (targetToken?.Type == JTokenType.Integer)\n searchMethod = \"by_id\";\n else if (!string.IsNullOrEmpty(searchTerm) && searchTerm.Contains('/'))\n searchMethod = \"by_path\";\n else\n searchMethod = \"by_name\"; // Default fallback\n }\n\n GameObject rootSearchObject = null;\n // If searching in children, find the initial target first\n if (searchInChildren && targetToken != null)\n {\n rootSearchObject = FindObjectInternal(targetToken, \"by_id_or_name_or_path\"); // Find the root for child search\n if (rootSearchObject == null)\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Root object '{targetToken}' for child search not found.\"\n );\n return results; // Return empty if root not found\n }\n }\n\n switch (searchMethod)\n {\n case \"by_id\":\n if (int.TryParse(searchTerm, out int instanceId))\n {\n // EditorUtility.InstanceIDToObject is slow, iterate manually if possible\n // GameObject obj = EditorUtility.InstanceIDToObject(instanceId) as GameObject;\n var allObjects = GetAllSceneObjects(searchInactive); // More efficient\n GameObject obj = allObjects.FirstOrDefault(go =>\n go.GetInstanceID() == instanceId\n );\n if (obj != null)\n results.Add(obj);\n }\n break;\n case \"by_name\":\n var searchPoolName = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolName.Where(go => go.name == searchTerm));\n break;\n case \"by_path\":\n // Path is relative to scene root or rootSearchObject\n Transform foundTransform = rootSearchObject\n ? rootSearchObject.transform.Find(searchTerm)\n : GameObject.Find(searchTerm)?.transform;\n if (foundTransform != null)\n results.Add(foundTransform.gameObject);\n break;\n case \"by_tag\":\n var searchPoolTag = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n results.AddRange(searchPoolTag.Where(go => go.CompareTag(searchTerm)));\n break;\n case \"by_layer\":\n var searchPoolLayer = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(searchInactive)\n .Select(t => t.gameObject)\n : GetAllSceneObjects(searchInactive);\n if (int.TryParse(searchTerm, out int layerIndex))\n {\n results.AddRange(searchPoolLayer.Where(go => go.layer == layerIndex));\n }\n else\n {\n int namedLayer = LayerMask.NameToLayer(searchTerm);\n if (namedLayer != -1)\n results.AddRange(searchPoolLayer.Where(go => go.layer == namedLayer));\n }\n break;\n case \"by_component\":\n Type componentType = FindType(searchTerm);\n if (componentType != null)\n {\n // Determine FindObjectsInactive based on the searchInactive flag\n FindObjectsInactive findInactive = searchInactive\n ? FindObjectsInactive.Include\n : FindObjectsInactive.Exclude;\n // Replace FindObjectsOfType with FindObjectsByType, specifying the sorting mode and inactive state\n var searchPoolComp = rootSearchObject\n ? rootSearchObject\n .GetComponentsInChildren(componentType, searchInactive)\n .Select(c => (c as Component).gameObject)\n : UnityEngine\n .Object.FindObjectsByType(\n componentType,\n findInactive,\n FindObjectsSortMode.None\n )\n .Select(c => (c as Component).gameObject);\n results.AddRange(searchPoolComp.Where(go => go != null)); // Ensure GO is valid\n }\n else\n {\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Component type not found: {searchTerm}\"\n );\n }\n break;\n case \"by_id_or_name_or_path\": // Helper method used internally\n if (int.TryParse(searchTerm, out int id))\n {\n var allObjectsId = GetAllSceneObjects(true); // Search inactive for internal lookup\n GameObject objById = allObjectsId.FirstOrDefault(go =>\n go.GetInstanceID() == id\n );\n if (objById != null)\n {\n results.Add(objById);\n break;\n }\n }\n GameObject objByPath = GameObject.Find(searchTerm);\n if (objByPath != null)\n {\n results.Add(objByPath);\n break;\n }\n\n var allObjectsName = GetAllSceneObjects(true);\n results.AddRange(allObjectsName.Where(go => go.name == searchTerm));\n break;\n default:\n Debug.LogWarning(\n $\"[ManageGameObject.Find] Unknown search method: {searchMethod}\"\n );\n break;\n }\n\n // If only one result is needed, return just the first one found.\n if (!findAll && results.Count > 1)\n {\n return new List { results[0] };\n }\n\n return results.Distinct().ToList(); // Ensure uniqueness\n }\n\n // Helper to get all scene objects efficiently\n private static IEnumerable GetAllSceneObjects(bool includeInactive)\n {\n // SceneManager.GetActiveScene().GetRootGameObjects() is faster than FindObjectsOfType()\n var rootObjects = SceneManager.GetActiveScene().GetRootGameObjects();\n var allObjects = new List();\n foreach (var root in rootObjects)\n {\n allObjects.AddRange(\n root.GetComponentsInChildren(includeInactive)\n .Select(t => t.gameObject)\n );\n }\n return allObjects;\n }\n\n /// \n /// Adds a component by type name and optionally sets properties.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object AddComponentInternal(\n GameObject targetGo,\n string typeName,\n JObject properties\n )\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error(\n $\"Component type '{typeName}' not found or is not a valid Component.\"\n );\n }\n if (!typeof(Component).IsAssignableFrom(componentType))\n {\n return Response.Error($\"Type '{typeName}' is not a Component.\");\n }\n\n // Prevent adding Transform again\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot add another Transform component.\");\n }\n\n // Check for 2D/3D physics component conflicts\n bool isAdding2DPhysics =\n typeof(Rigidbody2D).IsAssignableFrom(componentType)\n || typeof(Collider2D).IsAssignableFrom(componentType);\n bool isAdding3DPhysics =\n typeof(Rigidbody).IsAssignableFrom(componentType)\n || typeof(Collider).IsAssignableFrom(componentType);\n\n if (isAdding2DPhysics)\n {\n // Check if the GameObject already has any 3D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 2D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 3D Rigidbody or Collider.\"\n );\n }\n }\n else if (isAdding3DPhysics)\n {\n // Check if the GameObject already has any 2D Rigidbody or Collider\n if (\n targetGo.GetComponent() != null\n || targetGo.GetComponent() != null\n )\n {\n return Response.Error(\n $\"Cannot add 3D physics component '{typeName}' because the GameObject '{targetGo.name}' already has a 2D Rigidbody or Collider.\"\n );\n }\n }\n\n try\n {\n // Use Undo.AddComponent for undo support\n Component newComponent = Undo.AddComponent(targetGo, componentType);\n if (newComponent == null)\n {\n return Response.Error(\n $\"Failed to add component '{typeName}' to '{targetGo.name}'. It might be disallowed (e.g., adding script twice).\"\n );\n }\n\n // Set default values for specific component types\n if (newComponent is Light light)\n {\n // Default newly added lights to directional\n light.type = LightType.Directional;\n }\n\n // Set properties if provided\n if (properties != null)\n {\n var setResult = SetComponentPropertiesInternal(\n targetGo,\n typeName,\n properties,\n newComponent\n ); // Pass the new component instance\n if (setResult != null)\n {\n // If setting properties failed, maybe remove the added component?\n Undo.DestroyObjectImmediate(newComponent);\n return setResult; // Return the error from setting properties\n }\n }\n\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error adding component '{typeName}' to '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Removes a component by type name.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object RemoveComponentInternal(GameObject targetGo, string typeName)\n {\n Type componentType = FindType(typeName);\n if (componentType == null)\n {\n return Response.Error($\"Component type '{typeName}' not found for removal.\");\n }\n\n // Prevent removing essential components\n if (componentType == typeof(Transform))\n {\n return Response.Error(\"Cannot remove the Transform component.\");\n }\n\n Component componentToRemove = targetGo.GetComponent(componentType);\n if (componentToRemove == null)\n {\n return Response.Error(\n $\"Component '{typeName}' not found on '{targetGo.name}' to remove.\"\n );\n }\n\n try\n {\n // Use Undo.DestroyObjectImmediate for undo support\n Undo.DestroyObjectImmediate(componentToRemove);\n return null; // Success\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Error removing component '{typeName}' from '{targetGo.name}': {e.Message}\"\n );\n }\n }\n\n /// \n /// Sets properties on a component.\n /// Returns null on success, or an error response object on failure.\n /// \n private static object SetComponentPropertiesInternal(\n GameObject targetGo,\n string compName,\n JObject propertiesToSet,\n Component targetComponentInstance = null\n )\n {\n Component targetComponent = targetComponentInstance ?? targetGo.GetComponent(compName);\n if (targetComponent == null)\n {\n return Response.Error(\n $\"Component '{compName}' not found on '{targetGo.name}' to set properties.\"\n );\n }\n\n Undo.RecordObject(targetComponent, \"Set Component Properties\");\n\n foreach (var prop in propertiesToSet.Properties())\n {\n string propName = prop.Name;\n JToken propValue = prop.Value;\n\n try\n {\n if (!SetProperty(targetComponent, propName, propValue))\n {\n // Log warning if property could not be set\n Debug.LogWarning(\n $\"[ManageGameObject] Could not set property '{propName}' on component '{compName}' ('{targetComponent.GetType().Name}'). Property might not exist, be read-only, or type mismatch.\"\n );\n // Optionally return an error here instead of just logging\n // return Response.Error($\"Could not set property '{propName}' on component '{compName}'.\");\n }\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ManageGameObject] Error setting property '{propName}' on '{compName}': {e.Message}\"\n );\n // Optionally return an error here\n // return Response.Error($\"Error setting property '{propName}' on '{compName}': {e.Message}\");\n }\n }\n EditorUtility.SetDirty(targetComponent);\n return null; // Success (or partial success if warnings were logged)\n }\n\n /// \n /// Helper to set a property or field via reflection, handling basic types.\n /// \n private static bool SetProperty(object target, string memberName, JToken value)\n {\n Type type = target.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // --- Use a dedicated serializer for input conversion ---\n // Define this somewhere accessible, maybe static readonly field\n JsonSerializerSettings inputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n // Add specific converters needed for INPUT deserialization if different from output\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Crucial for finding references from instructions\n }\n // No ReferenceLoopHandling needed typically for input\n };\n JsonSerializer inputSerializer = JsonSerializer.Create(inputSerializerSettings);\n // --- End Serializer Setup ---\n\n try\n {\n // Handle special case for materials with dot notation (material.property)\n // Examples: material.color, sharedMaterial.color, materials[0].color\n if (memberName.Contains('.') || memberName.Contains('['))\n {\n // Pass the inputSerializer down for nested conversions\n return SetNestedProperty(target, memberName, value, inputSerializer);\n }\n\n PropertyInfo propInfo = type.GetProperty(memberName, flags);\n if (propInfo != null && propInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n propInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for property '{memberName}' (Type: {propInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo fieldInfo = type.GetField(memberName, flags);\n if (fieldInfo != null) // Check if !IsLiteral?\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null\n {\n fieldInfo.SetValue(target, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetProperty] Conversion failed for field '{memberName}' (Type: {fieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetProperty] Failed to set '{memberName}' on {type.Name}: {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n return false;\n }\n\n /// \n /// Sets a nested property using dot notation (e.g., \"material.color\") or array access (e.g., \"materials[0]\")\n /// \n // Pass the input serializer for conversions\n //Using the serializer helper\n private static bool SetNestedProperty(object target, string path, JToken value, JsonSerializer inputSerializer)\n {\n try\n {\n // Split the path into parts (handling both dot notation and array indexing)\n string[] pathParts = SplitPropertyPath(path);\n if (pathParts.Length == 0)\n return false;\n\n object currentObject = target;\n Type currentType = currentObject.GetType();\n BindingFlags flags =\n BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;\n\n // Traverse the path until we reach the final property\n for (int i = 0; i < pathParts.Length - 1; i++)\n {\n string part = pathParts[i];\n bool isArray = false;\n int arrayIndex = -1;\n\n // Check if this part contains array indexing\n if (part.Contains(\"[\"))\n {\n int startBracket = part.IndexOf('[');\n int endBracket = part.IndexOf(']');\n if (startBracket > 0 && endBracket > startBracket)\n {\n string indexStr = part.Substring(\n startBracket + 1,\n endBracket - startBracket - 1\n );\n if (int.TryParse(indexStr, out arrayIndex))\n {\n isArray = true;\n part = part.Substring(0, startBracket);\n }\n }\n }\n // Get the property/field\n PropertyInfo propInfo = currentType.GetProperty(part, flags);\n FieldInfo fieldInfo = null;\n if (propInfo == null)\n {\n fieldInfo = currentType.GetField(part, flags);\n if (fieldInfo == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find property or field '{part}' on type '{currentType.Name}'\"\n );\n return false;\n }\n }\n\n // Get the value\n currentObject =\n propInfo != null\n ? propInfo.GetValue(currentObject)\n : fieldInfo.GetValue(currentObject);\n //Need to stop if current property is null\n if (currentObject == null)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is null, cannot access nested properties.\"\n );\n return false;\n }\n // If this part was an array or list, access the specific index\n if (isArray)\n {\n if (currentObject is Material[])\n {\n var materials = currentObject as Material[];\n if (arrayIndex < 0 || arrayIndex >= materials.Length)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Material index {arrayIndex} out of range (0-{materials.Length - 1})\"\n );\n return false;\n }\n currentObject = materials[arrayIndex];\n }\n else if (currentObject is System.Collections.IList)\n {\n var list = currentObject as System.Collections.IList;\n if (arrayIndex < 0 || arrayIndex >= list.Count)\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Index {arrayIndex} out of range (0-{list.Count - 1})\"\n );\n return false;\n }\n currentObject = list[arrayIndex];\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Property '{part}' is not an array or list, cannot access by index.\"\n );\n return false;\n }\n }\n currentType = currentObject.GetType();\n }\n\n // Set the final property\n string finalPart = pathParts[pathParts.Length - 1];\n\n // Special handling for Material properties (shader properties)\n if (currentObject is Material material && finalPart.StartsWith(\"_\"))\n {\n // Use the serializer to convert the JToken value first\n if (value is JArray jArray)\n {\n // Try converting to known types that SetColor/SetVector accept\n if (jArray.Count == 4) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { }\n try { Vector4 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n } else if (jArray.Count == 3) {\n try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch { } // ToObject handles conversion to Color\n } else if (jArray.Count == 2) {\n try { Vector2 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch { }\n }\n }\n else if (value.Type == JTokenType.Float || value.Type == JTokenType.Integer)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer)); return true; } catch { }\n }\n else if (value.Type == JTokenType.Boolean)\n {\n try { material.SetFloat(finalPart, value.ToObject(inputSerializer) ? 1f : 0f); return true; } catch { }\n }\n else if (value.Type == JTokenType.String)\n {\n // Try converting to Texture using the serializer/converter\n try {\n Texture texture = value.ToObject(inputSerializer);\n if (texture != null) {\n material.SetTexture(finalPart, texture);\n return true;\n }\n } catch { }\n }\n\n Debug.LogWarning(\n $\"[SetNestedProperty] Unsupported or failed conversion for material property '{finalPart}' from value: {value.ToString(Formatting.None)}\"\n );\n return false;\n }\n\n // For standard properties (not shader specific)\n PropertyInfo finalPropInfo = currentType.GetProperty(finalPart, flags);\n if (finalPropInfo != null && finalPropInfo.CanWrite)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalPropInfo.PropertyType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalPropInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for property '{finalPart}' (Type: {finalPropInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n FieldInfo finalFieldInfo = currentType.GetField(finalPart, flags);\n if (finalFieldInfo != null)\n {\n // Use the inputSerializer for conversion\n object convertedValue = ConvertJTokenToType(value, finalFieldInfo.FieldType, inputSerializer);\n if (convertedValue != null || value.Type == JTokenType.Null)\n {\n finalFieldInfo.SetValue(currentObject, convertedValue);\n return true;\n }\n else {\n Debug.LogWarning($\"[SetNestedProperty] Final conversion failed for field '{finalPart}' (Type: {finalFieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}\");\n }\n }\n else\n {\n Debug.LogWarning(\n $\"[SetNestedProperty] Could not find final writable property or field '{finalPart}' on type '{currentType.Name}'\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n Debug.LogError(\n $\"[SetNestedProperty] Error setting nested property '{path}': {ex.Message}\\nToken: {value.ToString(Formatting.None)}\"\n );\n }\n\n return false;\n }\n\n\n /// \n /// Split a property path into parts, handling both dot notation and array indexers\n /// \n private static string[] SplitPropertyPath(string path)\n {\n // Handle complex paths with both dots and array indexers\n List parts = new List();\n int startIndex = 0;\n bool inBrackets = false;\n\n for (int i = 0; i < path.Length; i++)\n {\n char c = path[i];\n\n if (c == '[')\n {\n inBrackets = true;\n }\n else if (c == ']')\n {\n inBrackets = false;\n }\n else if (c == '.' && !inBrackets)\n {\n // Found a dot separator outside of brackets\n parts.Add(path.Substring(startIndex, i - startIndex));\n startIndex = i + 1;\n }\n }\n if (startIndex < path.Length)\n {\n parts.Add(path.Substring(startIndex));\n }\n return parts.ToArray();\n }\n\n /// \n /// Simple JToken to Type conversion for common Unity types, using JsonSerializer.\n /// \n // Pass the input serializer\n private static object ConvertJTokenToType(JToken token, Type targetType, JsonSerializer inputSerializer)\n {\n if (token == null || token.Type == JTokenType.Null)\n {\n if (targetType.IsValueType && Nullable.GetUnderlyingType(targetType) == null)\n {\n Debug.LogWarning($\"Cannot assign null to non-nullable value type {targetType.Name}. Returning default value.\");\n return Activator.CreateInstance(targetType);\n }\n return null;\n }\n\n try\n {\n // Use the provided serializer instance which includes our custom converters\n return token.ToObject(targetType, inputSerializer);\n }\n catch (JsonSerializationException jsonEx)\n {\n Debug.LogError($\"JSON Deserialization Error converting token to {targetType.FullName}: {jsonEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n // Optionally re-throw or return null/default\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n throw; // Re-throw to indicate failure higher up\n }\n catch (ArgumentException argEx)\n {\n Debug.LogError($\"Argument Error converting token to {targetType.FullName}: {argEx.Message}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n catch (Exception ex)\n {\n Debug.LogError($\"Unexpected error converting token to {targetType.FullName}: {ex}\\nToken: {token.ToString(Formatting.None)}\");\n throw;\n }\n // If ToObject succeeded, it would have returned. If it threw, we wouldn't reach here.\n // This fallback logic is likely unreachable if ToObject covers all cases or throws on failure.\n // Debug.LogWarning($\"Conversion failed for token to {targetType.FullName}. Token: {token.ToString(Formatting.None)}\");\n // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n }\n\n // --- ParseJTokenTo... helpers are likely redundant now with the serializer approach ---\n // Keep them temporarily for reference or if specific fallback logic is ever needed.\n\n private static Vector3 ParseJTokenToVector3(JToken token)\n {\n // ... (implementation - likely replaced by Vector3Converter) ...\n // Consider removing these if the serializer handles them reliably.\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\"))\n {\n return new Vector3(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 3)\n {\n return new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector3 using fallback. Returning Vector3.zero.\");\n return Vector3.zero;\n\n }\n private static Vector2 ParseJTokenToVector2(JToken token)\n {\n // ... (implementation - likely replaced by Vector2Converter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\"))\n {\n return new Vector2(obj[\"x\"].ToObject(), obj[\"y\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 2)\n {\n return new Vector2(arr[0].ToObject(), arr[1].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Vector2 using fallback. Returning Vector2.zero.\");\n return Vector2.zero;\n }\n private static Quaternion ParseJTokenToQuaternion(JToken token)\n {\n // ... (implementation - likely replaced by QuaternionConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"z\") && obj.ContainsKey(\"w\"))\n {\n return new Quaternion(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"z\"].ToObject(), obj[\"w\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Quaternion(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Quaternion using fallback. Returning Quaternion.identity.\");\n return Quaternion.identity;\n }\n private static Color ParseJTokenToColor(JToken token)\n {\n // ... (implementation - likely replaced by ColorConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"r\") && obj.ContainsKey(\"g\") && obj.ContainsKey(\"b\") && obj.ContainsKey(\"a\"))\n {\n return new Color(obj[\"r\"].ToObject(), obj[\"g\"].ToObject(), obj[\"b\"].ToObject(), obj[\"a\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Color(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Color using fallback. Returning Color.white.\");\n return Color.white;\n }\n private static Rect ParseJTokenToRect(JToken token)\n {\n // ... (implementation - likely replaced by RectConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"x\") && obj.ContainsKey(\"y\") && obj.ContainsKey(\"width\") && obj.ContainsKey(\"height\"))\n {\n return new Rect(obj[\"x\"].ToObject(), obj[\"y\"].ToObject(), obj[\"width\"].ToObject(), obj[\"height\"].ToObject());\n }\n if (token is JArray arr && arr.Count >= 4)\n {\n return new Rect(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject());\n }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Rect using fallback. Returning Rect.zero.\");\n return Rect.zero;\n }\n private static Bounds ParseJTokenToBounds(JToken token)\n {\n // ... (implementation - likely replaced by BoundsConverter) ...\n if (token is JObject obj && obj.ContainsKey(\"center\") && obj.ContainsKey(\"size\"))\n {\n // Requires Vector3 conversion, which should ideally use the serializer too\n Vector3 center = ParseJTokenToVector3(obj[\"center\"]); // Or use obj[\"center\"].ToObject(inputSerializer)\n Vector3 size = ParseJTokenToVector3(obj[\"size\"]); // Or use obj[\"size\"].ToObject(inputSerializer)\n return new Bounds(center, size);\n }\n // Array fallback for Bounds is less intuitive, maybe remove?\n // if (token is JArray arr && arr.Count >= 6)\n // {\n // return new Bounds(new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject()), new Vector3(arr[3].ToObject(), arr[4].ToObject(), arr[5].ToObject()));\n // }\n Debug.LogWarning($\"Could not parse JToken '{token}' as Bounds using fallback. Returning new Bounds(Vector3.zero, Vector3.zero).\");\n return new Bounds(Vector3.zero, Vector3.zero);\n }\n // --- End Redundant Parse Helpers ---\n\n /// \n /// Finds a specific UnityEngine.Object based on a find instruction JObject.\n /// Primarily used by UnityEngineObjectConverter during deserialization.\n /// \n // Made public static so UnityEngineObjectConverter can call it. Moved from ConvertJTokenToType.\n public static UnityEngine.Object FindObjectByInstruction(JObject instruction, Type targetType)\n {\n string findTerm = instruction[\"find\"]?.ToString();\n string method = instruction[\"method\"]?.ToString()?.ToLower();\n string componentName = instruction[\"component\"]?.ToString(); // Specific component to get\n\n if (string.IsNullOrEmpty(findTerm))\n {\n Debug.LogWarning(\"Find instruction missing 'find' term.\");\n return null;\n }\n\n // Use a flexible default search method if none provided\n string searchMethodToUse = string.IsNullOrEmpty(method) ? \"by_id_or_name_or_path\" : method;\n\n // If the target is an asset (Material, Texture, ScriptableObject etc.) try AssetDatabase first\n if (typeof(Material).IsAssignableFrom(targetType) ||\n typeof(Texture).IsAssignableFrom(targetType) ||\n typeof(ScriptableObject).IsAssignableFrom(targetType) ||\n targetType.FullName.StartsWith(\"UnityEngine.U2D\") || // Sprites etc.\n typeof(AudioClip).IsAssignableFrom(targetType) ||\n typeof(AnimationClip).IsAssignableFrom(targetType) ||\n typeof(Font).IsAssignableFrom(targetType) ||\n typeof(Shader).IsAssignableFrom(targetType) ||\n typeof(ComputeShader).IsAssignableFrom(targetType) ||\n typeof(GameObject).IsAssignableFrom(targetType) && findTerm.StartsWith(\"Assets/\")) // Prefab check\n {\n // Try loading directly by path/GUID first\n UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(findTerm, targetType);\n if (asset != null) return asset;\n asset = AssetDatabase.LoadAssetAtPath(findTerm); // Try generic if type specific failed\n if (asset != null && targetType.IsAssignableFrom(asset.GetType())) return asset;\n\n\n // If direct path failed, try finding by name/type using FindAssets\n string searchFilter = $\"t:{targetType.Name} {System.IO.Path.GetFileNameWithoutExtension(findTerm)}\"; // Search by type and name\n string[] guids = AssetDatabase.FindAssets(searchFilter);\n\n if (guids.Length == 1)\n {\n asset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]), targetType);\n if (asset != null) return asset;\n }\n else if (guids.Length > 1)\n {\n Debug.LogWarning($\"[FindObjectByInstruction] Ambiguous asset find: Found {guids.Length} assets matching filter '{searchFilter}'. Provide a full path or unique name.\");\n // Optionally return the first one? Or null? Returning null is safer.\n return null;\n }\n // If still not found, fall through to scene search (though unlikely for assets)\n }\n\n\n // --- Scene Object Search ---\n // Find the GameObject using the internal finder\n GameObject foundGo = FindObjectInternal(new JValue(findTerm), searchMethodToUse);\n\n if (foundGo == null)\n {\n // Don't warn yet, could still be an asset not found above\n // Debug.LogWarning($\"Could not find GameObject using instruction: {instruction}\");\n return null;\n }\n\n // Now, get the target object/component from the found GameObject\n if (targetType == typeof(GameObject))\n {\n return foundGo; // We were looking for a GameObject\n }\n else if (typeof(Component).IsAssignableFrom(targetType))\n {\n Type componentToGetType = targetType;\n if (!string.IsNullOrEmpty(componentName))\n {\n Type specificCompType = FindType(componentName);\n if (specificCompType != null && typeof(Component).IsAssignableFrom(specificCompType))\n {\n componentToGetType = specificCompType;\n }\n else\n {\n Debug.LogWarning($\"Could not find component type '{componentName}' specified in find instruction. Falling back to target type '{targetType.Name}'.\");\n }\n }\n\n Component foundComp = foundGo.GetComponent(componentToGetType);\n if (foundComp == null)\n {\n Debug.LogWarning($\"Found GameObject '{foundGo.name}' but could not find component of type '{componentToGetType.Name}'.\");\n }\n return foundComp;\n }\n else\n {\n Debug.LogWarning($\"Find instruction handling not implemented for target type: {targetType.Name}\");\n return null;\n }\n }\n\n\n /// \n /// Helper to find a Type by name, searching relevant assemblies.\n /// \n private static Type FindType(string typeName)\n {\n if (string.IsNullOrEmpty(typeName))\n return null;\n\n // Handle fully qualified names first\n Type type = Type.GetType(typeName);\n if (type != null) return type;\n\n // Handle common namespaces implicitly (add more as needed)\n string[] namespaces = { \"UnityEngine\", \"UnityEngine.UI\", \"UnityEngine.AI\", \"UnityEngine.Animations\", \"UnityEngine.Audio\", \"UnityEngine.EventSystems\", \"UnityEngine.InputSystem\", \"UnityEngine.Networking\", \"UnityEngine.Rendering\", \"UnityEngine.SceneManagement\", \"UnityEngine.Tilemaps\", \"UnityEngine.U2D\", \"UnityEngine.Video\", \"UnityEditor\", \"UnityEditor.AI\", \"UnityEditor.Animations\", \"UnityEditor.Experimental.GraphView\", \"UnityEditor.IMGUI.Controls\", \"UnityEditor.PackageManager.UI\", \"UnityEditor.SceneManagement\", \"UnityEditor.UI\", \"UnityEditor.U2D\", \"UnityEditor.VersionControl\" }; // Add more relevant namespaces\n\n foreach (string ns in namespaces) {\n type = Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}.CoreModule\") ?? // Heuristic: Check CoreModule first for UnityEngine/UnityEditor\n Type.GetType($\"{ns}.{typeName}, {ns.Split('.')[0]}\"); // Try assembly matching namespace root\n if (type != null) return type;\n }\n\n\n // If not found, search all loaded assemblies (slower, last resort)\n // Prioritize assemblies likely to contain game/editor types\n Assembly[] priorityAssemblies = {\n Assembly.Load(\"Assembly-CSharp\"), // Main game scripts\n Assembly.Load(\"Assembly-CSharp-Editor\"), // Main editor scripts\n // Add other important project assemblies if known\n };\n foreach (var assembly in priorityAssemblies.Where(a => a != null))\n {\n type = assembly.GetType(typeName) ?? assembly.GetType(\"UnityEngine.\" + typeName) ?? assembly.GetType(\"UnityEditor.\" + typeName);\n if (type != null) return type;\n }\n\n // Search remaining assemblies\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Except(priorityAssemblies))\n {\n try { // Protect against assembly loading errors\n type = assembly.GetType(typeName);\n if (type != null) return type;\n // Also check with common namespaces if simple name given\n foreach (string ns in namespaces) {\n type = assembly.GetType($\"{ns}.{typeName}\");\n if (type != null) return type;\n }\n } catch (Exception ex) {\n Debug.LogWarning($\"[FindType] Error searching assembly {assembly.FullName}: {ex.Message}\");\n }\n }\n\n Debug.LogWarning($\"[FindType] Type not found after extensive search: '{typeName}'\");\n return null; // Not found\n }\n\n /// \n /// Parses a JArray like [x, y, z] into a Vector3.\n /// \n private static Vector3? ParseVector3(JArray array)\n {\n if (array != null && array.Count == 3)\n {\n try\n {\n // Use ToObject for potentially better handling than direct indexing\n return new Vector3(\n array[0].ToObject(),\n array[1].ToObject(),\n array[2].ToObject()\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning($\"Failed to parse JArray as Vector3: {array}. Error: {ex.Message}\");\n }\n }\n return null;\n }\n\n // Removed GetGameObjectData, GetComponentData, and related private helpers/caching/serializer setup.\n // They are now in Helpers.GameObjectSerializer\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageEditor.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal; // Required for tag management\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles operations related to controlling and querying the Unity Editor state,\n /// including managing Tags and Layers.\n /// \n public static class ManageEditor\n {\n // Constant for starting user layer index\n private const int FirstUserLayerIndex = 8;\n\n // Constant for total layer count\n private const int TotalLayerCount = 32;\n\n /// \n /// Main handler for editor management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower();\n // Parameters for specific actions\n string tagName = @params[\"tagName\"]?.ToString();\n string layerName = @params[\"layerName\"]?.ToString();\n bool waitForCompletion = @params[\"waitForCompletion\"]?.ToObject() ?? false; // Example - not used everywhere\n\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n\n // Route action\n switch (action)\n {\n // Play Mode Control\n case \"play\":\n try\n {\n if (!EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = true;\n return Response.Success(\"Entered play mode.\");\n }\n return Response.Success(\"Already in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error entering play mode: {e.Message}\");\n }\n case \"pause\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPaused = !EditorApplication.isPaused;\n return Response.Success(\n EditorApplication.isPaused ? \"Game paused.\" : \"Game resumed.\"\n );\n }\n return Response.Error(\"Cannot pause/resume: Not in play mode.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error pausing/resuming game: {e.Message}\");\n }\n case \"stop\":\n try\n {\n if (EditorApplication.isPlaying)\n {\n EditorApplication.isPlaying = false;\n return Response.Success(\"Exited play mode.\");\n }\n return Response.Success(\"Already stopped (not in play mode).\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Error stopping play mode: {e.Message}\");\n }\n\n // Editor State/Info\n case \"get_state\":\n return GetEditorState();\n case \"get_windows\":\n return GetEditorWindows();\n case \"get_active_tool\":\n return GetActiveTool();\n case \"get_selection\":\n return GetSelection();\n case \"set_active_tool\":\n string toolName = @params[\"toolName\"]?.ToString();\n if (string.IsNullOrEmpty(toolName))\n return Response.Error(\"'toolName' parameter required for set_active_tool.\");\n return SetActiveTool(toolName);\n\n // Tag Management\n case \"add_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for add_tag.\");\n return AddTag(tagName);\n case \"remove_tag\":\n if (string.IsNullOrEmpty(tagName))\n return Response.Error(\"'tagName' parameter required for remove_tag.\");\n return RemoveTag(tagName);\n case \"get_tags\":\n return GetTags(); // Helper to list current tags\n\n // Layer Management\n case \"add_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for add_layer.\");\n return AddLayer(layerName);\n case \"remove_layer\":\n if (string.IsNullOrEmpty(layerName))\n return Response.Error(\"'layerName' parameter required for remove_layer.\");\n return RemoveLayer(layerName);\n case \"get_layers\":\n return GetLayers(); // Helper to list current layers\n\n // --- Settings (Example) ---\n // case \"set_resolution\":\n // int? width = @params[\"width\"]?.ToObject();\n // int? height = @params[\"height\"]?.ToObject();\n // if (!width.HasValue || !height.HasValue) return Response.Error(\"'width' and 'height' parameters required.\");\n // return SetGameViewResolution(width.Value, height.Value);\n // case \"set_quality\":\n // // Handle string name or int index\n // return SetQualityLevel(@params[\"qualityLevel\"]);\n\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Supported actions include play, pause, stop, get_state, get_windows, get_active_tool, get_selection, set_active_tool, add_tag, remove_tag, get_tags, add_layer, remove_layer, get_layers.\"\n );\n }\n }\n\n // --- Editor State/Info Methods ---\n private static object GetEditorState()\n {\n try\n {\n var state = new\n {\n isPlaying = EditorApplication.isPlaying,\n isPaused = EditorApplication.isPaused,\n isCompiling = EditorApplication.isCompiling,\n isUpdating = EditorApplication.isUpdating,\n applicationPath = EditorApplication.applicationPath,\n applicationContentsPath = EditorApplication.applicationContentsPath,\n timeSinceStartup = EditorApplication.timeSinceStartup,\n };\n return Response.Success(\"Retrieved editor state.\", state);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor state: {e.Message}\");\n }\n }\n\n private static object GetEditorWindows()\n {\n try\n {\n // Get all types deriving from EditorWindow\n var windowTypes = AppDomain\n .CurrentDomain.GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => type.IsSubclassOf(typeof(EditorWindow)))\n .ToList();\n\n var openWindows = new List();\n\n // Find currently open instances\n // Resources.FindObjectsOfTypeAll seems more reliable than GetWindow for finding *all* open windows\n EditorWindow[] allWindows = Resources.FindObjectsOfTypeAll();\n\n foreach (EditorWindow window in allWindows)\n {\n if (window == null)\n continue; // Skip potentially destroyed windows\n\n try\n {\n openWindows.Add(\n new\n {\n title = window.titleContent.text,\n typeName = window.GetType().FullName,\n isFocused = EditorWindow.focusedWindow == window,\n position = new\n {\n x = window.position.x,\n y = window.position.y,\n width = window.position.width,\n height = window.position.height,\n },\n instanceID = window.GetInstanceID(),\n }\n );\n }\n catch (Exception ex)\n {\n Debug.LogWarning(\n $\"Could not get info for window {window.GetType().Name}: {ex.Message}\"\n );\n }\n }\n\n return Response.Success(\"Retrieved list of open editor windows.\", openWindows);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting editor windows: {e.Message}\");\n }\n }\n\n private static object GetActiveTool()\n {\n try\n {\n Tool currentTool = UnityEditor.Tools.current;\n string toolName = currentTool.ToString(); // Enum to string\n bool customToolActive = UnityEditor.Tools.current == Tool.Custom; // Check if a custom tool is active\n string activeToolName = customToolActive\n ? EditorTools.GetActiveToolName()\n : toolName; // Get custom name if needed\n\n var toolInfo = new\n {\n activeTool = activeToolName,\n isCustom = customToolActive,\n pivotMode = UnityEditor.Tools.pivotMode.ToString(),\n pivotRotation = UnityEditor.Tools.pivotRotation.ToString(),\n handleRotation = UnityEditor.Tools.handleRotation.eulerAngles, // Euler for simplicity\n handlePosition = UnityEditor.Tools.handlePosition,\n };\n\n return Response.Success(\"Retrieved active tool information.\", toolInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting active tool: {e.Message}\");\n }\n }\n\n private static object SetActiveTool(string toolName)\n {\n try\n {\n Tool targetTool;\n if (Enum.TryParse(toolName, true, out targetTool)) // Case-insensitive parse\n {\n // Check if it's a valid built-in tool\n if (targetTool != Tool.None && targetTool <= Tool.Custom) // Tool.Custom is the last standard tool\n {\n UnityEditor.Tools.current = targetTool;\n return Response.Success($\"Set active tool to '{targetTool}'.\");\n }\n else\n {\n return Response.Error(\n $\"Cannot directly set tool to '{toolName}'. It might be None, Custom, or invalid.\"\n );\n }\n }\n else\n {\n // Potentially try activating a custom tool by name here if needed\n // This often requires specific editor scripting knowledge for that tool.\n return Response.Error(\n $\"Could not parse '{toolName}' as a standard Unity Tool (View, Move, Rotate, Scale, Rect, Transform, Custom).\"\n );\n }\n }\n catch (Exception e)\n {\n return Response.Error($\"Error setting active tool: {e.Message}\");\n }\n }\n\n private static object GetSelection()\n {\n try\n {\n var selectionInfo = new\n {\n activeObject = Selection.activeObject?.name,\n activeGameObject = Selection.activeGameObject?.name,\n activeTransform = Selection.activeTransform?.name,\n activeInstanceID = Selection.activeInstanceID,\n count = Selection.count,\n objects = Selection\n .objects.Select(obj => new\n {\n name = obj?.name,\n type = obj?.GetType().FullName,\n instanceID = obj?.GetInstanceID(),\n })\n .ToList(),\n gameObjects = Selection\n .gameObjects.Select(go => new\n {\n name = go?.name,\n instanceID = go?.GetInstanceID(),\n })\n .ToList(),\n assetGUIDs = Selection.assetGUIDs, // GUIDs for selected assets in Project view\n };\n\n return Response.Success(\"Retrieved current selection details.\", selectionInfo);\n }\n catch (Exception e)\n {\n return Response.Error($\"Error getting selection: {e.Message}\");\n }\n }\n\n // --- Tag Management Methods ---\n\n private static object AddTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n\n // Check if tag already exists\n if (InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' already exists.\");\n }\n\n try\n {\n // Add the tag using the internal utility\n InternalEditorUtility.AddTag(tagName);\n // Force save assets to ensure the change persists in the TagManager asset\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' added successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object RemoveTag(string tagName)\n {\n if (string.IsNullOrWhiteSpace(tagName))\n return Response.Error(\"Tag name cannot be empty or whitespace.\");\n if (tagName.Equals(\"Untagged\", StringComparison.OrdinalIgnoreCase))\n return Response.Error(\"Cannot remove the built-in 'Untagged' tag.\");\n\n // Check if tag exists before attempting removal\n if (!InternalEditorUtility.tags.Contains(tagName))\n {\n return Response.Error($\"Tag '{tagName}' does not exist.\");\n }\n\n try\n {\n // Remove the tag using the internal utility\n InternalEditorUtility.RemoveTag(tagName);\n // Force save assets\n AssetDatabase.SaveAssets();\n return Response.Success($\"Tag '{tagName}' removed successfully.\");\n }\n catch (Exception e)\n {\n // Catch potential issues if the tag is somehow in use or removal fails\n return Response.Error($\"Failed to remove tag '{tagName}': {e.Message}\");\n }\n }\n\n private static object GetTags()\n {\n try\n {\n string[] tags = InternalEditorUtility.tags;\n return Response.Success(\"Retrieved current tags.\", tags);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve tags: {e.Message}\");\n }\n }\n\n // --- Layer Management Methods ---\n\n private static object AddLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Check if layer name already exists (case-insensitive check recommended)\n for (int i = 0; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n return Response.Error($\"Layer '{layerName}' already exists at index {i}.\");\n }\n }\n\n // Find the first empty user layer slot (indices 8 to 31)\n int firstEmptyUserLayer = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++)\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n if (layerSP != null && string.IsNullOrEmpty(layerSP.stringValue))\n {\n firstEmptyUserLayer = i;\n break;\n }\n }\n\n if (firstEmptyUserLayer == -1)\n {\n return Response.Error(\"No empty User Layer slots available (8-31 are full).\");\n }\n\n // Assign the name to the found slot\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n firstEmptyUserLayer\n );\n targetLayerSP.stringValue = layerName;\n // Apply the changes to the TagManager asset\n tagManager.ApplyModifiedProperties();\n // Save assets to make sure it's written to disk\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' added successfully to slot {firstEmptyUserLayer}.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to add layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object RemoveLayer(string layerName)\n {\n if (string.IsNullOrWhiteSpace(layerName))\n return Response.Error(\"Layer name cannot be empty or whitespace.\");\n\n // Access the TagManager asset\n SerializedObject tagManager = GetTagManager();\n if (tagManager == null)\n return Response.Error(\"Could not access TagManager asset.\");\n\n SerializedProperty layersProp = tagManager.FindProperty(\"layers\");\n if (layersProp == null || !layersProp.isArray)\n return Response.Error(\"Could not find 'layers' property in TagManager.\");\n\n // Find the layer by name (must be user layer)\n int layerIndexToRemove = -1;\n for (int i = FirstUserLayerIndex; i < TotalLayerCount; i++) // Start from user layers\n {\n SerializedProperty layerSP = layersProp.GetArrayElementAtIndex(i);\n // Case-insensitive comparison is safer\n if (\n layerSP != null\n && layerName.Equals(layerSP.stringValue, StringComparison.OrdinalIgnoreCase)\n )\n {\n layerIndexToRemove = i;\n break;\n }\n }\n\n if (layerIndexToRemove == -1)\n {\n return Response.Error($\"User layer '{layerName}' not found.\");\n }\n\n // Clear the name for that index\n try\n {\n SerializedProperty targetLayerSP = layersProp.GetArrayElementAtIndex(\n layerIndexToRemove\n );\n targetLayerSP.stringValue = string.Empty; // Set to empty string to remove\n // Apply the changes\n tagManager.ApplyModifiedProperties();\n // Save assets\n AssetDatabase.SaveAssets();\n return Response.Success(\n $\"Layer '{layerName}' (slot {layerIndexToRemove}) removed successfully.\"\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to remove layer '{layerName}': {e.Message}\");\n }\n }\n\n private static object GetLayers()\n {\n try\n {\n var layers = new Dictionary();\n for (int i = 0; i < TotalLayerCount; i++)\n {\n string layerName = LayerMask.LayerToName(i);\n if (!string.IsNullOrEmpty(layerName)) // Only include layers that have names\n {\n layers.Add(i, layerName);\n }\n }\n return Response.Success(\"Retrieved current named layers.\", layers);\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to retrieve layers: {e.Message}\");\n }\n }\n\n // --- Helper Methods ---\n\n /// \n /// Gets the SerializedObject for the TagManager asset.\n /// \n private static SerializedObject GetTagManager()\n {\n try\n {\n // Load the TagManager asset from the ProjectSettings folder\n UnityEngine.Object[] tagManagerAssets = AssetDatabase.LoadAllAssetsAtPath(\n \"ProjectSettings/TagManager.asset\"\n );\n if (tagManagerAssets == null || tagManagerAssets.Length == 0)\n {\n Debug.LogError(\"[ManageEditor] TagManager.asset not found in ProjectSettings.\");\n return null;\n }\n // The first object in the asset file should be the TagManager\n return new SerializedObject(tagManagerAssets[0]);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ManageEditor] Error accessing TagManager.asset: {e.Message}\");\n return null;\n }\n }\n\n // --- Example Implementations for Settings ---\n /*\n private static object SetGameViewResolution(int width, int height) { ... }\n private static object SetQualityLevel(JToken qualityLevelToken) { ... }\n */\n }\n\n // Helper class to get custom tool names (remains the same)\n internal static class EditorTools\n {\n public static string GetActiveToolName()\n {\n // This is a placeholder. Real implementation depends on how custom tools\n // are registered and tracked in the specific Unity project setup.\n // It might involve checking static variables, calling methods on specific tool managers, etc.\n if (UnityEditor.Tools.current == Tool.Custom)\n {\n // Example: Check a known custom tool manager\n // if (MyCustomToolManager.IsActive) return MyCustomToolManager.ActiveToolName;\n return \"Unknown Custom Tool\";\n }\n return UnityEditor.Tools.current.ToString();\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ReadConsole.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEditorInternal;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles reading and clearing Unity Editor console log entries.\n /// Uses reflection to access internal LogEntry methods/properties.\n /// \n public static class ReadConsole\n {\n // Reflection members for accessing internal LogEntry data\n // private static MethodInfo _getEntriesMethod; // Removed as it's unused and fails reflection\n private static MethodInfo _startGettingEntriesMethod;\n private static MethodInfo _endGettingEntriesMethod; // Renamed from _stopGettingEntriesMethod, trying End...\n private static MethodInfo _clearMethod;\n private static MethodInfo _getCountMethod;\n private static MethodInfo _getEntryMethod;\n private static FieldInfo _modeField;\n private static FieldInfo _messageField;\n private static FieldInfo _fileField;\n private static FieldInfo _lineField;\n private static FieldInfo _instanceIdField;\n\n // Note: Timestamp is not directly available in LogEntry; need to parse message or find alternative?\n\n // Static constructor for reflection setup\n static ReadConsole()\n {\n try\n {\n Type logEntriesType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntries\"\n );\n if (logEntriesType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntries\");\n\n // Include NonPublic binding flags as internal APIs might change accessibility\n BindingFlags staticFlags =\n BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;\n BindingFlags instanceFlags =\n BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\n\n _startGettingEntriesMethod = logEntriesType.GetMethod(\n \"StartGettingEntries\",\n staticFlags\n );\n if (_startGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.StartGettingEntries\");\n\n // Try reflecting EndGettingEntries based on warning message\n _endGettingEntriesMethod = logEntriesType.GetMethod(\n \"EndGettingEntries\",\n staticFlags\n );\n if (_endGettingEntriesMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.EndGettingEntries\");\n\n _clearMethod = logEntriesType.GetMethod(\"Clear\", staticFlags);\n if (_clearMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.Clear\");\n\n _getCountMethod = logEntriesType.GetMethod(\"GetCount\", staticFlags);\n if (_getCountMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetCount\");\n\n _getEntryMethod = logEntriesType.GetMethod(\"GetEntryInternal\", staticFlags);\n if (_getEntryMethod == null)\n throw new Exception(\"Failed to reflect LogEntries.GetEntryInternal\");\n\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\"Could not find internal type UnityEditor.LogEntry\");\n\n _modeField = logEntryType.GetField(\"mode\", instanceFlags);\n if (_modeField == null)\n throw new Exception(\"Failed to reflect LogEntry.mode\");\n\n _messageField = logEntryType.GetField(\"message\", instanceFlags);\n if (_messageField == null)\n throw new Exception(\"Failed to reflect LogEntry.message\");\n\n _fileField = logEntryType.GetField(\"file\", instanceFlags);\n if (_fileField == null)\n throw new Exception(\"Failed to reflect LogEntry.file\");\n\n _lineField = logEntryType.GetField(\"line\", instanceFlags);\n if (_lineField == null)\n throw new Exception(\"Failed to reflect LogEntry.line\");\n\n _instanceIdField = logEntryType.GetField(\"instanceID\", instanceFlags);\n if (_instanceIdField == null)\n throw new Exception(\"Failed to reflect LogEntry.instanceID\");\n }\n catch (Exception e)\n {\n Debug.LogError(\n $\"[ReadConsole] Static Initialization Failed: Could not setup reflection for LogEntries/LogEntry. Console reading/clearing will likely fail. Specific Error: {e.Message}\"\n );\n // Set members to null to prevent NullReferenceExceptions later, HandleCommand should check this.\n _startGettingEntriesMethod =\n _endGettingEntriesMethod =\n _clearMethod =\n _getCountMethod =\n _getEntryMethod =\n null;\n _modeField = _messageField = _fileField = _lineField = _instanceIdField = null;\n }\n }\n\n // --- Main Handler ---\n\n public static object HandleCommand(JObject @params)\n {\n // Check if ALL required reflection members were successfully initialized.\n if (\n _startGettingEntriesMethod == null\n || _endGettingEntriesMethod == null\n || _clearMethod == null\n || _getCountMethod == null\n || _getEntryMethod == null\n || _modeField == null\n || _messageField == null\n || _fileField == null\n || _lineField == null\n || _instanceIdField == null\n )\n {\n // Log the error here as well for easier debugging in Unity Console\n Debug.LogError(\n \"[ReadConsole] HandleCommand called but reflection members are not initialized. Static constructor might have failed silently or there's an issue.\"\n );\n return Response.Error(\n \"ReadConsole handler failed to initialize due to reflection errors. Cannot access console logs.\"\n );\n }\n\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"get\";\n\n try\n {\n if (action == \"clear\")\n {\n return ClearConsole();\n }\n else if (action == \"get\")\n {\n // Extract parameters for 'get'\n var types =\n (@params[\"types\"] as JArray)?.Select(t => t.ToString().ToLower()).ToList()\n ?? new List { \"error\", \"warning\", \"log\" };\n int? count = @params[\"count\"]?.ToObject();\n string filterText = @params[\"filterText\"]?.ToString();\n string sinceTimestampStr = @params[\"sinceTimestamp\"]?.ToString(); // TODO: Implement timestamp filtering\n string format = (@params[\"format\"]?.ToString() ?? \"detailed\").ToLower();\n bool includeStacktrace =\n @params[\"includeStacktrace\"]?.ToObject() ?? true;\n\n if (types.Contains(\"all\"))\n {\n types = new List { \"error\", \"warning\", \"log\" }; // Expand 'all'\n }\n\n if (!string.IsNullOrEmpty(sinceTimestampStr))\n {\n Debug.LogWarning(\n \"[ReadConsole] Filtering by 'since_timestamp' is not currently implemented.\"\n );\n // Need a way to get timestamp per log entry.\n }\n\n return GetConsoleEntries(types, count, filterText, format, includeStacktrace);\n }\n else\n {\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'get' or 'clear'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n // --- Action Implementations ---\n\n private static object ClearConsole()\n {\n try\n {\n _clearMethod.Invoke(null, null); // Static method, no instance, no parameters\n return Response.Success(\"Console cleared successfully.\");\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to clear console: {e}\");\n return Response.Error($\"Failed to clear console: {e.Message}\");\n }\n }\n\n private static object GetConsoleEntries(\n List types,\n int? count,\n string filterText,\n string format,\n bool includeStacktrace\n )\n {\n List formattedEntries = new List();\n int retrievedCount = 0;\n\n try\n {\n // LogEntries requires calling Start/Stop around GetEntries/GetEntryInternal\n _startGettingEntriesMethod.Invoke(null, null);\n\n int totalEntries = (int)_getCountMethod.Invoke(null, null);\n // Create instance to pass to GetEntryInternal - Ensure the type is correct\n Type logEntryType = typeof(EditorApplication).Assembly.GetType(\n \"UnityEditor.LogEntry\"\n );\n if (logEntryType == null)\n throw new Exception(\n \"Could not find internal type UnityEditor.LogEntry during GetConsoleEntries.\"\n );\n object logEntryInstance = Activator.CreateInstance(logEntryType);\n\n for (int i = 0; i < totalEntries; i++)\n {\n // Get the entry data into our instance using reflection\n _getEntryMethod.Invoke(null, new object[] { i, logEntryInstance });\n\n // Extract data using reflection\n int mode = (int)_modeField.GetValue(logEntryInstance);\n string message = (string)_messageField.GetValue(logEntryInstance);\n string file = (string)_fileField.GetValue(logEntryInstance);\n\n int line = (int)_lineField.GetValue(logEntryInstance);\n // int instanceId = (int)_instanceIdField.GetValue(logEntryInstance);\n\n if (string.IsNullOrEmpty(message))\n continue; // Skip empty messages\n\n // --- Filtering ---\n // Filter by type\n LogType currentType = GetLogTypeFromMode(mode);\n if (!types.Contains(currentType.ToString().ToLowerInvariant()))\n {\n continue;\n }\n\n // Filter by text (case-insensitive)\n if (\n !string.IsNullOrEmpty(filterText)\n && message.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) < 0\n )\n {\n continue;\n }\n\n // TODO: Filter by timestamp (requires timestamp data)\n\n // --- Formatting ---\n string stackTrace = includeStacktrace ? ExtractStackTrace(message) : null;\n // Get first line if stack is present and requested, otherwise use full message\n string messageOnly =\n (includeStacktrace && !string.IsNullOrEmpty(stackTrace))\n ? message.Split(\n new[] { '\\n', '\\r' },\n StringSplitOptions.RemoveEmptyEntries\n )[0]\n : message;\n\n object formattedEntry = null;\n switch (format)\n {\n case \"plain\":\n formattedEntry = messageOnly;\n break;\n case \"json\":\n case \"detailed\": // Treat detailed as json for structured return\n default:\n formattedEntry = new\n {\n type = currentType.ToString(),\n message = messageOnly,\n file = file,\n line = line,\n // timestamp = \"\", // TODO\n stackTrace = stackTrace, // Will be null if includeStacktrace is false or no stack found\n };\n break;\n }\n\n formattedEntries.Add(formattedEntry);\n retrievedCount++;\n\n // Apply count limit (after filtering)\n if (count.HasValue && retrievedCount >= count.Value)\n {\n break;\n }\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Error while retrieving log entries: {e}\");\n // Ensure EndGettingEntries is called even if there's an error during iteration\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch\n { /* Ignore nested exception */\n }\n return Response.Error($\"Error retrieving log entries: {e.Message}\");\n }\n finally\n {\n // Ensure we always call EndGettingEntries\n try\n {\n _endGettingEntriesMethod.Invoke(null, null);\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ReadConsole] Failed to call EndGettingEntries: {e}\");\n // Don't return error here as we might have valid data, but log it.\n }\n }\n\n // Return the filtered and formatted list (might be empty)\n return Response.Success(\n $\"Retrieved {formattedEntries.Count} log entries.\",\n formattedEntries\n );\n }\n\n // --- Internal Helpers ---\n\n // Mapping from LogEntry.mode bits to LogType enum\n // Based on decompiled UnityEditor code or common patterns. Precise bits might change between Unity versions.\n // See comments below for LogEntry mode bits exploration.\n // Note: This mapping is simplified and might not cover all edge cases or future Unity versions perfectly.\n private const int ModeBitError = 1 << 0;\n private const int ModeBitAssert = 1 << 1;\n private const int ModeBitWarning = 1 << 2;\n private const int ModeBitLog = 1 << 3;\n private const int ModeBitException = 1 << 4; // Often combined with Error bits\n private const int ModeBitScriptingError = 1 << 9;\n private const int ModeBitScriptingWarning = 1 << 10;\n private const int ModeBitScriptingLog = 1 << 11;\n private const int ModeBitScriptingException = 1 << 18;\n private const int ModeBitScriptingAssertion = 1 << 22;\n\n private static LogType GetLogTypeFromMode(int mode)\n {\n // First, determine the type based on the original logic (most severe first)\n LogType initialType;\n if (\n (\n mode\n & (\n ModeBitError\n | ModeBitScriptingError\n | ModeBitException\n | ModeBitScriptingException\n )\n ) != 0\n )\n {\n initialType = LogType.Error;\n }\n else if ((mode & (ModeBitAssert | ModeBitScriptingAssertion)) != 0)\n {\n initialType = LogType.Assert;\n }\n else if ((mode & (ModeBitWarning | ModeBitScriptingWarning)) != 0)\n {\n initialType = LogType.Warning;\n }\n else\n {\n initialType = LogType.Log;\n }\n\n // Apply the observed \"one level lower\" correction\n switch (initialType)\n {\n case LogType.Error:\n return LogType.Warning; // Error becomes Warning\n case LogType.Warning:\n return LogType.Log; // Warning becomes Log\n case LogType.Assert:\n return LogType.Assert; // Assert remains Assert (no lower level defined)\n case LogType.Log:\n return LogType.Log; // Log remains Log\n default:\n return LogType.Log; // Default fallback\n }\n }\n\n /// \n /// Attempts to extract the stack trace part from a log message.\n /// Unity log messages often have the stack trace appended after the main message,\n /// starting on a new line and typically indented or beginning with \"at \".\n /// \n /// The complete log message including potential stack trace.\n /// The extracted stack trace string, or null if none is found.\n private static string ExtractStackTrace(string fullMessage)\n {\n if (string.IsNullOrEmpty(fullMessage))\n return null;\n\n // Split into lines, removing empty ones to handle different line endings gracefully.\n // Using StringSplitOptions.None might be better if empty lines matter within stack trace, but RemoveEmptyEntries is usually safer here.\n string[] lines = fullMessage.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n // If there's only one line or less, there's no separate stack trace.\n if (lines.Length <= 1)\n return null;\n\n int stackStartIndex = -1;\n\n // Start checking from the second line onwards.\n for (int i = 1; i < lines.Length; ++i)\n {\n // Performance: TrimStart creates a new string. Consider using IsWhiteSpace check if performance critical.\n string trimmedLine = lines[i].TrimStart();\n\n // Check for common stack trace patterns.\n if (\n trimmedLine.StartsWith(\"at \")\n || trimmedLine.StartsWith(\"UnityEngine.\")\n || trimmedLine.StartsWith(\"UnityEditor.\")\n || trimmedLine.Contains(\"(at \")\n || // Covers \"(at Assets/...\" pattern\n // Heuristic: Check if line starts with likely namespace/class pattern (Uppercase.Something)\n (\n trimmedLine.Length > 0\n && char.IsUpper(trimmedLine[0])\n && trimmedLine.Contains('.')\n )\n )\n {\n stackStartIndex = i;\n break; // Found the likely start of the stack trace\n }\n }\n\n // If a potential start index was found...\n if (stackStartIndex > 0)\n {\n // Join the lines from the stack start index onwards using standard newline characters.\n // This reconstructs the stack trace part of the message.\n return string.Join(\"\\n\", lines.Skip(stackStartIndex));\n }\n\n // No clear stack trace found based on the patterns.\n return null;\n }\n\n /* LogEntry.mode bits exploration (based on Unity decompilation/observation):\n May change between versions.\n\n Basic Types:\n kError = 1 << 0 (1)\n kAssert = 1 << 1 (2)\n kWarning = 1 << 2 (4)\n kLog = 1 << 3 (8)\n kFatal = 1 << 4 (16) - Often treated as Exception/Error\n\n Modifiers/Context:\n kAssetImportError = 1 << 7 (128)\n kAssetImportWarning = 1 << 8 (256)\n kScriptingError = 1 << 9 (512)\n kScriptingWarning = 1 << 10 (1024)\n kScriptingLog = 1 << 11 (2048)\n kScriptCompileError = 1 << 12 (4096)\n kScriptCompileWarning = 1 << 13 (8192)\n kStickyError = 1 << 14 (16384) - Stays visible even after Clear On Play\n kMayIgnoreLineNumber = 1 << 15 (32768)\n kReportBug = 1 << 16 (65536) - Shows the \"Report Bug\" button\n kDisplayPreviousErrorInStatusBar = 1 << 17 (131072)\n kScriptingException = 1 << 18 (262144)\n kDontExtractStacktrace = 1 << 19 (524288) - Hint to the console UI\n kShouldClearOnPlay = 1 << 20 (1048576) - Default behavior\n kGraphCompileError = 1 << 21 (2097152)\n kScriptingAssertion = 1 << 22 (4194304)\n kVisualScriptingError = 1 << 23 (8388608)\n\n Example observed values:\n Log: 2048 (ScriptingLog) or 8 (Log)\n Warning: 1028 (ScriptingWarning | Warning) or 4 (Warning)\n Error: 513 (ScriptingError | Error) or 1 (Error)\n Exception: 262161 (ScriptingException | Error | kFatal?) - Complex combination\n Assertion: 4194306 (ScriptingAssertion | Assert) or 2 (Assert)\n */\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ManageShader.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles CRUD operations for shader files within the Unity project.\n /// \n public static class ManageShader\n {\n /// \n /// Main handler for shader management actions.\n /// \n public static object HandleCommand(JObject @params)\n {\n // Extract parameters\n string action = @params[\"action\"]?.ToString().ToLower();\n string name = @params[\"name\"]?.ToString();\n string path = @params[\"path\"]?.ToString(); // Relative to Assets/\n string contents = null;\n\n // Check if we have base64 encoded contents\n bool contentsEncoded = @params[\"contentsEncoded\"]?.ToObject() ?? false;\n if (contentsEncoded && @params[\"encodedContents\"] != null)\n {\n try\n {\n contents = DecodeBase64(@params[\"encodedContents\"].ToString());\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to decode shader contents: {e.Message}\");\n }\n }\n else\n {\n contents = @params[\"contents\"]?.ToString();\n }\n\n // Validate required parameters\n if (string.IsNullOrEmpty(action))\n {\n return Response.Error(\"Action parameter is required.\");\n }\n if (string.IsNullOrEmpty(name))\n {\n return Response.Error(\"Name parameter is required.\");\n }\n // Basic name validation (alphanumeric, underscores, cannot start with number)\n if (!Regex.IsMatch(name, @\"^[a-zA-Z_][a-zA-Z0-9_]*$\"))\n {\n return Response.Error(\n $\"Invalid shader name: '{name}'. Use only letters, numbers, underscores, and don't start with a number.\"\n );\n }\n\n // Ensure path is relative to Assets/, removing any leading \"Assets/\"\n // Set default directory to \"Shaders\" if path is not provided\n string relativeDir = path ?? \"Shaders\"; // Default to \"Shaders\" if path is null\n if (!string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = relativeDir.Replace('\\\\', '/').Trim('/');\n if (relativeDir.StartsWith(\"Assets/\", StringComparison.OrdinalIgnoreCase))\n {\n relativeDir = relativeDir.Substring(\"Assets/\".Length).TrimStart('/');\n }\n }\n // Handle empty string case explicitly after processing\n if (string.IsNullOrEmpty(relativeDir))\n {\n relativeDir = \"Shaders\"; // Ensure default if path was provided as \"\" or only \"/\" or \"Assets/\"\n }\n\n // Construct paths\n string shaderFileName = $\"{name}.shader\";\n string fullPathDir = Path.Combine(Application.dataPath, relativeDir);\n string fullPath = Path.Combine(fullPathDir, shaderFileName);\n string relativePath = Path.Combine(\"Assets\", relativeDir, shaderFileName)\n .Replace('\\\\', '/'); // Ensure \"Assets/\" prefix and forward slashes\n\n // Ensure the target directory exists for create/update\n if (action == \"create\" || action == \"update\")\n {\n try\n {\n if (!Directory.Exists(fullPathDir))\n {\n Directory.CreateDirectory(fullPathDir);\n // Refresh AssetDatabase to recognize new folders\n AssetDatabase.Refresh();\n }\n }\n catch (Exception e)\n {\n return Response.Error(\n $\"Could not create directory '{fullPathDir}': {e.Message}\"\n );\n }\n }\n\n // Route to specific action handlers\n switch (action)\n {\n case \"create\":\n return CreateShader(fullPath, relativePath, name, contents);\n case \"read\":\n return ReadShader(fullPath, relativePath);\n case \"update\":\n return UpdateShader(fullPath, relativePath, name, contents);\n case \"delete\":\n return DeleteShader(fullPath, relativePath);\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are: create, read, update, delete.\"\n );\n }\n }\n\n /// \n /// Decode base64 string to normal text\n /// \n private static string DecodeBase64(string encoded)\n {\n byte[] data = Convert.FromBase64String(encoded);\n return System.Text.Encoding.UTF8.GetString(data);\n }\n\n /// \n /// Encode text to base64 string\n /// \n private static string EncodeBase64(string text)\n {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(data);\n }\n\n private static object CreateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n // Check if shader already exists\n if (File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader already exists at '{relativePath}'. Use 'update' action to modify.\"\n );\n }\n\n // Add validation for shader name conflicts in Unity\n if (Shader.Find(name) != null)\n {\n return Response.Error(\n $\"A shader with name '{name}' already exists in the project. Choose a different name.\"\n );\n }\n\n // Generate default content if none provided\n if (string.IsNullOrEmpty(contents))\n {\n contents = GenerateDefaultShaderContent(name);\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh(); // Ensure Unity recognizes the new shader\n return Response.Success(\n $\"Shader '{name}.shader' created successfully at '{relativePath}'.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to create shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object ReadShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n string contents = File.ReadAllText(fullPath);\n\n // Return both normal and encoded contents for larger files\n //TODO: Consider a threshold for large files\n bool isLarge = contents.Length > 10000; // If content is large, include encoded version\n var responseData = new\n {\n path = relativePath,\n contents = contents,\n // For large files, also include base64-encoded version\n encodedContents = isLarge ? EncodeBase64(contents) : null,\n contentsEncoded = isLarge,\n };\n\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' read successfully.\",\n responseData\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to read shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object UpdateShader(\n string fullPath,\n string relativePath,\n string name,\n string contents\n )\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error(\n $\"Shader not found at '{relativePath}'. Use 'create' action to add a new shader.\"\n );\n }\n if (string.IsNullOrEmpty(contents))\n {\n return Response.Error(\"Content is required for the 'update' action.\");\n }\n\n try\n {\n File.WriteAllText(fullPath, contents);\n AssetDatabase.ImportAsset(relativePath);\n AssetDatabase.Refresh();\n return Response.Success(\n $\"Shader '{Path.GetFileName(relativePath)}' updated successfully.\",\n new { path = relativePath }\n );\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to update shader '{relativePath}': {e.Message}\");\n }\n }\n\n private static object DeleteShader(string fullPath, string relativePath)\n {\n if (!File.Exists(fullPath))\n {\n return Response.Error($\"Shader not found at '{relativePath}'.\");\n }\n\n try\n {\n // Delete the asset through Unity's AssetDatabase first\n bool success = AssetDatabase.DeleteAsset(relativePath);\n if (!success)\n {\n return Response.Error($\"Failed to delete shader through Unity's AssetDatabase: '{relativePath}'\");\n }\n\n // If the file still exists (rare case), try direct deletion\n if (File.Exists(fullPath))\n {\n File.Delete(fullPath);\n }\n\n return Response.Success($\"Shader '{Path.GetFileName(relativePath)}' deleted successfully.\");\n }\n catch (Exception e)\n {\n return Response.Error($\"Failed to delete shader '{relativePath}': {e.Message}\");\n }\n }\n\n //This is a CGProgram template\n //TODO: making a HLSL template as well?\n private static string GenerateDefaultShaderContent(string name)\n {\n return @\"Shader \"\"\" + name + @\"\"\"\n {\n Properties\n {\n _MainTex (\"\"Texture\"\", 2D) = \"\"white\"\" {}\n }\n SubShader\n {\n Tags { \"\"RenderType\"\"=\"\"Opaque\"\" }\n LOD 100\n\n Pass\n {\n CGPROGRAM\n #pragma vertex vert\n #pragma fragment frag\n #include \"\"UnityCG.cginc\"\"\n\n struct appdata\n {\n float4 vertex : POSITION;\n float2 uv : TEXCOORD0;\n };\n\n struct v2f\n {\n float2 uv : TEXCOORD0;\n float4 vertex : SV_POSITION;\n };\n\n sampler2D _MainTex;\n float4 _MainTex_ST;\n\n v2f vert (appdata v)\n {\n v2f o;\n o.vertex = UnityObjectToClipPos(v.vertex);\n o.uv = TRANSFORM_TEX(v.uv, _MainTex);\n return o;\n }\n\n fixed4 frag (v2f i) : SV_Target\n {\n fixed4 col = tex2D(_MainTex, i.uv);\n return col;\n }\n ENDCG\n }\n }\n }\";\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/GameObjectSerializer.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Runtime.Serialization; // For Converters\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Handles serialization of GameObjects and Components for MCP responses.\n /// Includes reflection helpers and caching for performance.\n /// \n public static class GameObjectSerializer\n {\n // --- Data Serialization ---\n\n /// \n /// Creates a serializable representation of a GameObject.\n /// \n public static object GetGameObjectData(GameObject go)\n {\n if (go == null)\n return null;\n return new\n {\n name = go.name,\n instanceID = go.GetInstanceID(),\n tag = go.tag,\n layer = go.layer,\n activeSelf = go.activeSelf,\n activeInHierarchy = go.activeInHierarchy,\n isStatic = go.isStatic,\n scenePath = go.scene.path, // Identify which scene it belongs to\n transform = new // Serialize transform components carefully to avoid JSON issues\n {\n // Serialize Vector3 components individually to prevent self-referencing loops.\n // The default serializer can struggle with properties like Vector3.normalized.\n position = new\n {\n x = go.transform.position.x,\n y = go.transform.position.y,\n z = go.transform.position.z,\n },\n localPosition = new\n {\n x = go.transform.localPosition.x,\n y = go.transform.localPosition.y,\n z = go.transform.localPosition.z,\n },\n rotation = new\n {\n x = go.transform.rotation.eulerAngles.x,\n y = go.transform.rotation.eulerAngles.y,\n z = go.transform.rotation.eulerAngles.z,\n },\n localRotation = new\n {\n x = go.transform.localRotation.eulerAngles.x,\n y = go.transform.localRotation.eulerAngles.y,\n z = go.transform.localRotation.eulerAngles.z,\n },\n scale = new\n {\n x = go.transform.localScale.x,\n y = go.transform.localScale.y,\n z = go.transform.localScale.z,\n },\n forward = new\n {\n x = go.transform.forward.x,\n y = go.transform.forward.y,\n z = go.transform.forward.z,\n },\n up = new\n {\n x = go.transform.up.x,\n y = go.transform.up.y,\n z = go.transform.up.z,\n },\n right = new\n {\n x = go.transform.right.x,\n y = go.transform.right.y,\n z = go.transform.right.z,\n },\n },\n parentInstanceID = go.transform.parent?.gameObject.GetInstanceID() ?? 0, // 0 if no parent\n // Optionally include components, but can be large\n // components = go.GetComponents().Select(c => GetComponentData(c)).ToList()\n // Or just component names:\n componentNames = go.GetComponents()\n .Select(c => c.GetType().FullName)\n .ToList(),\n };\n }\n\n // --- Metadata Caching for Reflection ---\n private class CachedMetadata\n {\n public readonly List SerializableProperties;\n public readonly List SerializableFields;\n\n public CachedMetadata(List properties, List fields)\n {\n SerializableProperties = properties;\n SerializableFields = fields;\n }\n }\n // Key becomes Tuple\n private static readonly Dictionary, CachedMetadata> _metadataCache = new Dictionary, CachedMetadata>();\n // --- End Metadata Caching ---\n\n /// \n /// Creates a serializable representation of a Component, attempting to serialize\n /// public properties and fields using reflection, with caching and control over non-public fields.\n /// \n // Add the flag parameter here\n public static object GetComponentData(Component c, bool includeNonPublicSerializedFields = true)\n {\n // --- Add Early Logging --- \n // Debug.Log($\"[GetComponentData] Starting for component: {c?.GetType()?.FullName ?? \"null\"} (ID: {c?.GetInstanceID() ?? 0})\");\n // --- End Early Logging ---\n \n if (c == null) return null;\n Type componentType = c.GetType();\n\n // --- Special handling for Transform to avoid reflection crashes and problematic properties --- \n if (componentType == typeof(Transform))\n {\n Transform tr = c as Transform;\n // Debug.Log($\"[GetComponentData] Manually serializing Transform (ID: {tr.GetInstanceID()})\");\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", tr.GetInstanceID() },\n // Manually extract known-safe properties. Avoid Quaternion 'rotation' and 'lossyScale'.\n { \"position\", CreateTokenFromValue(tr.position, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localPosition\", CreateTokenFromValue(tr.localPosition, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"eulerAngles\", CreateTokenFromValue(tr.eulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() }, // Use Euler angles\n { \"localEulerAngles\", CreateTokenFromValue(tr.localEulerAngles, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"localScale\", CreateTokenFromValue(tr.localScale, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"right\", CreateTokenFromValue(tr.right, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"up\", CreateTokenFromValue(tr.up, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"forward\", CreateTokenFromValue(tr.forward, typeof(Vector3))?.ToObject() ?? new JObject() },\n { \"parentInstanceID\", tr.parent?.gameObject.GetInstanceID() ?? 0 },\n { \"rootInstanceID\", tr.root?.gameObject.GetInstanceID() ?? 0 },\n { \"childCount\", tr.childCount },\n // Include standard Object/Component properties\n { \"name\", tr.name }, \n { \"tag\", tr.tag }, \n { \"gameObjectInstanceID\", tr.gameObject?.GetInstanceID() ?? 0 }\n };\n }\n // --- End Special handling for Transform --- \n\n // --- Special handling for Camera to avoid matrix-related crashes ---\n if (componentType == typeof(Camera))\n {\n Camera cam = c as Camera;\n var cameraProperties = new Dictionary();\n\n // List of safe properties to serialize\n var safeProperties = new Dictionary>\n {\n { \"nearClipPlane\", () => cam.nearClipPlane },\n { \"farClipPlane\", () => cam.farClipPlane },\n { \"fieldOfView\", () => cam.fieldOfView },\n { \"renderingPath\", () => (int)cam.renderingPath },\n { \"actualRenderingPath\", () => (int)cam.actualRenderingPath },\n { \"allowHDR\", () => cam.allowHDR },\n { \"allowMSAA\", () => cam.allowMSAA },\n { \"allowDynamicResolution\", () => cam.allowDynamicResolution },\n { \"forceIntoRenderTexture\", () => cam.forceIntoRenderTexture },\n { \"orthographicSize\", () => cam.orthographicSize },\n { \"orthographic\", () => cam.orthographic },\n { \"opaqueSortMode\", () => (int)cam.opaqueSortMode },\n { \"transparencySortMode\", () => (int)cam.transparencySortMode },\n { \"depth\", () => cam.depth },\n { \"aspect\", () => cam.aspect },\n { \"cullingMask\", () => cam.cullingMask },\n { \"eventMask\", () => cam.eventMask },\n { \"backgroundColor\", () => cam.backgroundColor },\n { \"clearFlags\", () => (int)cam.clearFlags },\n { \"stereoEnabled\", () => cam.stereoEnabled },\n { \"stereoSeparation\", () => cam.stereoSeparation },\n { \"stereoConvergence\", () => cam.stereoConvergence },\n { \"enabled\", () => cam.enabled },\n { \"name\", () => cam.name },\n { \"tag\", () => cam.tag },\n { \"gameObject\", () => new { name = cam.gameObject.name, instanceID = cam.gameObject.GetInstanceID() } }\n };\n\n foreach (var prop in safeProperties)\n {\n try\n {\n var value = prop.Value();\n if (value != null)\n {\n AddSerializableValue(cameraProperties, prop.Key, value.GetType(), value);\n }\n }\n catch (Exception)\n {\n // Silently skip any property that fails\n continue;\n }\n }\n\n return new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", cam.GetInstanceID() },\n { \"properties\", cameraProperties }\n };\n }\n // --- End Special handling for Camera ---\n\n var data = new Dictionary\n {\n { \"typeName\", componentType.FullName },\n { \"instanceID\", c.GetInstanceID() }\n };\n\n // --- Get Cached or Generate Metadata (using new cache key) ---\n Tuple cacheKey = new Tuple(componentType, includeNonPublicSerializedFields);\n if (!_metadataCache.TryGetValue(cacheKey, out CachedMetadata cachedData))\n {\n var propertiesToCache = new List();\n var fieldsToCache = new List();\n\n // Traverse the hierarchy from the component type up to MonoBehaviour\n Type currentType = componentType;\n while (currentType != null && currentType != typeof(MonoBehaviour) && currentType != typeof(object))\n {\n // Get properties declared only at the current type level\n BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n foreach (var propInfo in currentType.GetProperties(propFlags))\n {\n // Basic filtering (readable, not indexer, not transform which is handled elsewhere)\n if (!propInfo.CanRead || propInfo.GetIndexParameters().Length > 0 || propInfo.Name == \"transform\") continue;\n // Add if not already added (handles overrides - keep the most derived version)\n if (!propertiesToCache.Any(p => p.Name == propInfo.Name)) {\n propertiesToCache.Add(propInfo);\n }\n }\n\n // Get fields declared only at the current type level (both public and non-public)\n BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;\n var declaredFields = currentType.GetFields(fieldFlags);\n\n // Process the declared Fields for caching\n foreach (var fieldInfo in declaredFields)\n {\n if (fieldInfo.Name.EndsWith(\"k__BackingField\")) continue; // Skip backing fields\n\n // Add if not already added (handles hiding - keep the most derived version)\n if (fieldsToCache.Any(f => f.Name == fieldInfo.Name)) continue;\n\n bool shouldInclude = false;\n if (includeNonPublicSerializedFields)\n {\n // If TRUE, include Public OR NonPublic with [SerializeField]\n shouldInclude = fieldInfo.IsPublic || (fieldInfo.IsPrivate && fieldInfo.IsDefined(typeof(SerializeField), inherit: false));\n }\n else // includeNonPublicSerializedFields is FALSE\n {\n // If FALSE, include ONLY if it is explicitly Public.\n shouldInclude = fieldInfo.IsPublic;\n }\n\n if (shouldInclude)\n {\n fieldsToCache.Add(fieldInfo);\n }\n }\n\n // Move to the base type\n currentType = currentType.BaseType;\n }\n // --- End Hierarchy Traversal ---\n\n cachedData = new CachedMetadata(propertiesToCache, fieldsToCache);\n _metadataCache[cacheKey] = cachedData; // Add to cache with combined key\n }\n // --- End Get Cached or Generate Metadata ---\n\n // --- Use cached metadata ---\n var serializablePropertiesOutput = new Dictionary();\n \n // --- Add Logging Before Property Loop ---\n // Debug.Log($\"[GetComponentData] Starting property loop for {componentType.Name}...\");\n // --- End Logging Before Property Loop ---\n\n // Use cached properties\n foreach (var propInfo in cachedData.SerializableProperties)\n {\n string propName = propInfo.Name;\n\n // --- Skip known obsolete/problematic Component shortcut properties ---\n bool skipProperty = false;\n if (propName == \"rigidbody\" || propName == \"rigidbody2D\" || propName == \"camera\" ||\n propName == \"light\" || propName == \"animation\" || propName == \"constantForce\" ||\n propName == \"renderer\" || propName == \"audio\" || propName == \"networkView\" ||\n propName == \"collider\" || propName == \"collider2D\" || propName == \"hingeJoint\" ||\n propName == \"particleSystem\" ||\n // Also skip potentially problematic Matrix properties prone to cycles/errors\n propName == \"worldToLocalMatrix\" || propName == \"localToWorldMatrix\")\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping generic property: {propName}\"); // Optional log\n skipProperty = true;\n }\n // --- End Skip Generic Properties ---\n\n // --- Skip specific potentially problematic Camera properties ---\n if (componentType == typeof(Camera) && \n (propName == \"pixelRect\" || \n propName == \"rect\" || \n propName == \"cullingMatrix\" ||\n propName == \"useOcclusionCulling\" ||\n propName == \"worldToCameraMatrix\" ||\n propName == \"projectionMatrix\" ||\n propName == \"nonJitteredProjectionMatrix\" ||\n propName == \"previousViewProjectionMatrix\" ||\n propName == \"cameraToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Camera property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Camera Properties ---\n\n // --- Skip specific potentially problematic Transform properties ---\n if (componentType == typeof(Transform) && \n (propName == \"lossyScale\" || \n propName == \"rotation\" ||\n propName == \"worldToLocalMatrix\" ||\n propName == \"localToWorldMatrix\"))\n {\n // Debug.Log($\"[GetComponentData] Explicitly skipping Transform property: {propName}\");\n skipProperty = true;\n }\n // --- End Skip Transform Properties ---\n\n // Skip if flagged\n if (skipProperty)\n {\n continue;\n }\n\n try\n {\n // --- Add detailed logging --- \n // Debug.Log($\"[GetComponentData] Accessing: {componentType.Name}.{propName}\");\n // --- End detailed logging ---\n object value = propInfo.GetValue(c);\n Type propType = propInfo.PropertyType;\n AddSerializableValue(serializablePropertiesOutput, propName, propType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read property {propName} on {componentType.Name}: {ex.Message}\");\n }\n }\n\n // --- Add Logging Before Field Loop ---\n // Debug.Log($\"[GetComponentData] Starting field loop for {componentType.Name}...\");\n // --- End Logging Before Field Loop ---\n\n // Use cached fields\n foreach (var fieldInfo in cachedData.SerializableFields)\n {\n try\n {\n // --- Add detailed logging for fields --- \n // Debug.Log($\"[GetComponentData] Accessing Field: {componentType.Name}.{fieldInfo.Name}\");\n // --- End detailed logging for fields ---\n object value = fieldInfo.GetValue(c);\n string fieldName = fieldInfo.Name;\n Type fieldType = fieldInfo.FieldType;\n AddSerializableValue(serializablePropertiesOutput, fieldName, fieldType, value);\n }\n catch (Exception ex)\n {\n // Debug.LogWarning($\"Could not read field {fieldInfo.Name} on {componentType.Name}: {ex.Message}\");\n }\n }\n // --- End Use cached metadata ---\n\n if (serializablePropertiesOutput.Count > 0)\n {\n data[\"properties\"] = serializablePropertiesOutput;\n }\n\n return data;\n }\n\n // Helper function to decide how to serialize different types\n private static void AddSerializableValue(Dictionary dict, string name, Type type, object value)\n {\n // Simplified: Directly use CreateTokenFromValue which uses the serializer\n if (value == null)\n {\n dict[name] = null;\n return;\n }\n\n try\n {\n // Use the helper that employs our custom serializer settings\n JToken token = CreateTokenFromValue(value, type);\n if (token != null) // Check if serialization succeeded in the helper\n {\n // Convert JToken back to a basic object structure for the dictionary\n dict[name] = ConvertJTokenToPlainObject(token);\n }\n // If token is null, it means serialization failed and a warning was logged.\n }\n catch (Exception e)\n {\n // Catch potential errors during JToken conversion or addition to dictionary\n Debug.LogWarning($\"[AddSerializableValue] Error processing value for '{name}' (Type: {type.FullName}): {e.Message}. Skipping.\");\n }\n }\n\n // Helper to convert JToken back to basic object structure\n private static object ConvertJTokenToPlainObject(JToken token)\n {\n if (token == null) return null;\n\n switch (token.Type)\n {\n case JTokenType.Object:\n var objDict = new Dictionary();\n foreach (var prop in ((JObject)token).Properties())\n {\n objDict[prop.Name] = ConvertJTokenToPlainObject(prop.Value);\n }\n return objDict;\n\n case JTokenType.Array:\n var list = new List();\n foreach (var item in (JArray)token)\n {\n list.Add(ConvertJTokenToPlainObject(item));\n }\n return list;\n\n case JTokenType.Integer:\n return token.ToObject(); // Use long for safety\n case JTokenType.Float:\n return token.ToObject(); // Use double for safety\n case JTokenType.String:\n return token.ToObject();\n case JTokenType.Boolean:\n return token.ToObject();\n case JTokenType.Date:\n return token.ToObject();\n case JTokenType.Guid:\n return token.ToObject();\n case JTokenType.Uri:\n return token.ToObject();\n case JTokenType.TimeSpan:\n return token.ToObject();\n case JTokenType.Bytes:\n return token.ToObject();\n case JTokenType.Null:\n return null;\n case JTokenType.Undefined:\n return null; // Treat undefined as null\n\n default:\n // Fallback for simple value types not explicitly listed\n if (token is JValue jValue && jValue.Value != null)\n {\n return jValue.Value;\n }\n // Debug.LogWarning($\"Unsupported JTokenType encountered: {token.Type}. Returning null.\");\n return null;\n }\n }\n\n // --- Define custom JsonSerializerSettings for OUTPUT ---\n private static readonly JsonSerializerSettings _outputSerializerSettings = new JsonSerializerSettings\n {\n Converters = new List\n {\n new Vector3Converter(),\n new Vector2Converter(),\n new QuaternionConverter(),\n new ColorConverter(),\n new RectConverter(),\n new BoundsConverter(),\n new UnityEngineObjectConverter() // Handles serialization of references\n },\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore,\n // ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } // Example if needed\n };\n private static readonly JsonSerializer _outputSerializer = JsonSerializer.Create(_outputSerializerSettings);\n // --- End Define custom JsonSerializerSettings ---\n\n // Helper to create JToken using the output serializer\n private static JToken CreateTokenFromValue(object value, Type type)\n {\n if (value == null) return JValue.CreateNull();\n\n try\n {\n // Use the pre-configured OUTPUT serializer instance\n return JToken.FromObject(value, _outputSerializer);\n }\n catch (JsonSerializationException e)\n {\n Debug.LogWarning($\"[GameObjectSerializer] Newtonsoft.Json Error serializing value of type {type.FullName}: {e.Message}. Skipping property/field.\");\n return null; // Indicate serialization failure\n }\n catch (Exception e) // Catch other unexpected errors\n {\n Debug.LogWarning($\"[GameObjectSerializer] Unexpected error serializing value of type {type.FullName}: {e}. Skipping property/field.\");\n return null; // Indicate serialization failure\n }\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Tools/ExecuteMenuItem.cs", "using System;\nusing System.Collections.Generic; // Added for HashSet\nusing Newtonsoft.Json.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityMcpBridge.Editor.Helpers; // For Response class\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Handles executing Unity Editor menu items by path.\n /// \n public static class ExecuteMenuItem\n {\n // Basic blacklist to prevent accidental execution of potentially disruptive menu items.\n // This can be expanded based on needs.\n private static readonly HashSet _menuPathBlacklist = new HashSet(\n StringComparer.OrdinalIgnoreCase\n )\n {\n \"File/Quit\",\n // Add other potentially dangerous items like \"Edit/Preferences...\", \"File/Build Settings...\" if needed\n };\n\n /// \n /// Main handler for executing menu items or getting available ones.\n /// \n public static object HandleCommand(JObject @params)\n {\n string action = @params[\"action\"]?.ToString().ToLower() ?? \"execute\"; // Default action\n\n try\n {\n switch (action)\n {\n case \"execute\":\n return ExecuteItem(@params);\n case \"get_available_menus\":\n // Getting a comprehensive list of *all* menu items dynamically is very difficult\n // and often requires complex reflection or maintaining a manual list.\n // Returning a placeholder/acknowledgement for now.\n Debug.LogWarning(\n \"[ExecuteMenuItem] 'get_available_menus' action is not fully implemented. Dynamically listing all menu items is complex.\"\n );\n // Returning an empty list as per the refactor plan's requirements.\n return Response.Success(\n \"'get_available_menus' action is not fully implemented. Returning empty list.\",\n new List()\n );\n // TODO: Consider implementing a basic list of common/known menu items or exploring reflection techniques if this feature becomes critical.\n default:\n return Response.Error(\n $\"Unknown action: '{action}'. Valid actions are 'execute', 'get_available_menus'.\"\n );\n }\n }\n catch (Exception e)\n {\n Debug.LogError($\"[ExecuteMenuItem] Action '{action}' failed: {e}\");\n return Response.Error($\"Internal error processing action '{action}': {e.Message}\");\n }\n }\n\n /// \n /// Executes a specific menu item.\n /// \n private static object ExecuteItem(JObject @params)\n {\n // Try both naming conventions: snake_case and camelCase\n string menuPath = @params[\"menu_path\"]?.ToString() ?? @params[\"menuPath\"]?.ToString();\n\n // string alias = @params[\"alias\"]?.ToString(); // TODO: Implement alias mapping based on refactor plan requirements.\n // JObject parameters = @params[\"parameters\"] as JObject; // TODO: Investigate parameter passing (often not directly supported by ExecuteMenuItem).\n\n if (string.IsNullOrWhiteSpace(menuPath))\n {\n return Response.Error(\"Required parameter 'menu_path' or 'menuPath' is missing or empty.\");\n }\n\n // Validate against blacklist\n if (_menuPathBlacklist.Contains(menuPath))\n {\n return Response.Error(\n $\"Execution of menu item '{menuPath}' is blocked for safety reasons.\"\n );\n }\n\n // TODO: Implement alias lookup here if needed (Map alias to actual menuPath).\n // if (!string.IsNullOrEmpty(alias)) { menuPath = LookupAlias(alias); if(menuPath == null) return Response.Error(...); }\n\n // TODO: Handle parameters ('parameters' object) if a viable method is found.\n // This is complex as EditorApplication.ExecuteMenuItem doesn't take arguments directly.\n // It might require finding the underlying EditorWindow or command if parameters are needed.\n\n try\n {\n // Attempt to execute the menu item on the main thread using delayCall for safety.\n EditorApplication.delayCall += () =>\n {\n try\n {\n bool executed = EditorApplication.ExecuteMenuItem(menuPath);\n // Log potential failure inside the delayed call.\n if (!executed)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to find or execute menu item via delayCall: '{menuPath}'. It might be invalid, disabled, or context-dependent.\"\n );\n }\n }\n catch (Exception delayEx)\n {\n Debug.LogError(\n $\"[ExecuteMenuItem] Exception during delayed execution of '{menuPath}': {delayEx}\"\n );\n }\n };\n\n // Report attempt immediately, as execution is delayed.\n return Response.Success(\n $\"Attempted to execute menu item: '{menuPath}'. Check Unity logs for confirmation or errors.\"\n );\n }\n catch (Exception e)\n {\n // Catch errors during setup phase.\n Debug.LogError(\n $\"[ExecuteMenuItem] Failed to setup execution for '{menuPath}': {e}\"\n );\n return Response.Error(\n $\"Error setting up execution for menu item '{menuPath}': {e.Message}\"\n );\n }\n }\n\n // TODO: Add helper for alias lookup if implementing aliases.\n // private static string LookupAlias(string alias) { ... return actualMenuPath or null ... }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Response.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Provides static methods for creating standardized success and error response objects.\n /// Ensures consistent JSON structure for communication back to the Python server.\n /// \n public static class Response\n {\n /// \n /// Creates a standardized success response object.\n /// \n /// A message describing the successful operation.\n /// Optional additional data to include in the response.\n /// An object representing the success response.\n public static object Success(string message, object data = null)\n {\n if (data != null)\n {\n return new\n {\n success = true,\n message = message,\n data = data,\n };\n }\n else\n {\n return new { success = true, message = message };\n }\n }\n\n /// \n /// Creates a standardized error response object.\n /// \n /// A message describing the error.\n /// Optional additional data (e.g., error details) to include.\n /// An object representing the error response.\n public static object Error(string errorMessage, object data = null)\n {\n if (data != null)\n {\n // Note: The key is \"error\" for error messages, not \"message\"\n return new\n {\n success = false,\n error = errorMessage,\n data = data,\n };\n }\n else\n {\n return new { success = false, error = errorMessage };\n }\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Runtime/Serialization/UnityTypeConverters.cs", "using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing UnityEngine;\n#if UNITY_EDITOR\nusing UnityEditor; // Required for AssetDatabase and EditorUtility\n#endif\n\nnamespace UnityMcpBridge.Runtime.Serialization\n{\n public class Vector3Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector3 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WriteEndObject();\n }\n\n public override Vector3 ReadJson(JsonReader reader, Type objectType, Vector3 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector3(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"]\n );\n }\n }\n\n public class Vector2Converter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WriteEndObject();\n }\n\n public override Vector2 ReadJson(JsonReader reader, Type objectType, Vector2 existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Vector2(\n (float)jo[\"x\"],\n (float)jo[\"y\"]\n );\n }\n }\n\n public class QuaternionConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Quaternion value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"z\");\n writer.WriteValue(value.z);\n writer.WritePropertyName(\"w\");\n writer.WriteValue(value.w);\n writer.WriteEndObject();\n }\n\n public override Quaternion ReadJson(JsonReader reader, Type objectType, Quaternion existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Quaternion(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"z\"],\n (float)jo[\"w\"]\n );\n }\n }\n\n public class ColorConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Color value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"r\");\n writer.WriteValue(value.r);\n writer.WritePropertyName(\"g\");\n writer.WriteValue(value.g);\n writer.WritePropertyName(\"b\");\n writer.WriteValue(value.b);\n writer.WritePropertyName(\"a\");\n writer.WriteValue(value.a);\n writer.WriteEndObject();\n }\n\n public override Color ReadJson(JsonReader reader, Type objectType, Color existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Color(\n (float)jo[\"r\"],\n (float)jo[\"g\"],\n (float)jo[\"b\"],\n (float)jo[\"a\"]\n );\n }\n }\n \n public class RectConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Rect value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"x\");\n writer.WriteValue(value.x);\n writer.WritePropertyName(\"y\");\n writer.WriteValue(value.y);\n writer.WritePropertyName(\"width\");\n writer.WriteValue(value.width);\n writer.WritePropertyName(\"height\");\n writer.WriteValue(value.height);\n writer.WriteEndObject();\n }\n\n public override Rect ReadJson(JsonReader reader, Type objectType, Rect existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n return new Rect(\n (float)jo[\"x\"],\n (float)jo[\"y\"],\n (float)jo[\"width\"],\n (float)jo[\"height\"]\n );\n }\n }\n \n public class BoundsConverter : JsonConverter\n {\n public override void WriteJson(JsonWriter writer, Bounds value, JsonSerializer serializer)\n {\n writer.WriteStartObject();\n writer.WritePropertyName(\"center\");\n serializer.Serialize(writer, value.center); // Use serializer to handle nested Vector3\n writer.WritePropertyName(\"size\");\n serializer.Serialize(writer, value.size); // Use serializer to handle nested Vector3\n writer.WriteEndObject();\n }\n\n public override Bounds ReadJson(JsonReader reader, Type objectType, Bounds existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n JObject jo = JObject.Load(reader);\n Vector3 center = jo[\"center\"].ToObject(serializer); // Use serializer to handle nested Vector3\n Vector3 size = jo[\"size\"].ToObject(serializer); // Use serializer to handle nested Vector3\n return new Bounds(center, size);\n }\n }\n\n // Converter for UnityEngine.Object references (GameObjects, Components, Materials, Textures, etc.)\n public class UnityEngineObjectConverter : JsonConverter\n {\n public override bool CanRead => true; // We need to implement ReadJson\n public override bool CanWrite => true;\n\n public override void WriteJson(JsonWriter writer, UnityEngine.Object value, JsonSerializer serializer)\n {\n if (value == null)\n {\n writer.WriteNull();\n return;\n }\n\n#if UNITY_EDITOR // AssetDatabase and EditorUtility are Editor-only\n if (UnityEditor.AssetDatabase.Contains(value))\n {\n // It's an asset (Material, Texture, Prefab, etc.)\n string path = UnityEditor.AssetDatabase.GetAssetPath(value);\n if (!string.IsNullOrEmpty(path))\n {\n writer.WriteValue(path);\n }\n else\n {\n // Asset exists but path couldn't be found? Write minimal info.\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"isAssetWithoutPath\");\n writer.WriteValue(true);\n writer.WriteEndObject();\n }\n }\n else\n {\n // It's a scene object (GameObject, Component, etc.)\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WriteEndObject();\n }\n#else\n // Runtime fallback: Write basic info without AssetDatabase\n writer.WriteStartObject();\n writer.WritePropertyName(\"name\");\n writer.WriteValue(value.name);\n writer.WritePropertyName(\"instanceID\");\n writer.WriteValue(value.GetInstanceID());\n writer.WritePropertyName(\"warning\");\n writer.WriteValue(\"UnityEngineObjectConverter running in non-Editor mode, asset path unavailable.\");\n writer.WriteEndObject();\n#endif\n }\n\n public override UnityEngine.Object ReadJson(JsonReader reader, Type objectType, UnityEngine.Object existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n if (reader.TokenType == JsonToken.Null)\n {\n return null;\n }\n\n#if UNITY_EDITOR\n if (reader.TokenType == JsonToken.String)\n {\n // Assume it's an asset path\n string path = reader.Value.ToString();\n return UnityEditor.AssetDatabase.LoadAssetAtPath(path, objectType);\n }\n\n if (reader.TokenType == JsonToken.StartObject)\n {\n JObject jo = JObject.Load(reader);\n if (jo.TryGetValue(\"instanceID\", out JToken idToken) && idToken.Type == JTokenType.Integer)\n {\n int instanceId = idToken.ToObject();\n UnityEngine.Object obj = UnityEditor.EditorUtility.InstanceIDToObject(instanceId);\n if (obj != null && objectType.IsAssignableFrom(obj.GetType()))\n {\n return obj;\n }\n }\n // Could potentially try finding by name as a fallback if ID lookup fails/isn't present\n // but that's less reliable.\n }\n#else\n // Runtime deserialization is tricky without AssetDatabase/EditorUtility\n // Maybe log a warning and return null or existingValue?\n Debug.LogWarning(\"UnityEngineObjectConverter cannot deserialize complex objects in non-Editor mode.\");\n // Skip the token to avoid breaking the reader\n if (reader.TokenType == JsonToken.StartObject) JObject.Load(reader);\n else if (reader.TokenType == JsonToken.String) reader.ReadAsString(); \n // Return null or existing value, depending on desired behavior\n return existingValue; \n#endif\n\n throw new JsonSerializationException($\"Unexpected token type '{reader.TokenType}' when deserializing UnityEngine.Object\");\n }\n }\n} "], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpStatus.cs", "namespace UnityMcpBridge.Editor.Models\n{\n // Enum representing the various status states for MCP clients\n public enum McpStatus\n {\n NotConfigured, // Not set up yet\n Configured, // Successfully configured\n Running, // Service is running\n Connected, // Successfully connected\n IncorrectPath, // Configuration has incorrect paths\n CommunicationError, // Connected but communication issues\n NoResponse, // Connected but not responding\n MissingConfig, // Config file exists but missing required elements\n UnsupportedOS, // OS is not supported\n Error, // General error state\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Tools/CommandRegistry.cs", "using System;\nusing System.Collections.Generic;\nusing Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Tools\n{\n /// \n /// Registry for all MCP command handlers (Refactored Version)\n /// \n public static class CommandRegistry\n {\n // Maps command names (matching those called from Python via ctx.bridge.unity_editor.HandlerName)\n // to the corresponding static HandleCommand method in the appropriate tool class.\n private static readonly Dictionary> _handlers = new()\n {\n { \"HandleManageScript\", ManageScript.HandleCommand },\n { \"HandleManageScene\", ManageScene.HandleCommand },\n { \"HandleManageEditor\", ManageEditor.HandleCommand },\n { \"HandleManageGameObject\", ManageGameObject.HandleCommand },\n { \"HandleManageAsset\", ManageAsset.HandleCommand },\n { \"HandleReadConsole\", ReadConsole.HandleCommand },\n { \"HandleExecuteMenuItem\", ExecuteMenuItem.HandleCommand },\n { \"HandleManageShader\", ManageShader.HandleCommand},\n };\n\n /// \n /// Gets a command handler by name.\n /// \n /// Name of the command handler (e.g., \"HandleManageAsset\").\n /// The command handler function if found, null otherwise.\n public static Func GetHandler(string commandName)\n {\n // Use case-insensitive comparison for flexibility, although Python side should be consistent\n return _handlers.TryGetValue(commandName, out var handler) ? handler : null;\n // Consider adding logging here if a handler is not found\n /*\n if (_handlers.TryGetValue(commandName, out var handler)) {\n return handler;\n } else {\n UnityEngine.Debug.LogError($\\\"[CommandRegistry] No handler found for command: {commandName}\\\");\n return null;\n }\n */\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Data/DefaultServerConfig.cs", "using UnityMcpBridge.Editor.Models;\n\nnamespace UnityMcpBridge.Editor.Data\n{\n public class DefaultServerConfig : ServerConfig\n {\n public new string unityHost = \"localhost\";\n public new int unityPort = 6400;\n public new int mcpPort = 6500;\n public new float connectionTimeout = 15.0f;\n public new int bufferSize = 32768;\n public new string logLevel = \"INFO\";\n public new string logFormat = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\";\n public new int maxRetries = 3;\n public new float retryDelay = 1.0f;\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfig\n {\n [JsonProperty(\"mcpServers\")]\n public McpConfigServers mcpServers;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/ServerConfig.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class ServerConfig\n {\n [JsonProperty(\"unity_host\")]\n public string unityHost = \"localhost\";\n\n [JsonProperty(\"unity_port\")]\n public int unityPort;\n\n [JsonProperty(\"mcp_port\")]\n public int mcpPort;\n\n [JsonProperty(\"connection_timeout\")]\n public float connectionTimeout;\n\n [JsonProperty(\"buffer_size\")]\n public int bufferSize;\n\n [JsonProperty(\"log_level\")]\n public string logLevel;\n\n [JsonProperty(\"log_format\")]\n public string logFormat;\n\n [JsonProperty(\"max_retries\")]\n public int maxRetries;\n\n [JsonProperty(\"retry_delay\")]\n public float retryDelay;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/McpTypes.cs", "namespace UnityMcpBridge.Editor.Models\n{\n public enum McpTypes\n {\n ClaudeDesktop,\n Cursor,\n VSCode,\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServers.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServers\n {\n [JsonProperty(\"unityMCP\")]\n public McpConfigServer unityMCP;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/MCPConfigServer.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n [Serializable]\n public class McpConfigServer\n {\n [JsonProperty(\"command\")]\n public string command;\n\n [JsonProperty(\"args\")]\n public string[] args;\n }\n}\n"], ["/unity-mcp/UnityMcpBridge/Editor/Helpers/Vector3Helper.cs", "using Newtonsoft.Json.Linq;\nusing UnityEngine;\n\nnamespace UnityMcpBridge.Editor.Helpers\n{\n /// \n /// Helper class for Vector3 operations\n /// \n public static class Vector3Helper\n {\n /// \n /// Parses a JArray into a Vector3\n /// \n /// The array containing x, y, z coordinates\n /// A Vector3 with the parsed coordinates\n /// Thrown when array is invalid\n public static Vector3 ParseVector3(JArray array)\n {\n if (array == null || array.Count != 3)\n throw new System.Exception(\"Vector3 must be an array of 3 floats [x, y, z].\");\n return new Vector3((float)array[0], (float)array[1], (float)array[2]);\n }\n }\n}\n\n"], ["/unity-mcp/UnityMcpBridge/Editor/Models/Command.cs", "using Newtonsoft.Json.Linq;\n\nnamespace UnityMcpBridge.Editor.Models\n{\n /// \n /// Represents a command received from the MCP client\n /// \n public class Command\n {\n /// \n /// The type of command to execute\n /// \n public string type { get; set; }\n\n /// \n /// The parameters for the command\n /// \n public JObject @params { get; set; }\n }\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-20 19:14:43", "created_task_model": "DeepSeek-R1", "function_skeleton": "public McpClients () {}", "code_description": "This code segment functions to: Initialize the state enumeration values for each client entry by mapping string-based configuration status indicators to their corresponding enum representations during object construction."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public McpClients()\n {\n foreach (var client in clients)\n {\n string configPath = Environment.OSVersion.Platform == PlatformID.Win32NT\n ? client.windowsConfigPath\n : client.linuxConfigPath;\n client.configStatus = File.Exists(configPath) ? \"Configured\" : \"Not Configured\";\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-15-13"}, "editdistance_info": {"edit_distance": 37.8378, "calculate_time": "2025-08-20 19:15:13", "true_code_clean": "public McpClients()\n {\n foreach (var client in clients)\n {\n if (client.configStatus == \"Not Configured\")\n {\n client.status = McpStatus.NotConfigured;\n }\n }\n }", "predict_code_clean": "public McpClients()\n {\n foreach (var client in clients)\n {\n string configPath = Environment.OSVersion.Platform == PlatformID.Win32NT\n ? client.windowsConfigPath\n : client.linuxConfigPath;\n client.configStatus = File.Exists(configPath) ? \"Configured\" : \"Not Configured\";\n }\n }"}}