UN

Unity MCP Server for AI Game Development

Integrate an MCP server into Unity to run AI logic at runtime with Editor/Runtime tools, C# Roslyn, reflection, unit tests and asset support for AI games.

Quick Install
npx -y @IvanMurzak/Unity-MCP

Overview

The Unity MCP Server provides a lightweight Model Context Protocol (MCP) host inside the Unity Editor or a built Unity player so you can run AI logic and experimentation loops at runtime. It exposes a local server and tooling that allow C# scripts, dynamically compiled code (via Roslyn), and reflected types to be used as AI model implementations or environment logic, together with asset-backed data and unit tests. This enables rapid iteration of agent behaviors, dialogue systems, and test harnesses without leaving Unity.

Because it integrates into both Editor and Runtime, the MCP server is useful for prototyping ML/AI workflows, running deterministic simulation steps during automated tests, or enabling an in-game AI backend for small-scale local model execution. The included tooling focuses on developer productivity: live compilation, reflection-based binding, asset integration, and a test runner to validate AI logic before and during play.

Features

  • Local MCP server hosting inside Unity Editor and player builds
  • Runtime and Editor tools for starting/stopping the server and inspecting routes
  • C# Roslyn-based runtime compilation for on-the-fly AI scripts
  • Reflection utilities to bind Unity types and assets to MCP endpoints
  • Unit test integration to run and verify AI logic with NUnit-style tests
  • Asset support: use ScriptableObjects, JSON, and Unity assets as model context/data
  • Simple configuration (port, allowed assemblies, sandbox rules)
  • Example editor windows and runtime hooks to accelerate integration

Installation / Configuration

Install the package via the Unity Package Manager by adding the Git URL to Packages/manifest.json:

{
  "dependencies": {
    "com.example.unity-mcp": "https://github.com/IvanMurzak/Unity-MCP.git#main"
  }
}

Alternatively, clone the repo and copy the Assets/UnityMCP folder into your project.

Basic runtime configuration can be provided in a ScriptableObject or JSON file. Example ScriptableObject fields:

// Example MCPConfig.cs (ScriptableObject)
using UnityEngine;

[CreateAssetMenu(menuName = "MCP/MCPConfig")]
public class MCPConfig : ScriptableObject {
    public int port = 8088;
    public string[] allowedAssemblies = new string[] { "Assembly-CSharp" };
    public bool enableRoslynCompilation = true;
}

Load and start the server from a MonoBehaviour:

using UnityEngine;
using UnityMCP;

public class MCPBootstrap : MonoBehaviour {
    public MCPConfig config;

    void Start() {
        var server = new MCPServer(config.port);
        server.ConfigureAllowedAssemblies(config.allowedAssemblies);
        if (config.enableRoslynCompilation) server.EnableRoslynCompilation();
        server.Start();
    }

    void OnDestroy() {
        MCPServer.Instance?.Stop();
    }
}

Note: The code above is a conceptual example. Refer to the package API for exact class/method names.

Available Tools

  • Editor Window: start/stop server, view registered endpoints, inspect logs
  • Runtime Console: toggleable in builds for basic server control and diagnostics
  • Roslyn Compiler Service: compile C# snippets/files into runtime assemblies
  • Reflection Binder: expose C# classes, methods, and ScriptableObjects as MCP handlers
  • Unit Test Runner: run NUnit-style tests that exercise AI handlers and provide pass/fail reporting
  • Asset Loader: utilities to load and serialize ScriptableObjects, prefabs, and JSON data for use as model context

Component Reference (quick view)

ComponentPurpose
MCPServerHost for MCP endpoints; manage lifecycle and routing
RoslynCompilerCompile C# code strings/files at runtime
ReflectionBinderMaps types/methods/assets to MCP handlers
MCPEditorWindowUnity Editor interface for server control
MCPTestRunnerRun unit tests against AI modules
AssetSupportHelpers to load/serialize Unity assets for model input

Use Cases

  • NPC Behavior Prototyping: Quickly iterate AI scripts with Roslyn compilation, run them in-editor against simulated scenes, and validate with unit tests before deployment.
  • Dialogue & Narrative Testing: Expose dialogue-generation logic as MCP endpoints and drive conversation scenarios from automated test scripts using asset-backed context (localized strings, actor profiles).
  • Deterministic Simulation for QA: Start the MCP server in batch or test players to run reproducible AI logic loops for automated quality checks.
  • Education & Research: Teach agent architectures by letting students write and swap AI implementations live inside Unity without rebuilding the project.
  • Local Model Integration: For small models or logic that runs locally, host the model execution inside the Unity process for low-latency decisions.

Example: Running a Simple Handler

A conceptual example handler that responds to a context request:

using UnityMCP;
using System.Threading.Tasks;

public class EchoHandler {
    // Exposed via ReflectionBinder to route "/echo"
    public Task<string> Handle(string input) {
        return Task.FromResult($"Echo: {input}");
    }
}

Registering via ReflectionBinder (conceptual):

var binder = new ReflectionBinder();
binder.RegisterHandler("/echo", typeof(EchoHandler), "Handle");
MCPServer.Instance.RegisterBinder(binder);

Clients can then call the “/echo” endpoint to receive processed responses.

Best Practices & Security

  • Restrict Roslyn compilation to trusted code and known assemblies. Avoid compiling arbitrary text from untrusted sources.
  • Configure allowed assemblies and type whitelists to minimize attack surface when using reflection.
  • Use unit tests to validate AI behavior deterministically; include edge cases and asset variations.
  • For multiplayer or public exposure, run the MCP server behind proper authentication or keep it local-only.

Troubleshooting

  • Server fails to start: check port availability and Unity console for binding errors.
  • Roslyn compilation errors: inspect compile diagnostics in the Editor window/logs.
  • Reflection binding missing types: ensure the target assembly is included in the allowed assemblies list and types are not stripped by IL2CPP build settings.

For API details and examples, consult the repository source and example scenes included with the package.