Skip to content

Conversation

@Scriptwonder
Copy link
Collaborator

@Scriptwonder Scriptwonder commented Nov 10, 2025

Add several custom tools that MCP Servers can call to dynamically generate code during any mode.

Summary by CodeRabbit

  • New Features

    • Runtime C# compilation and in-memory assembly loading with optional immediate execution during Play Mode.
    • Attach compiled MonoBehaviour scripts to GameObjects at runtime.
    • Editor window UI for composing, compiling, running, and inspecting code with diagnostics.
    • Commands/tools to compile, execute, list loaded assemblies/types, and manage compilation history.
  • Documentation

    • Added Roslyn Runtime Compilation Tool documentation.
  • Bug Fixes

    • Improved error reporting and diagnostics for compile/run failures.

* Update the .Bat file to include runtime folder
* Fix the inconsistent EditorPrefs variable so the GUI change on Script Validation could cause real change.
String to Int for consistency
Allows users to generate/compile codes during Playmode
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 10, 2025

Walkthrough

Introduces a Roslyn-based runtime C# compilation framework for Unity MCP: new editor command handler (ManageRuntimeCompilation), a full-featured in-memory Roslyn compiler and EditorWindow (RoslynRuntimeCompiler), a Python MCP tool interface (runtime_compilation_tool), docs, and Unity asset metadata.

Changes

Cohort / File(s) Change Summary
C# Runtime Compilation Core
CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs
Adds an in-memory Roslyn compiler and runtime execution helper: compile-to-memory, dynamic DLL load, MonoBehaviour attachment, coroutine support, static method invocation, history tracking/serialization, file export, and an EditorWindow UI (UNITY_EDITOR).
C# MCP Command Handler
CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs
New centralized command dispatcher HandleCommand(JObject) supporting actions: compile_and_load, list_loaded, get_types, execute_with_roslyn, get_history, save_history, clear_history; includes parameter validation, diagnostics, and error reporting (gated by USE_ROSLYN).
Python MCP Tool Interface
CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py
Adds async MCP tools that call into the C# handler: compile_runtime_code, list_loaded_assemblies, get_assembly_types, execute_with_roslyn, get_compilation_history, save_compilation_history, clear_compilation_history; includes unified error handling and context-aware messaging.
Documentation & Metadata
CustomTools/RoslynRuntimeCompilation/RoslynRuntime.md, CustomTools/RoslynRuntimeCompilation/*.meta
Adds user documentation and Unity .meta files for new sources/assets (ManageRuntimeCompilation.cs.meta, RoslynRuntimeCompiler.cs.meta, runtime_compilation_tool.py.meta, PythonTools.asset.meta).

Sequence Diagram(s)

sequenceDiagram
    actor Client as External MCP Client
    participant PythonTool as runtime_compilation_tool.py
    participant CmdHandler as ManageRuntimeCompilation
    participant Compiler as RoslynRuntimeCompiler
    participant Unity as Unity Engine

    Client->>PythonTool: execute_with_roslyn(code, className, methodName, target, attach)
    PythonTool->>CmdHandler: HandleCommand({action: "execute_with_roslyn", ...})
    CmdHandler->>Compiler: CompileInMemory(source, refs)
    Compiler->>Compiler: Parse & Emit DLL (in-memory)
    Compiler-->>CmdHandler: {assemblyInfo, diagnostics}

    alt attach == true
        CmdHandler->>Compiler: AttachMonoBehaviour(targetGameObject)
        Compiler->>Unity: Find GameObject -> Add/Replace component
        Compiler-->>CmdHandler: {attached:true, runtimeResult}
    else
        CmdHandler->>Compiler: InvokeEntry(targetGameObject)
        Compiler->>Compiler: Invoke static method or coroutine
        Compiler-->>CmdHandler: {executed:true, runtimeResult}
    end

    CmdHandler->>Compiler: AddHistoryEntry(result)
    CmdHandler-->>PythonTool: {success:true, data, diagnostics}
    PythonTool-->>Client: {success:true, payload}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • Pay extra attention to:
    • RoslynRuntimeCompiler.cs: Roslyn compilation details, reference resolution, assembly loading/unloading, coroutine and MonoBehaviour attachment safety.
    • ManageRuntimeCompilation.cs: parameter extraction, action dispatch, and error propagation across editor/runtime boundaries.
    • runtime_compilation_tool.py: async handling, payload construction, and consistent error mapping to MCP responses.

Possibly related PRs

  • Make it easier to add tools #301 — Changes to auto-discovery/registration (mcp_for_unity_tool / McpForUnityTool) that enable automatic registration of new MCP tools like runtime_compilation_tool and ManageRuntimeCompilation.
  • Standardize how we define MCP tools #292 — Refactors command registry/dispatch flow; directly related to how ManageRuntimeCompilation.HandleCommand integrates with MCP command execution.

Suggested reviewers

  • justinpbarnett
  • dsarno

Poem

🐰 I stitched some code with carrot-powered cheer,
Roslyn hummed, the editor drew near,
From Python call to C# surprise,
A script attaches, and the rabbit sighs,
Runtime blooms — hop, compile, appear!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 65.22% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 '[CUSTOM TOOLS] Roslyn Runtime Compilation Feature' accurately summarizes the main change—adding a Roslyn-based runtime compilation feature as a custom tool for dynamic code generation.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c5b2d35 and 8805933.

📒 Files selected for processing (3)
  • CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: msanatan
Repo: CoplayDev/unity-mcp PR: 316
File: TestProjects/UnityMCPTests/Assets/Tests/EditMode/Resources.meta:1-8
Timestamp: 2025-10-13T13:27:23.040Z
Learning: UnityMcpBridge is a legacy project kept for backwards compatibility; MCPForUnity is the only active Unity plugin project. GUID collisions between UnityMcpBridge and MCPForUnity are acceptable.
Learnt from: dsarno
Repo: CoplayDev/unity-mcp PR: 0
File: :0-0
Timestamp: 2025-09-03T16:00:55.839Z
Learning: ComponentResolver in UnityMcpBridge/Editor/Tools/ManageGameObject.cs is a nested static class within ManageGameObject, not a sibling type. The `using static MCPForUnity.Editor.Tools.ManageGameObject;` import is required to access ComponentResolver methods directly without the outer class qualifier.
📚 Learning: 2025-09-03T16:00:55.839Z
Learnt from: dsarno
Repo: CoplayDev/unity-mcp PR: 0
File: :0-0
Timestamp: 2025-09-03T16:00:55.839Z
Learning: ComponentResolver in UnityMcpBridge/Editor/Tools/ManageGameObject.cs is a nested static class within ManageGameObject, not a sibling type. The `using static MCPForUnity.Editor.Tools.ManageGameObject;` import is required to access ComponentResolver methods directly without the outer class qualifier.

Applied to files:

  • CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs
  • CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs
📚 Learning: 2025-10-13T13:41:00.086Z
Learnt from: JohanHoltby
Repo: CoplayDev/unity-mcp PR: 309
File: MCPForUnity/Editor/Helpers/ServerInstaller.cs:478-508
Timestamp: 2025-10-13T13:41:00.086Z
Learning: In the MCPForUnityTools feature (MCPForUnity/Editor/Helpers/ServerInstaller.cs), the design intentionally forces users to have only one .py file per MCPForUnityTools folder to keep file tracking simple. Package-style tools (subdirectories with __init__.py) are not supported.

Applied to files:

  • CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs
📚 Learning: 2025-09-05T16:22:04.960Z
Learnt from: dsarno
Repo: CoplayDev/unity-mcp PR: 265
File: README.md:204-204
Timestamp: 2025-09-05T16:22:04.960Z
Learning: In the Unity MCP project, the ServerInstaller.cs creates a symlink from ~/Library/AppSupport to ~/Library/Application Support on macOS to mitigate argument parsing and quoting issues in some MCP clients. The README documentation should use the shortened AppSupport path, not the full "Application Support" path with spaces.

Applied to files:

  • CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs
📚 Learning: 2025-09-05T16:22:04.960Z
Learnt from: dsarno
Repo: CoplayDev/unity-mcp PR: 265
File: README.md:204-204
Timestamp: 2025-09-05T16:22:04.960Z
Learning: In the Unity MCP project, the ServerInstaller.cs creates a symlink from ~/Library/AppSupport to ~/Library/Application Support on macOS to avoid spaces in paths that can cause arg parsing and quoting issues in some MCP clients. The README documentation should use the shortened AppSupport path, not the full "Application Support" path.

Applied to files:

  • CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs
🧬 Code graph analysis (2)
CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs (2)
CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs (8)
  • System (82-92)
  • System (682-686)
  • CompileAndExecute (394-494)
  • CompileAndExecute (499-504)
  • SaveHistoryToFile (595-626)
  • ClearHistory (676-680)
  • RoslynRuntimeCompiler (44-687)
  • RoslynRuntimeCompiler (699-719)
MCPForUnity/Editor/Helpers/Response.cs (2)
  • Response (10-61)
  • Success (18-33)
CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs (1)
CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs (3)
  • RoslynRuntimeCompiler (531-547)
  • GameObject (501-525)
  • List (465-498)
🪛 Ruff (0.14.3)
CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py

30-30: Do not catch blind exception: Exception

(BLE001)


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

@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: 4

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 14b11ba and c5b2d35.

📒 Files selected for processing (8)
  • CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs.meta (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/PythonTools.asset.meta (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/RoslynRuntime.md (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs.meta (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py (1 hunks)
  • CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py.meta (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: msanatan
Repo: CoplayDev/unity-mcp PR: 316
File: TestProjects/UnityMCPTests/Assets/Tests/EditMode/Resources.meta:1-8
Timestamp: 2025-10-13T13:27:23.040Z
Learning: UnityMcpBridge is a legacy project kept for backwards compatibility; MCPForUnity is the only active Unity plugin project. GUID collisions between UnityMcpBridge and MCPForUnity are acceptable.
📚 Learning: 2025-09-03T16:00:55.839Z
Learnt from: dsarno
Repo: CoplayDev/unity-mcp PR: 0
File: :0-0
Timestamp: 2025-09-03T16:00:55.839Z
Learning: ComponentResolver in UnityMcpBridge/Editor/Tools/ManageGameObject.cs is a nested static class within ManageGameObject, not a sibling type. The `using static MCPForUnity.Editor.Tools.ManageGameObject;` import is required to access ComponentResolver methods directly without the outer class qualifier.

Applied to files:

  • CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs
  • CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs
📚 Learning: 2025-10-13T13:41:00.086Z
Learnt from: JohanHoltby
Repo: CoplayDev/unity-mcp PR: 309
File: MCPForUnity/Editor/Helpers/ServerInstaller.cs:478-508
Timestamp: 2025-10-13T13:41:00.086Z
Learning: In the MCPForUnityTools feature (MCPForUnity/Editor/Helpers/ServerInstaller.cs), the design intentionally forces users to have only one .py file per MCPForUnityTools folder to keep file tracking simple. Package-style tools (subdirectories with __init__.py) are not supported.

Applied to files:

  • CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs
🧬 Code graph analysis (2)
CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs (1)
CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs (8)
  • System (82-92)
  • System (683-687)
  • CompileAndExecute (395-495)
  • CompileAndExecute (500-505)
  • SaveHistoryToFile (596-627)
  • ClearHistory (677-681)
  • RoslynRuntimeCompiler (44-688)
  • RoslynRuntimeCompiler (700-720)
CustomTools/RoslynRuntimeCompilation/RoslynRuntimeCompiler.cs (1)
CustomTools/RoslynRuntimeCompilation/ManageRuntimeCompilation.cs (3)
  • RoslynRuntimeCompiler (508-524)
  • GameObject (478-502)
  • List (442-475)
🪛 Ruff (0.14.3)
CustomTools/RoslynRuntimeCompilation/runtime_compilation_tool.py

30-30: Do not catch blind exception: Exception

(BLE001)

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