2025-12-30 01:30:45 +08:00
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Globalization;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
using MCPForUnity.Editor.Constants;
|
|
|
|
|
using MCPForUnity.Editor.Helpers;
|
|
|
|
|
using UnityEditor;
|
|
|
|
|
using UnityEngine;
|
|
|
|
|
using UnityEngine.UIElements;
|
|
|
|
|
|
|
|
|
|
namespace MCPForUnity.Editor.Windows
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Editor window for managing Unity EditorPrefs, specifically for MCP For Unity development
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class EditorPrefsWindow : EditorWindow
|
|
|
|
|
{
|
|
|
|
|
// UI Elements
|
|
|
|
|
private ScrollView scrollView;
|
|
|
|
|
private VisualElement prefsContainer;
|
2026-01-28 03:34:11 +08:00
|
|
|
private TextField searchField;
|
|
|
|
|
private string searchFilter = "";
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Data
|
|
|
|
|
private List<EditorPrefItem> currentPrefs = new List<EditorPrefItem>();
|
|
|
|
|
private HashSet<string> knownMcpKeys = new HashSet<string>();
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Type mapping for known EditorPrefs
|
|
|
|
|
private readonly Dictionary<string, EditorPrefType> knownPrefTypes = new Dictionary<string, EditorPrefType>
|
|
|
|
|
{
|
|
|
|
|
// Boolean prefs
|
|
|
|
|
{ EditorPrefKeys.DebugLogs, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.UseHttpTransport, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.ResumeHttpAfterReload, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.ResumeStdioAfterReload, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.UseEmbeddedServer, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.LockCursorConfig, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.AutoRegisterEnabled, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.SetupCompleted, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.SetupDismissed, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.CustomToolRegistrationEnabled, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.TelemetryDisabled, EditorPrefType.Bool },
|
Fix HTTP/Stdio Transport UX and Test Bug (#530)
* refactor: Split ParseColorOrDefault into two overloads and change default to Color.white
* Auto-format Python code
* Remove unused Python module
* Refactored VFX functionality into multiple files
Tested everything, works like a charm
* Rename ManageVfx folder to just Vfx
We know what it's managing
* Clean up whitespace on plugin tools and resources
* Make ManageGameObject less of a monolith by splitting it out into different files
* Remove obsolete FindObjectByInstruction method
We also update the namespace for ManageVFX
* Add local test harness for fast developer iteration
Scripts for running the NL/T/GO test suites locally against a GUI Unity
Editor, complementing the CI workflows in .github/workflows/.
Benefits:
- 10-100x faster than CI (no Docker startup)
- Real-time Unity console debugging
- Single test execution for rapid iteration
- Auto-detects HTTP vs stdio transport
Usage:
./scripts/local-test/setup.sh # One-time setup
./scripts/local-test/quick-test.sh NL-0 # Run single test
./scripts/local-test/run-nl-suite-local.sh # Full suite
See scripts/local-test/README.md for details.
Also updated .gitignore to:
- Allow scripts/local-test/ to be tracked
- Ignore generated artifacts (reports/*.xml, .claude/local/, .unity-mcp/)
* Fix issue #525: Save dirty scenes for all test modes
Move SaveDirtyScenesIfNeeded() call outside the PlayMode conditional
so EditMode tests don't get blocked by Unity's "Save Scene" modal dialog.
This prevents MCP from timing out when running EditMode tests with unsaved
scene changes.
* refactor: Consolidate editor state resources into single canonical implementation
Merged EditorStateV2 into EditorState, making get_editor_state the canonical resource. Updated Unity C# to use EditorStateCache directly. Enhanced Python implementation with advice/staleness enrichment, external changes detection, and instance ID inference. Removed duplicate EditorStateV2 resource and legacy fallback mapping.
* Validate editor state with Pydantic models in both C# and Python
Added strongly-typed Pydantic models for EditorStateV2 schema in Python and corresponding C# classes with JsonProperty attributes. Updated C# to serialize using typed classes instead of anonymous objects. Python now validates the editor state payload before returning it, catching schema mismatches early.
* Consolidate run_tests and run_tests_async into single async implementation
Merged run_tests_async into run_tests, making async job-based execution the default behavior. Removed synchronous blocking test execution. Updated RunTests.cs to start test jobs immediately and return job_id for polling. Changed TestJobManager methods to internal visibility. Updated README to reflect single run_tests_async tool. Python implementation now uses async job pattern exclusively.
* Validate test job responses with Pydantic models in Python
* Change resources URI from unity:// to mcpforunity://
It should reduce conflicts with other Unity MCPs that users try, and to comply with Unity's requests regarding use of their company and product name
* Update README with all tools + better listing for resources
* Update other references to resources
* Updated translated doc - unfortunately I cannot verify
* Update the Chinese translation of the dev docks
* Change menu item from Setup Window to Local Setup Window
We now differentiate whether it's HTTP local or remote
* Fix URIs for menu items and tests
* Shouldn't have removed it
* fix: add missing FAST_FAIL_TIMEOUT constant in PluginHub
The FAST_FAIL_TIMEOUT class attribute was referenced on line 149 but never
defined, causing AttributeError on every ping attempt. This error was silently
caught by the broad 'except Exception' handler, causing all fast-fail commands
(read_console, get_editor_state, ping) to fail after 6 seconds of retries with
'ping not answered' error.
Added FAST_FAIL_TIMEOUT = 10 to define a 10-second timeout for fast-fail
commands, matching the intent of the existing fast-fail infrastructure.
* feat(ScriptableObject): enhance dry-run validation for AnimationCurve and Quaternion
Dry-run validation now validates value formats, not just property existence:
- AnimationCurve: Validates structure ({keys:[...]} or direct array), checks
each keyframe is an object, validates numeric fields (time, value, inSlope,
outSlope, inWeight, outWeight) and integer fields (weightedMode)
- Quaternion: Validates array length (3 for Euler, 4 for raw) or object
structure ({x,y,z,w} or {euler:[x,y,z]}), ensures all components are numeric
Refactored shared validation helpers into appropriate locations:
- ParamCoercion: IsNumericToken, ValidateNumericField, ValidateIntegerField
- VectorParsing: ValidateAnimationCurveFormat, ValidateQuaternionFormat
Added comprehensive XML documentation clarifying keyframe field defaults
(all default to 0 except as noted).
Added 5 new dry-run validation tests covering valid and invalid formats
for both AnimationCurve and Quaternion properties.
* test: fix integration tests after merge
- test_refresh_unity_retry_recovery: Mock now handles both refresh_unity and
get_editor_state commands (refresh_unity internally calls get_editor_state
when wait_for_ready=True)
- test_run_tests_async_forwards_params: Mock response now includes required
'mode' field for RunTestsStartResponse Pydantic validation
- test_get_test_job_forwards_job_id: Updated to handle GetTestJobResponse as
Pydantic model instead of dict (use model_dump() for assertions)
* Update warning message to apply to all test modes
Follow-up to PR #527: Since SaveDirtyScenesIfNeeded() now runs for all test modes, update the warning message to say 'tests' instead of 'PlayMode tests'.
* feat(run_tests): add wait_timeout to get_test_job to avoid client loop detection
When polling for test completion, MCP clients like Cursor can detect the
repeated get_test_job calls as 'looping' and terminate the agent.
Added wait_timeout parameter that makes the server wait internally for tests
to complete (polling Unity every 2s) before returning. This dramatically
reduces client-side tool calls from 10-20 down to 1-2, avoiding loop detection.
Usage: get_test_job(job_id='xxx', wait_timeout=30)
- Returns immediately if tests complete within timeout
- Returns current status if timeout expires (client can call again)
- Recommended: 30-60 seconds
* fix: use Pydantic attribute access in test_run_tests_async for merge compatibility
* revert: remove local test harness - will be submitted in separate PR
* fix: stdio transport survives test runs without UI flicker
Root cause: WriteToConfigTests.TearDown() was unconditionally deleting
UseHttpTransport EditorPref even when tests were skipped on Windows
(NUnit runs TearDown even after Assert.Ignore).
Changes:
- Fix WriteToConfigTests to save/restore prefs instead of deleting
- Add centralized ShouldForceUvxRefresh() for local dev path detection
- Clean stale Python build/ artifacts before client configuration
- Improve reload handler flag management to prevent stuck Resuming state
- Show Resuming status during stdio bridge restart
- Initialize client config display on window open
- Add DevModeForceServerRefresh to EditorPrefs window known types
---------
Co-authored-by: Marcus Sanatan <msanatan@gmail.com>
Co-authored-by: Scott Jennings <scott.jennings+CIGINT@cloudimperiumgames.com>
2026-01-08 11:33:22 +08:00
|
|
|
{ EditorPrefKeys.DevModeForceServerRefresh, EditorPrefType.Bool },
|
2026-01-28 03:34:11 +08:00
|
|
|
{ EditorPrefKeys.UseBetaServer, EditorPrefType.Bool },
|
2026-01-22 01:07:52 +08:00
|
|
|
{ EditorPrefKeys.ProjectScopedToolsLocalHttp, EditorPrefType.Bool },
|
2025-12-30 01:30:45 +08:00
|
|
|
|
|
|
|
|
// Integer prefs
|
|
|
|
|
{ EditorPrefKeys.UnitySocketPort, EditorPrefType.Int },
|
|
|
|
|
{ EditorPrefKeys.ValidationLevel, EditorPrefType.Int },
|
2026-01-31 09:31:23 +08:00
|
|
|
{ EditorPrefKeys.LastUpdateCheck, EditorPrefType.String },
|
2025-12-30 01:30:45 +08:00
|
|
|
{ EditorPrefKeys.LastStdIoUpgradeVersion, EditorPrefType.Int },
|
2026-01-31 09:31:23 +08:00
|
|
|
{ EditorPrefKeys.LastLocalHttpServerPid, EditorPrefType.Int },
|
|
|
|
|
{ EditorPrefKeys.LastLocalHttpServerPort, EditorPrefType.Int },
|
2025-12-30 01:30:45 +08:00
|
|
|
|
|
|
|
|
// String prefs
|
|
|
|
|
{ EditorPrefKeys.EditorWindowActivePanel, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.ClaudeCliPathOverride, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.UvxPathOverride, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.HttpBaseUrl, EditorPrefType.String },
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
{ EditorPrefKeys.HttpRemoteBaseUrl, EditorPrefType.String },
|
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
|
|
|
{ EditorPrefKeys.HttpTransportScope, EditorPrefType.String },
|
2025-12-30 01:30:45 +08:00
|
|
|
{ EditorPrefKeys.SessionId, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.WebSocketUrlOverride, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.GitUrlOverride, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.PackageDeploySourcePath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.PackageDeployLastBackupPath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.PackageDeployLastTargetPath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.PackageDeployLastSourcePath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.ServerSrc, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.LatestKnownVersion, EditorPrefType.String },
|
2026-01-31 09:31:23 +08:00
|
|
|
{ EditorPrefKeys.LastAssetStoreUpdateCheck, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.LatestKnownAssetStoreVersion, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.LastLocalHttpServerStartedUtc, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.LastLocalHttpServerPidArgsHash, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.LastLocalHttpServerPidFilePath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.LastLocalHttpServerInstanceToken, EditorPrefType.String },
|
2025-12-30 01:30:45 +08:00
|
|
|
};
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Templates
|
|
|
|
|
private VisualTreeAsset itemTemplate;
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// Show the EditorPrefs window
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static void ShowWindow()
|
|
|
|
|
{
|
|
|
|
|
var window = GetWindow<EditorPrefsWindow>("EditorPrefs");
|
|
|
|
|
window.minSize = new Vector2(600, 400);
|
|
|
|
|
window.Show();
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
public void CreateGUI()
|
|
|
|
|
{
|
2026-02-03 15:16:30 +08:00
|
|
|
// Clear search filter on GUI recreation to avoid stale filtered results
|
|
|
|
|
searchFilter = "";
|
|
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
string basePath = AssetPathUtility.GetMcpPackageRootPath();
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Load UXML
|
|
|
|
|
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
|
|
|
|
|
$"{basePath}/Editor/Windows/EditorPrefs/EditorPrefsWindow.uxml"
|
|
|
|
|
);
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
if (visualTree == null)
|
|
|
|
|
{
|
2026-01-07 13:33:20 +08:00
|
|
|
McpLog.Error("Failed to load EditorPrefsWindow.uxml template");
|
2025-12-30 01:30:45 +08:00
|
|
|
return;
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Load item template
|
|
|
|
|
itemTemplate = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
|
|
|
|
|
$"{basePath}/Editor/Windows/EditorPrefs/EditorPrefItem.uxml"
|
|
|
|
|
);
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
if (itemTemplate == null)
|
|
|
|
|
{
|
2026-01-07 13:33:20 +08:00
|
|
|
McpLog.Error("Failed to load EditorPrefItem.uxml template");
|
2025-12-30 01:30:45 +08:00
|
|
|
return;
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
visualTree.CloneTree(rootVisualElement);
|
2026-01-28 03:34:11 +08:00
|
|
|
|
|
|
|
|
// Add search bar container at the top
|
|
|
|
|
var searchContainer = new VisualElement();
|
|
|
|
|
searchContainer.style.flexDirection = FlexDirection.Row;
|
|
|
|
|
searchContainer.style.marginTop = 8;
|
|
|
|
|
searchContainer.style.marginBottom = 20;
|
|
|
|
|
searchContainer.style.marginLeft = 4;
|
|
|
|
|
searchContainer.style.marginRight = 4;
|
|
|
|
|
|
|
|
|
|
searchField = new TextField("Search");
|
|
|
|
|
searchField.style.flexGrow = 1;
|
|
|
|
|
searchField.style.height = 28;
|
|
|
|
|
searchField.style.paddingTop = 2;
|
|
|
|
|
searchField.style.paddingBottom = 2;
|
|
|
|
|
searchField.labelElement.style.unityFontStyleAndWeight = FontStyle.Bold;
|
|
|
|
|
searchField.RegisterValueChangedCallback(evt =>
|
|
|
|
|
{
|
|
|
|
|
searchFilter = evt.newValue ?? "";
|
|
|
|
|
RefreshPrefs();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
var refreshButton = new Button(RefreshPrefs);
|
|
|
|
|
refreshButton.text = "↻";
|
|
|
|
|
refreshButton.tooltip = "Refresh prefs";
|
|
|
|
|
refreshButton.style.width = 30;
|
|
|
|
|
refreshButton.style.height = 28;
|
|
|
|
|
refreshButton.style.marginLeft = 6;
|
|
|
|
|
refreshButton.style.backgroundColor = new Color(0.9f, 0.5f, 0.1f);
|
|
|
|
|
|
|
|
|
|
searchContainer.Add(searchField);
|
|
|
|
|
searchContainer.Add(refreshButton);
|
|
|
|
|
rootVisualElement.Insert(0, searchContainer);
|
|
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Get references
|
|
|
|
|
scrollView = rootVisualElement.Q<ScrollView>("scroll-view");
|
|
|
|
|
prefsContainer = rootVisualElement.Q<VisualElement>("prefs-container");
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Load known MCP keys
|
|
|
|
|
LoadKnownMcpKeys();
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Load initial data
|
|
|
|
|
RefreshPrefs();
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
private void LoadKnownMcpKeys()
|
|
|
|
|
{
|
|
|
|
|
knownMcpKeys.Clear();
|
|
|
|
|
var fields = typeof(EditorPrefKeys).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
foreach (var field in fields)
|
|
|
|
|
{
|
|
|
|
|
if (field.IsLiteral && !field.IsInitOnly)
|
|
|
|
|
{
|
|
|
|
|
knownMcpKeys.Add(field.GetValue(null).ToString());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
private void RefreshPrefs()
|
|
|
|
|
{
|
|
|
|
|
currentPrefs.Clear();
|
|
|
|
|
prefsContainer.Clear();
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Get all EditorPrefs keys
|
|
|
|
|
var allKeys = new List<string>();
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Always show all MCP keys
|
|
|
|
|
allKeys.AddRange(knownMcpKeys);
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Try to find additional MCP keys
|
|
|
|
|
var mcpKeys = GetAllMcpKeys();
|
|
|
|
|
foreach (var key in mcpKeys)
|
|
|
|
|
{
|
|
|
|
|
if (!allKeys.Contains(key))
|
|
|
|
|
{
|
|
|
|
|
allKeys.Add(key);
|
|
|
|
|
}
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Sort keys
|
|
|
|
|
allKeys.Sort();
|
2026-01-28 03:34:11 +08:00
|
|
|
|
|
|
|
|
// Pre-trim filter once outside the loop
|
|
|
|
|
var filter = searchFilter?.Trim();
|
|
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Create items for existing prefs
|
|
|
|
|
foreach (var key in allKeys)
|
|
|
|
|
{
|
|
|
|
|
// Skip Customer UUID but show everything else that's defined
|
|
|
|
|
if (key != EditorPrefKeys.CustomerUuid)
|
|
|
|
|
{
|
2026-01-28 03:34:11 +08:00
|
|
|
// Apply search filter using OrdinalIgnoreCase for fewer allocations
|
|
|
|
|
if (!string.IsNullOrEmpty(filter) &&
|
|
|
|
|
key.IndexOf(filter, StringComparison.OrdinalIgnoreCase) < 0)
|
|
|
|
|
{
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
var item = CreateEditorPrefItem(key);
|
|
|
|
|
if (item != null)
|
|
|
|
|
{
|
|
|
|
|
currentPrefs.Add(item);
|
|
|
|
|
prefsContainer.Add(CreateItemUI(item));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
private List<string> GetAllMcpKeys()
|
|
|
|
|
{
|
|
|
|
|
// This is a simplified approach - in reality, getting all EditorPrefs is platform-specific
|
|
|
|
|
// For now, we'll return known MCP keys that might exist
|
|
|
|
|
var keys = new List<string>();
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Add some common MCP keys that might not be in EditorPrefKeys
|
|
|
|
|
keys.Add("MCPForUnity.TestKey");
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Filter to only those that actually exist
|
|
|
|
|
return keys.Where(EditorPrefs.HasKey).ToList();
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
private EditorPrefItem CreateEditorPrefItem(string key)
|
|
|
|
|
{
|
|
|
|
|
var item = new EditorPrefItem { Key = key, IsKnown = knownMcpKeys.Contains(key) };
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Check if we know the type of this pref
|
|
|
|
|
if (knownPrefTypes.TryGetValue(key, out var knownType))
|
|
|
|
|
{
|
2026-02-03 15:16:30 +08:00
|
|
|
// Check if the key actually exists
|
|
|
|
|
item.IsUnset = !EditorPrefs.HasKey(key);
|
|
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Use the known type
|
|
|
|
|
switch (knownType)
|
|
|
|
|
{
|
|
|
|
|
case EditorPrefType.Bool:
|
|
|
|
|
item.Type = EditorPrefType.Bool;
|
2026-02-03 15:16:30 +08:00
|
|
|
item.Value = item.IsUnset ? "Unset. Default: False" : EditorPrefs.GetBool(key, false).ToString();
|
2025-12-30 01:30:45 +08:00
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Int:
|
|
|
|
|
item.Type = EditorPrefType.Int;
|
2026-02-03 15:16:30 +08:00
|
|
|
item.Value = item.IsUnset ? "Unset. Default: 0" : EditorPrefs.GetInt(key, 0).ToString();
|
2025-12-30 01:30:45 +08:00
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Float:
|
|
|
|
|
item.Type = EditorPrefType.Float;
|
2026-02-03 15:16:30 +08:00
|
|
|
item.Value = item.IsUnset ? "Unset. Default: 0" : EditorPrefs.GetFloat(key, 0f).ToString();
|
2025-12-30 01:30:45 +08:00
|
|
|
break;
|
|
|
|
|
case EditorPrefType.String:
|
|
|
|
|
item.Type = EditorPrefType.String;
|
2026-02-03 15:16:30 +08:00
|
|
|
item.Value = item.IsUnset ? "Unset. Default: (empty)" : EditorPrefs.GetString(key, "");
|
2025-12-30 01:30:45 +08:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
// Only try to detect type for unknown keys that actually exist
|
|
|
|
|
if (!EditorPrefs.HasKey(key))
|
|
|
|
|
{
|
|
|
|
|
// Key doesn't exist and we don't know its type, skip it
|
|
|
|
|
return null;
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Unknown pref - try to detect type
|
|
|
|
|
var stringValue = EditorPrefs.GetString(key, "");
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
if (int.TryParse(stringValue, out var intValue))
|
|
|
|
|
{
|
|
|
|
|
item.Type = EditorPrefType.Int;
|
|
|
|
|
item.Value = intValue.ToString();
|
|
|
|
|
}
|
|
|
|
|
else if (float.TryParse(stringValue, out var floatValue))
|
|
|
|
|
{
|
|
|
|
|
item.Type = EditorPrefType.Float;
|
|
|
|
|
item.Value = floatValue.ToString();
|
|
|
|
|
}
|
|
|
|
|
else if (bool.TryParse(stringValue, out var boolValue))
|
|
|
|
|
{
|
|
|
|
|
item.Type = EditorPrefType.Bool;
|
|
|
|
|
item.Value = boolValue.ToString();
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
item.Type = EditorPrefType.String;
|
|
|
|
|
item.Value = stringValue;
|
|
|
|
|
}
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
return item;
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
private VisualElement CreateItemUI(EditorPrefItem item)
|
|
|
|
|
{
|
|
|
|
|
if (itemTemplate == null)
|
|
|
|
|
{
|
2026-01-07 13:33:20 +08:00
|
|
|
McpLog.Error("Item template not loaded");
|
2025-12-30 01:30:45 +08:00
|
|
|
return new VisualElement();
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
var itemElement = itemTemplate.CloneTree();
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Set values
|
|
|
|
|
itemElement.Q<Label>("key-label").text = item.Key;
|
|
|
|
|
var valueField = itemElement.Q<TextField>("value-field");
|
|
|
|
|
valueField.value = item.Value;
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
var typeDropdown = itemElement.Q<DropdownField>("type-dropdown");
|
|
|
|
|
typeDropdown.index = (int)item.Type;
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Buttons
|
|
|
|
|
var saveButton = itemElement.Q<Button>("save-button");
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2026-02-03 15:16:30 +08:00
|
|
|
// Style unset items
|
|
|
|
|
if (item.IsUnset)
|
|
|
|
|
{
|
|
|
|
|
valueField.SetEnabled(false);
|
|
|
|
|
valueField.style.opacity = 0.6f;
|
|
|
|
|
saveButton.SetEnabled(false);
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
// Callbacks
|
|
|
|
|
saveButton.clicked += () => SavePref(item, valueField.value, (EditorPrefType)typeDropdown.index);
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
return itemElement;
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
private void SavePref(EditorPrefItem item, string newValue, EditorPrefType newType)
|
|
|
|
|
{
|
|
|
|
|
SaveValue(item.Key, newValue, newType);
|
|
|
|
|
RefreshPrefs();
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
private void SaveValue(string key, string value, EditorPrefType type)
|
|
|
|
|
{
|
|
|
|
|
switch (type)
|
|
|
|
|
{
|
|
|
|
|
case EditorPrefType.String:
|
|
|
|
|
EditorPrefs.SetString(key, value);
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Int:
|
|
|
|
|
if (int.TryParse(value, out var intValue))
|
|
|
|
|
{
|
|
|
|
|
EditorPrefs.SetInt(key, intValue);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
EditorUtility.DisplayDialog("Error", $"Cannot convert '{value}' to int", "OK");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Float:
|
|
|
|
|
if (float.TryParse(value, out var floatValue))
|
|
|
|
|
{
|
|
|
|
|
EditorPrefs.SetFloat(key, floatValue);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
EditorUtility.DisplayDialog("Error", $"Cannot convert '{value}' to float", "OK");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Bool:
|
|
|
|
|
if (bool.TryParse(value, out var boolValue))
|
|
|
|
|
{
|
|
|
|
|
EditorPrefs.SetBool(key, boolValue);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
EditorUtility.DisplayDialog("Error", $"Cannot convert '{value}' to bool (use 'True' or 'False')", "OK");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// Represents an EditorPrefs item
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class EditorPrefItem
|
|
|
|
|
{
|
|
|
|
|
public string Key { get; set; }
|
|
|
|
|
public string Value { get; set; }
|
|
|
|
|
public EditorPrefType Type { get; set; }
|
|
|
|
|
public bool IsKnown { get; set; }
|
2026-02-03 15:16:30 +08:00
|
|
|
public bool IsUnset { get; set; }
|
2025-12-30 01:30:45 +08:00
|
|
|
}
|
Remote server auth (#644)
* Disable the gloabl default to first session when hosting remotely
* Remove calls to /plugin/sessions
The newer /api/instances covers that data, and we want to remove these "expose all" endpoints
* Disable CLI routes when running in remote hosted mode
* Update server README
* feat: add API key authentication support for remote-hosted HTTP transport
- Add API key field to connection UI (visible only in HTTP Remote mode)
- Add "Get API Key" and "Clear" buttons with login URL retrieval
- Include X-API-Key header in WebSocket connections when configured
- Add API key to CLI commands (mcp add, claude mcp add) when set
- Update config.json generation to include headers with API key
- Add API key validation service with caching and configurable endpoints
- Add /api/auth/login-url endpoint
* feat: add environment variable support for HTTP remote hosted mode
- Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag
- Accept "true", "1", or "yes" values (case-insensitive)
- Update CLI help text to document environment variable option
* feat: add user isolation enforcement for remote-hosted mode session listing
- Raise ValueError when list_sessions() called without user_id in remote-hosted mode
- Add comprehensive integration tests for multi-user session isolation
- Add unit tests for PluginRegistry user-scoped session filtering
- Verify cross-user isolation with same project hash
- Test unity_instances resource and set_active_instance user filtering
* feat: add comprehensive integration tests for API key authentication
- Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle
- Add startup config validation tests for remote-hosted mode requirements
- Test cache hit/miss scenarios, TTL expiration, and manual invalidation
- Test transient failure handling (5xx, timeouts, connection errors) with retry logic
- Test service token header injection and empty key fast-path validation
- Test startup validation requiring
* test: add autouse fixture to restore config state after startup validation tests
Ensures test isolation for config-dependent integration tests
* feat: skip user_id resolution in non-remote-hosted mode
Prevents unnecessary API key validation when not in remote-hosted mode
* test: add missing mock attributes to instance routing tests
- Add client_id to test context mock in set_active_instance test
- Add get_state mock to context in global instance routing test
* Fix broken telemetry test
* Add comprehensive API key authentication documentation
- Add user guide covering configuration, setup, and troubleshooting
- Add architecture reference documenting internal design and request flows
* Add remote-hosted mode and API key authentication documentation to server README
* Update reference doc for Docker Hub
* Specify exception being caught
* Ensure caplog handler cleanup in telemetry queue worker test
* Use NoUnitySessionError instead of RuntimeError in session isolation test
* Remove unusued monkeypatch arg
* Use more obviously fake API keys
* Reject connections when ApiKeyService is not initialized in remote-hosted mode
- Validate that user_id is present after successful key validation
- Expand transient error detection to include timeout and service errors
- Use consistent 1013 status code for retryable auth failures
* Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var
Consistent with repo
* Invalidate cached login URL when HTTP base URL changes
* Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues
* Cache API key in field instead of reading from EditorPrefs on each reconnection
* Align markdown table formatting in remote server auth documentation
* Minor fixes
* security: Sanitize API key values in shell commands and fix minor issues
Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions).
Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request
* Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class
Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError.
* Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases
Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead.
* Fix imports
* Filter session listing by user_id in all code paths to prevent cross-user session access
Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions.
* Consolidate get_session_id_by_hash methods into single method with optional user_id parameter
Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API.
* Add environment variable support for project-scoped-tools flag [skip ci]
Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option.
* Fix Python tests
* Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode.
* Update Server/src/main.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* Refactor HTTP transport configuration to support separate local and remote URLs
Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl).
Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP
* Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode
Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections.
* Hide Manual Server Launch foldout when not in HTTP Local mode
* Fix failing test
* Improve error messaging and API key validation for HTTP Remote transport
Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection
* Add missing .meta file
* Store transport mode in ServerConfig instead of environment variable
* Add autouse fixture to restore global config state between tests
Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation.
* Fix startup
* Replace _current_transport() calls with direct config.transport_mode access
* Minor cleanup
* Add integration tests for HTTP transport authentication behavior
Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error.
* Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes
Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
|
|
|
|
2025-12-30 01:30:45 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// EditorPrefs value types
|
|
|
|
|
/// </summary>
|
|
|
|
|
public enum EditorPrefType
|
|
|
|
|
{
|
|
|
|
|
String,
|
|
|
|
|
Int,
|
|
|
|
|
Float,
|
|
|
|
|
Bool
|
|
|
|
|
}
|
|
|
|
|
}
|