Skip to content

Conversation

dsarno
Copy link
Owner

@dsarno dsarno commented Aug 17, 2025

Summary

  • centralize framed socket read/write logic to trim duplication and enforce length checks
  • log tool registration instead of printing to avoid stdout interference
  • resolve resource paths relative to project root and block traversal
  • tighten script management helpers and handle framing handshake errors cleanly

Testing

  • pytest -q

https://chatgpt.com/codex/tasks/task_e_68a0e9a504208327bdbeb2a5e75223fc

Copy link

coderabbitai bot commented Aug 17, 2025

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.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/streamline-protocol-framing-in-c#-and-python

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dsarno dsarno merged commit 19b1b4f into protocol-framing Aug 17, 2025
2 checks passed
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Summary

This PR implements a comprehensive refactor of the Unity MCP (Model Context Protocol) Bridge focusing on protocol framing improvements, security hardening, and code consolidation. The changes span both the C# Unity Bridge and Python MCP server components.

Core Protocol Improvements:
The main enhancement centralizes framed socket I/O logic in UnityMcpBridge.cs by extracting duplicate read/write operations into reusable methods ReadFrameAsUtf8Async and WriteFrameAsync. This eliminates code duplication that existed across the HandleClientAsync method while adding robust frame size validation, including overflow checks for int.MaxValue. The framing protocol maintains backward compatibility while enforcing consistent length validation.

Security and Path Management:
Significant security improvements were made to path handling in the Python server. The new _resolve_safe_path_from_uri() function prevents directory traversal attacks by validating that all resolved paths remain within the project root using pathlib's relative_to() method. Environment variable support for UNITY_PROJECT_ROOT provides deployment flexibility while maintaining security boundaries.

Protocol Communication Fixes:
A critical fix addresses stdout interference in the MCP protocol communication. Tool registration now uses proper logging instead of print statements, preventing corruption of JSON message exchange between the server and AI clients. This is essential for MCP protocol compliance.

Development Workflow Improvements:
Script management tools were streamlined by deprecating the 'update' operation in favor of more granular apply_text_edits, aligning with modern LSP-style editing patterns. The edit bounds checking logic was enhanced to properly handle end-of-file append operations while maintaining safety.

Connection Robustness:
Handshake error handling was improved in the Unity connection layer, now sending properly framed error messages when FRAMING=1 requirements aren't met, along with better socket cleanup to prevent resource leaks.

Important Files Changed

File Changes Summary
Filename Score Overview
UnityMcpBridge/Editor/UnityMcpBridge.cs 4/5 Centralizes framed I/O logic into reusable methods and adds robust frame size validation
UnityMcpBridge/UnityMcpServer~/src/server.py 4/5 Implements secure path resolution with directory traversal protection and environment variable support
UnityMcpBridge/UnityMcpServer~/src/tools/init.py 5/5 Replaces print statements with proper logging to prevent stdout interference in MCP protocol
UnityMcpBridge/UnityMcpServer~/src/tools/manage_script.py 4/5 Deprecates 'update' operation and simplifies content handling logic
UnityMcpBridge/UnityMcpServer~/src/tools/manage_script_edits.py 4/5 Improves bounds checking logic for end-of-file append operations
UnityMcpBridge/UnityMcpServer~/src/unity_connection.py 4/5 Enhances handshake error handling with framed error responses and socket cleanup

Confidence score: 4/5

  • This PR is generally safe to merge with good architectural improvements and security enhancements
  • Score reflects solid refactoring with proper error handling, though some changes modify core protocol behavior
  • Pay close attention to the path resolution changes in server.py and truthiness logic changes in manage_script.py

Sequence Diagram

sequenceDiagram
    participant User
    participant Client as "MCP Client"
    participant Server as "Python Server"
    participant Unity as "Unity Bridge"
    
    User->>Client: "Send MCP command"
    Client->>Server: "Tool call with parameters"
    Server->>Server: "Validate parameters"
    Server->>Unity: "Connect via TCP socket"
    Unity->>Server: "WELCOME UNITY-MCP 1 FRAMING=1"
    Server->>Unity: "Send framed command with length header"
    Unity->>Unity: "Parse JSON command"
    Unity->>Unity: "Execute command via tool handlers"
    Unity->>Server: "Send framed response with results"
    Server->>Client: "Return structured response"
    Client->>User: "Display results"
Loading

6 files reviewed, 2 comments

Edit Code Review Bot Settings | Greptile

"scriptType": script_type,
}
if contents is not None:
if contents:
Copy link

Choose a reason for hiding this comment

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

logic: Changing from if contents is not None: to if contents: means empty strings will now be treated as falsy. This could break existing functionality if empty script creation was previously supported.

# Base64 encode the contents if they exist to avoid JSON escaping issues
if contents is not None:
if action in ['create', 'update']:
if contents:
Copy link

Choose a reason for hiding this comment

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

logic: Same truthiness change here - verify that empty string contents for non-create actions should be ignored rather than processed.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Bugbot free trial expires on August 31, 2025
Learn more in the Cursor dashboard.

if contents is not None:
if action in ['create', 'update']:
if contents:
if action == 'create':
Copy link

Choose a reason for hiding this comment

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

Bug: Empty Scripts Fail Base64 Encoding

The if contents: condition now treats empty strings as falsy, preventing base64 encoding and sending of explicitly empty script content. This breaks creating scripts with intentionally empty content, as Unity may expect the encodedContents field even for empty strings. This impacts both create_script and manage_script.

Additional Locations (1)
Fix in Cursor Fix in Web

header = self._read_exact(sock, 8)
payload_len = struct.unpack('>Q', header)[0]
if payload_len == 0 or payload_len > (64 * 1024 * 1024):
if payload_len > (64 * 1024 * 1024):
Copy link

Choose a reason for hiding this comment

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

Bug: Protocol Mismatch: Zero-Length Messages

The Python side now permits zero-length framed messages, but the Unity C# side still rejects them. This creates a protocol mismatch, leading to communication failures when empty frames are sent.

Additional Locations (1)
Fix in Cursor Fix in Web

@dsarno dsarno deleted the codex/streamline-protocol-framing-in-c#-and-python branch August 19, 2025 09:57
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.

1 participant