Skip to content

Conversation

@kripergvg
Copy link

@kripergvg kripergvg commented Jan 10, 2026

Problem: When the MCP server is configured to bind to 0.0.0.0:8080 (I am doing it locally to be able to access MCP from my local windows and from WSL), the WebSocket client would attempt to connect to 0.0.0.0, which fails because 0.0.0.0 is only valid for server binding, not client connections.

Solution: Added automatic URL translation that replaces 0.0.0.0 with localhost before establishing the WebSocket connection. This allows the server to bind on all interfaces while ensuring the client connects to the correct loopback address.

Summary by Sourcery

Bug Fixes:

  • Translate 0.0.0.0 to localhost in the constructed WebSocket endpoint URL to prevent client connection failures when the server listens on all interfaces.

Summary by CodeRabbit

  • Bug Fixes
    • Improved WebSocket endpoint construction and host normalization to handle edge host addresses (e.g., 0.0.0.0 → localhost).
    • Ensures the correct WebSocket scheme (wss/ws) is selected based on the connection protocol.
    • Consistently appends the required hub path segment so connections use a well-formed endpoint.

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

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jan 10, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

WebSocket client startup logic now normalizes server URLs that bind to 0.0.0.0 by replacing that host with localhost before constructing the WebSocket endpoint URI, ensuring client connections succeed when the server listens on all interfaces.

Sequence diagram for WebSocketTransportClient StartAsync with 0_0_0_0 to localhost normalization

sequenceDiagram
    actor Developer
    participant WebSocketTransportClient
    participant HttpEndpointUtility
    participant CancellationTokenSource

    Developer->>WebSocketTransportClient: StartAsync()
    WebSocketTransportClient->>WebSocketTransportClient: StopAsync()
    WebSocketTransportClient->>CancellationTokenSource: new CancellationTokenSource()
    WebSocketTransportClient->>HttpEndpointUtility: GetBaseUrl()
    HttpEndpointUtility-->>WebSocketTransportClient: baseUrl (may contain 0.0.0.0)
    WebSocketTransportClient->>WebSocketTransportClient: baseUrl = baseUrl.Replace(0.0.0.0, localhost)
    WebSocketTransportClient->>WebSocketTransportClient: _endpointUri = BuildWebSocketUri(baseUrl)
    WebSocketTransportClient->>WebSocketTransportClient: _sessionId = null
    WebSocketTransportClient->>WebSocketTransportClient: EstablishConnectionAsync(_lifecycleCts.Token)
    WebSocketTransportClient-->>Developer: bool (connectionEstablished)
Loading

Class diagram for updated WebSocketTransportClient StartAsync URL handling

classDiagram
    class WebSocketTransportClient {
        - CancellationTokenSource _lifecycleCts
        - Uri _endpointUri
        - string _sessionId
        + Task~bool~ StartAsync()
        + Task StopAsync()
        - Uri BuildWebSocketUri(string baseUrl)
        - Task~bool~ EstablishConnectionAsync(CancellationToken cancellationToken)
    }

    class HttpEndpointUtility {
        + static string GetBaseUrl()
    }

    WebSocketTransportClient ..> HttpEndpointUtility : uses GetBaseUrl
Loading

File-Level Changes

Change Details Files
Normalize 0.0.0.0 server base URLs to localhost before building the WebSocket endpoint URI used by the client.
  • Retrieve the base URL via HttpEndpointUtility.GetBaseUrl and store it in a local variable instead of passing it directly to BuildWebSocketUri.
  • Replace any occurrence of the host 0.0.0.0 in the base URL string with localhost to make it valid for client connections.
  • Use the modified base URL when calling BuildWebSocketUri to set _endpointUri during StartAsync initialization.
MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.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 10, 2026

📝 Walkthrough

Walkthrough

StartAsync in WebSocketTransportClient now builds the WebSocket endpoint with UriBuilder: it normalizes host (0.0.0.0localhost), selects scheme (wss for HTTPS, ws otherwise), appends /hub/plugin to the path (trimming trailing slash), and returns a Uri.

Changes

Cohort / File(s) Summary
WebSocket Transport URL Resolution
MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs
Replaced manual string URI construction with UriBuilder; normalize host 0.0.0.0localhost; choose wss when base is HTTPS (otherwise ws); append /hub/plugin with proper slash trimming; return Uri from builder.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 I hopped through paths and schemes anew,
Swapped zeros for local cozy view,
WSS or WS, the choice made clear,
"/hub/plugin" now snugly near,
A rabbit's cheer for connections true.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 accurately captures the main change: replacing 0.0.0.0 with localhost for WebSocket client connections, which is the primary bug fix in the changeset.

✏️ 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 420d2e3 and dd69992.

📒 Files selected for processing (1)
  • MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs
🚧 Files skipped from review as they are similar to previous changes (1)
  • MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.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

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:

  • The direct string replacement baseUrl.Replace("0.0.0.0", "localhost") is a bit brittle; consider parsing the URL as a Uri and only swapping the Host when it equals 0.0.0.0 to avoid accidental replacements in paths or query parameters.
  • It might be cleaner to move the 0.0.0.0localhost translation into HttpEndpointUtility.GetBaseUrl() or BuildWebSocketUri so that this behavior is centralized and consistently applied across any other consumers of the base URL.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The direct string replacement `baseUrl.Replace("0.0.0.0", "localhost")` is a bit brittle; consider parsing the URL as a `Uri` and only swapping the `Host` when it equals `0.0.0.0` to avoid accidental replacements in paths or query parameters.
- It might be cleaner to move the `0.0.0.0``localhost` translation into `HttpEndpointUtility.GetBaseUrl()` or `BuildWebSocketUri` so that this behavior is centralized and consistently applied across any other consumers of the base URL.

## Individual Comments

### Comment 1
<location> `MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs:85-92` </location>
<code_context>
+            
+            // Get base URL and replace 0.0.0.0 with localhost for client connections
+            // 0.0.0.0 is only valid for server binding, not client connections
+            string baseUrl = HttpEndpointUtility.GetBaseUrl();
+            baseUrl = baseUrl.Replace("0.0.0.0", "localhost");            
+            _endpointUri = BuildWebSocketUri(baseUrl);
             _sessionId = null;
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Use URI parsing instead of raw string replacement for the host adjustment.

This approach will replace any "0.0.0.0" substring, not just the host. Prefer parsing `baseUrl` as a `Uri`, checking `uri.Host == "0.0.0.0"`, and then using a `UriBuilder` with `Host = "localhost"` to ensure only the host component is changed.

```suggestion
            _lifecycleCts = new CancellationTokenSource();

            // Get base URL and normalize 0.0.0.0 to localhost for client connections
            // 0.0.0.0 is only valid for server binding, not client connections
            string baseUrl = HttpEndpointUtility.GetBaseUrl();
            var baseUri = new Uri(baseUrl, UriKind.Absolute);
            if (baseUri.Host == "0.0.0.0")
            {
                var uriBuilder = new UriBuilder(baseUri)
                {
                    Host = "localhost"
                };
                baseUri = uriBuilder.Uri;
            }

            _endpointUri = BuildWebSocketUri(baseUri.ToString());
            _sessionId = null;
```
</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.

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: 1

🤖 Fix all issues with AI agents
In
@MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs:
- Around line 86-92: The code currently uses string.Replace on the whole URL
which can corrupt other parts; instead parse the base URL returned by
HttpEndpointUtility.GetBaseUrl() into a Uri/UriBuilder, check the host and only
rewrite it if the host equals "0.0.0.0" (and optionally handle "127.0.0.1"
mapping if you prefer "localhost"), then rebuild the URL and pass that to
BuildWebSocketUri; update the block that sets _endpointUri (and leaves
_sessionId null) to use the Uri/UriBuilder host-only replacement and fall back
to the original string if parsing fails.
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c9beaf and b5e9ad6.

📒 Files selected for processing (1)
  • MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.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/Services/Transport/Transports/WebSocketTransportClient.cs
🧬 Code graph analysis (1)
MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.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 (1)
MCPForUnity/Editor/Services/Transport/Transports/WebSocketTransportClient.cs (1)

86-92: No other client transports require the same normalization.

WebSocketTransportClient is the only client transport using HttpEndpointUtility.GetBaseUrl() for establishing connections. StdioTransportClient uses a different mechanism (StdioBridgeHost), and ServerManagementService's calls to GetBaseUrl() are limited to server lifecycle management, not client connections.

@kripergvg kripergvg force-pushed the main branch 2 times, most recently from 420d2e3 to 5389b01 Compare January 10, 2026 17:34
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