### Install UnityNaturalMCP Package Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Installs the UnityNaturalMCP package and its dependencies (com.cysharp.unitask, System.Text.Json, ModelContextProtocol, Microsoft.Extensions.DependencyInjection) using the Unity Package Manager's `manifest.json` file or NuGetForUnity. ```json // Packages/manifest.json { "dependencies": { "jp.notargs.unity-natural-mcp": "https://github.com/notargs/UnityNaturalMCP.git?path=/UnityNaturalMCPServer", "com.cysharp.unitask": "2.5.0", "other-packages": "..." } } // Also install via NuGetForUnity: // - System.Text.Json 9.0.x // - ModelContextProtocol 0.2.x (enable "Show Prerelease") // - Microsoft.Extensions.DependencyInjection 9.0.x ``` -------------------------------- ### Internal HTTP Server Startup and Request Flow (C#) Source: https://context7.com/notargs/unitynaturalmcp/llms.txt This C# code snippet demonstrates the internal startup of the HTTP listener for UnityNaturalMCP and outlines the request flow for handling JSON-RPC 2.0 requests. It involves adding a prefix to the listener, starting the listener, and describes the path a request takes from the client to the server and back through pipes. Dependencies include the .NET `HttpListener` class. ```csharp var mcpEntPoint = $"http://{ipAddress}:{port}/mcp/"; httpListener.Prefixes.Add(mcpEntPoint); httpListener.Start(); // Request flow: // 1. MCP Client -> HTTP POST to /mcp endpoint // 2. HTTP Handler -> Pipe (clientToServerPipe) // 3. MCP Server processes request // 4. Response -> Pipe (serverToClientPipe) // 5. HTTP Handler -> Response to client // Example raw HTTP request: // POST http://localhost:56780/mcp/ // Content-Type: application/json // // {"jsonrpc":"2.0","method":"tools/call","params":{"name":"RefreshAssets","arguments":{}},"id":1} // Example response: // {"jsonrpc":"2.0","result":{"content":[{"type":"text","text":"Assets refreshed"}]},"id":1} ``` -------------------------------- ### Unity Package Manifest Configuration Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This JSON snippet shows how to add the UnityNaturalMCP package to your Unity project's manifest.json file for installation via the Unity Package Manager (UPM). Ensure you have UniTask and NugetForUnity installed beforehand. ```json { "dependencies": { "jp.notargs.unity-natural-mcp": "https://github.com/notargs/UnityNaturalMCP.git?path=/UnityNaturalMCPServer" } } ``` -------------------------------- ### MCP Tool Asynchronous Processing Example Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This C# code illustrates asynchronous processing for an MCP tool, essential when interacting with Unity's API from non-main threads. It uses `UniTask` for thread switching and delaying, ensuring proper execution context and returning a `ValueTask`. ```csharp [McpServerTool, Description("Example of asynchronous processing")] public async ValueTask AsyncMethod() { await UniTask.SwitchToMainThread(); await UniTask.Delay(1000); return "Finished async processing"; } ``` -------------------------------- ### Create Custom MCP Tools in C# Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Defines and registers custom MCP tools using C# with attributes like McpServerToolType and McpServerTool, and leverages dependency injection. Tools are discovered and registered via ScriptableObject builders. The example shows creating a GameManagerTool and its corresponding builder. ```csharp // Step 1: Define the MCP tool using System.ComponentModel; using ModelContextProtocol.Server; using Cysharp.Threading.Tasks; using UnityEngine; [McpServerToolType, Description("Custom game management tools")] public class GameManagerTool { [McpServerTool, Description("Generate new level configuration")] public async ValueTask GenerateLevel( [Description("Level difficulty (1-10)")] int difficulty, [Description("Level theme")] string theme) { try { await UniTask.SwitchToMainThread(); // Your custom logic here var config = $"Generated level: Theme={theme}, Difficulty={difficulty}"; Debug.Log(config); return config; } catch (Exception e) { Debug.LogError(e); throw; } } } // Step 2: Create builder ScriptableObject using Microsoft.Extensions.DependencyInjection; using UnityEngine; using UnityNaturalMCP.Editor; [CreateAssetMenu(fileName = "GameManagerToolBuilder", menuName = "UnityNaturalMCP/Game Manager Tool Builder")] public class GameManagerToolBuilder : McpBuilderScriptableObject { public override void Build(IMcpServerBuilder builder) { builder.WithTools(); } } // Step 3: Create the ScriptableObject asset in Unity // Right-click in Project window > Create > UnityNaturalMCP > Game Manager Tool Builder // Then: Edit > Project Settings > Unity Natural MCP > Refresh ``` -------------------------------- ### MCP Tool Error Handling Example Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This C# code demonstrates robust error handling within an MCP tool. It uses a try-catch block to log exceptions using `Debug.LogError` and then rethrows the exception, ensuring that errors are captured and propagated correctly. ```csharp [McpServerTool, Description("Example of error-returning process")] public async void ErrorMethod() { try { throw new Exception("This is an error example"); } catch (Exception e) { Debug.LogError(e); throw; } } ``` -------------------------------- ### Get Unity Compilation Logs (MCP Client) Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Specialized method to clear the console and retrieve only compilation-related logs (errors and warnings). It's equivalent to calling ClearConsoleLogs() followed by GetCurrentConsoleLogs() with compile-specific filters. Returns filtered compilation results. ```json // Usage from MCP client GetCompileLogs( filter: "", maxCount: 20, onlyFirstLine: true, isChronological: false ) // Returns filtered compilation results: // [ // { "Condition": "Assets/Scripts/GameManager.cs(15,25): error CS0246: The type or namespace name 'UnityEngine' could not be found", "Type": "compile-error" }, // { "Condition": "Assets/Scripts/UI/Menu.cs(8,10): warning CS0649: Field is never assigned to", "Type": "compile-warning" } // ] ``` -------------------------------- ### Get Unity Console Logs with Filters (MCP Client) Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Retrieves Unity console logs with options for filtering by log type, regex matching, count limits, and chronological sorting. Optimized for reduced token usage with sensible defaults. Returns a list of LogEntry objects. ```json // Get last 20 compile errors only GetCurrentConsoleLogs( logTypes: ["compile-error"], maxCount: 20, onlyFirstLine: true ) // Get all warnings with specific filter GetCurrentConsoleLogs( logTypes: ["warning"], filter: "NullReferenceException", maxCount: 50, onlyFirstLine: false, isChronological: true ) // Returns: List // [ // { "Condition": "Assets/Scripts/Player.cs(42,15): error CS001: Identifier expected", "Type": "compile-error" }, // { "Condition": "NullReferenceException: Object reference not set", "Type": "error" } // ] ``` -------------------------------- ### GitHub Copilot VSCode Configuration for Unity Natural MCP Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This JSON configuration snippet sets up the connection for GitHub Copilot (VSCode) to the Unity Natural MCP server. It specifies the URL for the mcp service, typically running on localhost. ```json { "servers": { "unity-natural-mcp": { "url": "http://localhost:56780/mcp" } } } ``` -------------------------------- ### Configure GitHub Copilot / VSCode Client Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Sets up VSCode to connect to UnityNaturalMCP via streamable HTTP by configuring the MCP configuration file located at `.vscode/mcp.json`. ```json // .vscode/mcp.json { "servers": { "unity-natural-mcp": { "url": "http://localhost:56780/mcp" } } } ``` -------------------------------- ### Cursor Configuration for Unity Natural MCP via stdio Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This configuration is for Cursor, which requires connecting via stdio due to lack of Streamable HTTP support. It specifies the command and arguments to run the mcp-stdio-to-streamable-http executable, along with environment variables for the MCP server IP and port. ```json { "mcpServers": { "unity-natural-mcp": { "command": "node", "args": ["path/to/mcp-stdio-to-streamable-http/dist/index.js"], "env": { "MCP_SERVER_IP": "localhost", "MCP_SERVER_PORT": "56780" } } } } ``` -------------------------------- ### Configure Cursor Client with stdio relay Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Configures the Cursor IDE to connect via the `mcp-stdio-to-streamable-http` relay server for stdio-based MCP clients. This involves setting up the `mcp.json` file in the `.cursor` directory with the necessary command and arguments. ```json // .cursor/mcp.json { "mcpServers": { "unity-natural-mcp": { "command": "node", "args": ["/path/to/mcp-stdio-to-streamable-http/dist/index.js"], "env": { "MCP_SERVER_IP": "localhost", "MCP_SERVER_PORT": "56780" } } } } ``` -------------------------------- ### Configure MCP Server Settings Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Configures MCP server settings such as IP address, port, logging, and default tools via Unity's Project Settings. The configuration is stored in `ProjectSettings/UnityNaturalMCPSetting.asset`. Programmatic access to settings is also provided. ```json // Configuration stored in ProjectSettings/UnityNaturalMCPSetting.asset { "ipAddress": "localhost", // Use "*" for WSL2 mirror mode "port": 56780, // Default: 56780 (ASCII for "CP") "showMcpServerLog": true, // Enable server logging "enableDefaultMcpTools": true // Load built-in MCP tools } ``` ```csharp // Access settings programmatically using UnityNaturalMCP.Editor; var settings = MCPSetting.instance; Debug.Log($"MCP Server running on {settings.ipAddress}:{settings.port}"); settings.port = 12345; settings.Save(); ``` -------------------------------- ### Register MCP with Claude Code CLI Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Registers the UnityNaturalMCP server with Claude Code using the command-line interface to enable direct HTTP communication. Includes commands for adding, verifying, and removing the MCP server configuration. ```bash # Register MCP server with Claude Code claude mcp add -s project --transport http unity-natural-mcp http://localhost:56780/mcp # Verify configuration claude mcp list # Remove if needed claude mcp remove unity-natural-mcp ``` -------------------------------- ### Register MCP Server with Claude Code Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This command registers the UnityNaturalMCP server with Claude Code. It specifies the project transport as 'http' and provides the local URL where the UnityNaturalMCP server is running. Replace the port if you have configured a different one. ```shell claude mcp add -s project --transport http unity-natural-mcp http://localhost:56780/mcp ``` -------------------------------- ### UnityNaturalMCP APIs Source: https://context7.com/notargs/unitynaturalmcp/llms.txt This section details the available API endpoints for interacting with Unity Editor through the UnityNaturalMCP server. ```APIDOC ## RefreshAssets ### Description Executes Unity's AssetDatabase.Refresh() to reimport modified assets and compile scripts. This tool is essential after any file system changes or script modifications to ensure Unity recognizes the updates. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **method** (string) - Required - The method name, should be "RefreshAssets". - **params** (object) - Optional - Arguments for the method, if any. ### Request Example ```json { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "RefreshAssets", "arguments": {} }, "id": 1 } ``` ### Response #### Success Response (200) - **result** (object) - Contains the result of the operation. - **content** (array) - An array of content parts, typically text. #### Response Example ```json { "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "Assets refreshed successfully." } ] }, "id": 1 } ``` ``` ```APIDOC ## GetCurrentConsoleLogs ### Description Retrieves Unity console logs with advanced filtering options including log type filtering, regex matching, count limits, and chronological sorting. Optimized to reduce token usage with sensible defaults. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **method** (string) - Required - The method name, should be "GetCurrentConsoleLogs". - **params** (object) - Required - Arguments for the method. - **logTypes** (array) - Optional - Filters logs by type (e.g., "compile-error", "warning", "error"). - **maxCount** (integer) - Optional - Maximum number of logs to retrieve. - **onlyFirstLine** (boolean) - Optional - If true, only returns the first line of each log message. - **isChronological** (boolean) - Optional - If true, sorts logs chronologically. - **filter** (string) - Optional - A string or regex to filter log messages by content. ### Request Example ```json { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "GetCurrentConsoleLogs", "arguments": { "logTypes": ["compile-error"], "maxCount": 20, "onlyFirstLine": true } }, "id": 1 } ``` ### Response #### Success Response (200) - **result** (object) - Contains the result of the operation. - **content** (array) - An array of log entries. - **Condition** (string) - The log message content. - **Type** (string) - The type of log (e.g., "compile-error", "warning"). #### Response Example ```json { "jsonrpc": "2.0", "result": { "content": [ { "Condition": "Assets/Scripts/Player.cs(42,15): error CS001: Identifier expected", "Type": "compile-error" }, { "Condition": "NullReferenceException: Object reference not set", "Type": "error" } ] }, "id": 1 } ``` ``` ```APIDOC ## GetCompileLogs ### Description Specialized method that clears console and retrieves only compilation-related logs (errors and warnings). Equivalent to calling ClearConsoleLogs() followed by GetCurrentConsoleLogs() with compile-specific filters. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **method** (string) - Required - The method name, should be "GetCompileLogs". - **params** (object) - Required - Arguments for the method. - **filter** (string) - Optional - A string or regex to filter compilation log messages by content. - **maxCount** (integer) - Optional - Maximum number of logs to retrieve. - **onlyFirstLine** (boolean) - Optional - If true, only returns the first line of each log message. - **isChronological** (boolean) - Optional - If true, sorts logs chronologically. ### Request Example ```json { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "GetCompileLogs", "arguments": { "maxCount": 20, "onlyFirstLine": true } }, "id": 1 } ``` ### Response #### Success Response (200) - **result** (object) - Contains the result of the operation. - **content** (array) - An array of compilation log entries. - **Condition** (string) - The log message content. - **Type** (string) - The type of log (e.g., "compile-error", "compile-warning"). #### Response Example ```json { "jsonrpc": "2.0", "result": { "content": [ { "Condition": "Assets/Scripts/GameManager.cs(15,25): error CS0246: The type or namespace name 'UnityEngine' could not be found", "Type": "compile-error" }, { "Condition": "Assets/Scripts/UI/Menu.cs(8,10): warning CS0649: Field is never assigned to", "Type": "compile-warning" } ] }, "id": 1 } ``` ``` ```APIDOC ## ClearConsoleLogs ### Description Clears all logs from the Unity Console window. Useful before running operations where you want to capture only new log output. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **method** (string) - Required - The method name, should be "ClearConsoleLogs". - **params** (object) - Optional - Arguments for the method, if any. ### Request Example ```json { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "ClearConsoleLogs", "arguments": {} }, "id": 1 } ``` ### Response #### Success Response (200) - **result** (object) - Contains the result of the operation. - **content** (array) - An array of content parts, typically text indicating success. #### Response Example ```json { "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "Console cleared successfully" } ] }, "id": 1 } ``` ``` ```APIDOC ## RunEditModeTests ### Description Executes Unity Test Runner tests in Edit Mode with filtering by assembly names, categories, groups (regex), or specific test names. Recommended to filter tests to narrow scope and reduce execution time. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **method** (string) - Required - The method name, should be "RunEditModeTests". - **params** (object) - Required - Arguments for the method. - **assemblyNames** (array) - Optional - Filters tests by assembly names. - **categoryNames** (array) - Optional - Filters tests by category names. - **groupNames** (array) - Optional - Filters tests by group names (can use regex). - **testNames** (array) - Optional - Filters tests by specific test names. ### Request Example ```json { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "RunEditModeTests", "arguments": { "assemblyNames": ["MyGame.Tests.Editor"] } }, "id": 1 } ``` ### Response #### Success Response (200) - **result** (object) - Contains the result of the operation. - **content** (string) - A string summarizing the test results (e.g., "Passed: 15, Failed: 2, Skipped: 1"). #### Response Example ```json { "jsonrpc": "2.0", "result": { "content": "Passed: 15, Failed: 2, Skipped: 1\n Failed Tests:\n - EditorTests.TestAssetValidation: Expected 5 but was 3\n - EditorTests.TestSceneSetup: NullReferenceException" }, "id": 1 } ``` ``` -------------------------------- ### Run Unity Play Mode Tests Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Executes Unity Test Runner tests in Play Mode with filtering by assembly, category, group, or test name. Requires domain reload to be disabled in Project Settings for stable connections. Returns a summary string of test results. ```csharp // Run all Play Mode tests in assembly RunPlayModeTests( assemblyNames: ["MyGame.Tests.PlayMode"], categoryNames: null, groupNames: null, testNames: null ) // Run tests by category RunPlayModeTests( categoryNames: ["Integration", "Physics"], assemblyNames: null, groupNames: null, testNames: null ) // Returns: // "Passed: 42, Failed: 0, Skipped: 3 // All tests passed successfully!" ``` -------------------------------- ### POST /mcp/ Source: https://context7.com/notargs/unitynaturalmcp/llms.txt The UnityNaturalMCP HTTP server listens for JSON-RPC 2.0 requests on the /mcp/ endpoint. It receives requests via HTTP POST, processes them using an internal pipe-based stream to the MCP C# SDK, and returns the result. ```APIDOC ## POST /mcp/ ### Description Handles incoming JSON-RPC 2.0 requests from AI tools and forwards them to the MCP C# SDK for processing within the Unity Editor. ### Method POST ### Endpoint /mcp/ ### Parameters #### Header Parameters - **Content-Type** (string) - Required - Must be `application/json`. #### Request Body - **jsonrpc** (string) - Required - The JSON-RPC version, must be "2.0". - **method** (string) - Required - The method to be called (e.g., `tools/call`). - **params** (object) - Optional - Parameters for the method call. - **name** (string) - Required - The name of the tool or function to execute (e.g., `RefreshAssets`). - **arguments** (object) - Optional - Arguments for the tool/function. - **id** (integer) - Required - A unique identifier for the request. ### Request Example ```json { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "RefreshAssets", "arguments": {} }, "id": 1 } ``` ### Response #### Success Response (200) - **jsonrpc** (string) - The JSON-RPC version, will be "2.0". - **result** (object) - The result of the method execution. - **content** (array) - An array of content objects returned by the tool/function. - **type** (string) - The type of content (e.g., `text`). - **text** (string) - The actual text content. - **id** (integer) - The identifier for the request. #### Response Example ```json { "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "Assets refreshed" } ] }, "id": 1 } ``` ``` -------------------------------- ### Configure WSL2 Networking for Unity Natural MCP Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This configuration enables mirror mode for WSL2 networking, allowing communication between WSL2 and the host OS via localhost. It requires modifying the `.wslconfig` file. A workaround for C# server binding issues involves setting the IP Address to '*' in Unity's Project Settings. ```ini [wsl2] networkingMode=mirrored ``` -------------------------------- ### Create Custom MCP Tool in C# Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This C# code defines a custom MCP tool using the MCP C# SDK. It includes attributes to mark the class and methods as MCP tools, along with descriptions for documentation purposes. This forms the basis for extending Unity Natural MCP functionality. ```csharp using System.ComponentModel; using ModelContextProtocol.Server; [McpServerToolType, Description("Description of custom MCP tool")] public class MyCustomMCPTool { [McpServerTool, Description("Method description")] public string MyMethod() { return "Hello from Unity!"; } } ``` -------------------------------- ### Gemini CLI Configuration for Unity Natural MCP Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This JSON configuration enables Streamable HTTP for the Gemini CLI to connect to the Unity Natural MCP server. It specifies the HTTP URL, allowing for communication with the MCP server, potentially on a custom port. ```json { "mcpServers": { "httpServer": { "httpUrl": "http://localhost:56780/mcp" } } } ``` -------------------------------- ### Create MCP Tool Builder ScriptableObject Source: https://github.com/notargs/unitynaturalmcp/blob/main/README.md This C# script defines a ScriptableObject that inherits from McpBuilderScriptableObject. It is used to register custom MCP tools with the MCP server by implementing the Build method, which configures the MCP server builder. ```csharp using Microsoft.Extensions.DependencyInjection; using UnityEngine; using UnityNaturalMCP.Editor; [CreateAssetMenu(fileName = "MyCustomMCPToolBuilder", menuName = "UnityNaturalMCP/My Custom Tool Builder")] public class MyCustomMCPToolBuilder : McpBuilderScriptableObject { public override void Build(IMcpServerBuilder builder) { builder.WithTools(); } } ``` -------------------------------- ### Run Unity Edit Mode Tests with Filters (MCP Client) Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Executes Unity Test Runner tests in Edit Mode. Allows filtering by assembly names, categories, groups (regex), or specific test names. Recommended to filter tests to narrow scope and reduce execution time. Returns a summary of test results. ```json // Run tests from specific assembly RunEditModeTests( assemblyNames: ["MyGame.Tests.Editor"], categoryNames: null, groupNames: null, testNames: null ) // Run specific namespace using regex RunEditModeTests( assemblyNames: null, groupNames: ["^MyGame\.Editor\.Tests\."], categoryNames: null, testNames: null ) // Run specific test RunEditModeTests( testNames: ["EditorTests.TestScriptGeneration"], assemblyNames: null, categoryNames: null, groupNames: null ) // Returns test results: // "Passed: 15, Failed: 2, Skipped: 1 // Failed Tests: // - EditorTests.TestAssetValidation: Expected 5 but was 3 // - EditorTests.TestSceneSetup: NullReferenceException" ``` -------------------------------- ### Refresh Unity Assets with C# Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Executes Unity's AssetDatabase.Refresh() to reimport modified assets and compile scripts. This is essential after file system changes to ensure Unity recognizes updates. It requires the UnityEditor and ModelContextProtocol.Server namespaces and runs on the main thread. ```csharp using System.ComponentModel; using ModelContextProtocol.Server; using Cysharp.Threading.Tasks; using UnityEditor; [McpServerToolType, Description("Control Unity Editor tools")] public class MyEditorTool { [McpServerTool, Description("Execute AssetDatabase.Refresh")] public async ValueTask RefreshAssets() { try { await UniTask.SwitchToMainThread(); AssetDatabase.Refresh(); } catch (Exception e) { Debug.LogError(e); throw; } } } ``` -------------------------------- ### Clear Unity Console Logs via HTTP POST (curl) Source: https://context7.com/notargs/unitynaturalmcp/llms.txt Clears all logs from the Unity Console window using an HTTP POST request to the MCP server. This is useful before capturing new log output. The request specifies the 'ClearConsoleLogs' method. ```bash curl -X POST http://localhost:56780/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "ClearConsoleLogs", "arguments": {} }, "id": 1 }' // Response: // { // "jsonrpc": "2.0", // "result": { // "content": [{"type": "text", "text": "Console cleared successfully"}] // }, // "id": 1 // } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.