Логотип Code Mode for Unity Editor

Code Mode for Unity Editor

Сообщество
RomaRogov

AI Code Mode extension for Unity featuring UTCP Server with MCP wrapper

ИздательRomaRogov
Репозиторийunity-code-mode
ЯзыкC#
Форки
2
Звёзды
16
Доступные инструменты
7
Тип транспортаstdio
Категории
ЛицензияApache-2.0
Ссылки
  • Подключайте инструменты к рабочим процессам с ИИ

    Code Mode for Unity Editor предоставляет возможности MCP, доступные совместимым ИИ-клиентам и агентам.

  • Доступные инструменты: 7

    Ниже представлены доступные для вызова действия с названиями и описаниями, если сервер их предоставляет.

  • Готовая конфигурация для копирования

    Используйте примеры конфигурации, чтобы настроить этот сервер в предпочитаемом MCP-клиенте.

  • Показатели интереса к открытому проекту

    Звёзды: 16, форки: 2 — в связанном репозитории.

Code Mode for Unity Editor

Code Mode for Unity turns the Unity Editor into an AI-controllable tool. It runs an HTTP server inside the editor that exposes scene manipulation, asset management, and property inspection as structured tool calls via UTCP Protocol - letting AI agents build, inspect, and modify Unity projects the same way a developer would through the UI. These tools are combined in UTCP Code Mode environment to achieve maximum performance and token efficiency for AI agents, letting them call the tools in isolated JS sandbox.

Quickstart

  1. Install extension in the Unity project
  2. Integrate extension with CodeMode MCP Server
  3. Design a system prompt for you agent or use provided example
  4. Ask AI to help you and see how it learns!

What is Code Mode?

In contrast to rigid MCP tool defenitions, which always kept in LLM context, CodeMode is an approach which helps AI to call tools in the most familiar way - by writing JavaScript code based on TypeScript defenitions of tools. This helps AI to keep token consumption low, implement loops and chained calls for complex tasks, organize output in compact form and reuse output from different existing servers and endpoints in one JavaScript execution context, isolating LLM context from unnecessary data. This opens endless possibilities for interaction between different environments. Here is some examples:

  1. Move scene from blender with Blender MCP, exporting particular objects as FBX straight into Unity project
  2. Use Figma MCP to fetch UI layout from figma and implement these layouts in your project in the smart way instead of blindly recreating every panel
  3. Use Cocos Code Mode to perform game porting between engines
  4. Bring your own examples 🙃

All this becomes possible with community-friendly, flexible and open solution from UTCP team: CodeMode and it's MCP Server. You can read more about Code Mode concept in papers from Anthropic, Apple and Cloudflare.

Tools

Tools <> UI Mapping

CategoryToolsPurpose
SceneGameObjectGetTree, GameObjectGetAtPath, GameObjectCreate, GameObjectCreatePrimitive, GameObjectOperateNavigate and build scene hierarchy
ComponentsGameObjectComponentsGet, GameObjectComponentAdd, GameObjectComponentRemove, GameObjectGetAvailableComponentTypesAttach, remove, and discover components
InspectorInspectorGetInstanceDefinition, InspectorGetInstanceProperties, InspectorSetInstancePropertiesIntrospect types and read/write properties
AssetsAssetGetTree, AssetGetAtPath, AssetCreate, AssetImport, AssetOperate, AssetGetPreviewBrowse, create, and manage project assets
EditorEditorOperate, EditorGetLogs, EditorGetScenePreviewControl editor state and capture previews
SettingsSettingsGetDefinition, SettingsGetProperties, SettingsSetPropertiesRead and modify project settings

How It Works

This extension architecture follows a discover, then act pattern. AI agents never guess at property names or component structures — they query for the real definitions first.

1. Get the scene tree         →  find the object you need
2. Get its type definition    →  learn its actual properties
3. Set properties by name     →  make precise changes

Example

typescript
// Find the camera
const tree = UnityEditor.GameObjectGetTree({});
const cameraTransform = tree.children[0].components[0]; // Transform ref

// Discover what properties Transform has
const def = UnityEditor.InspectorGetInstanceDefinition({ reference: cameraTransform });
// → "export class Transform { localPosition: Vector3; localRotation: Vector3; localScale: Vector3; }"

// Set multiple properties in one call
UnityEditor.InspectorSetInstanceProperties({
  reference: cameraTransform,
  propertyPaths: ["localPosition", "localRotation"],
  values: [{ x: 0, y: 5, z: -10 }, { x: 30, y: 0, z: 0 }]
});

Technical implementation details

Tool Execution

HTTP requests arrive on a background thread. All tool execution is marshaled to Unity's main thread via an EditorApplication.update queue.

  • Fire-and-forget tools (void / UniTask return) — enqueued and return { success: true } immediately. The caller doesn't wait.
  • Value-returning tools (T / UniTask<T> return) — enqueued with a completion source. The HTTP response waits until the tool finishes on the main thread.

This means chained calls from AI agents don't block on side-effect-only operations like property changes or editor commands.

Tool Declarations

Tools are plain static methods marked with [UtcpTool]. The ToolRegistry finds them at startup via Unity's TypeCache, generates JSON schemas from their C# signatures, and serves a UTCP manual at /utcp endpoint.

csharp
[UtcpTool("Get the hierarchy tree of a GameObject", httpMethod: "GET",
    tags: new[] { "scene", "hierarchy", "tree" })]
public static SceneTreeItem GameObjectGetTree(InstanceReference<GameObject> reference)
{
    // ...
}

Two input modes:

  • Parameter-based — each method parameter becomes an input field
  • Class-based — a single UtcpInput-derived class for complex inputs

At the moment tool output always should have class type or void, may be also UniTask or UniTask<T> for async operations.

Instance References

Objects are passed around as lightweight handles:

typescript
{ id: "29880", type: "Camera" }

Returned by tree queries, component lookups, and creation tools. They are resolved to Unity objects when passed back, usually with InstanceReference.Instance getter or with EditorUtility.InstanceIDToObject(id).

Custom AI Agent Editors

For components where the raw SerializedProperty layout doesn't map cleanly to what an AI agent should see (RectTransform, Camera, AnimatorController, etc.), Code Mode provides the AiAgentEditor system.

Each editor declares:

  • OnEnable — bind serialized properties and register handlers
  • OnDumpRequested — emit a clean JSON snapshot of current values
  • OnDefinitionRequested — emit a TypeScript class definition

Editors support inheritance. For example, ColliderAgentEditor (base) handles common collider properties like isTrigger or physic material; BoxColliderAgentEditor extend it with type-specific properties:

csharp
[CustomAiAgentEditor(typeof(BoxCollider))]
public class BoxColliderAgentEditor : ColliderAgentEditor
{
    private SerializedProperty m_Center;
    private SerializedProperty m_Size;

    protected override void OnEnable()
    {
        base.OnEnable();
        m_Center = serializedObject.FindProperty("m_Center");
        m_Size = serializedObject.FindProperty("m_Size");

        AddSettingPropertyHandler("center",
            () => m_Center.vector3Value.SerializeToJObject(),
            v => m_Center.vector3Value = v.DeserializeToVector3());

        AddSettingPropertyHandler("size",
            () => m_Size.vector3Value.SerializeToJObject(),
            v => m_Size.vector3Value = v.DeserializeToVector3());
    }

    protected override void OnDumpRequested()
    {
        base.OnDumpRequested();
        DumpProperty("center", m_Center.vector3Value.SerializeToJObject());
        DumpProperty("size", m_Size.vector3Value.SerializeToJObject());
    }

    protected override void OnDefinitionRequested()
    {
        base.OnDefinitionRequested();
        EmitClassDefinition("BoxCollider", new List<TsPropertyDef>
        {
            TsPropertyDef.Field("center", "Vector3"),
            TsPropertyDef.Field("size", "Vector3"),
        }, "Collider");
    }
}

Components without a custom editor fall back to automatic serialization from SerializedObject.

Installation

  1. Open Package Manager → + → Add package from git URL
  2. Enter: https://github.com/romarogov/unity-code-mode.git?path=Packages/com.roro.codemode

Adding Custom Tools

csharp
using CodeMode.Editor.Tools.Attributes;

public static class MyTools
{
    [UtcpTool("Describe what this tool does", httpMethod: "POST")]
    public static MyResult DoSomething(string input, int count = 10)
    {
        // Implementation — runs on main thread
    }
}

Tools are discovered automatically at startup. No registration needed.

UTCP Call Templates Configuration

This extension also have a special configuration utility for UTCP call templates, which can be used to connect different UTCP tools (including MCP servers!) into one Code Mode execution context. It is accessible from Code Mode → UTCP Templates menu.

You can find Call Template structures in UTCP documentation:

Integration

Code Mode works with any UTCP-compatible client, including the Code Mode MCP server for AI assistants.

MCP Server Config

This extension provides example of integration config for UTCP Code Mode MCP server with prefilled path to config in Preferences → Code Mode page:

json
{
  "mcpServers": {
    "code-mode": {
      "command": "npx",
      "args": ["@utcp/code-mode-mcp"],
      "env": {
        "UTCP_CONFIG_FILE": "/path/to/.utcp_config.json"
      }
    }
  }
}

Claude Code Configuration

To setup a Claude Code agent to use Code Mode, open your project and run following command:

Linux/MacOS:

bash
claude mcp add --transport stdio --env UTCP_CONFIG_FILE="/path/to/.utcp_config.json" -- code-mode npx @utcp/code-mode-mcp

Windows:

powershell
claude mcp add --transport stdio --env UTCP_CONFIG_FILE="/path/to/.utcp_config.json" -- code-mode cmd /c npx @utcp/code-mode-mcp

Установка

TypingMind
{
  "mcpServers": {
    "unity-code-mode": {
      "command": "npx",
      "args": [
        "@utcp/code-mode-mcp"
      ],
      "env": {
        "UTCP_CONFIG_FILE": "<UTCP_CONFIG_FILE>"
      }
    }
  }
}

Доступные инструменты

  • register_manual

    Registers a new tool provider by providing its call template.

  • deregister_manual

    Deregisters a tool provider from the UTCP client.

  • search_tools

    Searches for relevant tools based on a task description.

  • list_tools

    Returns a list of all tool names currently registered.

  • get_required_keys_for_tool

    Get required environment variables for a registered tool.

  • tools_info

    Get complete information about a specified list of tools, including TypeScript interface definition.

  • call_tool_chain

    Execute TypeScript code with direct access to all registered tools as hierarchical functions (e.g., manual.tool()).

Используйте MCP Code Mode for Unity Editor с разными ИИ-моделями

TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому после подключения Code Mode for Unity Editor вы можете использовать их с разными моделями ИИ в TypingMind, не настраивая подключение отдельно для каждой модели. Эта интеграция MCP работает локально на вашем устройстве через коннектор MCP TypingMind.

Руководство по настройке локального коннектора

Выберите этот способ, если серверу MCP нужен доступ к локальным файлам, приложениям или закрытым ресурсам на вашем компьютере.

1

Откройте настройки MCP

В TypingMind откройте «Настройки», затем «Расширенные настройки», перейдите в раздел «Протокол контекста модели» и выберите «Настроить коннектор».

  1. Откройте TypingMind в браузере.
  2. Нажмите значок настроек.
  3. Перейдите в «Расширенные настройки».
  4. Откройте раздел «Протокол контекста модели».
  5. Нажмите «Настроить коннектор» и выберите «Это устройство».
Экран настройки коннектора MCP в TypingMind с выбранным вариантом «Это устройство»
2

Выполните команду коннектора

Выберите «Это устройство», скопируйте команду из TypingMind и выполните её в терминале. Не останавливайте процесс, пока используете MCP.

  1. Скопируйте команду настройки, показанную в TypingMind.
  2. Откройте «Терминал» в macOS или Windows Terminal в Windows.
  3. Вставьте и выполните команду.
  4. Подтвердите установку пакета, если терминал запросит разрешение продолжить.
  5. Не закрывайте окно терминала и не останавливайте процесс, пока используете инструменты MCP.
3

Добавьте Code Mode for Unity Editor как сервер

Когда статус коннектора сменится на «Готов», нажмите «Изменить серверы» и вставьте конфигурацию сервера MCP.

  1. Дождитесь, пока статус коннектора сменится на «Готов».
  2. Нажмите «Изменить серверы».
  3. Вставьте конфигурацию сервера MCP для Code Mode for Unity Editor.
  4. Сохраните список серверов.
  5. Обновите статус, если хотите убедиться, что коннектор по-прежнему готов к работе.
Настройки MCP в TypingMind с активным сервером и кнопкой «Изменить серверы»
{
  "mcpServers": {
    "unity-code-mode": {
      "command": "npx",
      "args": [
        "-y",
        "@utcp/code-mode-mcp"
      ]
    }
  }
}
4

Используйте подключение с разными моделями

Сохраните список серверов, откройте раздел «Плагины», включите инструменты MCP для Code Mode for Unity Editor, затем выберите любую поддерживаемую модель ИИ в TypingMind и используйте инструменты в чате или назначьте их ИИ-агенту.

  1. Откройте страницу «Плагины» в TypingMind.
  2. Включите инструменты MCP для Code Mode for Unity Editor.
  3. Начните чат и выберите модель ИИ, которую хотите использовать.
  4. Используйте инструменты MCP в чате или назначьте их ИИ-агенту.
  5. При необходимости переключайтесь на другую модель ИИ без повторного подключения MCP.
Чат TypingMind с включёнными инструментами MCP и выбранной ИИ-моделью
Можете помочь мне с этой задачей с помощью Code Mode for Unity Editor?
Code Mode for Unity Editor
Конечно. Я всё прочитал.
Вот что я нашёл с помощью Code Mode for Unity Editor.

Часто задаваемые вопросы

Для чего используется сервер MCP Code Mode for Unity Editor?

Code Mode for Unity Editor — это сервер MCP, который позволяет совместимым ИИ-клиентам подключаться к внешним инструментам и получать контекст. В TypingMind достаточно один раз добавить этот сервер MCP, чтобы его инструменты стали доступны в вашем рабочем пространстве с ИИ.

Можно ли использовать сервер MCP Code Mode for Unity Editor с несколькими ИИ-моделями в TypingMind?

Да. TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому вы можете использовать Code Mode for Unity Editor с разными ИИ-моделями, например Claude, ChatGPT, Gemini или другими моделями, настроенными в TypingMind, без отдельной настройки сервера MCP для каждой модели.

Зачем использовать MCP Code Mode for Unity Editor с TypingMind?

TypingMind — один из лучших интерфейсов для чата с LLM: он объединяет разные ИИ-модели, промпты, плагины, ИИ-агентов, ключи API и инструменты MCP в одном рабочем пространстве. Подключив Code Mode for Unity Editor, вы сможете использовать его инструменты MCP с предпочитаемыми моделями, сохраняя удобную организацию работы с чатами в TypingMind.

Как подключить сервер MCP Code Mode for Unity Editor к TypingMind?

Code Mode for Unity Editor работает через локальный коннектор MCP TypingMind. Этот вариант лучше всего подходит, когда серверу MCP нужен доступ к локальным файлам, настольным приложениям, инструментам командной строки или закрытым ресурсам на вашем компьютере.

Какие инструменты предоставляет сервер MCP Code Mode for Unity Editor в TypingMind?

Code Mode for Unity Editor предоставляет инструменты MCP (7), которые можно включить на странице «Плагины» в TypingMind и использовать в чате или назначить ИИ-агентам.

Нужно ли передавать TypingMind свои ключи API для использования сервера MCP Code Mode for Unity Editor?

Нет. TypingMind ориентирован прежде всего на локальную работу и позволяет вам контролировать выбор провайдеров моделей, ключи API, промпты и конфигурацию MCP. Если Code Mode for Unity Editor требует аутентификации, при создании подключения добавьте необходимые заголовки, настройки OAuth или локальную конфигурацию для этого сервера MCP.

utcp_codemode_usage

Comprehensive guide on how to use the UTCP Code Mode MCP server for executing TypeScript code with tool access.

Похожие серверы MCP

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇