unity-mcp/MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs

621 lines
24 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MCPForUnity.Editor.Constants;
using MCPForUnity.Editor.Helpers;
using MCPForUnity.Editor.Services;
using MCPForUnity.Editor.Windows.Components.Advanced;
using MCPForUnity.Editor.Windows.Components.ClientConfig;
using MCPForUnity.Editor.Windows.Components.Connection;
using MCPForUnity.Editor.Windows.Components.Resources;
using MCPForUnity.Editor.Windows.Components.Tools;
using MCPForUnity.Editor.Windows.Components.Validation;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace MCPForUnity.Editor.Windows
{
public class MCPForUnityEditorWindow : EditorWindow
{
// Section controllers
private McpConnectionSection connectionSection;
private McpClientConfigSection clientConfigSection;
private McpValidationSection validationSection;
private McpAdvancedSection advancedSection;
private McpToolsSection toolsSection;
private McpResourcesSection resourcesSection;
// UI Elements
private Label versionLabel;
private VisualElement updateNotification;
private Label updateNotificationText;
private ToolbarToggle clientsTabToggle;
private ToolbarToggle validationTabToggle;
private ToolbarToggle advancedTabToggle;
private ToolbarToggle toolsTabToggle;
private ToolbarToggle resourcesTabToggle;
private VisualElement clientsPanel;
private VisualElement validationPanel;
private VisualElement advancedPanel;
private VisualElement toolsPanel;
private VisualElement resourcesPanel;
private static readonly HashSet<MCPForUnityEditorWindow> OpenWindows = new();
private bool guiCreated = false;
private bool toolsLoaded = false;
private bool resourcesLoaded = false;
private double lastRefreshTime = 0;
private const double RefreshDebounceSeconds = 0.5;
private enum ActivePanel
{
Clients,
Validation,
Advanced,
Tools,
Resources
}
internal static void CloseAllWindows()
{
var windows = OpenWindows.Where(window => window != null).ToArray();
foreach (var window in windows)
{
window.Close();
}
}
public static void ShowWindow()
{
var window = GetWindow<MCPForUnityEditorWindow>("MCP For Unity");
window.minSize = new Vector2(500, 340);
}
// Helper to check and manage open windows from other classes
public static bool HasAnyOpenWindow()
{
return OpenWindows.Count > 0;
}
public static void CloseAllOpenWindows()
{
if (OpenWindows.Count == 0)
return;
// Copy to array to avoid modifying the collection while iterating
var arr = new MCPForUnityEditorWindow[OpenWindows.Count];
OpenWindows.CopyTo(arr);
foreach (var window in arr)
{
try
{
window?.Close();
}
catch (Exception ex)
{
McpLog.Warn($"Error closing MCP window: {ex.Message}");
}
}
}
public void CreateGUI()
{
// Guard against repeated CreateGUI calls (e.g., domain reloads)
if (guiCreated)
return;
string basePath = AssetPathUtility.GetMcpPackageRootPath();
// Load main window UXML
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{basePath}/Editor/Windows/MCPForUnityEditorWindow.uxml"
);
if (visualTree == null)
{
McpLog.Error(
$"Failed to load UXML at: {basePath}/Editor/Windows/MCPForUnityEditorWindow.uxml"
);
return;
}
visualTree.CloneTree(rootVisualElement);
// Load main window USS
var mainStyleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(
$"{basePath}/Editor/Windows/MCPForUnityEditorWindow.uss"
);
if (mainStyleSheet != null)
{
rootVisualElement.styleSheets.Add(mainStyleSheet);
}
// Load common USS
var commonStyleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(
$"{basePath}/Editor/Windows/Components/Common.uss"
);
if (commonStyleSheet != null)
{
rootVisualElement.styleSheets.Add(commonStyleSheet);
}
// Cache UI elements
versionLabel = rootVisualElement.Q<Label>("version-label");
updateNotification = rootVisualElement.Q<VisualElement>("update-notification");
updateNotificationText = rootVisualElement.Q<Label>("update-notification-text");
clientsPanel = rootVisualElement.Q<VisualElement>("clients-panel");
validationPanel = rootVisualElement.Q<VisualElement>("validation-panel");
advancedPanel = rootVisualElement.Q<VisualElement>("advanced-panel");
toolsPanel = rootVisualElement.Q<VisualElement>("tools-panel");
resourcesPanel = rootVisualElement.Q<VisualElement>("resources-panel");
var clientsContainer = rootVisualElement.Q<VisualElement>("clients-container");
var validationContainer = rootVisualElement.Q<VisualElement>("validation-container");
var advancedContainer = rootVisualElement.Q<VisualElement>("advanced-container");
var toolsContainer = rootVisualElement.Q<VisualElement>("tools-container");
var resourcesContainer = rootVisualElement.Q<VisualElement>("resources-container");
if (clientsPanel == null || validationPanel == null || advancedPanel == null || toolsPanel == null || resourcesPanel == null)
{
McpLog.Error("Failed to find tab panels in UXML");
return;
}
if (clientsContainer == null)
{
McpLog.Error("Failed to find clients-container in UXML");
return;
}
if (validationContainer == null)
{
McpLog.Error("Failed to find validation-container in UXML");
return;
}
if (advancedContainer == null)
{
McpLog.Error("Failed to find advanced-container in UXML");
return;
}
if (toolsContainer == null)
{
McpLog.Error("Failed to find tools-container in UXML");
return;
}
if (resourcesContainer == null)
{
McpLog.Error("Failed to find resources-container in UXML");
return;
}
// Initialize version label
fix: Claude Code registration, thread-safety, and auto-detect beta server (#664) (#667) * Fix Git URL in README for package installation Updated the Git URL for adding the package to include the branch name. * fix: Clean up Claude Code config from all scopes to prevent stale config conflicts (#664) - Add RemoveFromAllScopes helper to remove from local/user/project scopes - Use explicit --scope local when registering - Update manual snippets to show multi-scope cleanup - Handle legacy 'unityMCP' naming in all scopes Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: Make Claude Code status check thread-safe (#664) The background thread status check was accessing main-thread-only Unity APIs (Application.platform, EditorPrefs via HttpEndpointUtility and AssetPathUtility), causing "GetString can only be called from main thread" errors. Now all main-thread-only values are captured before Task.Run() and passed as parameters to CheckStatusWithProjectDir(). Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: Persist client dropdown selection and remove dead IO code - Remember last selected client in EditorPrefs so it restores on window reopen (prevents hiding config issues by defaulting to first client) - Remove dead Outbound class, _outbox BlockingCollection, and writer thread that was never used (nothing ever enqueued to outbox) - Keep only failure IO logs, remove verbose success logging Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: Auto-detect beta package to enable UseBetaServer + workflow updates - Add IsPreReleaseVersion() helper to detect beta/alpha/rc package versions - UseBetaServer now defaults to true only for prerelease package versions - Main branch users get false default, beta branch users get true default - Update beta-release.yml to set Unity package version with -beta.1 suffix - Update release.yml to merge beta → main and strip beta suffix - Fix CodexConfigHelperTests to explicitly set UseBetaServer for determinism - Use EditorConfigurationCache consistently for UseBetaServer access Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: Address code review feedback for thread-safety and validation - Add thread-safe overloads for GetBetaServerFromArgs/List that accept pre-captured useBetaServer and gitUrlOverride parameters - Use EditorConfigurationCache.SetUseBetaServer() in McpAdvancedSection for atomic cache + EditorPrefs update - Add semver validation guard in beta-release.yml before version arithmetic - Add semver validation guard in release.yml after stripping prerelease suffix Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: Complete thread-safety for GetBetaServerFromArgs overloads - Add packageSource parameter to thread-safe overloads to avoid calling GetMcpServerPackageSource() (which uses EditorPrefs) from background threads - Apply quoteFromPath logic to gitUrlOverride and packageSource paths to handle local paths with spaces correctly Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: Patch legacy connection pool in transport tests to prevent real Unity discovery The auto-select tests were failing because they only patched PluginHub but not the fallback legacy connection pool discovery. When PluginHub returns no results, the middleware falls back to discovering instances via get_unity_connection_pool(), which found the real running Unity. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 07:35:01 +08:00
UpdateVersionLabel(EditorConfigurationCache.Instance.UseBetaServer);
SetupTabs();
// Load and initialize Connection section
var connectionTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{basePath}/Editor/Windows/Components/Connection/McpConnectionSection.uxml"
);
if (connectionTree != null)
{
var connectionRoot = connectionTree.Instantiate();
clientsContainer.Add(connectionRoot);
connectionSection = new McpConnectionSection(connectionRoot);
connectionSection.OnManualConfigUpdateRequested += () =>
clientConfigSection?.UpdateManualConfiguration();
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
connectionSection.OnTransportChanged += () =>
clientConfigSection?.RefreshSelectedClient(forceImmediate: true);
}
// Load and initialize Client Configuration section
var clientConfigTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{basePath}/Editor/Windows/Components/ClientConfig/McpClientConfigSection.uxml"
);
if (clientConfigTree != null)
{
var clientConfigRoot = clientConfigTree.Instantiate();
clientsContainer.Add(clientConfigRoot);
clientConfigSection = new McpClientConfigSection(clientConfigRoot);
// Wire up transport mismatch detection: when client status is checked,
// update the connection section's warning banner if there's a mismatch
clientConfigSection.OnClientTransportDetected += (clientName, transport) =>
connectionSection?.UpdateTransportMismatchWarning(clientName, transport);
fix: speed up Claude Code config check by reading JSON directly (#682) * fix: speed up Claude Code config check by reading JSON directly Instead of running `claude mcp list` (15+ seconds due to health checks), read the config directly from ~/.claude.json (instant). Changes: - Add ReadClaudeCodeConfig() to parse Claude's JSON config file - Walk up directory tree to find config at parent directories - Handle duplicate path entries (forward/backslash variants) - Add beta/stable version mismatch detection with clear messages - Add IsBetaPackageSource() to detect PyPI beta versions and prerelease ranges - Change button label from "Register" to "Configure" for consistency Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: speed up Claude Code config check by reading JSON directly Instead of running `claude mcp list` (15+ seconds due to health checks), read the config directly from ~/.claude.json (instant). Changes: - Add ReadClaudeCodeConfig() to parse Claude's JSON config file - Walk up directory tree to find config at parent directories - Handle duplicate path entries (forward/backslash variants) - Add beta/stable version mismatch detection with clear messages - Add IsBetaPackageSource() to detect PyPI beta versions and prerelease ranges - Change button label from "Register" to "Configure" for consistency - Refresh client status when switching to Connect tab or toggling beta mode Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add VersionMismatch status for Claude Code config detection - Add McpStatus.VersionMismatch enum value for version mismatch cases - Show "Version Mismatch" with yellow warning indicator instead of "Error" - Use VersionMismatch for beta/stable package source mismatches - Keep Error status for transport mismatches and general errors Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add version mismatch warning banner in Server section - Add version-mismatch-warning banner to McpConnectionSection.uxml - Add UpdateVersionMismatchWarning method to show/hide the banner - Fire OnClientConfigMismatch event when VersionMismatch status detected - Wire up event in main window to update the warning banner - Store mismatch details in configStatus for both Error and VersionMismatch Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: simplify version mismatch messages for non-technical users Before: "Beta/stable mismatch: registered with beta 'mcpforunityserver>=0.0.0a0' but plugin is stable 'mcpforunityserver==9.4.0'." After: "Configured for beta server, but 'Use Beta Server' is disabled in Advanced settings." Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address PR review feedback - Treat missing ~/.claude.json as "not configured" instead of error (distinguishes "no Claude Code installed" from actual read failures) - Handle --from=VALUE format in ExtractPackageSourceFromConfig (in addition to existing --from VALUE format) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add beta/stable version mismatch detection to all JSON-based clients - Move GetExpectedPackageSourceForValidation() and IsBetaPackageSource() to base class so all configurators can use them - Update JsonFileMcpConfigurator.CheckStatus() to use beta-aware comparison - Show VersionMismatch status with clear messaging for Claude Desktop, Cursor, Windsurf, VS Code, and other JSON-based clients - Auto-rewrite still attempts to fix mismatches automatically Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: add beta-aware validation to CodexMcpConfigurator CodexMcpConfigurator was still using the non-beta-aware package source comparison. Now uses GetExpectedPackageSourceForValidation() and shows VersionMismatch status with clear messaging like other configurators. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 06:48:44 +08:00
// Wire up version mismatch detection: when client status is checked,
// update the connection section's warning banner if there's a version mismatch
clientConfigSection.OnClientConfigMismatch += (clientName, mismatchMessage) =>
connectionSection?.UpdateVersionMismatchWarning(clientName, mismatchMessage);
}
// Load and initialize Validation section
var validationTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{basePath}/Editor/Windows/Components/Validation/McpValidationSection.uxml"
);
if (validationTree != null)
{
var validationRoot = validationTree.Instantiate();
validationContainer.Add(validationRoot);
validationSection = new McpValidationSection(validationRoot);
}
// Load and initialize Advanced section
var advancedTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{basePath}/Editor/Windows/Components/Advanced/McpAdvancedSection.uxml"
);
if (advancedTree != null)
{
var advancedRoot = advancedTree.Instantiate();
advancedContainer.Add(advancedRoot);
advancedSection = new McpAdvancedSection(advancedRoot);
// Wire up events from Advanced section
advancedSection.OnGitUrlChanged += () =>
clientConfigSection?.UpdateManualConfiguration();
advancedSection.OnHttpServerCommandUpdateRequested += () =>
connectionSection?.UpdateHttpServerCommandDisplay();
advancedSection.OnTestConnectionRequested += async () =>
{
if (connectionSection != null)
await connectionSection.VerifyBridgeConnectionAsync();
};
feat: Add beta server mode with PyPI pre-release support (#640) * feat: add TestPyPI toggle for pre-release server package testing - Add UseTestPyPI editor preference key - Add TestPyPI toggle to Advanced settings UI with tooltip - Configure uvx to use test.pypi.org when TestPyPI mode enabled - Skip version pinning in TestPyPI mode to get latest pre-release - Update ConfigJsonBuilder to handle TestPyPI index URL * Update .meta file * fix: Use PyPI pre-release versions instead of TestPyPI for beta server TestPyPI has polluted packages (broken httpx, mcp, fastapi) that cause server startup failures. Switch to publishing beta versions directly to PyPI as pre-releases (e.g., 9.3.0b20260127). Key changes: - beta-release.yml: Publish to PyPI instead of TestPyPI, use beta suffix - Use --prerelease explicit with version specifier (>=0.0.0a0) to only get prereleases of our package, not broken dependency prereleases - Default "Use Beta Server" toggle to true on beta branch - Rename UI label from "Use TestPyPI" to "Use Beta Server" - Add UseTestPyPI to EditorPrefsWindow known prefs - Add search field and refresh button to EditorPrefsWindow Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * feat: Add beta mode indicator to UI badge and server version logging - Show "β" suffix on version badge when beta server mode is enabled - Badge updates dynamically when toggle changes - Add server version to startup log: "MCP for Unity Server v9.2.0 starting up" - Add version field to /health endpoint response Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * refactor: Rename UseTestPyPI to UseBetaServer and fix EditorPrefs margin - Rename EditorPref key from UseTestPyPI to UseBetaServer for clarity - Rename all related variables and UXML element names - Increase bottom margin on EditorPrefs search bar to prevent clipping first entry Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * refactor: Address code review feedback - Centralize beta server uvx args in AssetPathUtility.GetBetaServerFromArgs() to avoid duplication between HTTP and stdio transports - Cache server version at startup instead of calling get_package_version() on every /health request - Add robustness to beta version parsing in workflow: strip existing pre-release suffix and validate X.Y.Z format before parsing Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * Prioritize explicit fromUrl override and optimize search filter - GetBetaServerFromArgs/GetBetaServerFromArgsList now check for explicit GitUrlOverride before applying beta server mode, ensuring local dev paths and custom URLs are honored - EditorPrefsWindow search filter uses IndexOf with OrdinalIgnoreCase instead of ToLowerInvariant().Contains() for fewer allocations Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> --------- Co-authored-by: Marcus Sanatan <msanatan@gmail.com> Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-28 03:34:11 +08:00
advancedSection.OnBetaModeChanged += UpdateVersionLabel;
fix: speed up Claude Code config check by reading JSON directly (#682) * fix: speed up Claude Code config check by reading JSON directly Instead of running `claude mcp list` (15+ seconds due to health checks), read the config directly from ~/.claude.json (instant). Changes: - Add ReadClaudeCodeConfig() to parse Claude's JSON config file - Walk up directory tree to find config at parent directories - Handle duplicate path entries (forward/backslash variants) - Add beta/stable version mismatch detection with clear messages - Add IsBetaPackageSource() to detect PyPI beta versions and prerelease ranges - Change button label from "Register" to "Configure" for consistency Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: speed up Claude Code config check by reading JSON directly Instead of running `claude mcp list` (15+ seconds due to health checks), read the config directly from ~/.claude.json (instant). Changes: - Add ReadClaudeCodeConfig() to parse Claude's JSON config file - Walk up directory tree to find config at parent directories - Handle duplicate path entries (forward/backslash variants) - Add beta/stable version mismatch detection with clear messages - Add IsBetaPackageSource() to detect PyPI beta versions and prerelease ranges - Change button label from "Register" to "Configure" for consistency - Refresh client status when switching to Connect tab or toggling beta mode Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add VersionMismatch status for Claude Code config detection - Add McpStatus.VersionMismatch enum value for version mismatch cases - Show "Version Mismatch" with yellow warning indicator instead of "Error" - Use VersionMismatch for beta/stable package source mismatches - Keep Error status for transport mismatches and general errors Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add version mismatch warning banner in Server section - Add version-mismatch-warning banner to McpConnectionSection.uxml - Add UpdateVersionMismatchWarning method to show/hide the banner - Fire OnClientConfigMismatch event when VersionMismatch status detected - Wire up event in main window to update the warning banner - Store mismatch details in configStatus for both Error and VersionMismatch Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: simplify version mismatch messages for non-technical users Before: "Beta/stable mismatch: registered with beta 'mcpforunityserver>=0.0.0a0' but plugin is stable 'mcpforunityserver==9.4.0'." After: "Configured for beta server, but 'Use Beta Server' is disabled in Advanced settings." Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address PR review feedback - Treat missing ~/.claude.json as "not configured" instead of error (distinguishes "no Claude Code installed" from actual read failures) - Handle --from=VALUE format in ExtractPackageSourceFromConfig (in addition to existing --from VALUE format) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add beta/stable version mismatch detection to all JSON-based clients - Move GetExpectedPackageSourceForValidation() and IsBetaPackageSource() to base class so all configurators can use them - Update JsonFileMcpConfigurator.CheckStatus() to use beta-aware comparison - Show VersionMismatch status with clear messaging for Claude Desktop, Cursor, Windsurf, VS Code, and other JSON-based clients - Auto-rewrite still attempts to fix mismatches automatically Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: add beta-aware validation to CodexMcpConfigurator CodexMcpConfigurator was still using the non-beta-aware package source comparison. Now uses GetExpectedPackageSourceForValidation() and shows VersionMismatch status with clear messaging like other configurators. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 06:48:44 +08:00
advancedSection.OnBetaModeChanged += _ => clientConfigSection?.RefreshSelectedClient(forceImmediate: true);
// Wire up health status updates from Connection to Advanced
connectionSection?.SetHealthStatusUpdateCallback((isHealthy, statusText) =>
advancedSection?.UpdateHealthStatus(isHealthy, statusText));
}
// Load and initialize Tools section
var toolsTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{basePath}/Editor/Windows/Components/Tools/McpToolsSection.uxml"
);
if (toolsTree != null)
{
var toolsRoot = toolsTree.Instantiate();
toolsContainer.Add(toolsRoot);
toolsSection = new McpToolsSection(toolsRoot);
if (toolsTabToggle != null && toolsTabToggle.value)
{
EnsureToolsLoaded();
}
}
else
{
McpLog.Warn("Failed to load tools section UXML. Tool configuration will be unavailable.");
}
// Load and initialize Resources section
var resourcesTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{basePath}/Editor/Windows/Components/Resources/McpResourcesSection.uxml"
);
if (resourcesTree != null)
{
var resourcesRoot = resourcesTree.Instantiate();
resourcesContainer.Add(resourcesRoot);
resourcesSection = new McpResourcesSection(resourcesRoot);
if (resourcesTabToggle != null && resourcesTabToggle.value)
{
EnsureResourcesLoaded();
}
}
else
{
McpLog.Warn("Failed to load resources section UXML. Resource configuration will be unavailable.");
}
// Apply .section-last class to last section in each stack
// (Unity UI Toolkit doesn't support :last-child pseudo-class)
ApplySectionLastClasses();
guiCreated = true;
// Initial updates
RefreshAllData();
}
feat: Add beta server mode with PyPI pre-release support (#640) * feat: add TestPyPI toggle for pre-release server package testing - Add UseTestPyPI editor preference key - Add TestPyPI toggle to Advanced settings UI with tooltip - Configure uvx to use test.pypi.org when TestPyPI mode enabled - Skip version pinning in TestPyPI mode to get latest pre-release - Update ConfigJsonBuilder to handle TestPyPI index URL * Update .meta file * fix: Use PyPI pre-release versions instead of TestPyPI for beta server TestPyPI has polluted packages (broken httpx, mcp, fastapi) that cause server startup failures. Switch to publishing beta versions directly to PyPI as pre-releases (e.g., 9.3.0b20260127). Key changes: - beta-release.yml: Publish to PyPI instead of TestPyPI, use beta suffix - Use --prerelease explicit with version specifier (>=0.0.0a0) to only get prereleases of our package, not broken dependency prereleases - Default "Use Beta Server" toggle to true on beta branch - Rename UI label from "Use TestPyPI" to "Use Beta Server" - Add UseTestPyPI to EditorPrefsWindow known prefs - Add search field and refresh button to EditorPrefsWindow Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * feat: Add beta mode indicator to UI badge and server version logging - Show "β" suffix on version badge when beta server mode is enabled - Badge updates dynamically when toggle changes - Add server version to startup log: "MCP for Unity Server v9.2.0 starting up" - Add version field to /health endpoint response Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * refactor: Rename UseTestPyPI to UseBetaServer and fix EditorPrefs margin - Rename EditorPref key from UseTestPyPI to UseBetaServer for clarity - Rename all related variables and UXML element names - Increase bottom margin on EditorPrefs search bar to prevent clipping first entry Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * refactor: Address code review feedback - Centralize beta server uvx args in AssetPathUtility.GetBetaServerFromArgs() to avoid duplication between HTTP and stdio transports - Cache server version at startup instead of calling get_package_version() on every /health request - Add robustness to beta version parsing in workflow: strip existing pre-release suffix and validate X.Y.Z format before parsing Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * Prioritize explicit fromUrl override and optimize search filter - GetBetaServerFromArgs/GetBetaServerFromArgsList now check for explicit GitUrlOverride before applying beta server mode, ensuring local dev paths and custom URLs are honored - EditorPrefsWindow search filter uses IndexOf with OrdinalIgnoreCase instead of ToLowerInvariant().Contains() for fewer allocations Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> --------- Co-authored-by: Marcus Sanatan <msanatan@gmail.com> Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-28 03:34:11 +08:00
private void UpdateVersionLabel(bool useBetaServer)
{
if (versionLabel == null)
{
return;
}
string version = AssetPathUtility.GetPackageVersion();
fix: beta workflow no longer auto-bumps minor version (#673) * fix: beta workflow no longer auto-bumps minor version Changes to beta-release.yml: - Beta now bumps patch instead of minor (9.3.1 → 9.3.2-beta.1) - Allows patch releases without being forced into minor bumps - Increment beta number if already a beta version Changes to release.yml: - Added "none" bump option to release beta version as-is - Added version status display showing main/beta versions and what the release version will be Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * chore: remove redundant β character from version badge The version string now includes "-beta.N" suffix, making the separate β indicator redundant. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: improve version consistency in release workflows beta-release.yml: - Changed from already_beta to needs_update flag - Only skip updates when computed version matches current - PyPI versioning now detects existing prereleases and keeps the same base version instead of always bumping patch release.yml: - Preview step outputs stripped_version to GITHUB_OUTPUT - Compute step uses previewed value for "none" bump option - Added sanity check warning if versions diverge unexpectedly This ensures the released version matches what was shown to the user and prevents unnecessary patch bumps on consecutive beta runs. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 01:53:01 +08:00
versionLabel.text = $"v{version}";
feat: Add beta server mode with PyPI pre-release support (#640) * feat: add TestPyPI toggle for pre-release server package testing - Add UseTestPyPI editor preference key - Add TestPyPI toggle to Advanced settings UI with tooltip - Configure uvx to use test.pypi.org when TestPyPI mode enabled - Skip version pinning in TestPyPI mode to get latest pre-release - Update ConfigJsonBuilder to handle TestPyPI index URL * Update .meta file * fix: Use PyPI pre-release versions instead of TestPyPI for beta server TestPyPI has polluted packages (broken httpx, mcp, fastapi) that cause server startup failures. Switch to publishing beta versions directly to PyPI as pre-releases (e.g., 9.3.0b20260127). Key changes: - beta-release.yml: Publish to PyPI instead of TestPyPI, use beta suffix - Use --prerelease explicit with version specifier (>=0.0.0a0) to only get prereleases of our package, not broken dependency prereleases - Default "Use Beta Server" toggle to true on beta branch - Rename UI label from "Use TestPyPI" to "Use Beta Server" - Add UseTestPyPI to EditorPrefsWindow known prefs - Add search field and refresh button to EditorPrefsWindow Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * feat: Add beta mode indicator to UI badge and server version logging - Show "β" suffix on version badge when beta server mode is enabled - Badge updates dynamically when toggle changes - Add server version to startup log: "MCP for Unity Server v9.2.0 starting up" - Add version field to /health endpoint response Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * refactor: Rename UseTestPyPI to UseBetaServer and fix EditorPrefs margin - Rename EditorPref key from UseTestPyPI to UseBetaServer for clarity - Rename all related variables and UXML element names - Increase bottom margin on EditorPrefs search bar to prevent clipping first entry Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * refactor: Address code review feedback - Centralize beta server uvx args in AssetPathUtility.GetBetaServerFromArgs() to avoid duplication between HTTP and stdio transports - Cache server version at startup instead of calling get_package_version() on every /health request - Add robustness to beta version parsing in workflow: strip existing pre-release suffix and validate X.Y.Z format before parsing Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * Prioritize explicit fromUrl override and optimize search filter - GetBetaServerFromArgs/GetBetaServerFromArgsList now check for explicit GitUrlOverride before applying beta server mode, ensuring local dev paths and custom URLs are honored - EditorPrefsWindow search filter uses IndexOf with OrdinalIgnoreCase instead of ToLowerInvariant().Contains() for fewer allocations Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> --------- Co-authored-by: Marcus Sanatan <msanatan@gmail.com> Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-28 03:34:11 +08:00
versionLabel.tooltip = useBetaServer
? "Beta server mode - fetching pre-release server versions from PyPI"
: $"MCP For Unity v{version}";
}
private void EnsureToolsLoaded()
{
if (toolsLoaded)
{
return;
}
if (toolsSection == null)
{
return;
}
toolsLoaded = true;
toolsSection.Refresh();
}
private void EnsureResourcesLoaded()
{
if (resourcesLoaded)
{
return;
}
if (resourcesSection == null)
{
return;
}
resourcesLoaded = true;
resourcesSection.Refresh();
}
/// <summary>
/// Applies the .section-last class to the last .section element in each .section-stack container.
/// This is a workaround for Unity UI Toolkit not supporting the :last-child pseudo-class.
/// </summary>
private void ApplySectionLastClasses()
{
var sectionStacks = rootVisualElement.Query<VisualElement>(className: "section-stack").ToList();
foreach (var stack in sectionStacks)
{
var sections = stack.Children().Where(c => c.ClassListContains("section")).ToList();
if (sections.Count > 0)
{
// Remove class from all sections first (in case of refresh)
foreach (var section in sections)
{
section.RemoveFromClassList("section-last");
}
// Add class to the last section
sections[sections.Count - 1].AddToClassList("section-last");
}
}
}
fix: comprehensive performance optimizations, claude code config, and stability improvements (issue #577) (#595) * fix: reduce per-frame GC allocations causing editor hitches (issue #577) Eliminate memory allocations that occurred every frame, which triggered garbage collection spikes (~28ms) approximately every second. Changes: - EditorStateCache: Skip BuildSnapshot() entirely when state unchanged (check BEFORE building). Increased poll interval from 0.25s to 1.0s. Cache DeepClone() results to avoid allocations on GetSnapshot(). - TransportCommandDispatcher: Early exit before lock/list allocation when Pending.Count == 0, eliminating per-frame allocations when idle. - StdioBridgeHost: Same early exit pattern for commandQueue. - MCPForUnityEditorWindow: Throttle OnEditorUpdate to 2-second intervals instead of every frame, preventing expensive socket checks 60+/sec. Fixes GitHub issue #577: High performance impact even when MCP server is off * fix: prevent multiple domain reloads when calling refresh_unity (issue #577) Root Cause: - send_command() had a hardcoded retry loop (min 6 attempts) on connection errors - Each retry resent the refresh_unity command, causing Unity to reload 6 times - retry_on_reload=False only controlled reload-state retries, not connection retries The Fix: 1. Unity C# (MCPForUnity/Editor): - Added --reinstall flag to uvx commands in dev mode - Ensures local development changes are picked up by uvx/Claude Code - Applies to all client configurators (Claude Code, Codex, etc.) 2. Python Server (Server/src): - Added max_attempts parameter to send_command() - Pass max_attempts=0 when retry_on_reload=False - Fixed type handling in refresh_unity.py (handle MCPResponse objects) - Added timeout to connection error recovery conditions - Recovery logic now returns success instead of error to prevent client retries Changes: - MCPForUnity/Editor: Added --reinstall to dev mode uvx commands - Server/refresh_unity.py: Fixed type handling, improved error recovery - Server/unity_connection.py: Added max_attempts param, disable retries when retry_on_reload=False Result: refresh_unity with compile=request now triggers only 1 domain reload instead of 6 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: UI and server stability improvements Unity Editor (C#): - Fix "Resuming..." stuck state when manually clicking End Session Clear ResumeStdioAfterReload and ResumeHttpAfterReload flags in OnConnectionToggleClicked and EndOrphanedSessionAsync to prevent UI from getting stuck showing "Resuming..." with disabled button - Remove unsupported --reinstall flag from all uvx command builders uvx does not support --reinstall and shows warning when used Use --no-cache --refresh instead for dev mode cache busting Python Server: - Add "aborted" to connection error patterns in refresh_unity Handle WinError 10053 (connection aborted) gracefully during Unity domain reload, treating it as expected behavior - Add WindowsSafeRotatingFileHandler to suppress log rotation errors Windows file locking prevents log rotation when file is open by another process; catch PermissionError to avoid noisy stack traces - Fix packaging: add py-modules = ["main"] to pyproject.toml setuptools.packages.find only discovers packages (directories with __init__.py), must explicitly list standalone module files Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * docs: improve refresh_unity connection loss handling documentation Add detailed comments and logging to clarify why connection loss during compile is treated as success (expected domain reload behavior, not failure). This addresses PR feedback about potentially masking real connection errors. The logic is intentional and correct: - Connection loss only treated as success when compile='request' - Domain reload causing disconnect is expected Unity behavior - Subsequent wait_for_ready loop validates Unity becomes ready - Prevents multiple domain reload loops (issue #577) Added logging for observability: - Info log when expected disconnect detected - Warning log for non-recoverable errors Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: add missing logger import in refresh_unity Missing logger import causes NameError at runtime when connection loss handling paths are triggered (lines 82 and 91). Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: address code review feedback on thread safety and semantics Addresses four issues raised in code review: 1. EditorStateCache.GetSnapshot() - Remove shared cached clone - Revert to always returning fresh DeepClone() to prevent mutation bugs - Main GC optimization remains: state-change detection prevents unnecessary _cached rebuilds (the expensive operation) - Removed _cachedClone and _cachedCloneSequence fields 2. refresh_unity.py - Fix blocking reason terminology mismatch - Changed "asset_refresh" to "asset_import" to match activityPhase values from EditorStateCache.cs - Ensures asset import is correctly detected as blocking state 3. TransportCommandDispatcher - Fix unsynchronized Count access - Moved Pending.Count check inside PendingLock - Prevents data races and InvalidOperationException from concurrent dictionary access 4. StdioBridgeHost - Fix unsynchronized Count access - Moved commandQueue.Count check inside lockObj - Ensures all collection access is properly serialized All changes maintain the GC allocation optimizations while fixing thread safety violations and semantic contract changes. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: address code review feedback on thread safety and timeout handling - refresh_unity.py: Track readiness explicitly and return failure on timeout instead of silently returning success when wait loop exits without confirming ready_for_tools=true - McpClientConfiguratorBase.cs: Add thread safety guard for Configure() call in CheckStatusWithProjectDir(). Changed default attemptAutoRewrite to false and added runtime check to prevent calling Configure() from background threads. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-21 10:11:25 +08:00
// Throttle OnEditorUpdate to avoid per-frame overhead (GitHub issue #577).
// Connection status polling every frame caused expensive network checks 60+ times/sec.
private double _lastEditorUpdateTime;
private const double EditorUpdateIntervalSeconds = 2.0;
private void OnEnable()
{
EditorApplication.update += OnEditorUpdate;
OpenWindows.Add(this);
}
private void OnDisable()
{
EditorApplication.update -= OnEditorUpdate;
OpenWindows.Remove(this);
guiCreated = false;
toolsLoaded = false;
resourcesLoaded = false;
}
private void OnFocus()
{
// Only refresh data if UI is built
if (rootVisualElement == null || rootVisualElement.childCount == 0)
return;
RefreshAllData();
}
private void OnEditorUpdate()
{
fix: comprehensive performance optimizations, claude code config, and stability improvements (issue #577) (#595) * fix: reduce per-frame GC allocations causing editor hitches (issue #577) Eliminate memory allocations that occurred every frame, which triggered garbage collection spikes (~28ms) approximately every second. Changes: - EditorStateCache: Skip BuildSnapshot() entirely when state unchanged (check BEFORE building). Increased poll interval from 0.25s to 1.0s. Cache DeepClone() results to avoid allocations on GetSnapshot(). - TransportCommandDispatcher: Early exit before lock/list allocation when Pending.Count == 0, eliminating per-frame allocations when idle. - StdioBridgeHost: Same early exit pattern for commandQueue. - MCPForUnityEditorWindow: Throttle OnEditorUpdate to 2-second intervals instead of every frame, preventing expensive socket checks 60+/sec. Fixes GitHub issue #577: High performance impact even when MCP server is off * fix: prevent multiple domain reloads when calling refresh_unity (issue #577) Root Cause: - send_command() had a hardcoded retry loop (min 6 attempts) on connection errors - Each retry resent the refresh_unity command, causing Unity to reload 6 times - retry_on_reload=False only controlled reload-state retries, not connection retries The Fix: 1. Unity C# (MCPForUnity/Editor): - Added --reinstall flag to uvx commands in dev mode - Ensures local development changes are picked up by uvx/Claude Code - Applies to all client configurators (Claude Code, Codex, etc.) 2. Python Server (Server/src): - Added max_attempts parameter to send_command() - Pass max_attempts=0 when retry_on_reload=False - Fixed type handling in refresh_unity.py (handle MCPResponse objects) - Added timeout to connection error recovery conditions - Recovery logic now returns success instead of error to prevent client retries Changes: - MCPForUnity/Editor: Added --reinstall to dev mode uvx commands - Server/refresh_unity.py: Fixed type handling, improved error recovery - Server/unity_connection.py: Added max_attempts param, disable retries when retry_on_reload=False Result: refresh_unity with compile=request now triggers only 1 domain reload instead of 6 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: UI and server stability improvements Unity Editor (C#): - Fix "Resuming..." stuck state when manually clicking End Session Clear ResumeStdioAfterReload and ResumeHttpAfterReload flags in OnConnectionToggleClicked and EndOrphanedSessionAsync to prevent UI from getting stuck showing "Resuming..." with disabled button - Remove unsupported --reinstall flag from all uvx command builders uvx does not support --reinstall and shows warning when used Use --no-cache --refresh instead for dev mode cache busting Python Server: - Add "aborted" to connection error patterns in refresh_unity Handle WinError 10053 (connection aborted) gracefully during Unity domain reload, treating it as expected behavior - Add WindowsSafeRotatingFileHandler to suppress log rotation errors Windows file locking prevents log rotation when file is open by another process; catch PermissionError to avoid noisy stack traces - Fix packaging: add py-modules = ["main"] to pyproject.toml setuptools.packages.find only discovers packages (directories with __init__.py), must explicitly list standalone module files Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * docs: improve refresh_unity connection loss handling documentation Add detailed comments and logging to clarify why connection loss during compile is treated as success (expected domain reload behavior, not failure). This addresses PR feedback about potentially masking real connection errors. The logic is intentional and correct: - Connection loss only treated as success when compile='request' - Domain reload causing disconnect is expected Unity behavior - Subsequent wait_for_ready loop validates Unity becomes ready - Prevents multiple domain reload loops (issue #577) Added logging for observability: - Info log when expected disconnect detected - Warning log for non-recoverable errors Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: add missing logger import in refresh_unity Missing logger import causes NameError at runtime when connection loss handling paths are triggered (lines 82 and 91). Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: address code review feedback on thread safety and semantics Addresses four issues raised in code review: 1. EditorStateCache.GetSnapshot() - Remove shared cached clone - Revert to always returning fresh DeepClone() to prevent mutation bugs - Main GC optimization remains: state-change detection prevents unnecessary _cached rebuilds (the expensive operation) - Removed _cachedClone and _cachedCloneSequence fields 2. refresh_unity.py - Fix blocking reason terminology mismatch - Changed "asset_refresh" to "asset_import" to match activityPhase values from EditorStateCache.cs - Ensures asset import is correctly detected as blocking state 3. TransportCommandDispatcher - Fix unsynchronized Count access - Moved Pending.Count check inside PendingLock - Prevents data races and InvalidOperationException from concurrent dictionary access 4. StdioBridgeHost - Fix unsynchronized Count access - Moved commandQueue.Count check inside lockObj - Ensures all collection access is properly serialized All changes maintain the GC allocation optimizations while fixing thread safety violations and semantic contract changes. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: address code review feedback on thread safety and timeout handling - refresh_unity.py: Track readiness explicitly and return failure on timeout instead of silently returning success when wait loop exits without confirming ready_for_tools=true - McpClientConfiguratorBase.cs: Add thread safety guard for Configure() call in CheckStatusWithProjectDir(). Changed default attemptAutoRewrite to false and added runtime check to prevent calling Configure() from background threads. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-21 10:11:25 +08:00
// Throttle to 2-second intervals instead of every frame.
// This prevents the expensive IsLocalHttpServerReachable() socket checks from running
// 60+ times per second, which caused main thread blocking and GC pressure.
double now = EditorApplication.timeSinceStartup;
if (now - _lastEditorUpdateTime < EditorUpdateIntervalSeconds)
{
return;
}
_lastEditorUpdateTime = now;
if (rootVisualElement == null || rootVisualElement.childCount == 0)
return;
connectionSection?.UpdateConnectionStatus();
}
private void RefreshAllData()
{
// Debounce rapid successive calls (e.g., from OnFocus being called multiple times)
double currentTime = EditorApplication.timeSinceStartup;
if (currentTime - lastRefreshTime < RefreshDebounceSeconds)
{
return;
}
lastRefreshTime = currentTime;
connectionSection?.UpdateConnectionStatus();
if (MCPServiceLocator.Bridge.IsRunning)
{
_ = connectionSection?.VerifyBridgeConnectionAsync();
}
advancedSection?.UpdatePathOverrides();
clientConfigSection?.RefreshSelectedClient();
}
private void SetupTabs()
{
clientsTabToggle = rootVisualElement.Q<ToolbarToggle>("clients-tab");
validationTabToggle = rootVisualElement.Q<ToolbarToggle>("validation-tab");
advancedTabToggle = rootVisualElement.Q<ToolbarToggle>("advanced-tab");
toolsTabToggle = rootVisualElement.Q<ToolbarToggle>("tools-tab");
resourcesTabToggle = rootVisualElement.Q<ToolbarToggle>("resources-tab");
clientsPanel?.RemoveFromClassList("hidden");
validationPanel?.RemoveFromClassList("hidden");
advancedPanel?.RemoveFromClassList("hidden");
toolsPanel?.RemoveFromClassList("hidden");
resourcesPanel?.RemoveFromClassList("hidden");
if (clientsTabToggle != null)
{
clientsTabToggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue) SwitchPanel(ActivePanel.Clients);
});
}
if (validationTabToggle != null)
{
validationTabToggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue) SwitchPanel(ActivePanel.Validation);
});
}
if (advancedTabToggle != null)
{
advancedTabToggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue) SwitchPanel(ActivePanel.Advanced);
});
}
if (toolsTabToggle != null)
{
toolsTabToggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue) SwitchPanel(ActivePanel.Tools);
});
}
if (resourcesTabToggle != null)
{
resourcesTabToggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue) SwitchPanel(ActivePanel.Resources);
});
}
var savedPanel = EditorPrefs.GetString(EditorPrefKeys.EditorWindowActivePanel, ActivePanel.Clients.ToString());
if (!Enum.TryParse(savedPanel, out ActivePanel initialPanel))
{
initialPanel = ActivePanel.Clients;
}
SwitchPanel(initialPanel);
}
private void SwitchPanel(ActivePanel panel)
{
// Hide all panels
if (clientsPanel != null)
{
clientsPanel.style.display = DisplayStyle.None;
}
if (validationPanel != null)
{
validationPanel.style.display = DisplayStyle.None;
}
if (advancedPanel != null)
{
advancedPanel.style.display = DisplayStyle.None;
}
if (toolsPanel != null)
{
toolsPanel.style.display = DisplayStyle.None;
}
if (resourcesPanel != null)
{
resourcesPanel.style.display = DisplayStyle.None;
}
// Show selected panel
switch (panel)
{
case ActivePanel.Clients:
if (clientsPanel != null) clientsPanel.style.display = DisplayStyle.Flex;
fix: speed up Claude Code config check by reading JSON directly (#682) * fix: speed up Claude Code config check by reading JSON directly Instead of running `claude mcp list` (15+ seconds due to health checks), read the config directly from ~/.claude.json (instant). Changes: - Add ReadClaudeCodeConfig() to parse Claude's JSON config file - Walk up directory tree to find config at parent directories - Handle duplicate path entries (forward/backslash variants) - Add beta/stable version mismatch detection with clear messages - Add IsBetaPackageSource() to detect PyPI beta versions and prerelease ranges - Change button label from "Register" to "Configure" for consistency Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: speed up Claude Code config check by reading JSON directly Instead of running `claude mcp list` (15+ seconds due to health checks), read the config directly from ~/.claude.json (instant). Changes: - Add ReadClaudeCodeConfig() to parse Claude's JSON config file - Walk up directory tree to find config at parent directories - Handle duplicate path entries (forward/backslash variants) - Add beta/stable version mismatch detection with clear messages - Add IsBetaPackageSource() to detect PyPI beta versions and prerelease ranges - Change button label from "Register" to "Configure" for consistency - Refresh client status when switching to Connect tab or toggling beta mode Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add VersionMismatch status for Claude Code config detection - Add McpStatus.VersionMismatch enum value for version mismatch cases - Show "Version Mismatch" with yellow warning indicator instead of "Error" - Use VersionMismatch for beta/stable package source mismatches - Keep Error status for transport mismatches and general errors Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add version mismatch warning banner in Server section - Add version-mismatch-warning banner to McpConnectionSection.uxml - Add UpdateVersionMismatchWarning method to show/hide the banner - Fire OnClientConfigMismatch event when VersionMismatch status detected - Wire up event in main window to update the warning banner - Store mismatch details in configStatus for both Error and VersionMismatch Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: simplify version mismatch messages for non-technical users Before: "Beta/stable mismatch: registered with beta 'mcpforunityserver>=0.0.0a0' but plugin is stable 'mcpforunityserver==9.4.0'." After: "Configured for beta server, but 'Use Beta Server' is disabled in Advanced settings." Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address PR review feedback - Treat missing ~/.claude.json as "not configured" instead of error (distinguishes "no Claude Code installed" from actual read failures) - Handle --from=VALUE format in ExtractPackageSourceFromConfig (in addition to existing --from VALUE format) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add beta/stable version mismatch detection to all JSON-based clients - Move GetExpectedPackageSourceForValidation() and IsBetaPackageSource() to base class so all configurators can use them - Update JsonFileMcpConfigurator.CheckStatus() to use beta-aware comparison - Show VersionMismatch status with clear messaging for Claude Desktop, Cursor, Windsurf, VS Code, and other JSON-based clients - Auto-rewrite still attempts to fix mismatches automatically Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: add beta-aware validation to CodexMcpConfigurator CodexMcpConfigurator was still using the non-beta-aware package source comparison. Now uses GetExpectedPackageSourceForValidation() and shows VersionMismatch status with clear messaging like other configurators. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 06:48:44 +08:00
// Refresh client status when switching to Connect tab (e.g., after changing beta mode in Advanced)
clientConfigSection?.RefreshSelectedClient(forceImmediate: true);
break;
case ActivePanel.Validation:
if (validationPanel != null) validationPanel.style.display = DisplayStyle.Flex;
break;
case ActivePanel.Advanced:
if (advancedPanel != null) advancedPanel.style.display = DisplayStyle.Flex;
break;
case ActivePanel.Tools:
if (toolsPanel != null) toolsPanel.style.display = DisplayStyle.Flex;
EnsureToolsLoaded();
break;
case ActivePanel.Resources:
if (resourcesPanel != null) resourcesPanel.style.display = DisplayStyle.Flex;
EnsureResourcesLoaded();
break;
}
// Update toggle states
clientsTabToggle?.SetValueWithoutNotify(panel == ActivePanel.Clients);
validationTabToggle?.SetValueWithoutNotify(panel == ActivePanel.Validation);
advancedTabToggle?.SetValueWithoutNotify(panel == ActivePanel.Advanced);
toolsTabToggle?.SetValueWithoutNotify(panel == ActivePanel.Tools);
resourcesTabToggle?.SetValueWithoutNotify(panel == ActivePanel.Resources);
EditorPrefs.SetString(EditorPrefKeys.EditorWindowActivePanel, panel.ToString());
}
internal static void RequestHealthVerification()
{
foreach (var window in OpenWindows)
{
window?.ScheduleHealthCheck();
}
}
private void ScheduleHealthCheck()
{
EditorApplication.delayCall += async () =>
{
// Ensure window and components are still valid before execution
if (this == null || connectionSection == null)
{
return;
}
try
{
await connectionSection.VerifyBridgeConnectionAsync();
}
catch (Exception ex)
{
// Log but don't crash if verification fails during cleanup
McpLog.Warn($"Health check verification failed: {ex.Message}");
}
};
}
}
}