Skip to content

Conversation

@dsarno
Copy link
Collaborator

@dsarno dsarno commented Jan 15, 2026

Summary

  • use fast socket reachability check for HTTP local server UI state
  • avoid expensive process inspection for periodic UI polling
  • keep existing session/orphan logic intact

Testing

  • Unity EditMode tests (UnityMCPTests) — pass
  • Unity PlayMode tests (UnityMCPTests) — pass
  • Server pytest suite — pass

Summary by Sourcery

Use a lightweight TCP reachability probe for local HTTP server status in the Unity editor and wire it into connection UI logic.

Enhancements:

  • Add a fast TCP-based IsLocalHttpServerReachable check for the configured local HTTP endpoint.
  • Update connection UI polling, toggle handling, and auto-start logic to use the new reachability check instead of the heavier process-based status check.
  • Extend the server management service interface to expose the new reachability API for editor consumers.

Summary by CodeRabbit

  • New Features

    • Added a fast local HTTP server reachability probe used by the UI.
  • Improvements

    • Start/stop controls and auto-start detection now use the quick reachability check for snappier UI state and more reliable server detection.

✏️ Tip: You can customize this high-level summary in your review settings.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jan 15, 2026

Reviewer's Guide

Introduce a fast TCP reachability check for the local HTTP server and update UI logic to use this lightweight probe instead of the heavier process/port inspection, while keeping existing server/session semantics intact.

Sequence diagram for UI polling of local HTTP server reachability

sequenceDiagram
    actor UnityEditor
    participant McpConnectionSection
    participant MCPServiceLocator
    participant IServerManagementService
    participant ServerManagementService
    participant HttpEndpointUtility
    participant TcpClient

    UnityEditor->>McpConnectionSection: UpdateStartHttpButtonState()
    McpConnectionSection->>McpConnectionSection: check httpLocalSelected
    McpConnectionSection->>McpConnectionSection: check poll interval and httpServerToggleInProgress
    alt need_new_poll
        McpConnectionSection->>MCPServiceLocator: Server
        MCPServiceLocator-->>McpConnectionSection: IServerManagementService
        McpConnectionSection->>IServerManagementService: IsLocalHttpServerReachable()
        IServerManagementService-->>ServerManagementService: dispatch
        ServerManagementService->>HttpEndpointUtility: GetBaseUrl()
        HttpEndpointUtility-->>ServerManagementService: httpUrl
        ServerManagementService->>ServerManagementService: IsLocalUrl(httpUrl)
        alt is_local_url
            ServerManagementService->>ServerManagementService: parse Uri and port
            ServerManagementService->>TcpClient: TryConnectToLocalPort(host, port, timeoutMs)
            TcpClient-->>ServerManagementService: reachable bool
            ServerManagementService-->>McpConnectionSection: reachable bool
            McpConnectionSection->>McpConnectionSection: lastLocalServerRunning = result
        else not_local_or_invalid
            ServerManagementService-->>McpConnectionSection: false
            McpConnectionSection->>McpConnectionSection: lastLocalServerRunning = false
        end
    end
    McpConnectionSection->>McpConnectionSection: localServerRunning = lastLocalServerRunning
    McpConnectionSection->>UnityEditor: update button enabled state and label
Loading

Updated class diagram for server management reachability check

classDiagram
    class IServerManagementService {
        <<interface>>
        bool IsLocalHttpServerRunning()
        bool IsLocalHttpServerReachable()
    }

    class ServerManagementService {
        bool IsLocalHttpServerRunning()
        bool IsLocalHttpServerReachable()
        static bool TryConnectToLocalPort(string host, int port, int timeoutMs)
        bool IsLocalUrl(string url)
    }

    class MCPServiceLocator {
        static IServerManagementService Server
    }

    class HttpEndpointUtility {
        static string GetBaseUrl()
    }

    class McpConnectionSection {
        double lastLocalServerRunningPollTime
        bool lastLocalServerRunning
        void UpdateStartHttpButtonState()
        void OnHttpServerToggleClicked()
        Task TryAutoStartSessionAsync()
        bool IsHttpLocalSelected()
    }

    IServerManagementService <|.. ServerManagementService
    MCPServiceLocator o-- IServerManagementService : Server
    McpConnectionSection ..> MCPServiceLocator : uses
    McpConnectionSection ..> IServerManagementService : calls
    ServerManagementService ..> HttpEndpointUtility : uses
    ServerManagementService ..> System_Net_Sockets_TcpClient : uses

    class System_Net_Sockets_TcpClient {
        bool Connected
        Task ConnectAsync(string host, int port)
    }
Loading

File-Level Changes

Change Details Files
Add a lightweight TCP reachability probe for the configured local HTTP server endpoint.
  • Introduce IsLocalHttpServerReachable() that validates the configured HTTP base URL, ensures it is local, parses its port, and delegates to a new port-probing helper.
  • Implement TryConnectToLocalPort() to attempt short-timeout TCP connections against one or more host representations (including localhost/loopback variants) and treat any failures as unreachable.
  • Handle all parsing and connectivity exceptions defensively to ensure the reachability check fails closed without throwing.
MCPForUnity/Editor/Services/ServerManagementService.cs
MCPForUnity/Editor/Services/IServerManagementService.cs
Switch UI logic to use the new reachability probe for local HTTP server status in polling and session startup flows.
  • Update connection section polling to cache and refresh local server status using IsLocalHttpServerReachable() instead of IsLocalHttpServerRunning(), keeping the existing throttling behavior.
  • Change the HTTP server toggle click handler to base its running/not-running decision on the new reachability check.
  • Update auto-start session logic to rely on IsLocalHttpServerReachable() when detecting when the local server is ready to accept connections.
MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 15, 2026

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix local HTTP server UI check' directly aligns with the main objective: introducing a lightweight TCP-based reachability check and wiring it into Unity editor connection UI logic to replace expensive process-inspection checks.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings


📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 51333d1 and 22bac8a.

📒 Files selected for processing (1)
  • MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs
🚧 Files skipped from review as they are similar to previous changes (1)
  • MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • In TryConnectToLocalPort, you’re blocking on client.ConnectAsync with Wait(timeoutMs), which can be inefficient and risks thread-pool blocking; consider using a purely synchronous connect with timeout or an async pattern (e.g., Task.WhenAny and await) to avoid blocking in polling paths.
  • The new IsLocalHttpServerReachable re-derives the base URL and performs its own local/port checks; consider refactoring to share URL/host/port resolution logic with the existing server checks to avoid divergence in behavior over time.
  • In OnHttpServerToggleClicked, the new serverRunning assignment line appears misindented relative to the surrounding code block; align its indentation to match the other statements in the method for consistency.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `TryConnectToLocalPort`, you’re blocking on `client.ConnectAsync` with `Wait(timeoutMs)`, which can be inefficient and risks thread-pool blocking; consider using a purely synchronous connect with timeout or an async pattern (e.g., `Task.WhenAny` and `await`) to avoid blocking in polling paths.
- The new `IsLocalHttpServerReachable` re-derives the base URL and performs its own local/port checks; consider refactoring to share URL/host/port resolution logic with the existing server checks to avoid divergence in behavior over time.
- In `OnHttpServerToggleClicked`, the new `serverRunning` assignment line appears misindented relative to the surrounding code block; align its indentation to match the other statements in the method for consistency.

## Individual Comments

### Comment 1
<location> `MCPForUnity/Editor/Services/ServerManagementService.cs:652-653` </location>
<code_context>
+                    {
+                        using (var client = new TcpClient())
+                        {
+                            var connectTask = client.ConnectAsync(target, port);
+                            if (connectTask.Wait(timeoutMs) && client.Connected)
+                            {
+                                return true;
</code_context>

<issue_to_address>
**issue (performance):** Blocking on `ConnectAsync` with `Wait(timeoutMs)` may cause editor UI hitches.

Because this runs on the editor UI update path, `connectTask.Wait(timeoutMs)` will block the UI thread, and slow DNS or socket delays can still cause visible stutters even with a 50ms timeout. Please either move the probe to a background task and cache the result for the UI, or use an async pattern (e.g. `Task.WhenAny` with cancellation) to enforce a strict timeout without blocking the main thread.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +652 to +653
var connectTask = client.ConnectAsync(target, port);
if (connectTask.Wait(timeoutMs) && client.Connected)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (performance): Blocking on ConnectAsync with Wait(timeoutMs) may cause editor UI hitches.

Because this runs on the editor UI update path, connectTask.Wait(timeoutMs) will block the UI thread, and slow DNS or socket delays can still cause visible stutters even with a 50ms timeout. Please either move the probe to a background task and cache the result for the UI, or use an async pattern (e.g. Task.WhenAny with cancellation) to enforce a strict timeout without blocking the main thread.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs (1)

2-2: Remove unused import System.Net.Sockets.

This namespace is no longer used in this file after the refactoring — TCP operations are encapsulated in ServerManagementService.TryConnectToLocalPort().

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b611b26 and 51333d1.

📒 Files selected for processing (3)
  • MCPForUnity/Editor/Services/IServerManagementService.cs
  • MCPForUnity/Editor/Services/ServerManagementService.cs
  • MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-12-29T15:23:11.613Z
Learnt from: msanatan
Repo: CoplayDev/unity-mcp PR: 491
File: MCPForUnity/Editor/Windows/EditorPrefs/EditorPrefsWindow.cs:78-115
Timestamp: 2025-12-29T15:23:11.613Z
Learning: In MCPForUnity, prefer relying on the established testing process to catch UI initialization issues instead of adding defensive null checks for UI elements in editor windows. This means during reviews, verify that tests cover UI initialization paths and that code avoids repetitive null-check boilerplate in Editor Windows. If a UI element can be null, ensure there is a well-tested fallback or that its initialization is guaranteed by design, rather than sprinkling null checks throughout editor code.

Applied to files:

  • MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs
  • MCPForUnity/Editor/Services/IServerManagementService.cs
  • MCPForUnity/Editor/Services/ServerManagementService.cs
🧬 Code graph analysis (3)
MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs (3)
MCPForUnity/Editor/Services/MCPServiceLocator.cs (1)
  • MCPServiceLocator (11-91)
MCPForUnity/Editor/Services/IServerManagementService.cs (1)
  • IsLocalHttpServerReachable (42-42)
MCPForUnity/Editor/Services/ServerManagementService.cs (1)
  • IsLocalHttpServerReachable (604-625)
MCPForUnity/Editor/Services/IServerManagementService.cs (1)
MCPForUnity/Editor/Services/ServerManagementService.cs (1)
  • IsLocalHttpServerReachable (604-625)
MCPForUnity/Editor/Services/ServerManagementService.cs (1)
MCPForUnity/Editor/Helpers/HttpEndpointUtility.cs (2)
  • HttpEndpointUtility (12-85)
  • GetBaseUrl (20-24)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (6)
MCPForUnity/Editor/Services/IServerManagementService.cs (1)

38-42: LGTM!

The new IsLocalHttpServerReachable() method is a clean additive change to the interface. The XML documentation clearly distinguishes this fast TCP-based probe from the existing IsLocalHttpServerRunning() process inspection method, which aligns well with the PR's goal of separating UI polling concerns from session/orphan handling logic.

MCPForUnity/Editor/Services/ServerManagementService.cs (2)

604-625: LGTM!

The IsLocalHttpServerReachable() implementation is well-structured with proper validation and exception handling. The 50ms timeout is appropriately aggressive for UI polling purposes, and returning false on any exception is a safe default.


627-671: Sound implementation with appropriate exception handling.

The TCP probe logic correctly handles common localhost variations. A few notes:

  1. The Task.Wait(timeoutMs) blocking call is acceptable here given the short 50ms timeout and UI-polling use case.
  2. Exception swallowing per-host is appropriate for a probe that only needs a boolean result.
  3. The TcpClient disposal via using properly cleans up even when the connection attempt times out.

One minor observation: connecting to 0.0.0.0 as a destination typically fails (it's a bind-any address, not routable), but the fallback to 127.0.0.1 handles this case correctly.

MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs (3)

485-494: LGTM!

The switch from IsLocalHttpServerRunning() to IsLocalHttpServerReachable() in the UI polling path is the core optimization of this PR. Combined with the existing 0.75-second throttle, this should significantly reduce CPU overhead during periodic UI updates while maintaining accurate server state detection.


534-534: LGTM!

Using the fast reachability check here is appropriate — the toggle decision only needs to know whether something is accepting connections on the port, not the full process identity.


594-594: LGTM!

Using IsLocalHttpServerReachable() in the startup polling loop is semantically correct — it verifies the server is actually accepting TCP connections rather than just that a process exists, which better reflects "ready to use" status.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@dsarno dsarno merged commit 3f08ac0 into CoplayDev:main Jan 15, 2026
2 checks passed
@dsarno dsarno deleted the fix/http-local-socket-probe branch January 15, 2026 16:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant