Class McpToolRegistry
Central registry for managing MCP tools with automatic discovery and runtime registration. Provides discovery of attribute-decorated tools and dynamic tool registration at runtime.
Inherited Members
Namespace: Unity.AI.MCP.Editor.ToolRegistry
Assembly: Unity.AI.MCP.Editor.dll
Syntax
public static class McpToolRegistry
Remarks
The registry automatically discovers tools at editor startup using Unity's TypeCache system:
- Static methods marked with [McpTool]
- Classes implementing IUnityMcpTool or IUnityMcpTool<T> marked with [McpTool]
Tools can also be registered dynamically at runtime using RegisterTool(string, IUnityMcpTool, string, bool, string[]) methods. Dynamic tools override attribute-discovered tools with the same name.
Tool Discovery:
- Triggered automatically via [InitializeOnLoadMethod]
- Can be manually refreshed with RefreshTools()
- Discovers across all assemblies in the project
Thread Safety: All operations should be called from Unity's main thread.
Examples
Registering a tool at runtime:
public class MyToolParams
{
public string Name { get; set; }
}
public class MyTool : IUnityMcpTool<MyToolParams>
{
public object Execute(MyToolParams parameters)
{
return new { result = $"Hello " };
}
}
// Register at runtime (e.g., in an InitializeOnLoadMethod)
McpToolRegistry.RegisterTool("my_runtime_tool", new MyTool(), "A dynamically registered tool");
Methods
ExecuteToolAsync(string, JObject)
Executes a registered tool asynchronously by name with the provided parameters.
Declaration
public static Task<object> ExecuteToolAsync(string toolName, JObject parameters)
Parameters
| Type | Name | Description |
|---|---|---|
| string | toolName | The unique name of the tool to execute |
| JObject | parameters | Tool parameters as a Newtonsoft.Json.Linq.JObject, or null for parameterless tools |
Returns
| Type | Description |
|---|---|
| Task<object> | A task containing the tool's return value, which can be any object that will be serialized to JSON |
Remarks
This is the main entry point for tool execution. Parameters are provided as a JObject and automatically deserialized to the tool's expected parameter type.
The tool is executed asynchronously, allowing async tools to run without blocking. Exceptions thrown by tools are unwrapped from TargetInvocationException for clearer error messages.
Exceptions
| Type | Condition |
|---|---|
| ArgumentException | Thrown if toolName is null/empty or if the tool is not found in the registry |
| Exception | Rethrows any exception thrown by the tool during execution |
GetAllToolsForSettings()
Returns every registered tool with its current enabled state and default flag, bypassing any programmatic filters. Intended for the settings UI.
Declaration
public static ToolSettingsEntry[] GetAllToolsForSettings()
Returns
| Type | Description |
|---|---|
| ToolSettingsEntry[] | An array of ToolSettingsEntry describing all registered tools with their current enabled state. |
GetAvailableTools(bool)
Gets information about all available tools for MCP clients, including schemas and descriptions.
Declaration
public static McpToolInfo[] GetAvailableTools(bool ignoreEnabledState = false)
Parameters
| Type | Name | Description |
|---|---|---|
| bool | ignoreEnabledState | If true, returns all tools; if false (default), only returns enabled tools |
Returns
| Type | Description |
|---|---|
| McpToolInfo[] | Array of McpToolInfo objects describing each available tool |
Remarks
Returns tool metadata suitable for sending to MCP clients, including:
- Tool name, title, and description
- Input and output JSON schemas
- MCP annotations
By default, only tools enabled in settings are returned. Set ignoreEnabledState to true to get all registered tools regardless of their enabled state.
Results are sorted alphabetically by tool name.
HasTool(string)
Checks whether a tool with the specified name exists in the registry.
Declaration
public static bool HasTool(string toolName)
Parameters
| Type | Name | Description |
|---|---|---|
| string | toolName | The name of the tool to check for |
Returns
| Type | Description |
|---|---|
| bool | true if the tool exists in the registry; otherwise, false |
Initialize()
Initializes the registry by discovering all tools marked with [McpTool] attribute. Called automatically at editor startup via [InitializeOnLoadMethod].
Declaration
[InitializeOnLoadMethod]
public static void Initialize()
Remarks
You typically don't need to call this directly. It's invoked automatically when the editor loads. If you need to rediscover tools after making changes, use RefreshTools() instead.
NotifyToolAvailabilityChanged(string)
Notifies subscribers that a tool's availability has changed without modifying the registry. Use this when a tool's enabled state changes in settings.
Declaration
public static void NotifyToolAvailabilityChanged(string toolName)
Parameters
| Type | Name | Description |
|---|---|---|
| string | toolName | The name of the tool whose availability changed |
Remarks
This is a lightweight notification that doesn't trigger tool rediscovery. It triggers a ToolsChanged event with Updated.
Use this when:
- A tool is enabled/disabled in project settings
- A tool's behavior changes dynamically
- You need to notify MCP clients to refresh their tool list
RefreshTools()
Refreshes the tool registry by rediscovering all tools from scratch. Clears existing tools and performs a fresh discovery scan across all assemblies.
Declaration
public static void RefreshTools()
Remarks
Call this when:
- After assembly reloads or script compilation
- When external tools are added to the project
- To force a re-scan of available tools
This will trigger a ToolsChanged event with Refreshed. Dynamically registered tools will be cleared and need to be re-registered.
RegisterTool(string, IUnityMcpTool, string, bool, string[])
Registers a tool instance dynamically at runtime without requiring attribute decoration. Dynamically registered tools override attribute-discovered tools with the same name.
Declaration
public static void RegisterTool(string toolName, IUnityMcpTool toolInstance, string description = null, bool enabledByDefault = false, string[] groups = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | toolName | Unique name for the tool (must not be null or empty) |
| IUnityMcpTool | toolInstance | Tool instance implementing IUnityMcpTool (must not be null) |
| string | description | Human-readable description of what the tool does (if null, a default description is generated) |
| bool | enabledByDefault | Whether this tool should be enabled by default when no user override exists |
| string[] | groups | Optional category groups for organizing the tool in the settings UI |
Remarks
Use this method to register tools programmatically, such as:
- Tools generated or configured at runtime
- Tools from external plugins or packages
- Tools that need to adapt based on project settings
The tool instance will be reused for all executions (singleton pattern). Triggers a ToolsChanged event with Added or Updated.
To unregister, call UnregisterTool(string). Note: Dynamically registered tools are cleared when RefreshTools() is called.
Examples
[InitializeOnLoadMethod]
static void RegisterCustomTool()
{
var tool = new MyCustomTool();
McpToolRegistry.RegisterTool(
"custom_tool",
tool,
"Performs custom operations based on project settings"
);
}
Exceptions
| Type | Condition |
|---|---|
| ArgumentException | Thrown if toolName is null or empty |
| ArgumentNullException | Thrown if toolInstance is null |
RegisterTool<TParams>(string, IUnityMcpTool<TParams>, string, bool, string[])
Registers a tool instance with strongly-typed parameters dynamically at runtime. This variant provides automatic schema generation from the parameter type.
Declaration
public static void RegisterTool<TParams>(string toolName, IUnityMcpTool<TParams> toolInstance, string description = null, bool enabledByDefault = false, string[] groups = null) where TParams : class
Parameters
| Type | Name | Description |
|---|---|---|
| string | toolName | Unique name for the tool (must not be null or empty) |
| IUnityMcpTool<TParams> | toolInstance | Tool instance implementing IUnityMcpTool<TParams> (must not be null) |
| string | description | Human-readable description of what the tool does (if null, a default description is generated) |
| bool | enabledByDefault | Whether this tool should be enabled by default when no user override exists |
| string[] | groups | Optional category groups for organizing the tool in the settings UI |
Type Parameters
| Name | Description |
|---|---|
| TParams | The strongly-typed parameter class. Must be a reference type with a parameterless constructor |
Remarks
Prefer this overload when your tool uses typed parameters, as it provides:
- Automatic JSON schema generation from
TParams - Type safety without manual casting
- Better IntelliSense support
The parameter type should have public properties decorated with McpDescriptionAttribute for comprehensive schema documentation.
Triggers a ToolsChanged event with Added or Updated.
Examples
public class SearchParams
{
[McpDescription("Search query", Required = true)]
public string Query { get; set; }
[McpDescription("Maximum results to return")]
public int Limit { get; set; } = 10;
}
public class SearchTool : IUnityMcpTool<SearchParams>
{
public object Execute(SearchParams parameters)
{
// Perform search with parameters.Query and parameters.Limit
return new { results = new[] { "result1", "result2" } };
}
}
[InitializeOnLoadMethod]
static void RegisterSearchTool()
{
McpToolRegistry.RegisterTool("search", new SearchTool(), "Searches the project");
}
Exceptions
| Type | Condition |
|---|---|
| ArgumentException | Thrown if toolName is null or empty |
| ArgumentNullException | Thrown if toolInstance is null |
SanitizeToolName(string)
Sanitize a tool name for cross-provider compatibility. OpenAI requires tool names to match ^[a-zA-Z0-9_-]+$ (no periods allowed).
Declaration
public static string SanitizeToolName(string name)
Parameters
| Type | Name | Description |
|---|---|---|
| string | name | The tool name to sanitize. |
Returns
| Type | Description |
|---|---|
| string | The sanitized tool name with periods replaced by underscores, or null if |
UnregisterTool(string)
Unregisters a dynamically registered tool, removing it from the registry.
Declaration
public static bool UnregisterTool(string toolName)
Parameters
| Type | Name | Description |
|---|---|---|
| string | toolName | The name of the tool to remove |
Returns
| Type | Description |
|---|---|
| bool | true if the tool was found and removed; false if the tool was not found |
Remarks
This only removes dynamically registered tools added via RegisterTool(string, IUnityMcpTool, string, bool, string[]) methods. Attribute-discovered tools will be re-added when RefreshTools() is called.
Triggers a ToolsChanged event with Removed if the tool existed.
Events
ToolsChanged
Event fired when the tool registry changes (tools added, removed, updated, or refreshed). Subscribe to this event to respond to tool availability changes.
Declaration
public static event Action<McpToolRegistry.ToolChangeEventArgs> ToolsChanged
Event Type
| Type | Description |
|---|---|
| Action<McpToolRegistry.ToolChangeEventArgs> |
Remarks
This event is useful for:
- Notifying MCP clients about tool changes
- Updating UI displays of available tools
- Invalidating cached tool lists
The event is fired on Unity's main thread.