UnityMcp.SemanticKernel.Plugin 1.0.0

dotnet add package UnityMcp.SemanticKernel.Plugin --version 1.0.0
                    
NuGet\Install-Package UnityMcp.SemanticKernel.Plugin -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="UnityMcp.SemanticKernel.Plugin" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="UnityMcp.SemanticKernel.Plugin" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="UnityMcp.SemanticKernel.Plugin" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add UnityMcp.SemanticKernel.Plugin --version 1.0.0
                    
#r "nuget: UnityMcp.SemanticKernel.Plugin, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package UnityMcp.SemanticKernel.Plugin@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=UnityMcp.SemanticKernel.Plugin&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=UnityMcp.SemanticKernel.Plugin&version=1.0.0
                    
Install as a Cake Tool

Unity-MCP-SK-Plugin

A .NET 10 Semantic Kernel plugin that enables AI agents to interact with Unity Editor through the Model Context Protocol (MCP). This plugin acts as a bridge between Semantic Kernel applications and the Unity-MCP-Server, providing seamless Unity automation capabilities for AI-powered workflows.

Overview

The Unity-MCP-SK-Plugin is a production-ready .NET class library that follows clean architecture principles and SOLID design patterns. It enables Semantic Kernel applications to discover and invoke Unity Editor functions through stdio-based MCP communication, supporting scenarios like automated scene creation, asset management, and Unity project manipulation from AI agents.

Key Features

  • Automatic Tool Discovery: Dynamically discovers available Unity functions from the MCP server
  • Type-Safe Parameter Conversion: Automatic conversion between C# types and MCP formats
  • Robust Error Handling: Comprehensive exception hierarchy with detailed diagnostics
  • Retry Logic: Configurable retry policies with exponential/linear backoff strategies
  • Health Monitoring: Connection health checks and graceful degradation
  • Secure Logging: Automatic sanitization of sensitive data in logs
  • Thread-Safe: Designed for concurrent usage in multi-threaded applications
  • High Performance: Uses System.Text.Json source generators and modern .NET patterns

Architecture

The plugin follows clean architecture with three distinct layers:

┌─────────────────────────────────────────────────────────────┐
│                    Semantic Kernel Layer                     │
│                  (Consumer Applications)                     │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                      Plugin Layer                            │
│  • Function Mapping    • Parameter Conversion               │
│  • SK Integration      • Dependency Injection               │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                   Infrastructure Layer                       │
│  • MCP Client (stdio)  • Process Management                 │
│  • Request Handling    • Retry Logic                        │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                       Core Layer                             │
│  • Interfaces          • Domain Models                      │
│  • Exceptions          • Abstractions                       │
└─────────────────────────────────────────────────────────────┘

Installation

Prerequisites

  • .NET 10 SDK or later
  • Unity-MCP-Server installed as a global tool (dotnet tool install -g unity-mcp)
  • Unity Editor (for the MCP server to connect to)

NuGet Package

Install the plugin via NuGet Package Manager:

dotnet add package UnityMcp.SemanticKernel.Plugin

Or via Package Manager Console:

Install-Package UnityMcp.SemanticKernel.Plugin

Or add to your .csproj file:

<PackageReference Include="UnityMcp.SemanticKernel.Plugin" Version="1.0.0" />

Quick Start

Basic Usage

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.SemanticKernel;
using UnityMcp.Plugin.Extensions;

// Create host with dependency injection
var builder = Host.CreateApplicationBuilder(args);

// Register Unity MCP plugin
builder.Services.AddUnityMcp(builder.Configuration);

// Register Semantic Kernel
builder.Services.AddSingleton<Kernel>();

var host = builder.Build();

// Initialize plugin and create kernel
var plugin = host.Services.GetRequiredService<UnityPlugin>();
await plugin.InitializeAsync();

var kernel = host.Services.GetRequiredService<Kernel>();

// Invoke Unity function
var result = await plugin.InvokeToolAsync(
    "unity_create_scene",
    new Dictionary<string, object?>
    {
        ["sceneName"] = "MyNewScene",
        ["addToHierarchy"] = true
    });

Console.WriteLine($"Scene created: {result}");

Automatic Tool Invocation with Semantic Kernel (.NET 10)

Use this when you want the model to decide when to call Unity tools.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using UnityMcp.Plugin;
using UnityMcp.Plugin.Extensions;

var hostBuilder = Host.CreateApplicationBuilder(args);

// Register Unity MCP plugin services
hostBuilder.Services.AddUnityMcp(options =>
{
    options.ExecutablePath = "unity-mcp";
    options.ConnectionTimeoutSeconds = 30;
    options.RequestTimeoutSeconds = 60;
});

using var host = hostBuilder.Build();

// Resolve and initialize Unity plugin
var unityPlugin = host.Services.GetRequiredService<UnityPlugin>();
await unityPlugin.InitializeAsync();

// Build kernel with chat-completion model (client responsibility)
var kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOpenAIChatCompletion(
    modelId: "gpt-4.1-mini",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")!);

var kernel = kernelBuilder.Build();

// Register Unity plugin functions into kernel
// UnityPlugin exposes [KernelFunction("invoke_unity_tool")] already.
kernel.Plugins.AddFromObject(unityPlugin, "unity");

// Enable automatic function/tool calling
var settings = new OpenAIPromptExecutionSettings
{
    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};

var response = await kernel.InvokePromptAsync(
    """
    Create a new Unity scene called AutoScene.
    Use Unity tooling and set addToHierarchy to true.
    """,
    new(settings));

Console.WriteLine(response);

Notes:

  • No extra plugin attributes are required. UnityPlugin.InvokeToolAsync is already decorated with KernelFunction and descriptions.
  • Automatic invocation is configured by the client app (model connector + FunctionChoiceBehavior.Auto())

Configuration via appsettings.json

{
  "UnityMcp": {
    "ExecutablePath": "unity-mcp",
    "ConnectionTimeoutSeconds": 30,
    "RequestTimeoutSeconds": 60,
    "MaxRetryAttempts": 3,
    "BackoffStrategy": "Exponential",
    "InitialRetryDelayMs": 1000,
    "EnableProcessPooling": true,
    "MaxIdleTimeSeconds": 300,
    "EnableMessageLogging": false
  }
}

Inline Configuration

builder.Services.AddUnityMcp(options =>
{
    options.ExecutablePath = "unity-mcp";
    options.ConnectionTimeoutSeconds = 30;
    options.RequestTimeoutSeconds = 60;
    options.MaxRetryAttempts = 3;
    options.BackoffStrategy = BackoffStrategy.Exponential;
});

Configuration Options

Option Type Default Description
ExecutablePath string "unity-mcp" Path to the unity-mcp executable
ConnectionTimeoutSeconds int 30 Maximum time to wait for connection establishment
RequestTimeoutSeconds int 60 Maximum time to wait for request completion
MaxRetryAttempts int 3 Number of retry attempts for transient failures
BackoffStrategy enum Exponential Retry backoff strategy (Linear or Exponential)
InitialRetryDelayMs int 1000 Initial delay before first retry in milliseconds
EnableProcessPooling bool true Reuse unity-mcp process across requests
MaxIdleTimeSeconds int 300 Maximum idle time before process shutdown
ToolDefinitionsPath string? null Path to predefined tool definitions (fallback)
EnableMessageLogging bool false Enable detailed request/response logging

Backoff Strategies

  • Linear: Delay = InitialRetryDelayMs × attempt number
  • Exponential: Delay = InitialRetryDelayMs × 2^(attempt number)

Available Functions

The plugin automatically discovers available Unity functions from the Unity-MCP-Server. Common functions include:

Scene Management

  • unity_create_scene - Create a new Unity scene
  • unity_load_scene - Load an existing scene
  • unity_save_scene - Save the current scene

GameObject Operations

  • unity_create_gameobject - Create a new GameObject
  • unity_delete_gameobject - Delete a GameObject
  • unity_find_gameobject - Find GameObject by name or tag

Asset Management

  • unity_import_asset - Import an asset into the project
  • unity_create_material - Create a new material
  • unity_create_prefab - Create a prefab from GameObject

Project Information

  • unity_get_project_info - Get Unity project information
  • unity_list_scenes - List all scenes in the project

Note: The exact list of available functions depends on the Unity-MCP-Server version. Use ListToolsAsync() to discover all available functions at runtime.

Advanced Usage

Custom Type Converters

Register custom converters for specialized types:

var parameterConverter = host.Services.GetRequiredService<IParameterConverter>();

parameterConverter.RegisterConverter(new MyCustomTypeConverter());

public class MyCustomTypeConverter : ITypeConverter<MyCustomType>
{
    public object? ToMcp(MyCustomType value)
    {
        // Convert to MCP format
        return new { /* ... */ };
    }

    public MyCustomType? FromMcp(object? mcpValue)
    {
        // Convert from MCP format
        return new MyCustomType(/* ... */);
    }
}

Error Handling

The plugin provides a comprehensive exception hierarchy:

try
{
    await plugin.InvokeToolAsync("unity_create_scene", parameters);
}
catch (TimeoutException ex)
{
    Console.WriteLine($"Request timed out after {ex.Timeout}");
}
catch (McpServerException ex)
{
    Console.WriteLine($"Unity server error: {ex.Message} (Code: {ex.ErrorCode})");
}
catch (NetworkException ex)
{
    Console.WriteLine($"Network error: {ex.Message}");
}
catch (ProtocolException ex)
{
    Console.WriteLine($"Protocol violation: {ex.Message}");
}
catch (UnityMcpException ex)
{
    Console.WriteLine($"General error: {ex.Message}");
}

Health Monitoring

Check connection health:

var mcpClient = host.Services.GetRequiredService<IMcpClient>();

bool isHealthy = await mcpClient.PingAsync();
Console.WriteLine($"Connection healthy: {isHealthy}");

var state = mcpClient.State;
Console.WriteLine($"Connection state: {state}");

Graceful Degradation

Use predefined tool definitions as fallback:

{
  "UnityMcp": {
    "ToolDefinitionsPath": "unity-tools.json"
  }
}

Create unity-tools.json:

[
  {
    "name": "unity_create_scene",
    "description": "Creates a new Unity scene",
    "parameters": {
      "sceneName": {
        "name": "sceneName",
        "type": "string",
        "description": "Name of the scene",
        "required": true
      }
    }
  }
]

Project Structure

Unity-MCP-SK-Plugin/
├── src/
│   ├── UnityMcp.Core/              # Domain models, interfaces, and exceptions
│   │   ├── Interfaces/             # Core abstractions (IMcpClient, IParameterConverter, etc.)
│   │   ├── Models/                 # DTOs and domain models (McpRequest, McpResponse, etc.)
│   │   ├── Exceptions/             # Custom exception types
│   │   └── Utilities/              # Helper utilities (LogSanitizer)
│   ├── UnityMcp.Infrastructure/    # MCP client and process management
│   │   ├── Client/                 # StdioMcpClient implementation
│   │   ├── Process/                # ProcessManager for unity-mcp lifecycle
│   │   ├── Serialization/          # JSON-RPC request/response handling
│   │   ├── Conversion/             # Parameter type conversion
│   │   └── Configuration/          # Configuration options and validation
│   └── UnityMcp.Plugin/            # Semantic Kernel integration
│       ├── Mapping/                # FunctionMapper for tool discovery
│       ├── Extensions/             # ServiceCollectionExtensions for DI
│       ├── Validation/             # Input validation
│       └── UnityPlugin.cs          # Main plugin class
└── tests/
    └── UnityMcp.Tests/             # Unit and integration tests
        ├── CoreTests/              # Core layer tests
        ├── InfrastructureTests/    # Infrastructure layer tests
        └── PluginTests/            # Plugin layer tests

Technology Stack

  • .NET 10 (2026 LTS) - Latest long-term support release
  • C# 13 - File-scoped namespaces, collection expressions, required members
  • Microsoft.SemanticKernel - AI agent framework integration
  • System.Text.Json - High-performance JSON serialization with source generators
  • xUnit - Unit testing framework
  • NSubstitute - Mocking framework for tests
  • FsCheck - Property-based testing library

Security

The plugin implements comprehensive security measures:

Secure Logging

All logging operations automatically sanitize sensitive information:

  • Passwords and Tokens: Never logged in plain text
  • API Keys: Automatically redacted from logs
  • Email Addresses: Replaced with [EMAIL_REDACTED]
  • JWT Tokens: Detected and redacted (eyJ... format)
  • Bearer Tokens: Removed from authorization headers
  • Connection Strings: Password fields redacted

The LogSanitizer utility provides automatic detection and redaction of sensitive data patterns.

Input Validation

All parameters are validated before being sent to the Unity-MCP server:

  • Tool names validated against registered tools
  • Parameter types checked for compatibility
  • Null values handled appropriately
  • Prevents injection attacks and malformed requests

Error Message Sanitization

Error messages are sanitized to prevent information disclosure about internal system details while maintaining useful diagnostic information.

Performance

The plugin is optimized for high performance:

  • System.Text.Json Source Generators: Zero-reflection serialization
  • FrozenDictionary: Immutable, high-performance lookups for tool definitions
  • PipeReader/PipeWriter: Efficient stdio communication
  • ValueTask: Reduced allocations for hot paths
  • LoggerMessage Source Generators: Zero-allocation structured logging
  • Process Pooling: Reuse unity-mcp process across requests

Contributing

Contributions are welcome! Please follow these guidelines:

Development Setup

  1. Clone the repository
  2. Install .NET 10 SDK
  3. Install Unity-MCP-Server: dotnet tool install -g unity-mcp
  4. Restore dependencies: dotnet restore
  5. Build the solution: dotnet build
  6. Run tests: dotnet test

Code Style

  • Follow clean architecture principles
  • Use file-scoped namespaces
  • Enable nullable reference types
  • Use collection expressions for initialization
  • Add XML documentation comments to all public APIs
  • Write unit tests for all new functionality
  • Maintain >80% code coverage

Pull Request Process

  1. Create a feature branch from main
  2. Implement your changes with tests
  3. Ensure all tests pass: dotnet test
  4. Update documentation as needed
  5. Submit a pull request with a clear description

Testing Guidelines

  • Write both unit tests and property-based tests
  • Use NSubstitute for mocking dependencies
  • Test error handling and edge cases
  • Verify thread safety for concurrent scenarios
  • Include integration tests for end-to-end flows

Building and Testing

Build

# Build entire solution
dotnet build UnityMcp.sln

# Build specific project
dotnet build src/UnityMcp.Plugin/UnityMcp.Plugin.csproj

# Build in Release mode
dotnet build -c Release

Test

# Run all tests
dotnet test UnityMcp.sln

# Run tests with coverage
dotnet test --collect:"XPlat Code Coverage"

# Run specific test project
dotnet test tests/UnityMcp.Tests/UnityMcp.Tests.csproj

# Run tests with detailed output
dotnet test --logger "console;verbosity=detailed"

Package

# Create NuGet package
dotnet pack -c Release

# Package will be created in bin/Release/

Troubleshooting

Connection Issues

Problem: NetworkException: Failed to connect to Unity-MCP server

Solutions:

  • Verify unity-mcp is installed: dotnet tool list -g
  • Check Unity Editor is running
  • Increase ConnectionTimeoutSeconds in configuration
  • Check unity-mcp logs for errors

Timeout Errors

Problem: TimeoutException: Request timed out

Solutions:

  • Increase RequestTimeoutSeconds for long-running operations
  • Check Unity Editor is responsive
  • Verify network connectivity
  • Enable EnableMessageLogging to debug request/response flow

Tool Not Found

Problem: UnityMcpException: Tool not found: unity_xxx

Solutions:

  • Verify Unity-MCP-Server version supports the tool
  • Call ListToolsAsync() to see available tools
  • Check tool name spelling
  • Provide ToolDefinitionsPath as fallback

Process Management Issues

Problem: Multiple unity-mcp processes running

Solutions:

  • Enable EnableProcessPooling to reuse processes
  • Properly dispose of UnityPlugin and services
  • Check MaxIdleTimeSeconds configuration
  • Manually kill orphaned processes

License

MIT License - See LICENSE file for details

Acknowledgments

Support

  • Issues: Report bugs and feature requests on GitHub Issues
  • Discussions: Join community discussions on GitHub Discussions
  • Documentation: Full API documentation available in XML comments

Version History

1.0.0 (Initial Release)

  • Stdio-based MCP communication
  • Automatic tool discovery
  • Type-safe parameter conversion
  • Retry logic with configurable backoff
  • Health monitoring
  • Secure logging
  • Comprehensive test coverage (>80%)
  • Clean architecture implementation
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 112 3/18/2026