Skip to content

Refactor instance resolution, simplify stdio tools handling, and remove redundant status-file try/catch#12

Merged
whatevertogo merged 1 commit into
feat/stdio-tool-toggle-from-devfrom
codex/simplify-duplicated-branches-in-middleware
Feb 19, 2026
Merged

Refactor instance resolution, simplify stdio tools handling, and remove redundant status-file try/catch#12
whatevertogo merged 1 commit into
feat/stdio-tool-toggle-from-devfrom
codex/simplify-duplicated-branches-in-middleware

Conversation

@whatevertogo

@whatevertogo whatevertogo commented Feb 19, 2026

Copy link
Copy Markdown
Owner

Motivation

  • Remove duplicated logic for resolving instance identifiers and stdio status normalization to make behavior centralized and easier to maintain.
  • Use a non-recursive lock where no recursive acquisition occurs to better express intent.
  • Avoid redundant exception handling around StdioBridgeHost.RefreshStatusFile() since the callee already handles errors.

Description

  • Simplified UnityInstanceMiddleware._build_stdio_tools_state_signature() by merging duplicate set / list branches into a single isinstance(enabled_raw, (set, list)) check and normalization of tool names.
  • Switched _session_lock from RLock() to Lock() in UnityInstanceMiddleware to reflect non-recursive usage (Server/src/transport/unity_instance_middleware.py).
  • Refactored the set_active_instance tool to delegate all port/hash/Name@hash resolution to the middleware method UnityInstanceMiddleware._resolve_instance_value(...), removing the duplicated resolution/discovery code and reusing middleware validation (Server/src/services/tools/set_active_instance.py).
  • Removed the outer try/catch wrapper from ManageEditor.RefreshStdioStatusFile() since StdioBridgeHost.RefreshStatusFile() already catches and logs exceptions (MCPForUnity/Editor/Tools/ManageEditor.cs).

Testing

  • Ran python -m py_compile Server/src/transport/unity_instance_middleware.py Server/src/services/tools/set_active_instance.py which succeeded.
  • Attempted targeted pytest for relevant tests, but test collection failed due to a missing runtime dependency (ModuleNotFoundError: No module named 'starlette') in the current environment, so full test execution could not be completed here.

Codex Task

Summary by Sourcery

Refactor Unity instance selection and stdio tooling state handling while simplifying error and lock management across server and editor components.

Enhancements:

  • Centralize Unity instance identifier resolution in middleware and update the set_active_instance tool to delegate all resolution and validation to it, including error messaging.
  • Simplify stdio tools state signature construction by unifying list/set handling and normalizing enabled tool names.
  • Switch the UnityInstanceMiddleware session lock from a recursive lock to a standard lock to better reflect its non-recursive use.
  • Remove redundant exception handling around stdio status file refresh in the Unity editor, relying on StdioBridgeHost for error handling.

Summary by CodeRabbit

Refactor

  • Instance resolution now uses centralized middleware services, reducing transport-specific complexity and improving consistency
  • Internal synchronization mechanisms refined for improved concurrent operation efficiency and reliability
  • Status refresh operations streamlined with simplified and more robust error handling
  • Tool configuration state management enhanced for greater flexibility, supporting multiple input formats

Copilot AI review requested due to automatic review settings February 19, 2026 09:32
@sourcery-ai

sourcery-ai Bot commented Feb 19, 2026

Copy link
Copy Markdown
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Refactors Unity instance resolution to be centralized in middleware, simplifies stdio tools state handling, tightens locking semantics, and removes redundant exception handling around stdio status refresh.

Sequence diagram for centralized Unity instance resolution in set_active_instance tool

sequenceDiagram
    actor User
    participant SetActiveInstanceTool as set_active_instance_tool
    participant UnityInstanceMiddleware

    User->>SetActiveInstanceTool: set_active_instance(ctx, instance)
    SetActiveInstanceTool->>SetActiveInstanceTool: normalize value from instance
    SetActiveInstanceTool->>UnityInstanceMiddleware: _resolve_instance_value(value, ctx)
    alt resolution succeeds
        UnityInstanceMiddleware-->>SetActiveInstanceTool: resolved_id
        SetActiveInstanceTool->>UnityInstanceMiddleware: set_active_instance(ctx, resolved_id)
        SetActiveInstanceTool->>UnityInstanceMiddleware: get_session_key(ctx)
        UnityInstanceMiddleware-->>SetActiveInstanceTool: session_key
        SetActiveInstanceTool-->>User: success, message, instance, session_key
    else resolution raises ValueError
        UnityInstanceMiddleware-->>SetActiveInstanceTool: ValueError
        SetActiveInstanceTool-->>User: success False, error message
    end
Loading

Updated class diagram for UnityInstanceMiddleware and related tools

classDiagram
    class UnityInstanceMiddleware {
        -dict~str,str~ _active_by_key
        -RLock _lock
        -RLock _metadata_lock
        -Lock _session_lock
        -set~str~ _unity_managed_tool_names
        -dict~str,str~ _tool_alias_to_unity_target
        -set~str~ _server_only_tool_names
        +tuple _build_stdio_tools_state_signature()
        +str _resolve_instance_value(str value, Context ctx)
        +void set_active_instance(Context ctx, str instance_id)
        +str get_session_key(Context ctx)
    }

    class SetActiveInstanceTool {
        +dict~str,Any~ set_active_instance(Context ctx, str instance)
    }

    class ManageEditor {
        +void RefreshStdioStatusFile()
    }

    class StdioBridgeHost {
        +void RefreshStatusFile(str source)
    }

    SetActiveInstanceTool --> UnityInstanceMiddleware : uses
    ManageEditor --> StdioBridgeHost : calls
Loading

File-Level Changes

Change Details Files
Centralize instance resolution logic in middleware and simplify the set_active_instance tool.
  • Remove inline transport-specific discovery and resolution (port, Name@hash, hash prefix) from the set_active_instance tool.
  • Delegate instance lookup and validation to UnityInstanceMiddleware._resolve_instance_value, mapping ValueError to a user-facing error response.
  • Retain middleware-based persistence of the active instance and session key, now using the resolved identifier string instead of a resolved instance object.
Server/src/services/tools/set_active_instance.py
Adjust locking semantics for session management in UnityInstanceMiddleware.
  • Change _session_lock from RLock to Lock to reflect non-recursive usage while leaving other RLocks unchanged.
Server/src/transport/unity_instance_middleware.py
Simplify stdio tools state signature construction.
  • Merge separate set and list handling branches into a single isinstance(enabled_raw, (set, list)) path while preserving validation and sorting of string tool names.
Server/src/transport/unity_instance_middleware.py
Remove redundant exception handling around stdio status file refresh in the Unity editor integration.
  • Call StdioBridgeHost.RefreshStatusFile directly from ManageEditor.RefreshStdioStatusFile, relying on internal error handling and logging in the callee.
MCPForUnity/Editor/Tools/ManageEditor.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

@whatevertogo whatevertogo merged commit aaa3260 into feat/stdio-tool-toggle-from-dev Feb 19, 2026
6 of 7 checks passed
@coderabbitai

coderabbitai Bot commented Feb 19, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/simplify-duplicated-branches-in-middleware

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.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • The set_active_instance tool now relies on the private method UnityInstanceMiddleware._resolve_instance_value; consider promoting this to a public helper or moving the logic to a shared utility to avoid cross-module dependence on a private implementation detail.
  • Catching a bare ValueError in set_active_instance and returning str(exc) directly makes user-visible errors tightly coupled to the middleware implementation; you may want a more structured error contract (e.g., custom exception types or error codes) to keep internal changes from unintentionally altering API responses.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `set_active_instance` tool now relies on the private method `UnityInstanceMiddleware._resolve_instance_value`; consider promoting this to a public helper or moving the logic to a shared utility to avoid cross-module dependence on a private implementation detail.
- Catching a bare `ValueError` in `set_active_instance` and returning `str(exc)` directly makes user-visible errors tightly coupled to the middleware implementation; you may want a more structured error contract (e.g., custom exception types or error codes) to keep internal changes from unintentionally altering API responses.

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors Unity instance targeting and stdio tool-state handling to centralize resolution/validation logic in UnityInstanceMiddleware, and removes redundant exception handling around stdio status refresh in the Unity editor integration.

Changes:

  • Simplifies stdio enabled-tools signature generation by unifying set/list handling.
  • Switches session tracking lock from RLock to Lock to reflect non-recursive usage.
  • Refactors the set_active_instance tool to reuse middleware instance-resolution logic instead of duplicating discovery/validation.
  • Removes redundant try/catch around StdioBridgeHost.RefreshStatusFile() in ManageEditor.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
Server/src/transport/unity_instance_middleware.py Uses a non-recursive session lock and simplifies stdio tools signature construction; provides centralized instance resolution helper.
Server/src/services/tools/set_active_instance.py Delegates instance parsing/validation to the middleware resolver and simplifies the tool implementation.
MCPForUnity/Editor/Tools/ManageEditor.cs Removes redundant exception handling around stdio status refresh.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +29 to +30
try:
resolved_id = await middleware._resolve_instance_value(value, ctx)

Copilot AI Feb 19, 2026

Copy link

Choose a reason for hiding this comment

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

set_active_instance is calling UnityInstanceMiddleware._resolve_instance_value(...), which is a private (underscore-prefixed) middleware helper. Since this tool lives outside the middleware module, this creates a brittle cross-module dependency on internal implementation details. Consider exposing a public method (e.g., resolve_instance_value) or a small shared resolver utility, and have both the middleware and tool call that instead of reaching into a private method.

Suggested change
try:
resolved_id = await middleware._resolve_instance_value(value, ctx)
resolver = getattr(middleware, "resolve_instance_value", None)
if resolver is None or not callable(resolver):
raise RuntimeError(
"Unity instance resolver is not available. "
"Expected UnityInstanceMiddleware.resolve_instance_value(...) to be implemented."
)
try:
resolved_id = await resolver(value, ctx)

Copilot uses AI. Check for mistakes.
@whatevertogo

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants