How to Troubleshoot Common Unity MCP Errors: A Complete Guide
All Unity MCP tools return an ErrorResponse object instead of throwing exceptions, allowing you to diagnose connection, compilation, and API issues by inspecting the error field and correlating it with specific source files.
Unity MCP (Model Context Protocol) bridges AI assistants and the Unity editor through a strict "no-exception-leak" policy. When you troubleshoot common Unity MCP errors, you are typically dealing with structured ErrorResponse objects that originate from specific tools in the CoplayDev/unity-mcp repository. Understanding the error-handling architecture and the specific validation logic in tools like UnityReflect.cs and PortManager.cs enables rapid diagnosis of everything from compilation-state conflicts to port binding failures.
Understanding the Unity MCP Error Architecture
The bridge implements a layered error-handling strategy where failures are captured and wrapped rather than propagated as raw exceptions.
At the foundation, C# Editor tools in MCPForUnity/Editor/Tools/* (such as UnityReflect.cs, RefreshUnity.cs, and RunTests.cs) validate inputs and Unity state before executing operations. When validation fails, these tools return new ErrorResponse("msg", data) rather than throwing. This ErrorResponse class is defined in MCPForUnity/Editor/Helpers/Response.cs and implements the IMcpResponse interface, ensuring consistent serialization to JSON for transport across the MCP protocol.
The Python MCP server deserializes these responses and exposes them as dictionary-like objects with an error key, while the client side (Claude, Cursor, etc.) renders the error field to the user interface. This architecture ensures that domain reloads, compilation locks, or transport failures never crash the Unity process.
Common Unity MCP Error Categories and Solutions
Invalid or Missing Parameters
Errors like "Parameters cannot be null." or "Action is required" indicate that the tool received a malformed payload. In MCPForUnity/Editor/Tools/UnityReflect.cs, tools explicitly check if (params == null) early in execution and return an ErrorResponse immediately.
Fix: Verify that the JSON payload sent from your AI client matches the tool’s signature exactly. Cross-reference the expected parameters with the @mcp_for_unity_tool decorator docstrings on the Python side or the C# method signatures in the Editor tools.
Unity Compilation and Domain-Reload State
The error "Cannot reflect while Unity is compiling. Wait for domain reload to complete." originates from UnityReflect.cs at line 103, which checks EditorApplication.isCompiling before invoking reflection operations.
Fix: Implement a polling mechanism or wait for the Compilation Finished callback before sending the request. You can verify Unity’s state by querying EditorApplication.isCompiling in your client logic before dispatching MCP commands.
File-System and I/O Failures
Symptoms like IOException: Connection closed while reading line (Stdio transport) or DirectoryNotFoundException indicate transport layer discontinuities. The StdioBridgeReconnectTests.cs file at line 169 simulates these broken pipe scenarios to test resilience.
Fix: Ensure the Unity process is running and the bridge binary has read/write permissions to the transport streams. Confirm that your client configuration specifies the correct transport protocol (STDIO vs HTTP) and that the client_id matches the active Unity instance.
Port and Network Conflicts
SocketException errors or "Connection refused" messages indicate that the HTTP server cannot bind to its configured port. The MCPForUnity/Editor/Helpers/PortManager.cs handles port allocation and raises these exceptions when the default port 5666 is already occupied.
Fix: Check for port conflicts using your system’s network tools, or change the binding port via the MCP Setup window in Unity. Alternatively, set the MCP_PORT environment variable before launching the editor to use a non-standard port.
Version Compatibility and Missing Unity APIs
MissingMethodException or "API may have changed" errors occur when tools attempt to use Unity APIs that differ across versions. The MemorySnapshotOps.cs file at line 78 guards against these changes by wrapping reflection failures in ErrorResponse objects. The compatibility layer in MCPForUnity/Runtime/Helpers/UnityCompatShims.cs provides shims for supported Unity versions.
Fix: Verify you are running a Unity version supported by the bridge. If you recently upgraded Unity, run tools/check-unity-versions.sh to detect shim mismatches and API changes that require bridge updates.
Practical Debugging Workflow for Unity MCP
Use this C# snippet to intercept and inspect ErrorResponse objects within the Unity editor:
// 1️⃣ Inspect the raw response in the client console
Debug.Log($"MCP reply: {responseJson}");
// 2️⃣ If it’s an ErrorResponse, deserialize and read the `error` field
var reply = JsonUtility.FromJson<Dictionary<string, object>>(responseJson);
if (reply.TryGetValue("error", out var errObj))
{
Debug.LogError($"MCP error: {errObj}");
// Optionally break into the Unity editor for live inspection
UnityEditor.EditorApplication.isPaused = true;
}
// 3️⃣ Correlate the error message with the source
// Example: "Cannot reflect while Unity is compiling"
if (errObj is string msg && msg.Contains("compiling"))
{
// Wait for compilation to finish
EditorApplication.update += WaitForCompilation;
}
// Helper
void WaitForCompilation()
{
if (!EditorApplication.isCompiling)
{
EditorApplication.update -= WaitForCompilation;
// retry the original request here
}
}
Python client side (example with requests):
import json, requests
def call_tool(tool, params):
payload = {"tool": tool, "params": params}
r = requests.post("http://localhost:5666/api/mcp", json=payload)
data = r.json()
if "error" in data:
print("MCP error:", data["error"])
# raise or retry depending on the error type
else:
return data["result"]
Key Source Files to Reference
Bookmark these locations in the CoplayDev/unity-mcp repository to accelerate troubleshooting:
MCPForUnity/Editor/Helpers/Response.cs– CoreErrorResponseandSuccessResponsedefinitionsMCPForUnity/Editor/Tools/UnityReflect.cs– Reflection tool with parameter validation and compilation state checksMCPForUnity/Editor/Windows/Components/Tools/McpToolsSection.cs– UI component that rendersErrorResponse.Errorto usersTestProjects/UnityMCPTests/Assets/Tests/EditMode/Services/StdioBridgeReconnectTests.cs– Simulated StdIO transport failures for testing reconnection logicMCPForUnity/Editor/Helpers/PortManager.cs– Port allocation logic and conflict detectionMCPForUnity/Runtime/Helpers/UnityCompatShims.cs– Compatibility layer for Unity version differencestools/check-unity-versions.sh– CI script that validates compilation against supported Unity versions
Summary
- All errors are
ErrorResponseobjects: Unity MCP never throws exceptions; it returns structured error responses that serialize to JSON. - Check compilation state first: Many reflection tools fail explicitly when
EditorApplication.isCompilingis true. - Validate transport configuration: Distinguish between STDIO pipe failures and HTTP port conflicts by checking
PortManager.csand transport settings. - Correlate messages with source: Search the exact error string in the repository to locate the originating tool (e.g.,
UnityReflect.cs). - Maintain version compatibility: Use
UnityCompatShims.csand runcheck-unity-versions.shafter upgrading Unity to prevent API mismatch errors.
Frequently Asked Questions
What is an ErrorResponse in Unity MCP?
An ErrorResponse is a concrete implementation of IMcpResponse defined in MCPForUnity/Editor/Helpers/Response.cs. It wraps error messages and optional data objects into a JSON-serializable format that travels from the C# Editor tools through the Python server to your AI client, ensuring the Unity process remains stable even when operations fail.
How do I fix "Cannot reflect while Unity is compiling" errors?
This error originates from UnityReflect.cs at line 103 when EditorApplication.isCompiling returns true. Wait for the domain reload to complete by polling EditorApplication.isCompiling in your client code, or subscribe to the Compilation Finished callback before retrying the reflection request.
Why am I getting port conflicts with Unity MCP?
The default port 5666 is likely in use by another process. The PortManager.cs file handles port allocation and will raise a SocketException on binding failure. Change the port in the MCP Setup window or set the MCP_PORT environment variable before launching Unity to use an available port.
How do I verify Unity version compatibility with the MCP bridge?
Check MCPForUnity/Runtime/Helpers/UnityCompatShims.cs for the compatibility layer implementations, and run tools/check-unity-versions.sh to compile the bridge against your specific Unity version. If you encounter MissingMethodException errors in MemorySnapshotOps.cs or similar files, the shim layer likely needs updates for your Unity version.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →