diff --git a/CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs b/CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs
index c5b6daab..799341b2 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 @@ public static object HandleCommand(JObject @params)
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 @@ public static object HandleCommand(JObject @params)
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 @@ private static object CompileAndLoad(JObject @params)
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 @@ private static object CompileAndLoad(JObject @params)
// 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 @@ private static object CompileAndLoad(JObject @params)
// 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 @@ private static object CompileAndLoad(JObject @params)
})
.ToList();
- return Response.Error("Compilation failed", new
+ return new ErrorResponse("Compilation failed", new
{
errors = errors,
error_count = errors.Count
@@ -222,7 +208,7 @@ private static object CompileAndLoad(JObject @params)
}
}
- 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 @@ private static object CompileAndLoad(JObject @params)
}
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 @@ private static object CompileAndLoad(JObject @params)
}
#endif
}
-
+
private static object ListLoadedAssemblies()
{
var assemblies = LoadedAssemblies.Values.Select(info => new
@@ -254,33 +240,26 @@ private static object ListLoadedAssemblies()
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 @@ private static object GetAssemblyTypes(JObject @params)
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 @@ private static object ExecuteWithRoslyn(JObject @params)
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 @@ private static object ExecuteWithRoslyn(JObject @params)
if (targetObject == null)
{
- return Response.Error($"Target GameObject '{targetObjectName}' not found");
+ return new ErrorResponse($"Target GameObject '{targetObjectName}' not found");
}
}
@@ -352,7 +331,7 @@ out string errorMessage
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 @@ out string errorMessage
}
else
{
- return Response.Error($"Execution failed: {errorMessage}", new
+ return new ErrorResponse($"Execution failed: {errorMessage}", new
{
diagnostics = compiler.lastCompileDiagnostics
});
@@ -371,7 +350,7 @@ out string errorMessage
}
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 @@ private static object GetCompilationHistory()
: 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 @@ private static object GetCompilationHistory()
}
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 @@ private static object SaveCompilationHistory()
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 @@ private static object SaveCompilationHistory()
}
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 @@ private static object ClearCompilationHistory()
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 91d05d5b..00000000
--- 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 977b9f71..00000000
--- 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 30dcd2bb..570e9f9d 100644
--- a/MCPForUnity/Editor/Constants/EditorPrefKeys.cs
+++ b/MCPForUnity/Editor/Constants/EditorPrefKeys.cs
@@ -25,6 +25,9 @@ internal static class EditorPrefKeys
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 01ceb2b6..300f00e0 100644
--- a/MCPForUnity/Editor/Services/IToolDiscoveryService.cs
+++ b/MCPForUnity/Editor/Services/IToolDiscoveryService.cs
@@ -13,9 +13,12 @@ public class ToolMetadata
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 @@ public interface IToolDiscoveryService
///
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 0f3406a1..0dcfc79b 100644
--- a/MCPForUnity/Editor/Services/ToolDiscoveryService.cs
+++ b/MCPForUnity/Editor/Services/ToolDiscoveryService.cs
@@ -2,6 +2,8 @@
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 @@ public List DiscoverAllTools()
if (metadata != null)
{
_cachedTools[metadata.Name] = metadata;
+ EnsurePreferenceInitialized(metadata);
}
}
}
@@ -64,6 +69,41 @@ public ToolMetadata GetToolMetadata(string toolName)
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 @@ private ToolMetadata ExtractToolMetadata(Type type, McpForUnityToolAttribute too
// Extract parameters
var parameters = ExtractParameters(type);
- return new ToolMetadata
+ var metadata = new ToolMetadata
{
Name = toolName,
Description = description,
@@ -90,10 +130,24 @@ private ToolMetadata ExtractToolMetadata(Type type, McpForUnityToolAttribute too
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 @@ public void InvalidateCache()
{
_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 35011a80..0648193e 100644
--- a/MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs
+++ b/MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs
@@ -421,7 +421,8 @@ private async Task SendRegisterToolsAsync(CancellationToken token)
{
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/BatchExecute.cs b/MCPForUnity/Editor/Tools/BatchExecute.cs
new file mode 100644
index 00000000..655d196a
--- /dev/null
+++ b/MCPForUnity/Editor/Tools/BatchExecute.cs
@@ -0,0 +1,130 @@
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using MCPForUnity.Editor.Helpers;
+using Newtonsoft.Json.Linq;
+
+namespace MCPForUnity.Editor.Tools
+{
+ ///
+ /// Executes multiple MCP commands within a single Unity-side handler. Commands are executed sequentially
+ /// on the main thread to preserve determinism and Unity API safety.
+ ///
+ [McpForUnityTool("batch_execute", AutoRegister = false)]
+ public static class BatchExecute
+ {
+ private const int MaxCommandsPerBatch = 25;
+
+ public static async Task