Tool: execute-dynamic-code
Relevant source files
The following files were used as context for generating this wiki page:- Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeTool.cs
- Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeSchema.cs
- Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeResponse.cs
- Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/SKILL.md
- Packages/src/README.md
- SECURITY.md
- Assets/Tests/Editor/DynamicCodeToolTests/WrapCodeWithUsingStatementsAdvancedTests.cs
- Packages/src/TypeScriptServer~/src/tools/dynamic-unity-command-tool.ts
The execute-dynamic-code tool is a core feature of uLoopMCP, enabling AI agents to perform rich Unity Editor automation by executing C# code snippets dynamically. It is designed for tasks like scene manipulation, GameObject creation, component wiring, and batch processing, forming a crucial part of the autonomous development loop. The tool operates with a multi-level security model to ensure safe execution, especially when driven by AI-generated code.
A prerequisite for this tool is the installation of the Microsoft.CodeAnalysis.CSharp (Roslyn) package, which provides the necessary compilation services. The tool is exposed to LLMs via the MCP server and can also be invoked directly through the uloop CLI.
Sources: Packages/src/README.md:14-20, 150-154, Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeTool.cs:10-29
Architecture and Core Components
The execute-dynamic-code feature is composed of several key classes that handle the request, execution, and response cycle. The ExecuteDynamicCodeTool class serves as the main entry point, orchestrating the process. It uses ExecuteDynamicCodeSchema to define its input parameters and ExecuteDynamicCodeResponse for the structured output. The actual code compilation and execution are delegated to an IDynamicCodeExecutor instance, which is created by a factory based on the currently configured security level.
Sources: Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeTool.cs:31-48, Packages/src/ARCHITECTURE.md
This diagram shows the relationship between the main classes involved in the dynamic code execution process.
Execution Flow
The tool follows a sequence of steps to process a request, including security checks, compilation, execution, and intelligent error handling.
This sequence diagram illustrates the end-to-end flow from an MCP client request to the final response.
Security Model
A three-tier security model is implemented to control the capabilities of the executed code. The level is configured in the uLoopMCP Editor Window and is checked at the beginning of every execution request.
Sources: Packages/src/README.md:172-200, SECURITY.md:27-28
| Level | Name | Description |
|---|---|---|
| 0 | Disabled | The safest setting. All dynamic code compilation and execution are blocked. The tool will immediately return an error. |
| 1 | Restricted | Recommended setting. Allows access to most Unity APIs and user-defined assemblies (Assembly-CSharp). Critically sensitive operations are blocked, including file I/O (File.Delete, File.Write*), network access (HttpClient), process execution (Process.Start), and reflection-based dynamic execution (Assembly.Load*). |
| 2 | FullAccess | All assemblies and APIs are accessible with no restrictions. This level poses security risks and should only be used with fully trusted code. |
Sources: Packages/src/README.md:172-200, Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeTool.cs:83-99
Parameters (Input Schema)
The tool accepts several parameters to control its behavior, defined in ExecuteDynamicCodeSchema.cs.
| Parameter | Type | Default | Description |
|---|---|---|---|
Code | string | "" | The C# code snippet to execute. Should contain direct statements; using directives are allowed and will be hoisted. |
Parameters | Dictionary<string, object> | new() | Advanced feature to pass runtime parameters to the snippet. Values are mapped to parameters["param0"], parameters["param1"], etc. |
CompileOnly | bool | false | If true, the code is compiled using Roslyn for validation, but not executed. |
AutoQualifyUnityTypesOnce | bool | false | If true and compilation fails with common "not found" errors (e.g., CS0103), the tool will add using UnityEngine; and retry compilation once. |
Sources: Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeSchema.cs
Response (Output Schema)
The tool returns a structured response object, ExecuteDynamicCodeResponse, containing the results of the execution.
| Field | Type | Description |
|---|---|---|
Success | bool | true if compilation and execution were successful. |
Result | string | The string representation of the value returned from the code snippet. |
Logs | List<string> | A list of log messages, including user-friendly explanations and suggestions on failure. |
CompilationErrors | List<CompilationErrorDto> | Deprecated alias for Diagnostics. |
ErrorMessage | string | A friendly, high-level error message on failure. |
SecurityLevel | string | The security level under which the code was executed ("Disabled", "Restricted", "FullAccess"). |
UpdatedCode | string | The final code that was compiled after any automatic modifications (e.g., adding using statements). |
DiagnosticsSummary | string | A concise summary of compilation errors, e.g., "Errors: 1 unique (1 total). First at L2: CS0103 ...". |
Diagnostics | List<CompilationErrorDto> | A structured list of compilation errors for rich client-side display. |
Sources: Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeResponse.cs
CompilationErrorDto Structure
When compilation fails, the Diagnostics list is populated with CompilationErrorDto objects, providing detailed error information.
| Field | Type | Description |
|---|---|---|
Message | string | The raw error message from the compiler. |
Line | int | The line number of the error in the UpdatedCode. |
Column | int | The column number of the error. |
ErrorCode | string | The compiler error code (e.g., "CS0103"). |
Hint | string | An optional hint for resolving the error. |
Suggestions | List<string> | A list of suggested fixes. |
Context | string | A few lines of code surrounding the error, with a ^ pointer. |
PointerColumn | int | The column for rendering the caret pointer. |
Sources: Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeResponse.cs:51-73
Error Handling and Retries
The tool includes several mechanisms to provide better feedback and automatically fix common, simple errors.
- User-Friendly Errors: A
UserFriendlyErrorConverterprocesses compilation and runtime errors to generate helpfulLogswith explanations, examples, and potential solutions. - Automatic
return: If compilation fails with an error indicating a missing return value (CS0161, CS0127), the tool automatically appendsreturn null;and retries. - Automatic
using: IfAutoQualifyUnityTypesOnceis enabled and compilation fails with errors suggesting a missing namespace (CS0103, CS0246), the tool prependsusing UnityEngine;and retries compilation. This is a best-effort convenience feature. - Structured Diagnostics: The
DiagnosticsandDiagnosticsSummaryfields provide detailed, structured information about compilation errors, which is more useful for programmatic analysis by an AI agent than raw log parsing.
Sources: Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/ExecuteDynamicCodeTool.cs:150-200, 222-243
CLI and Skills Integration
The execute-dynamic-code tool is accessible via the uloop command-line interface and is defined as a "Skill," making it discoverable and usable by compatible LLM tools like Claude Code.
CLI Usage
The tool can be invoked from the command line. Note that string literals must be escaped correctly for the shell being used.
bash/zsh:
uloop execute-dynamic-code --code 'new UnityEngine.GameObject("MyObject"); return "Created";'
PowerShell:
uloop execute-dynamic-code --code 'new UnityEngine.GameObject(""MyObject""); return ""Created"";'
Skill Definition
A SKILL.md file provides metadata and documentation for the tool, allowing LLM agents to understand its purpose, parameters, and usage patterns. This file also links to more detailed examples for specific use cases like scene, prefab, and material operations.
Sources: Packages/src/Editor/Api/McpTools/ExecuteDynamicCode/SKILL.md, Packages/src/README.md:320-330