Skip to content

fix(execute_code): route CodeDom references through a response file (#1144)#1170

Merged
Scriptwonder merged 1 commit into
CoplayDev:betafrom
Scriptwonder:fix/issue-1144-codedom-arg-length
May 26, 2026
Merged

fix(execute_code): route CodeDom references through a response file (#1144)#1170
Scriptwonder merged 1 commit into
CoplayDev:betafrom
Scriptwonder:fix/issue-1144-codedom-arg-length

Conversation

@Scriptwonder
Copy link
Copy Markdown
Collaborator

@Scriptwonder Scriptwonder commented May 26, 2026

Summary

Fixes #1144execute_code with compiler=\"codedom\" fails on Windows in large projects with:

SystemException: Error running …mono.exe: The filename or extension is too long.
  at MCPForUnity.Editor.Tools.ExecuteCode.HandleExecute (ExecuteCode.cs:115)

Root cause

CodeDomCompile shoves every entry from GetAssemblyPaths() into CompilerParameters.ReferencedAssemblies. Mono's CSharpCodeCompiler.BuildArgs (mcs source, lines 388-392) turns each reference into a literal /r:\"<absolute_path>\" flag and concatenates them inline on the mono.exe csc … command line. Projects with ~100+ asmdefs (very common in large Unity projects) overflow Windows' 32 KB CreateProcess argument limit, Process.Start raises ERROR_FILENAME_EXCED_RANGE, and Mono rethrows it as SystemException.

Reporter's repro: Windows 10/11, Unity 2022.3.62f2, MCP for Unity 9.6.9-beta.8, project with 100+ asmdefs.

Fix

Write all /r:\"…\" lines to a GUID-named temp response file under Path.GetTempPath(), then pass @\"<path>\" via CompilerParameters.CompilerOptions. BuildArgs (line 396 of the same Mono source) appends CompilerOptions verbatim to the csc invocation, so the inline reference flags are replaced by a single short argument regardless of reference count.

Both legacy mcs and Roslyn csc support @responsefile syntax (it's standard C# compiler behavior, documented here). So the change is:

  • ✅ Cross-platform — same path on macOS/Linux/Windows. POSIX doesn't have the 32 KB limit, but the response file works identically.
  • ✅ Backwards-compatible — no change to public API or tool surface.
  • ✅ Cleanup-safe — temp file removed in finally (best-effort; OS reaps Temp on its own otherwise).

Rejected alternatives

Approach Why not
Shorten paths (drive-relative tricks) Fragile, doesn't scale, breaks on shared drives.
Split compilation into chunks CSharpCodeProvider has no API for it; would require building a chunking layer.
Roslyn-only path Defeats the codedom backend's purpose for users who can't install Microsoft.CodeAnalysis.

Tests

Two new EditMode regression tests in TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs, scoped to the codedom backend:

  • Execute_CodedomBackend_CompilesAndRuns — basic compile + execute, asserts result + compiler == \"codedom\".
  • Execute_CodedomBackend_ResolvesUnityTypes — verifies Unity references resolve through the response file by calling UnityEngine.Application.unityVersion.

What I couldn't verify

  • The exact 32 KB failure on Windows. I'm on macOS where Mono's POSIX Process.Start doesn't hit the limit. The response-file path is mechanically equivalent regardless of reference count, but a Windows + ~100-asmdef smoke test from a reviewer (e.g. the reporter @lgarczyn) would confirm end-to-end.
  • Local matrix compile check. None of the CI-matrix Unity Hub editors are installed on this machine; tools/check-unity-versions.sh reports all 4 as skipped.

Test plan

  • Recommend labelling safe-to-test + full-matrix so the Unity test suite fans out across 2021.3.45f2 + 2022.3.62f1 + 6000.0.75f1 + 6000.4.8f1.
  • If possible, reporter or another Windows user smokes the fix against their large-asmdef project (the repro from the issue) and confirms the SystemException is gone.

Related

Summary by CodeRabbit

  • Bug Fixes

    • Improved compiler compatibility when handling projects with many referenced assemblies on Windows systems.
  • Tests

    • Added regression tests for the codedom compiler backend to ensure reliability.

Review Change Stack

…oplayDev#1144)

`CodeDomCompile` in `MCPForUnity/Editor/Tools/ExecuteCode.cs` pushed every
filtered assembly path into `CompilerParameters.ReferencedAssemblies`. Mono's
`CSharpCodeCompiler.BuildArgs` (verified at
mcs/class/System/Microsoft.CSharp/CSharpCodeCompiler.cs:388-392) turns each
reference into a literal `/r:"<absolute_path>"` flag and concatenates them
inline on the `mono.exe csc ...` command line.

Projects with ~100+ asmdefs (a perfectly normal large Unity project) overflow
Windows' 32 KB CreateProcess argument limit and `Process.Start` throws
Win32 `ERROR_FILENAME_EXCED_RANGE`, which Mono surfaces as:

    SystemException: Error running …mono.exe: The filename or extension is too long.

…exactly the failure reported in CoplayDev#1144 at ExecuteCode.cs:115 on Windows
10/11 + Unity 2022.3.62f2 + MCP for Unity 9.6.9-beta.8.

Fix: write all `/r:"…"` lines to a GUID-named temp response file and pass
`@"<path>"` via `CompilerParameters.CompilerOptions` (which `BuildArgs`
appends verbatim, confirmed at line 396 of the same Mono source). One short
argument regardless of reference count — the 32 KB ceiling is no longer
reachable.

Both legacy mcs and Roslyn csc accept `@responsefile`, so the change is
cross-platform: macOS/Linux Mono behaves identically, and the path doesn't
have a 32 KB limit there to begin with. Response file is cleaned up in a
`finally` block (best-effort; OS reaps temp on its own otherwise).

Tests: added two EditMode regression tests in `ExecuteCodeTests.cs` that
exercise the codedom backend end-to-end:
- `Execute_CodedomBackend_CompilesAndRuns` — basic compile + execute.
- `Execute_CodedomBackend_ResolvesUnityTypes` — verifies Unity references
  resolve through the response file.

Could not reproduce the exact 32 KB failure on macOS (Mono on POSIX doesn't
hit the limit), but the response-file path is the only path in the new code,
so the fix is mechanically equivalent for any reference-set size on any
platform.

Sources:
- Mono CSharpCodeCompiler.cs — BuildArgs converts ReferencedAssemblies to
  `/r:"…"` inline and appends CompilerOptions verbatim.
- C# compiler — ResponseFiles option (`@responsefile` syntax).
Copilot AI review requested due to automatic review settings May 26, 2026 08:44
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 26, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 47e13b36-e02f-4a05-a45f-c8aa5e593e7e

📥 Commits

Reviewing files that changed from the base of the PR and between d1338ed and 67445df.

📒 Files selected for processing (2)
  • MCPForUnity/Editor/Tools/ExecuteCode.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs

📝 Walkthrough

Walkthrough

CodeDOM compiler backend now writes assembly references to a temporary response file instead of passing them as inline command-line arguments, avoiding Windows process argument length limits on projects with many assemblies. Regression tests verify successful codedom compilation and Unity API resolution.

Changes

CodeDOM Windows Argument Limit Fix

Layer / File(s) Summary
CodeDOM response file implementation
MCPForUnity/Editor/Tools/ExecuteCode.cs
CodeDomCompile refactored to build a temporary .rsp response file containing all /r:"..." reference directives and pass it via CompilerOptions instead of appending each path to ReferencedAssemblies. Includes cleanup in a finally block while preserving error collection and line-offset logic.
CodeDOM backend regression tests
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs
Two new NUnit tests verify codedom backend execution: arithmetic evaluation and resolution of Unity API values like UnityEngine.Application.unityVersion. Both confirm successful execution and correct compiler identification.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

🐰 A rabbit hops through Windows paths so long,
Response files sing where arguments belong,
No more command-line breaches, just responses small,
CodeDOM compiles smoothly—unity for all! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: using a response file to route CodeDom assembly references, directly addressing the Windows command-line length overflow issue.
Description check ✅ Passed The description is comprehensive and well-structured, covering root cause, fix, alternatives, tests, and limitations. However, some sections from the template (Type of Change, Compatibility/Package Source, Testing checkboxes) are not formally checked.
Linked Issues check ✅ Passed The code changes directly address issue #1144 by implementing response-file routing for CodeDom assembly references, preventing Windows command-line overflow and restoring compilation on large projects.
Out of Scope Changes check ✅ Passed All changes are scoped to the issue: ExecuteCode.cs modifications route references through a response file, and ExecuteCodeTests.cs adds only codedom-specific regression tests.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Fixes a Windows-specific failure in the execute_code tool when using the CodeDom backend in large Unity projects by moving long /r: reference lists off the process command line and into a temporary @responsefile.

Changes:

  • Update CodeDom compilation to write assembly references to a temp .rsp file and pass it via CompilerParameters.CompilerOptions.
  • Add EditMode regression tests verifying the CodeDom backend can compile/execute and resolve Unity types.

Reviewed changes

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

File Description
MCPForUnity/Editor/Tools/ExecuteCode.cs Routes CodeDom assembly references through a temp response file to avoid Windows command-line length limits.
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs Adds regression coverage for the CodeDom execution path and Unity-type resolution.

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

Comment on lines +287 to +291
using (var writer = new StreamWriter(responseFilePath, append: false, Encoding.UTF8))
{
GenerateInMemory = true,
GenerateExecutable = false,
TreatWarningsAsErrors = false,
};
foreach (var path in filtered)
{
writer.Write("/r:\"");
@Scriptwonder Scriptwonder added safe-to-test Triggers CI checks full-matrix Enable full-matrix CI test labels May 26, 2026
@Scriptwonder Scriptwonder merged commit 5a4a3f0 into CoplayDev:beta May 26, 2026
8 of 10 checks passed
@Scriptwonder Scriptwonder deleted the fix/issue-1144-codedom-arg-length branch May 26, 2026 09:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

full-matrix Enable full-matrix CI test safe-to-test Triggers CI checks

Projects

None yet

Development

Successfully merging this pull request may close these issues.

execute_code with codedom fails on large projects: mono.exe: filename or extension is too long

2 participants