From 7f8ca2a3bd1e9932863b2b1f75366e1241f67289 Mon Sep 17 00:00:00 2001 From: Shutong Wu <51266340+Scriptwonder@users.noreply.github.com> Date: Sun, 7 Dec 2025 19:38:32 -0500 Subject: [PATCH] [FEATURE] Custom Tool Fix and Add inspection window for all the tools (#414) * Update .Bat file and Bug fix on ManageScript * Update the .Bat file to include runtime folder * Fix the inconsistent EditorPrefs variable so the GUI change on Script Validation could cause real change. * Further changes String to Int for consistency * [Custom Tool] Roslyn Runtime Compilation Allows users to generate/compile codes during Playmode * Fix based on CR * Create claude_skill_unity.zip Upload the unity_claude_skill that can be uploaded to Claude for a combo of unity-mcp-skill. * Update for Custom_Tool Fix and Detection 1. Fix Original Roslyn Compilation Custom Tool to fit the V8 standard 2. Add a new panel in the GUI to see and toggle/untoggle the tools. The toggle feature will be implemented in the future, right now its implemented here to discuss with the team if this is a good feature to add; 3. Add few missing summary in certain tools * Revert "Update for Custom_Tool Fix and Detection" This reverts commit ae8cfe5e256c70ac4a16c79d50341a39cbac18ba. * Update README.md * Reapply "Update for Custom_Tool Fix and Detection" This reverts commit f423c2f25e9ccff4f3b89d1d360ee9cf13143733. * Update ManageScript.cs Fix the layout problem of manage_script in the panel * Update To comply with the current server setting * Update on Batch Tested object generation/modification with batch and it works perfectly! We should push and let users test for a while and see PS: I tried both VS Copilot and Claude Desktop. Claude Desktop works but VS Copilot does not due to the nested structure of batch. Will look into it more. * Revert "Merge pull request #1 from Scriptwonder/batching" This reverts commit 55ee76810be161d414e1f5f5abaa5ee30ddd0052, reversing changes made to ae2eedd7fb2c6a66ff008bacac481aefb1b0d176. --- .../ManageRuntimeCompilation.cs | 87 +++--- .../RoslynRuntimeCompilation/RoslynRuntime.md | 3 - .../runtime_compilation_tool.py | 269 ----------------- .../Editor/Constants/EditorPrefKeys.cs | 3 + .../Editor/Services/IToolDiscoveryService.cs | 18 ++ .../Editor/Services/ToolDiscoveryService.cs | 224 ++++++++++++++- .../Transports/WebSocketTransportClient.cs | 3 +- MCPForUnity/Editor/Tools/CommandRegistry.cs | 30 ++ MCPForUnity/Editor/Tools/ExecuteMenuItem.cs | 3 + MCPForUnity/Editor/Tools/ManageScript.cs | 5 +- .../Editor/Tools/Prefabs/ManagePrefabs.cs | 3 + .../Editor/Windows/Components/Common.uss | 85 ++++++ .../Editor/Windows/Components/Tools.meta | 6 +- .../Components/Tools/McpToolsSection.cs | 270 ++++++++++++++++++ .../Components/Tools/McpToolsSection.cs.meta | 11 + .../Components/Tools/McpToolsSection.uxml | 15 + .../Tools/McpToolsSection.uxml.meta | 4 +- .../Editor/Windows/MCPForUnityEditorWindow.cs | 147 +++++++++- .../Windows/MCPForUnityEditorWindow.uss | 27 +- .../Windows/MCPForUnityEditorWindow.uxml | 15 +- Server/src/services/tools/batch_execute.py | 78 +++++ 21 files changed, 958 insertions(+), 348 deletions(-) delete mode 100644 CustomTools/RoslynRuntimeCompilation/RoslynRuntime.md delete mode 100644 CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py rename CustomTools/RoslynRuntimeCompilation/PythonTools.asset.meta => MCPForUnity/Editor/Windows/Components/Tools.meta (52%) create mode 100644 MCPForUnity/Editor/Windows/Components/Tools/McpToolsSection.cs create mode 100644 MCPForUnity/Editor/Windows/Components/Tools/McpToolsSection.cs.meta create mode 100644 MCPForUnity/Editor/Windows/Components/Tools/McpToolsSection.uxml rename CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py.meta => MCPForUnity/Editor/Windows/Components/Tools/McpToolsSection.uxml.meta (58%) create mode 100644 Server/src/services/tools/batch_execute.py diff --git a/CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs b/CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs index c5b6daa..799341b 100644 --- a/CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs +++ b/CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs @@ -19,9 +19,11 @@ namespace MCPForUnity.Editor.Tools { /// /// Runtime compilation tool for MCP Unity. - /// Compiles and loads C# code at runtime without triggering domain reload. + /// Compiles and loads C# code at runtime without triggering domain reload via Roslyn Runtime Compilation, where in traditional Unity workflow it would take seconds to reload assets and reset script states for each script change. /// - [McpForUnityTool("runtime_compilation")] + [McpForUnityTool( + name:"runtime_compilation", + Description = "Enable runtime compilation of C# code within Unity without domain reload via Roslyn.")] public static class ManageRuntimeCompilation { private static readonly Dictionary LoadedAssemblies = new Dictionary(); @@ -42,7 +44,7 @@ namespace MCPForUnity.Editor.Tools if (string.IsNullOrEmpty(action)) { - return Response.Error("Action parameter is required. Valid actions: compile_and_load, list_loaded, get_types, execute_with_roslyn, get_history, save_history, clear_history"); + return new ErrorResponse("Action parameter is required. Valid actions: compile_and_load, list_loaded, get_types, execute_with_roslyn, get_history, save_history, clear_history"); } switch (action) @@ -69,14 +71,14 @@ namespace MCPForUnity.Editor.Tools return ClearCompilationHistory(); default: - return Response.Error($"Unknown action '{action}'. Valid actions: compile_and_load, list_loaded, get_types, execute_with_roslyn, get_history, save_history, clear_history"); + return new ErrorResponse($"Unknown action '{action}'. Valid actions: compile_and_load, list_loaded, get_types, execute_with_roslyn, get_history, save_history, clear_history"); } } private static object CompileAndLoad(JObject @params) { #if !USE_ROSLYN - return Response.Error( + return new ErrorResponse( "Runtime compilation requires Roslyn. Please install Microsoft.CodeAnalysis.CSharp NuGet package and add USE_ROSLYN to Scripting Define Symbols. " + "See ManageScript.cs header for installation instructions." ); @@ -84,16 +86,13 @@ namespace MCPForUnity.Editor.Tools try { string code = @params["code"]?.ToString(); - var assemblyToken = @params["assembly_name"]; - string assemblyName = assemblyToken == null || string.IsNullOrWhiteSpace(assemblyToken.ToString()) - ? $"DynamicAssembly_{DateTime.Now.Ticks}" - : assemblyToken.ToString().Trim(); + string assemblyName = @params["assembly_name"]?.ToString() ?? $"DynamicAssembly_{DateTime.Now.Ticks}"; string attachTo = @params["attach_to"]?.ToString(); bool loadImmediately = @params["load_immediately"]?.ToObject() ?? true; if (string.IsNullOrEmpty(code)) { - return Response.Error("'code' parameter is required"); + return new ErrorResponse("'code' parameter is required"); } // Ensure unique assembly name @@ -104,21 +103,8 @@ namespace MCPForUnity.Editor.Tools // Create output directory Directory.CreateDirectory(DynamicAssembliesPath); - string basePath = Path.GetFullPath(DynamicAssembliesPath); - Directory.CreateDirectory(basePath); - string safeFileName = SanitizeAssemblyFileName(assemblyName); - string dllPath = Path.GetFullPath(Path.Combine(basePath, $"{safeFileName}.dll")); - - if (!dllPath.StartsWith(basePath, StringComparison.Ordinal)) - { - return Response.Error("Assembly name must resolve inside the dynamic assemblies directory."); - } - - if (File.Exists(dllPath)) - { - dllPath = Path.GetFullPath(Path.Combine(basePath, $"{safeFileName}_{DateTime.Now.Ticks}.dll")); - } - + string dllPath = Path.Combine(DynamicAssembliesPath, $"{assemblyName}.dll"); + // Parse code var syntaxTree = CSharpSyntaxTree.ParseText(code); @@ -137,7 +123,7 @@ namespace MCPForUnity.Editor.Tools // Emit to file EmitResult emitResult; - using (var stream = new FileStream(dllPath, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var stream = new FileStream(dllPath, FileMode.Create)) { emitResult = compilation.Emit(stream); } @@ -156,7 +142,7 @@ namespace MCPForUnity.Editor.Tools }) .ToList(); - return Response.Error("Compilation failed", new + return new ErrorResponse("Compilation failed", new { errors = errors, error_count = errors.Count @@ -222,7 +208,7 @@ namespace MCPForUnity.Editor.Tools } } - return Response.Success("Runtime compilation completed successfully", new + return new SuccessResponse("Runtime compilation completed successfully", new { assembly_name = assemblyName, dll_path = dllPath, @@ -235,7 +221,7 @@ namespace MCPForUnity.Editor.Tools } catch (Exception ex) { - return Response.Error($"Runtime compilation failed: {ex.Message}", new + return new ErrorResponse($"Runtime compilation failed: {ex.Message}", new { exception = ex.GetType().Name, stack_trace = ex.StackTrace @@ -243,7 +229,7 @@ namespace MCPForUnity.Editor.Tools } #endif } - + private static object ListLoadedAssemblies() { var assemblies = LoadedAssemblies.Values.Select(info => new @@ -254,33 +240,26 @@ namespace MCPForUnity.Editor.Tools type_count = info.TypeNames.Count, types = info.TypeNames }).ToList(); - - return Response.Success($"Found {assemblies.Count} loaded dynamic assemblies", new + + return new SuccessResponse($"Found {assemblies.Count} loaded dynamic assemblies", new { count = assemblies.Count, assemblies = assemblies }); } - private static string SanitizeAssemblyFileName(string assemblyName) - { - var invalidChars = Path.GetInvalidFileNameChars(); - var sanitized = new string(assemblyName.Where(c => !invalidChars.Contains(c)).ToArray()); - return string.IsNullOrWhiteSpace(sanitized) ? $"DynamicAssembly_{DateTime.Now.Ticks}" : sanitized; - } - private static object GetAssemblyTypes(JObject @params) { string assemblyName = @params["assembly_name"]?.ToString(); if (string.IsNullOrEmpty(assemblyName)) { - return Response.Error("'assembly_name' parameter is required"); + return new ErrorResponse("'assembly_name' parameter is required"); } if (!LoadedAssemblies.TryGetValue(assemblyName, out var info)) { - return Response.Error($"Assembly '{assemblyName}' not found in loaded assemblies"); + return new ErrorResponse($"Assembly '{assemblyName}' not found in loaded assemblies"); } var types = info.Assembly.GetTypes().Select(t => new @@ -294,7 +273,7 @@ namespace MCPForUnity.Editor.Tools base_type = t.BaseType?.FullName }).ToList(); - return Response.Success($"Retrieved {types.Count} types from {assemblyName}", new + return new SuccessResponse($"Retrieved {types.Count} types from {assemblyName}", new { assembly_name = assemblyName, type_count = types.Count, @@ -318,7 +297,7 @@ namespace MCPForUnity.Editor.Tools if (string.IsNullOrEmpty(code)) { - return Response.Error("'code' parameter is required"); + return new ErrorResponse("'code' parameter is required"); } // Get or create the RoslynRuntimeCompiler instance @@ -336,7 +315,7 @@ namespace MCPForUnity.Editor.Tools if (targetObject == null) { - return Response.Error($"Target GameObject '{targetObjectName}' not found"); + return new ErrorResponse($"Target GameObject '{targetObjectName}' not found"); } } @@ -352,7 +331,7 @@ namespace MCPForUnity.Editor.Tools if (success) { - return Response.Success($"Code compiled and executed successfully", new + return new SuccessResponse($"Code compiled and executed successfully", new { class_name = className, method_name = methodName, @@ -363,7 +342,7 @@ namespace MCPForUnity.Editor.Tools } else { - return Response.Error($"Execution failed: {errorMessage}", new + return new ErrorResponse($"Execution failed: {errorMessage}", new { diagnostics = compiler.lastCompileDiagnostics }); @@ -371,7 +350,7 @@ namespace MCPForUnity.Editor.Tools } catch (Exception ex) { - return Response.Error($"Failed to execute with Roslyn: {ex.Message}", new + return new ErrorResponse($"Failed to execute with Roslyn: {ex.Message}", new { exception = ex.GetType().Name, stack_trace = ex.StackTrace @@ -402,7 +381,7 @@ namespace MCPForUnity.Editor.Tools : entry.sourceCode }).ToList(); - return Response.Success($"Retrieved {historyData.Count} history entries", new + return new SuccessResponse($"Retrieved {historyData.Count} history entries", new { count = historyData.Count, history = historyData @@ -410,7 +389,7 @@ namespace MCPForUnity.Editor.Tools } catch (Exception ex) { - return Response.Error($"Failed to get history: {ex.Message}"); + return new ErrorResponse($"Failed to get history: {ex.Message}"); } } @@ -425,7 +404,7 @@ namespace MCPForUnity.Editor.Tools if (compiler.SaveHistoryToFile(out string savedPath, out string error)) { - return Response.Success($"History saved successfully", new + return new SuccessResponse($"History saved successfully", new { path = savedPath, entry_count = compiler.CompilationHistory.Count @@ -433,12 +412,12 @@ namespace MCPForUnity.Editor.Tools } else { - return Response.Error($"Failed to save history: {error}"); + return new ErrorResponse($"Failed to save history: {error}"); } } catch (Exception ex) { - return Response.Error($"Failed to save history: {ex.Message}"); + return new ErrorResponse($"Failed to save history: {ex.Message}"); } } @@ -453,11 +432,11 @@ namespace MCPForUnity.Editor.Tools int count = compiler.CompilationHistory.Count; compiler.ClearHistory(); - return Response.Success($"Cleared {count} history entries"); + return new SuccessResponse($"Cleared {count} history entries"); } catch (Exception ex) { - return Response.Error($"Failed to clear history: {ex.Message}"); + return new ErrorResponse($"Failed to clear history: {ex.Message}"); } } diff --git a/CustomTools/RoslynRuntimeCompilation/RoslynRuntime.md b/CustomTools/RoslynRuntimeCompilation/RoslynRuntime.md deleted file mode 100644 index 91d05d5..0000000 --- a/CustomTools/RoslynRuntimeCompilation/RoslynRuntime.md +++ /dev/null @@ -1,3 +0,0 @@ -# Roslyn Runtime Compilation Tool - -This custom tool uses Roslyn Runtime Compilation to have users run script generation and compilation during Playmode in realtime, where in traditional Unity workflow it would take seconds to reload assets and reset script states for each script change. diff --git a/CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py b/CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py deleted file mode 100644 index 977b9f7..0000000 --- a/CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py +++ /dev/null @@ -1,269 +0,0 @@ -""" -Runtime compilation tool for MCP Unity. -Compiles and loads C# code at runtime without domain reload. -""" - -from typing import Annotated, Any -from fastmcp import Context -from registry import mcp_for_unity_tool -from unity_connection import send_command_with_retry - - -async def safe_info(ctx: Context, message: str) -> None: - """Safely send info messages when a request context is available.""" - try: - if ctx and hasattr(ctx, "info"): - await ctx.info(message) - except RuntimeError as ex: - # FastMCP raises this when called outside of an active request - if "outside of a request" not in str(ex): - raise - - -def handle_unity_command(command_name: str, params: dict) -> dict[str, Any]: - """ - Wrapper for Unity commands with better error handling. - """ - try: - response = send_command_with_retry(command_name, params) - return response if isinstance(response, dict) else {"success": False, "message": str(response)} - except Exception as e: - error_msg = str(e) - if "Context is not available" in error_msg or "not available outside of a request" in error_msg: - return { - "success": False, - "message": "Unity is not connected. Please ensure Unity Editor is running and MCP bridge is active.", - "error": "connection_error", - "details": "This tool requires an active connection to Unity. Make sure the Unity project is open and the MCP bridge is initialized." - } - return { - "success": False, - "message": f"Command failed: {error_msg}", - "error": "tool_error" - } - - -@mcp_for_unity_tool( - description="Compile and load C# code at runtime without domain reload. Creates dynamic assemblies that can be attached to GameObjects during Play Mode. Requires Roslyn (Microsoft.CodeAnalysis.CSharp) to be installed in Unity." -) -async def compile_runtime_code( - ctx: Context, - code: Annotated[str, "Complete C# code including using statements, namespace, and class definition"], - assembly_name: Annotated[str, "Unique name for the dynamic assembly. If not provided, a timestamp-based name will be generated."] | None = None, - attach_to_gameobject: Annotated[str, "Name or hierarchy path of GameObject to attach the compiled script to (e.g., 'Player' or 'Canvas/Panel')"] | None = None, - load_immediately: Annotated[bool, "Whether to load the assembly immediately after compilation. Default is true."] = True -) -> dict[str, Any]: - """ - Compile C# code at runtime and optionally attach it to a GameObject. Only enable it with Roslyn installed in Unity. - - REQUIREMENTS: - - Unity must be running and connected - - Roslyn (Microsoft.CodeAnalysis.CSharp) must be installed via NuGet - - USE_ROSLYN scripting define symbol must be set - - This tool allows you to: - - Compile new C# scripts without restarting Unity - - Load compiled assemblies into the running Unity instance - - Attach MonoBehaviour scripts to GameObjects dynamically - - Preserve game state during script additions - - Example code: - ```csharp - using UnityEngine; - - namespace DynamicScripts - { - public class MyDynamicBehavior : MonoBehaviour - { - void Start() - { - Debug.Log("Dynamic script loaded!"); - } - } - } - ``` - """ - await safe_info(ctx, f"Compiling runtime code for assembly: {assembly_name or 'auto-generated'}") - - params = { - "action": "compile_and_load", - "code": code, - "assembly_name": assembly_name, - "attach_to": attach_to_gameobject, - "load_immediately": load_immediately, - } - params = {k: v for k, v in params.items() if v is not None} - - return handle_unity_command("runtime_compilation", params) - - -@mcp_for_unity_tool( - description="List all dynamically loaded assemblies in the current Unity session" -) -async def list_loaded_assemblies( - ctx: Context, -) -> dict[str, Any]: - """ - Get a list of all dynamically loaded assemblies created during this session. - - Returns information about: - - Assembly names - - Number of types in each assembly - - Load timestamps - - DLL file paths - """ - await safe_info(ctx, "Retrieving loaded dynamic assemblies...") - - params = {"action": "list_loaded"} - return handle_unity_command("runtime_compilation", params) - - -@mcp_for_unity_tool( - description="Get all types (classes) from a dynamically loaded assembly" -) -async def get_assembly_types( - ctx: Context, - assembly_name: Annotated[str, "Name of the assembly to query"], -) -> dict[str, Any]: - """ - Retrieve all types defined in a specific dynamic assembly. - - This is useful for: - - Inspecting what was compiled - - Finding MonoBehaviour classes to attach - - Debugging compilation results - """ - await safe_info(ctx, f"Getting types from assembly: {assembly_name}") - - params = {"action": "get_types", "assembly_name": assembly_name} - return handle_unity_command("runtime_compilation", params) - - -@mcp_for_unity_tool( - description="Execute C# code using the RoslynRuntimeCompiler with full GUI tool features including history tracking, MonoBehaviour support, and coroutines" -) -async def execute_with_roslyn( - ctx: Context, - code: Annotated[str, "Complete C# source code to compile and execute"], - class_name: Annotated[str, "Name of the class to instantiate/invoke (default: AIGenerated)"] = "AIGenerated", - method_name: Annotated[str, "Name of the static method to call (default: Run)"] = "Run", - target_object: Annotated[str, "Name or path of target GameObject (optional)"] | None = None, - attach_as_component: Annotated[bool, "If true and type is MonoBehaviour, attach as component (default: false)"] = False, -) -> dict[str, Any]: - """ - Execute C# code using Unity's RoslynRuntimeCompiler tool with advanced features: - - - MonoBehaviour attachment: Set attach_as_component=true for classes inheriting MonoBehaviour - - Static method execution: Call public static methods (e.g., public static void Run(GameObject host)) - - Coroutine support: Methods returning IEnumerator will be started as coroutines - - History tracking: All compilations are tracked in history for later review - - Supported method signatures: - - public static void Run() - - public static void Run(GameObject host) - - public static void Run(MonoBehaviour host) - - public static IEnumerator RunCoroutine(MonoBehaviour host) - - Example MonoBehaviour: - ```csharp - using UnityEngine; - public class Rotator : MonoBehaviour { - void Update() { - transform.Rotate(Vector3.up * 30f * Time.deltaTime); - } - } - ``` - - Example Static Method: - ```csharp - using UnityEngine; - public class AIGenerated { - public static void Run(GameObject host) { - Debug.Log($"Hello from {host.name}!"); - } - } - ``` - """ - await safe_info(ctx, f"Executing code with RoslynRuntimeCompiler: {class_name}.{method_name}") - - params = { - "action": "execute_with_roslyn", - "code": code, - "class_name": class_name, - "method_name": method_name, - "target_object": target_object, - "attach_as_component": attach_as_component, - } - params = {k: v for k, v in params.items() if v is not None} - - return handle_unity_command("runtime_compilation", params) - - -@mcp_for_unity_tool( - description="Get the compilation history from RoslynRuntimeCompiler showing all previous compilations and executions" -) -async def get_compilation_history( - ctx: Context, -) -> dict[str, Any]: - """ - Retrieve the compilation history from the RoslynRuntimeCompiler. - - History includes: - - Timestamp of each compilation - - Class and method names - - Success/failure status - - Compilation diagnostics - - Target GameObject names - - Source code previews - - This is useful for: - - Reviewing what code has been compiled - - Debugging failed compilations - - Tracking execution flow - - Auditing dynamic code changes - """ - await safe_info(ctx, "Retrieving compilation history...") - - params = {"action": "get_history"} - return handle_unity_command("runtime_compilation", params) - - -@mcp_for_unity_tool( - description="Save the compilation history to a JSON file outside the Assets folder" -) -async def save_compilation_history( - ctx: Context, -) -> dict[str, Any]: - """ - Save all compilation history to a timestamped JSON file. - - The file is saved to: ProjectRoot/RoslynHistory/RoslynHistory_TIMESTAMP.json - - This allows you to: - - Keep a permanent record of dynamic compilations - - Review history after Unity restarts - - Share compilation sessions with team members - - Archive successful code patterns - """ - await safe_info(ctx, "Saving compilation history to file...") - - params = {"action": "save_history"} - return handle_unity_command("runtime_compilation", params) - - -@mcp_for_unity_tool( - description="Clear all compilation history from RoslynRuntimeCompiler" -) -async def clear_compilation_history( - ctx: Context, -) -> dict[str, Any]: - """ - Clear all compilation history entries. - - This removes all tracked compilations from memory but does not delete - saved history files. Use this to start fresh or reduce memory usage. - """ - await safe_info(ctx, "Clearing compilation history...") - - params = {"action": "clear_history"} - return handle_unity_command("runtime_compilation", params) diff --git a/MCPForUnity/Editor/Constants/EditorPrefKeys.cs b/MCPForUnity/Editor/Constants/EditorPrefKeys.cs index 30dcd2b..570e9f9 100644 --- a/MCPForUnity/Editor/Constants/EditorPrefKeys.cs +++ b/MCPForUnity/Editor/Constants/EditorPrefKeys.cs @@ -25,6 +25,9 @@ namespace MCPForUnity.Editor.Constants internal const string UseEmbeddedServer = "MCPForUnity.UseEmbeddedServer"; internal const string LockCursorConfig = "MCPForUnity.LockCursorConfig"; internal const string AutoRegisterEnabled = "MCPForUnity.AutoRegisterEnabled"; + internal const string ToolEnabledPrefix = "MCPForUnity.ToolEnabled."; + internal const string ToolFoldoutStatePrefix = "MCPForUnity.ToolFoldout."; + internal const string EditorWindowActivePanel = "MCPForUnity.EditorWindow.ActivePanel"; internal const string SetupCompleted = "MCPForUnity.SetupCompleted"; internal const string SetupDismissed = "MCPForUnity.SetupDismissed"; diff --git a/MCPForUnity/Editor/Services/IToolDiscoveryService.cs b/MCPForUnity/Editor/Services/IToolDiscoveryService.cs index 01ceb2b..300f00e 100644 --- a/MCPForUnity/Editor/Services/IToolDiscoveryService.cs +++ b/MCPForUnity/Editor/Services/IToolDiscoveryService.cs @@ -13,9 +13,12 @@ namespace MCPForUnity.Editor.Services public List Parameters { get; set; } public string ClassName { get; set; } public string Namespace { get; set; } + public string AssemblyName { get; set; } + public string AssetPath { get; set; } public bool AutoRegister { get; set; } = true; public bool RequiresPolling { get; set; } = false; public string PollAction { get; set; } = "status"; + public bool IsBuiltIn { get; set; } } /// @@ -45,6 +48,21 @@ namespace MCPForUnity.Editor.Services /// ToolMetadata GetToolMetadata(string toolName); + /// + /// Returns only the tools currently enabled for registration + /// + List GetEnabledTools(); + + /// + /// Checks whether a tool is currently enabled for registration + /// + bool IsToolEnabled(string toolName); + + /// + /// Updates the enabled state for a tool + /// + void SetToolEnabled(string toolName, bool enabled); + /// /// Invalidates the tool discovery cache /// diff --git a/MCPForUnity/Editor/Services/ToolDiscoveryService.cs b/MCPForUnity/Editor/Services/ToolDiscoveryService.cs index 0f3406a..0dcfc79 100644 --- a/MCPForUnity/Editor/Services/ToolDiscoveryService.cs +++ b/MCPForUnity/Editor/Services/ToolDiscoveryService.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Text.RegularExpressions; +using MCPForUnity.Editor.Constants; using MCPForUnity.Editor.Helpers; using MCPForUnity.Editor.Tools; using UnityEditor; @@ -11,6 +13,8 @@ namespace MCPForUnity.Editor.Services public class ToolDiscoveryService : IToolDiscoveryService { private Dictionary _cachedTools; + private readonly Dictionary _scriptPathCache = new(); + private readonly Dictionary _summaryCache = new(); public List DiscoverAllTools() { @@ -40,6 +44,7 @@ namespace MCPForUnity.Editor.Services if (metadata != null) { _cachedTools[metadata.Name] = metadata; + EnsurePreferenceInitialized(metadata); } } } @@ -64,6 +69,41 @@ namespace MCPForUnity.Editor.Services return _cachedTools.TryGetValue(toolName, out var metadata) ? metadata : null; } + public List GetEnabledTools() + { + return DiscoverAllTools() + .Where(tool => IsToolEnabled(tool.Name)) + .ToList(); + } + + public bool IsToolEnabled(string toolName) + { + if (string.IsNullOrEmpty(toolName)) + { + return false; + } + + string key = GetToolPreferenceKey(toolName); + if (EditorPrefs.HasKey(key)) + { + return EditorPrefs.GetBool(key, true); + } + + var metadata = GetToolMetadata(toolName); + return metadata?.AutoRegister ?? false; + } + + public void SetToolEnabled(string toolName, bool enabled) + { + if (string.IsNullOrEmpty(toolName)) + { + return; + } + + string key = GetToolPreferenceKey(toolName); + EditorPrefs.SetBool(key, enabled); + } + private ToolMetadata ExtractToolMetadata(Type type, McpForUnityToolAttribute toolAttr) { try @@ -82,7 +122,7 @@ namespace MCPForUnity.Editor.Services // Extract parameters var parameters = ExtractParameters(type); - return new ToolMetadata + var metadata = new ToolMetadata { Name = toolName, Description = description, @@ -90,10 +130,24 @@ namespace MCPForUnity.Editor.Services Parameters = parameters, ClassName = type.Name, Namespace = type.Namespace ?? "", + AssemblyName = type.Assembly.GetName().Name, + AssetPath = ResolveScriptAssetPath(type), AutoRegister = toolAttr.AutoRegister, RequiresPolling = toolAttr.RequiresPolling, PollAction = string.IsNullOrEmpty(toolAttr.PollAction) ? "status" : toolAttr.PollAction }; + + metadata.IsBuiltIn = DetermineIsBuiltIn(type, metadata); + if (metadata.IsBuiltIn) + { + string summaryDescription = ExtractSummaryDescription(type, metadata); + if (!string.IsNullOrWhiteSpace(summaryDescription)) + { + metadata.Description = summaryDescription; + } + } + return metadata; + } catch (Exception ex) { @@ -180,5 +234,173 @@ namespace MCPForUnity.Editor.Services { _cachedTools = null; } + + private void EnsurePreferenceInitialized(ToolMetadata metadata) + { + if (metadata == null || string.IsNullOrEmpty(metadata.Name)) + { + return; + } + + string key = GetToolPreferenceKey(metadata.Name); + if (!EditorPrefs.HasKey(key)) + { + bool defaultValue = metadata.AutoRegister || metadata.IsBuiltIn; + EditorPrefs.SetBool(key, defaultValue); + return; + } + + if (metadata.IsBuiltIn && !metadata.AutoRegister) + { + bool currentValue = EditorPrefs.GetBool(key, metadata.AutoRegister); + if (currentValue == metadata.AutoRegister) + { + EditorPrefs.SetBool(key, true); + } + } + } + + private static string GetToolPreferenceKey(string toolName) + { + return EditorPrefKeys.ToolEnabledPrefix + toolName; + } + + private string ResolveScriptAssetPath(Type type) + { + if (type == null) + { + return null; + } + + if (_scriptPathCache.TryGetValue(type, out var cachedPath)) + { + return cachedPath; + } + + string resolvedPath = null; + + try + { + string filter = string.IsNullOrEmpty(type.Name) ? "t:MonoScript" : $"{type.Name} t:MonoScript"; + var guids = AssetDatabase.FindAssets(filter); + + foreach (var guid in guids) + { + string assetPath = AssetDatabase.GUIDToAssetPath(guid); + if (string.IsNullOrEmpty(assetPath)) + { + continue; + } + + var script = AssetDatabase.LoadAssetAtPath(assetPath); + if (script == null) + { + continue; + } + + var scriptClass = script.GetClass(); + if (scriptClass == type) + { + resolvedPath = assetPath.Replace('\\', '/'); + break; + } + } + } + catch (Exception ex) + { + McpLog.Warn($"Failed to resolve asset path for {type.FullName}: {ex.Message}"); + } + + _scriptPathCache[type] = resolvedPath; + return resolvedPath; + } + + private bool DetermineIsBuiltIn(Type type, ToolMetadata metadata) + { + if (metadata == null) + { + return false; + } + + if (!string.IsNullOrEmpty(metadata.AssetPath)) + { + string normalizedPath = metadata.AssetPath.Replace("\\", "/"); + string packageRoot = AssetPathUtility.GetMcpPackageRootPath(); + + if (!string.IsNullOrEmpty(packageRoot)) + { + string normalizedRoot = packageRoot.Replace("\\", "/"); + if (!normalizedRoot.EndsWith("/", StringComparison.Ordinal)) + { + normalizedRoot += "/"; + } + + string builtInRoot = normalizedRoot + "Editor/Tools/"; + if (normalizedPath.StartsWith(builtInRoot, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + + if (!string.IsNullOrEmpty(metadata.AssemblyName) && metadata.AssemblyName.Equals("MCPForUnity.Editor", StringComparison.Ordinal)) + { + return true; + } + + return false; + } + + private string ExtractSummaryDescription(Type type, ToolMetadata metadata) + { + if (metadata == null || string.IsNullOrEmpty(metadata.AssetPath)) + { + return null; + } + + if (_summaryCache.TryGetValue(metadata.AssetPath, out var cachedSummary)) + { + return cachedSummary; + } + + string summary = null; + + try + { + var monoScript = AssetDatabase.LoadAssetAtPath(metadata.AssetPath); + string scriptText = monoScript?.text; + if (string.IsNullOrEmpty(scriptText)) + { + _summaryCache[metadata.AssetPath] = null; + return null; + } + + string classPattern = $@"///\s*\s*(?[\s\S]*?)\s*\s*(?:\[[^\]]*\]\s*)*(?:public\s+)?(?:static\s+)?class\s+{Regex.Escape(type.Name)}"; + var match = Regex.Match(scriptText, classPattern); + + if (!match.Success) + { + match = Regex.Match(scriptText, @"///\s*\s*(?[\s\S]*?)\s*"); + } + + if (!match.Success) + { + _summaryCache[metadata.AssetPath] = null; + return null; + } + + summary = match.Groups["content"].Value; + summary = Regex.Replace(summary, @"^\s*///\s?", string.Empty, RegexOptions.Multiline); + summary = Regex.Replace(summary, @"<[^>]+>", string.Empty); + summary = Regex.Replace(summary, @"\s+", " ").Trim(); + } + catch (System.Exception ex) + { + McpLog.Warn($"Failed to extract summary description for {type?.FullName}: {ex.Message}"); + } + + _summaryCache[metadata.AssetPath] = summary; + return summary; + } } } diff --git a/MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs b/MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs index 35011a8..0648193 100644 --- a/MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs +++ b/MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs @@ -421,7 +421,8 @@ namespace MCPForUnity.Editor.Services.Transport.Transports { if (_toolDiscoveryService == null) return; - var tools = _toolDiscoveryService.DiscoverAllTools(); + var tools = _toolDiscoveryService.GetEnabledTools(); + McpLog.Info($"[WebSocket] Preparing to register {tools.Count} tool(s) with the bridge."); var toolsArray = new JArray(); foreach (var tool in tools) diff --git a/MCPForUnity/Editor/Tools/CommandRegistry.cs b/MCPForUnity/Editor/Tools/CommandRegistry.cs index 406f84e..2551311 100644 --- a/MCPForUnity/Editor/Tools/CommandRegistry.cs +++ b/MCPForUnity/Editor/Tools/CommandRegistry.cs @@ -248,6 +248,36 @@ namespace MCPForUnity.Editor.Tools return handlerInfo.SyncHandler(@params); } + /// + /// Execute a command handler and return its raw result, regardless of sync or async implementation. + /// Used internally for features like batch execution where commands need to be composed. + /// + /// The registered command to execute. + /// Parameters to pass to the command (optional). + public static Task InvokeCommandAsync(string commandName, JObject @params) + { + var handlerInfo = GetHandlerInfo(commandName); + var payload = @params ?? new JObject(); + + if (handlerInfo.IsAsync) + { + if (handlerInfo.AsyncHandler == null) + { + throw new InvalidOperationException($"Async handler for '{commandName}' is not configured correctly"); + } + + return handlerInfo.AsyncHandler(payload); + } + + if (handlerInfo.SyncHandler == null) + { + throw new InvalidOperationException($"Handler for '{commandName}' does not provide a synchronous implementation"); + } + + object result = handlerInfo.SyncHandler(payload); + return Task.FromResult(result); + } + /// /// Create a delegate for an async handler method that returns Task or Task. /// The delegate will invoke the method and await its completion, returning the result. diff --git a/MCPForUnity/Editor/Tools/ExecuteMenuItem.cs b/MCPForUnity/Editor/Tools/ExecuteMenuItem.cs index 2ce1c84..f606f77 100644 --- a/MCPForUnity/Editor/Tools/ExecuteMenuItem.cs +++ b/MCPForUnity/Editor/Tools/ExecuteMenuItem.cs @@ -7,6 +7,9 @@ using UnityEditor; namespace MCPForUnity.Editor.Tools { [McpForUnityTool("execute_menu_item", AutoRegister = false)] + /// + /// Tool to execute a Unity Editor menu item by its path. + /// public static class ExecuteMenuItem { // Basic blacklist to prevent execution of disruptive menu items. diff --git a/MCPForUnity/Editor/Tools/ManageScript.cs b/MCPForUnity/Editor/Tools/ManageScript.cs index 5e268ca..3745ec7 100644 --- a/MCPForUnity/Editor/Tools/ManageScript.cs +++ b/MCPForUnity/Editor/Tools/ManageScript.cs @@ -26,7 +26,8 @@ namespace MCPForUnity.Editor.Tools { /// /// Handles CRUD operations for C# scripts within the Unity project. - /// + /// + /// /// ROSLYN INSTALLATION GUIDE: /// To enable advanced syntax validation with Roslyn compiler services: /// @@ -49,7 +50,7 @@ namespace MCPForUnity.Editor.Tools /// /// Note: Without Roslyn, the system falls back to basic structural validation. /// Roslyn provides full C# compiler diagnostics with line numbers and detailed error messages. - /// + /// [McpForUnityTool("manage_script", AutoRegister = false)] public static class ManageScript { diff --git a/MCPForUnity/Editor/Tools/Prefabs/ManagePrefabs.cs b/MCPForUnity/Editor/Tools/Prefabs/ManagePrefabs.cs index d30053e..18b4ae0 100644 --- a/MCPForUnity/Editor/Tools/Prefabs/ManagePrefabs.cs +++ b/MCPForUnity/Editor/Tools/Prefabs/ManagePrefabs.cs @@ -10,6 +10,9 @@ using UnityEngine.SceneManagement; namespace MCPForUnity.Editor.Tools.Prefabs { [McpForUnityTool("manage_prefabs", AutoRegister = false)] + /// + /// Tool to manage Unity Prefab stages and create prefabs from GameObjects. + /// public static class ManagePrefabs { private const string SupportedActions = "open_stage, close_stage, save_open_stage, create_from_gameobject"; diff --git a/MCPForUnity/Editor/Windows/Components/Common.uss b/MCPForUnity/Editor/Windows/Components/Common.uss index 4c2f05f..e89e0be 100644 --- a/MCPForUnity/Editor/Windows/Components/Common.uss +++ b/MCPForUnity/Editor/Windows/Components/Common.uss @@ -293,6 +293,75 @@ margin-top: 4px; } +/* Tools Section */ +.tool-actions { + flex-direction: row; + flex-wrap: wrap; + margin-top: 8px; + margin-bottom: 8px; +} + +.tool-action-button { + flex-grow: 1; + min-width: 0; + height: 26px; + margin-bottom: 4px; +} + +.tool-category-container { + flex-direction: column; + margin-top: 8px; +} + +.tool-item { + flex-direction: column; + padding: 8px; + margin-bottom: 8px; + background-color: rgba(0, 0, 0, 0.04); + border-radius: 4px; + border-width: 1px; + border-color: rgba(0, 0, 0, 0.12); +} + +.tool-item-header { + flex-direction: row; + align-items: center; +} + +.tool-item-toggle { + flex-shrink: 0; + min-width: 0; +} + +.tool-tags { + flex-direction: row; + flex-wrap: wrap; + margin-left: auto; + padding-left: 8px; +} + +.tool-tag { + font-size: 10px; + padding: 2px 6px; + margin-left: 4px; + margin-top: 2px; + background-color: rgba(100, 100, 100, 0.25); + border-radius: 3px; + color: rgba(40, 40, 40, 1); +} + +.tool-item-description, +.tool-parameters { + font-size: 11px; + color: rgba(120, 120, 120, 1); + white-space: normal; + margin-top: 4px; +} + +.tool-parameters { + font-style: italic; +} + /* Advanced Settings */ .advanced-settings-foldout { margin-top: 16px; @@ -400,6 +469,22 @@ border-color: rgba(0, 0, 0, 0.15); } +.unity-theme-dark .tool-tag { + color: rgba(220, 220, 220, 1); + background-color: rgba(80, 80, 80, 0.6); +} + +.unity-theme-dark .tool-item { + background-color: rgba(255, 255, 255, 0.04); + border-color: rgba(255, 255, 255, 0.08); +} + +.unity-theme-dark .tool-item-description, +.unity-theme-dark .tool-parameters { + color: rgba(200, 200, 200, 0.8); +} + + .unity-theme-light .validation-description { background-color: rgba(100, 150, 200, 0.1); } diff --git a/CustomTools/RoslynRuntimeCompilation/PythonTools.asset.meta b/MCPForUnity/Editor/Windows/Components/Tools.meta similarity index 52% rename from CustomTools/RoslynRuntimeCompilation/PythonTools.asset.meta rename to MCPForUnity/Editor/Windows/Components/Tools.meta index 58dd3a6..a1165e9 100644 --- a/CustomTools/RoslynRuntimeCompilation/PythonTools.asset.meta +++ b/MCPForUnity/Editor/Windows/Components/Tools.meta @@ -1,8 +1,8 @@ fileFormatVersion: 2 -guid: a3b463767742cdf43b366f68a656e42e -NativeFormatImporter: +guid: c2f853b1b3974f829a2cc09d52d3d7ad +folderAsset: yes +DefaultImporter: externalObjects: {} - mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant: diff --git a/MCPForUnity/Editor/Windows/Components/Tools/McpToolsSection.cs b/MCPForUnity/Editor/Windows/Components/Tools/McpToolsSection.cs new file mode 100644 index 0000000..b6fc2b4 --- /dev/null +++ b/MCPForUnity/Editor/Windows/Components/Tools/McpToolsSection.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using MCPForUnity.Editor.Constants; +using MCPForUnity.Editor.Helpers; +using MCPForUnity.Editor.Services; +using UnityEditor; +using UnityEngine.UIElements; + +namespace MCPForUnity.Editor.Windows.Components.Tools +{ + /// + /// Controller for the Tools section inside the MCP For Unity editor window. + /// Provides discovery, filtering, and per-tool enablement toggles. + /// + public class McpToolsSection + { + private readonly Dictionary toolToggleMap = new(); + private Label summaryLabel; + private Label noteLabel; + private Button enableAllButton; + private Button disableAllButton; + private Button rescanButton; + private VisualElement categoryContainer; + private List allTools = new(); + + public VisualElement Root { get; } + + public McpToolsSection(VisualElement root) + { + Root = root; + CacheUIElements(); + RegisterCallbacks(); + } + + private void CacheUIElements() + { + summaryLabel = Root.Q