2025-11-28 06:18:44 +08:00
using System ;
using System.Collections.Generic ;
using System.IO ;
using System.Runtime.InteropServices ;
using MCPForUnity.Editor.Constants ;
using MCPForUnity.Editor.Helpers ;
using MCPForUnity.Editor.Models ;
using MCPForUnity.Editor.Services ;
using Newtonsoft.Json ;
using Newtonsoft.Json.Linq ;
using UnityEditor ;
using UnityEngine ;
namespace MCPForUnity.Editor.Clients
{
/// <summary>Shared base class for MCP configurators.</summary>
public abstract class McpClientConfiguratorBase : IMcpClientConfigurator
{
protected readonly McpClient client ;
protected McpClientConfiguratorBase ( McpClient client )
{
this . client = client ;
}
internal McpClient Client = > client ;
public string Id = > client . name . Replace ( " " , "" ) . ToLowerInvariant ( ) ;
public virtual string DisplayName = > client . name ;
public McpStatus Status = > client . status ;
public virtual bool SupportsAutoConfigure = > true ;
public virtual string GetConfigureActionLabel ( ) = > "Configure" ;
public abstract string GetConfigPath ( ) ;
public abstract McpStatus CheckStatus ( bool attemptAutoRewrite = true ) ;
public abstract void Configure ( ) ;
public abstract string GetManualSnippet ( ) ;
public abstract IList < string > GetInstallationSteps ( ) ;
protected string GetUvxPathOrError ( )
{
string uvx = MCPServiceLocator . Paths . GetUvxPath ( ) ;
if ( string . IsNullOrEmpty ( uvx ) )
{
throw new InvalidOperationException ( "uv not found. Install uv/uvx or set the override in Advanced Settings." ) ;
}
return uvx ;
}
protected string CurrentOsPath ( )
{
if ( RuntimeInformation . IsOSPlatform ( OSPlatform . Windows ) )
return client . windowsConfigPath ;
if ( RuntimeInformation . IsOSPlatform ( OSPlatform . OSX ) )
return client . macConfigPath ;
return client . linuxConfigPath ;
}
protected bool UrlsEqual ( string a , string b )
{
if ( string . IsNullOrWhiteSpace ( a ) | | string . IsNullOrWhiteSpace ( b ) )
{
return false ;
}
if ( Uri . TryCreate ( a . Trim ( ) , UriKind . Absolute , out var uriA ) & &
Uri . TryCreate ( b . Trim ( ) , UriKind . Absolute , out var uriB ) )
{
return Uri . Compare (
uriA ,
uriB ,
UriComponents . HttpRequestUrl ,
UriFormat . SafeUnescaped ,
StringComparison . OrdinalIgnoreCase ) = = 0 ;
}
string Normalize ( string value ) = > value . Trim ( ) . TrimEnd ( '/' ) ;
return string . Equals ( Normalize ( a ) , Normalize ( b ) , StringComparison . OrdinalIgnoreCase ) ;
}
}
/// <summary>JSON-file based configurator (Cursor, Windsurf, VS Code, etc.).</summary>
public abstract class JsonFileMcpConfigurator : McpClientConfiguratorBase
{
public JsonFileMcpConfigurator ( McpClient client ) : base ( client ) { }
public override string GetConfigPath ( ) = > CurrentOsPath ( ) ;
public override McpStatus CheckStatus ( bool attemptAutoRewrite = true )
{
try
{
string path = GetConfigPath ( ) ;
if ( ! File . Exists ( path ) )
{
client . SetStatus ( McpStatus . NotConfigured ) ;
return client . status ;
}
string configJson = File . ReadAllText ( path ) ;
string [ ] args = null ;
string configuredUrl = null ;
bool configExists = false ;
if ( client . IsVsCodeLayout )
{
var vsConfig = JsonConvert . DeserializeObject < JToken > ( configJson ) as JObject ;
if ( vsConfig ! = null )
{
var unityToken =
vsConfig [ "servers" ] ? [ "unityMCP" ]
? ? vsConfig [ "mcp" ] ? [ "servers" ] ? [ "unityMCP" ] ;
if ( unityToken is JObject unityObj )
{
configExists = true ;
var argsToken = unityObj [ "args" ] ;
if ( argsToken is JArray )
{
args = argsToken . ToObject < string [ ] > ( ) ;
}
var urlToken = unityObj [ "url" ] ? ? unityObj [ "serverUrl" ] ;
if ( urlToken ! = null & & urlToken . Type ! = JTokenType . Null )
{
configuredUrl = urlToken . ToString ( ) ;
}
}
}
}
else
{
McpConfig standardConfig = JsonConvert . DeserializeObject < McpConfig > ( configJson ) ;
if ( standardConfig ? . mcpServers ? . unityMCP ! = null )
{
args = standardConfig . mcpServers . unityMCP . args ;
configExists = true ;
}
}
if ( ! configExists )
{
client . SetStatus ( McpStatus . MissingConfig ) ;
return client . status ;
}
bool matches = false ;
if ( args ! = null & & args . Length > 0 )
{
string expectedUvxUrl = AssetPathUtility . GetMcpServerGitUrl ( ) ;
string configuredUvxUrl = McpConfigurationHelper . ExtractUvxUrl ( args ) ;
matches = ! string . IsNullOrEmpty ( configuredUvxUrl ) & &
McpConfigurationHelper . PathsEqual ( configuredUvxUrl , expectedUvxUrl ) ;
}
else if ( ! string . IsNullOrEmpty ( configuredUrl ) )
{
string expectedUrl = HttpEndpointUtility . GetMcpRpcUrl ( ) ;
matches = UrlsEqual ( configuredUrl , expectedUrl ) ;
}
if ( matches )
{
client . SetStatus ( McpStatus . Configured ) ;
return client . status ;
}
if ( attemptAutoRewrite )
{
var result = McpConfigurationHelper . WriteMcpConfiguration ( path , client ) ;
if ( result = = "Configured successfully" )
{
client . SetStatus ( McpStatus . Configured ) ;
}
else
{
client . SetStatus ( McpStatus . IncorrectPath ) ;
}
}
else
{
client . SetStatus ( McpStatus . IncorrectPath ) ;
}
}
catch ( Exception ex )
{
client . SetStatus ( McpStatus . Error , ex . Message ) ;
}
return client . status ;
}
public override void Configure ( )
{
string path = GetConfigPath ( ) ;
McpConfigurationHelper . EnsureConfigDirectoryExists ( path ) ;
string result = McpConfigurationHelper . WriteMcpConfiguration ( path , client ) ;
if ( result = = "Configured successfully" )
{
client . SetStatus ( McpStatus . Configured ) ;
}
else
{
throw new InvalidOperationException ( result ) ;
}
}
public override string GetManualSnippet ( )
{
try
{
string uvx = GetUvxPathOrError ( ) ;
return ConfigJsonBuilder . BuildManualConfigJson ( uvx , client ) ;
}
catch ( Exception ex )
{
var errorObj = new { error = ex . Message } ;
return JsonConvert . SerializeObject ( errorObj ) ;
}
}
public override IList < string > GetInstallationSteps ( ) = > new List < string > { "Configuration steps not available for this client." } ;
}
/// <summary>Codex (TOML) configurator.</summary>
public abstract class CodexMcpConfigurator : McpClientConfiguratorBase
{
public CodexMcpConfigurator ( McpClient client ) : base ( client ) { }
public override string GetConfigPath ( ) = > CurrentOsPath ( ) ;
public override McpStatus CheckStatus ( bool attemptAutoRewrite = true )
{
try
{
string path = GetConfigPath ( ) ;
if ( ! File . Exists ( path ) )
{
client . SetStatus ( McpStatus . NotConfigured ) ;
return client . status ;
}
string toml = File . ReadAllText ( path ) ;
if ( CodexConfigHelper . TryParseCodexServer ( toml , out _ , out var args , out var url ) )
{
bool matches = false ;
if ( ! string . IsNullOrEmpty ( url ) )
{
matches = UrlsEqual ( url , HttpEndpointUtility . GetMcpRpcUrl ( ) ) ;
}
else if ( args ! = null & & args . Length > 0 )
{
string expected = AssetPathUtility . GetMcpServerGitUrl ( ) ;
string configured = McpConfigurationHelper . ExtractUvxUrl ( args ) ;
matches = ! string . IsNullOrEmpty ( configured ) & &
McpConfigurationHelper . PathsEqual ( configured , expected ) ;
}
if ( matches )
{
client . SetStatus ( McpStatus . Configured ) ;
return client . status ;
}
}
if ( attemptAutoRewrite )
{
string result = McpConfigurationHelper . ConfigureCodexClient ( path , client ) ;
if ( result = = "Configured successfully" )
{
client . SetStatus ( McpStatus . Configured ) ;
}
else
{
client . SetStatus ( McpStatus . IncorrectPath ) ;
}
}
else
{
client . SetStatus ( McpStatus . IncorrectPath ) ;
}
}
catch ( Exception ex )
{
client . SetStatus ( McpStatus . Error , ex . Message ) ;
}
return client . status ;
}
public override void Configure ( )
{
string path = GetConfigPath ( ) ;
McpConfigurationHelper . EnsureConfigDirectoryExists ( path ) ;
string result = McpConfigurationHelper . ConfigureCodexClient ( path , client ) ;
if ( result = = "Configured successfully" )
{
client . SetStatus ( McpStatus . Configured ) ;
}
else
{
throw new InvalidOperationException ( result ) ;
}
}
public override string GetManualSnippet ( )
{
try
{
string uvx = GetUvxPathOrError ( ) ;
return CodexConfigHelper . BuildCodexServerBlock ( uvx ) ;
}
catch ( Exception ex )
{
return $"# error: {ex.Message}" ;
}
}
public override IList < string > GetInstallationSteps ( ) = > new List < string >
{
"Run 'codex config edit' or open the config path" ,
"Paste the TOML" ,
"Save and restart Codex"
} ;
}
/// <summary>CLI-based configurator (Claude Code).</summary>
public abstract class ClaudeCliMcpConfigurator : McpClientConfiguratorBase
{
public ClaudeCliMcpConfigurator ( McpClient client ) : base ( client ) { }
public override bool SupportsAutoConfigure = > true ;
public override string GetConfigureActionLabel ( ) = > client . status = = McpStatus . Configured ? "Unregister" : "Register" ;
public override string GetConfigPath ( ) = > "Managed via Claude CLI" ;
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
/// <summary>
/// Checks the Claude CLI registration status.
/// MUST be called from the main Unity thread due to EditorPrefs and Application.dataPath access.
/// </summary>
2025-11-28 06:18:44 +08:00
public override McpStatus CheckStatus ( bool attemptAutoRewrite = true )
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
{
// Capture main-thread-only values before delegating to thread-safe method
string projectDir = Path . GetDirectoryName ( Application . dataPath ) ;
bool useHttpTransport = EditorPrefs . GetBool ( EditorPrefKeys . UseHttpTransport , true ) ;
// Resolve claudePath on the main thread (EditorPrefs access)
string claudePath = MCPServiceLocator . Paths . GetClaudeCliPath ( ) ;
return CheckStatusWithProjectDir ( projectDir , useHttpTransport , claudePath , attemptAutoRewrite ) ;
}
/// <summary>
/// Internal thread-safe version of CheckStatus.
/// Can be called from background threads because all main-thread-only values are passed as parameters.
/// projectDir, useHttpTransport, and claudePath are REQUIRED (non-nullable) to enforce thread safety at compile time.
/// </summary>
internal McpStatus CheckStatusWithProjectDir ( string projectDir , bool useHttpTransport , string claudePath , bool attemptAutoRewrite = true )
2025-11-28 06:18:44 +08:00
{
try
{
if ( string . IsNullOrEmpty ( claudePath ) )
{
client . SetStatus ( McpStatus . NotConfigured , "Claude CLI not found" ) ;
return client . status ;
}
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
// projectDir is required - no fallback to Application.dataPath
if ( string . IsNullOrEmpty ( projectDir ) )
{
throw new ArgumentNullException ( nameof ( projectDir ) , "Project directory must be provided for thread-safe execution" ) ;
}
2025-11-28 06:18:44 +08:00
string pathPrepend = null ;
if ( Application . platform = = RuntimePlatform . OSXEditor )
{
pathPrepend = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" ;
}
else if ( Application . platform = = RuntimePlatform . LinuxEditor )
{
pathPrepend = "/usr/local/bin:/usr/bin:/bin" ;
}
try
{
string claudeDir = Path . GetDirectoryName ( claudePath ) ;
if ( ! string . IsNullOrEmpty ( claudeDir ) )
{
pathPrepend = string . IsNullOrEmpty ( pathPrepend )
? claudeDir
: $"{claudeDir}:{pathPrepend}" ;
}
}
catch { }
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
// Check if UnityMCP exists
if ( ExecPath . TryRun ( claudePath , "mcp list" , projectDir , out var listStdout , out var listStderr , 10000 , pathPrepend ) )
2025-11-28 06:18:44 +08:00
{
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
if ( ! string . IsNullOrEmpty ( listStdout ) & & listStdout . IndexOf ( "UnityMCP" , StringComparison . OrdinalIgnoreCase ) > = 0 )
2025-11-28 06:18:44 +08:00
{
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
// UnityMCP is registered - now verify transport mode matches
// useHttpTransport parameter is required (non-nullable) to ensure thread safety
bool currentUseHttp = useHttpTransport ;
// Get detailed info about the registration to check transport type
if ( ExecPath . TryRun ( claudePath , "mcp get UnityMCP" , projectDir , out var getStdout , out var getStderr , 7000 , pathPrepend ) )
{
// Parse the output to determine registered transport mode
// The CLI output format contains "Type: http" or "Type: stdio"
bool registeredWithHttp = getStdout . Contains ( "Type: http" , StringComparison . OrdinalIgnoreCase ) ;
bool registeredWithStdio = getStdout . Contains ( "Type: stdio" , StringComparison . OrdinalIgnoreCase ) ;
// Check for transport mismatch
if ( ( currentUseHttp & & registeredWithStdio ) | | ( ! currentUseHttp & & registeredWithHttp ) )
{
string registeredTransport = registeredWithHttp ? "HTTP" : "stdio" ;
string currentTransport = currentUseHttp ? "HTTP" : "stdio" ;
string errorMsg = $"Transport mismatch: Claude Code is registered with {registeredTransport} but current setting is {currentTransport}. Click Configure to re-register." ;
client . SetStatus ( McpStatus . Error , errorMsg ) ;
McpLog . Warn ( errorMsg ) ;
return client . status ;
}
}
2025-11-28 06:18:44 +08:00
client . SetStatus ( McpStatus . Configured ) ;
return client . status ;
}
}
client . SetStatus ( McpStatus . NotConfigured ) ;
}
catch ( Exception ex )
{
client . SetStatus ( McpStatus . Error , ex . Message ) ;
}
return client . status ;
}
public override void Configure ( )
{
if ( client . status = = McpStatus . Configured )
{
Unregister ( ) ;
}
else
{
Register ( ) ;
}
}
private void Register ( )
{
var pathService = MCPServiceLocator . Paths ;
string claudePath = pathService . GetClaudeCliPath ( ) ;
if ( string . IsNullOrEmpty ( claudePath ) )
{
throw new InvalidOperationException ( "Claude CLI not found. Please install Claude Code first." ) ;
}
bool useHttpTransport = EditorPrefs . GetBool ( EditorPrefKeys . UseHttpTransport , true ) ;
string args ;
if ( useHttpTransport )
{
string httpUrl = HttpEndpointUtility . GetMcpRpcUrl ( ) ;
args = $"mcp add --transport http UnityMCP {httpUrl}" ;
}
else
{
var ( uvxPath , gitUrl , packageName ) = AssetPathUtility . GetUvxCommandParts ( ) ;
2025-12-29 12:57:57 +08:00
bool devForceRefresh = GetDevModeForceRefresh ( ) ;
string devFlags = devForceRefresh ? "--no-cache --refresh " : string . Empty ;
args = $"mcp add --transport stdio UnityMCP -- \" { uvxPath } \ " {devFlags}--from \"{gitUrl}\" {packageName}" ;
2025-11-28 06:18:44 +08:00
}
string projectDir = Path . GetDirectoryName ( Application . dataPath ) ;
string pathPrepend = null ;
if ( Application . platform = = RuntimePlatform . OSXEditor )
{
pathPrepend = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" ;
}
else if ( Application . platform = = RuntimePlatform . LinuxEditor )
{
pathPrepend = "/usr/local/bin:/usr/bin:/bin" ;
}
try
{
string claudeDir = Path . GetDirectoryName ( claudePath ) ;
if ( ! string . IsNullOrEmpty ( claudeDir ) )
{
pathPrepend = string . IsNullOrEmpty ( pathPrepend )
? claudeDir
: $"{claudeDir}:{pathPrepend}" ;
}
}
catch { }
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
// Check if UnityMCP already exists and remove it first to ensure clean registration
// This ensures we always use the current transport mode setting
bool serverExists = ExecPath . TryRun ( claudePath , "mcp get UnityMCP" , projectDir , out _ , out _ , 7000 , pathPrepend ) ;
if ( serverExists )
2025-11-28 06:18:44 +08:00
{
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
McpLog . Info ( "Existing UnityMCP registration found - removing to ensure transport mode is up-to-date" ) ;
if ( ! ExecPath . TryRun ( claudePath , "mcp remove UnityMCP" , projectDir , out var removeStdout , out var removeStderr , 10000 , pathPrepend ) )
2025-11-28 06:18:44 +08:00
{
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
McpLog . Warn ( $"Failed to remove existing UnityMCP registration: {removeStderr}. Attempting to register anyway..." ) ;
2025-11-28 06:18:44 +08:00
}
}
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
// Now add the registration with the current transport mode
if ( ! ExecPath . TryRun ( claudePath , args , projectDir , out var stdout , out var stderr , 15000 , pathPrepend ) )
2025-11-28 06:18:44 +08:00
{
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
throw new InvalidOperationException ( $"Failed to register with Claude Code:\n{stderr}\n{stdout}" ) ;
2025-11-28 06:18:44 +08:00
}
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
McpLog . Info ( $"Successfully registered with Claude Code using {(useHttpTransport ? " HTTP " : " stdio ")} transport." ) ;
// Set status to Configured immediately after successful registration
// The UI will trigger an async verification check separately to avoid blocking
client . SetStatus ( McpStatus . Configured ) ;
2025-11-28 06:18:44 +08:00
}
private void Unregister ( )
{
var pathService = MCPServiceLocator . Paths ;
string claudePath = pathService . GetClaudeCliPath ( ) ;
if ( string . IsNullOrEmpty ( claudePath ) )
{
throw new InvalidOperationException ( "Claude CLI not found. Please install Claude Code first." ) ;
}
string projectDir = Path . GetDirectoryName ( Application . dataPath ) ;
string pathPrepend = null ;
if ( Application . platform = = RuntimePlatform . OSXEditor )
{
pathPrepend = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" ;
}
else if ( Application . platform = = RuntimePlatform . LinuxEditor )
{
pathPrepend = "/usr/local/bin:/usr/bin:/bin" ;
}
bool serverExists = ExecPath . TryRun ( claudePath , "mcp get UnityMCP" , projectDir , out _ , out _ , 7000 , pathPrepend ) ;
if ( ! serverExists )
{
client . SetStatus ( McpStatus . NotConfigured ) ;
McpLog . Info ( "No MCP for Unity server found - already unregistered." ) ;
return ;
}
if ( ExecPath . TryRun ( claudePath , "mcp remove UnityMCP" , projectDir , out var stdout , out var stderr , 10000 , pathPrepend ) )
{
McpLog . Info ( "MCP server successfully unregistered from Claude Code." ) ;
}
else
{
throw new InvalidOperationException ( $"Failed to unregister: {stderr}" ) ;
}
client . SetStatus ( McpStatus . NotConfigured ) ;
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
// Status is already set - no need for blocking CheckStatus() call
2025-11-28 06:18:44 +08:00
}
public override string GetManualSnippet ( )
{
string uvxPath = MCPServiceLocator . Paths . GetUvxPath ( ) ;
bool useHttpTransport = EditorPrefs . GetBool ( EditorPrefKeys . UseHttpTransport , true ) ;
if ( useHttpTransport )
{
string httpUrl = HttpEndpointUtility . GetMcpRpcUrl ( ) ;
return "# Register the MCP server with Claude Code:\n" +
$"claude mcp add --transport http UnityMCP {httpUrl}\n\n" +
"# Unregister the MCP server:\n" +
"claude mcp remove UnityMCP\n\n" +
"# List registered servers:\n" +
"claude mcp list # Only works when claude is run in the project's directory" ;
}
if ( string . IsNullOrEmpty ( uvxPath ) )
{
return "# Error: Configuration not available - check paths in Advanced Settings" ;
}
string gitUrl = AssetPathUtility . GetMcpServerGitUrl ( ) ;
2025-12-29 12:57:57 +08:00
bool devForceRefresh = GetDevModeForceRefresh ( ) ;
string devFlags = devForceRefresh ? "--no-cache --refresh " : string . Empty ;
2025-11-28 06:18:44 +08:00
return "# Register the MCP server with Claude Code:\n" +
2025-12-29 12:57:57 +08:00
$"claude mcp add --transport stdio UnityMCP -- \" { uvxPath } \ " {devFlags}--from \"{gitUrl}\" mcp-for-unity\n\n" +
2025-11-28 06:18:44 +08:00
"# Unregister the MCP server:\n" +
"claude mcp remove UnityMCP\n\n" +
"# List registered servers:\n" +
"claude mcp list # Only works when claude is run in the project's directory" ;
}
2025-12-29 12:57:57 +08:00
private static bool GetDevModeForceRefresh ( )
{
try { return EditorPrefs . GetBool ( EditorPrefKeys . DevModeForceServerRefresh , false ) ; }
catch { return false ; }
}
2025-11-28 06:18:44 +08:00
public override IList < string > GetInstallationSteps ( ) = > new List < string >
{
"Ensure Claude CLI is installed" ,
"Use Register to add UnityMCP (or run claude mcp add UnityMCP)" ,
"Restart Claude Code"
} ;
}
}