Skip to main content
Glama

emptysock-mcp

Сервер Model Context Protocol для игрового движка EmptySock. Предоставляет системные компоненты движка — NavMesh, Physics, Scene, Save и Actor — как инструменты MCP, доступные для Claude Desktop, AI-агентов и Claude API.


Требования

  • Node.js 20+

  • npm 9+


Related MCP server: Hayba

Установка

git clone https://github.com/eleferrets/emptysock-mcp.git
cd emptysock-mcp
npm install
npm run build

Конфигурация

Скопируйте пример env-файла и заполните нужные значения:

cp .env.example .env

Переменная

Обязательно

Описание

EMPTYSOCK_API_TOKEN

Нет

Bearer-токен для аутентифицированных вызовов к API движка

MCP_AUTH_TOKEN

Нет

Обязательный Bearer-токен для запросов на SSE-транспорте. Оставьте пустым, чтобы отключить аутентификацию.

SAVE_BASE_DIR

Нет

Абсолютный путь, который инструменты сохранения могут читать/записывать. По умолчанию — рабочая директория процесса. В продакшене задавайте явно.

Никогда не коммитьте .env — он в .gitignore. Храните секреты в менеджере секретов CI/CD, а не в репозитории.


Запуск сервера

stdio (рекомендуется для локального использования и Claude Desktop)

npm run dev          # development — tsx, no build step
# or after building:
node dist/server.js

Сервер общается через stdin/stdout. Сетевого порта и поверхности аутентификации нет.

Claude Desktop

Добавьте сервер в конфиг Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json на macOS):

{
  "mcpServers": {
    "emptysock": {
      "command": "node",
      "args": ["/absolute/path/to/emptysock-mcp/dist/server.js"],
      "env": {
        "SAVE_BASE_DIR": "/absolute/path/to/your/saves"
      }
    }
  }
}

Перезапустите Claude Desktop. Инструменты EmptySock появятся в выборе инструментов.


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

NavMesh

Инструмент

Описание

navmesh_find_path

Путь A* между двумя 2D-точками мира по загруженной навмеше. Возвращает упорядоченные путевые точки или [], если путь не существует.

navmesh_nearest_node

Ближайший проходимый узел навмеша к заданной точке мира.

Пример — поиск пути:

{
  "from": { "x": 0, "y": 0 },
  "to":   { "x": 100, "y": 50 },
  "mapId": "level1"
}

Physics

Инструмент

Описание

physics_raycast_2d

Запускает луч в 2D-физическом пространстве; возвращает первую задетую сущность, точку попадания и нормаль.

physics_raycast_3d

Запускает луч в 3D-физическом пространстве (Rapier3D); возвращает первое попадание.

physics_overlap_circle

Все идентификаторы сущностей, чьи 2D-коллайдеры пересекают окружность.

physics_body_state

Текущая позиция, скорость и угловая скорость физического тела по идентификатору сущности.

Пример — перекрытие окружности:

{
  "center": { "x": 50, "y": 50 },
  "radius": 20,
  "layerMask": 3
}

Scene

Инструмент

Описание

scene_list_entities

Все идентификаторы сущностей, активных в сцене.

scene_entity_info

Тег, состояние активности и список компонентов для конкретной сущности.

scene_get_component

Сериализованное состояние конкретного компонента на сущности.

Пример — получение компонента:

{
  "sceneId": "gameplay",
  "entityId": "player-001",
  "componentType": "Transform"
}

Save

Все инструменты сохранения изолированы в SAVE_BASE_DIR. Обход пути (.., абсолютные пути) отклоняется на уровне схемы и повторно на этапе разрешения.

Инструмент

Описание

save_read

Читает слот сохранения с диска и возвращает его JSON-данные.

save_write

Записывает JSON-объект в именованный слот сохранения.

save_delete

Удаляет слот сохранения.

save_list

Перечисляет все доступные слоты сохранения.

Пример — запись:

{
  "slot": "autosave",
  "data": { "level": 3, "score": 4200, "checkpoint": "bridge" }
}

Имена слотов — только алфавитно-цифровые символы, дефисы и подчёркивания (например, slot1, autosave, new-game-plus).


Actor

Инструмент

Описание

actor_send_message

Ставит сообщение в очередь входящих сообщений конкретного актора. Обрабатывается при следующем сбросе ActorSystem.

actor_broadcast

Рассылает сообщение всем зарегистрированным акторам.

actor_inbox_size

Количество ожидающих сообщений во входящих актора.

Пример — отправка сообщения:

{
  "actorId": "enemy-spawner",
  "message": { "type": "SPAWN_WAVE", "payload": { "wave": 3 } }
}

Примечание о порядке: ActorSystem обрабатывает входящие каждого актора перед вызовом update(). Сообщения, отправленные во время кадра N, полностью обрабатываются до выполнения логики обновления кадра N.


Разработка

npm run lint        # TypeScript type-check (no emit)
npm test            # run Vitest suite
npm run test:watch  # watch mode

Тесты находятся в src/tests/. Они покрывают валидацию входных данных, диспетчеризацию инструментов и инварианты безопасности (обход пути, инъекция шелл-метасимволов, неизвестные имена инструментов).


Добавление инструмента

  1. Создайте src/tools/<domain>.ts — экспортируйте запись массива toolDef и функцию handler.

  2. Зарегистрируйте оба в src/tools/index.ts через вызов register() в buildRegistry().

  3. Добавьте запись в api-reference.json в emptysock-engine.

  4. Добавьте файл навыка в eleferrets/emptysock-ai-skills.

Используйте общие помощники в src/lib/:

  • parse(schema, raw) — Zod-разбор, который выбрасывает McpError(InvalidParams) при сбое

  • SafeRelPath, SafeId, Vec2, Vec3, GameNum — переиспользуемые Zod-схемы

  • textResponse(data) — формирует стандартный текстовый ответ MCP

  • wrapError(err) — логирует в stderr и повторно выбрасывает как McpError(InternalError)


Модель безопасности

Угроза

Меры защиты

Некорректные аргументы

Zod safeParse на каждом входе; при сбое возвращается McpError(InvalidParams)

Обход пути

Схема SafeRelPath + проверка ограничения path.resolve в обработчике сохранения

Шелл-инъекция

Никаких exec() с шаблонными строками; execFile с массивами argv, когда нужны подпроцессы

Утечка учётных данных

Секреты только из process.env; стеки логируются в stderr, никогда клиенту

Чрезмерно большой вход

Длины строк ограничены для каждого поля схемы

Неизвестные инструменты

McpError(MethodNotFound) — нет проваливания к непредусмотренным обработчикам

Available Tools

21 tools
actor_broadcastB

Broadcast a message to all registered actors in the current ActorSystem.

Inputs: message (required).

actor_inbox_sizeB

Return the number of pending messages in an actor's inbox.

Inputs: actorId (required).

actor_send_messageA

Enqueue a message in a specific actor's inbox. The actor processes it on the next flush pass.

Inputs: actorId (required), message (required).

emptysock_layer_infoA

Return reference documentation for the EmptySock LayerSystem API: defineLayer, addToLayer, setVisible, setParallax, and RenderSystem integration.

Inputs: no named parameters.

gms2_inspect_projectA

Read a GameMaker Studio 2 .yyp project file and return a JSON summary: project name, asset counts by type, and lists of object and script names. Read-only — does not modify any files.

Inputs: yypPath (required).

particle_emitter_configA

Get or set a ParticleSystem emitter configuration by emitter ID. Omit config to read; provide config to write.

Inputs: emitterId (required), config.

physics_body_stateA

Return the current position, velocity, and angular velocity of a physics body by entity ID.

Inputs: entityId (required).

physics_overlap_circleB

Return all entity IDs whose 2D colliders overlap a circle.

Inputs: center (required), radius (required), layerMask.

physics_raycast_2dB

Cast a ray in 2D physics space and return the first hit entity, hit point, and normal.

Inputs: origin (required), direction (required), maxDistance (required), layerMask.

physics_raycast_3dC

Cast a ray in 3D physics space (Rapier3D) and return the first hit.

Inputs: origin (required), direction (required), maxDistance (required), layerMask.

save_deleteA

Delete a save slot from disk.

Inputs: slot (required).

save_listA

List all available save slots.

Inputs: subdir.

save_readA

Read a save slot from disk and return its JSON data.

Inputs: slot (required).

save_writeA

Write JSON data to a save slot on disk.

Inputs: data (required), slot (required).

scene_create_entityC

Add a new entity to a scene. Returns the new entity's ID.

Inputs: sceneId (required), tag, components.

scene_entity_infoC

Return the tag, active state, and component list for a specific entity.

Inputs: sceneId (required), entityId (required).

scene_get_componentB

Retrieve the serialised state of a specific component on an entity.

Inputs: sceneId (required), entityId (required), componentType (required).

scene_list_entitiesB

List all entity IDs currently active in a scene.

Inputs: sceneId (required).

story_graph_exportA

Export the Story Graph (VNSystem) for a named scene as a JSON object containing nodes and edges.

Inputs: sceneId (required), graphId.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 21 tools

    Disambiguation5/5

    Tools are clearly separated by domain (navmesh, physics, scene, save, actor, etc.) and each tool targets a distinct action or query. Even within physics, 2D and 3D raycasts are explicitly differentiated. No two tools appear to do the same thing.

    Naming Consistency5/5

    All tools follow a consistent domain_verb_noun pattern (e.g., scene_create_entity, save_list, actor_send_message). Suffixes like _2d and _3d are uniform, and the one odd name (emptysock_layer_info) still adheres to the same style. Naming is predictable and coherent.

    Tool Count3/5

    With 21 tools, the count falls in the 16-25 range, which is borderline heavy. However, the server covers many distinct subsystems, so each tool arguably earns its place, but the overall number feels slightly excessive for a single MCP server.

    Completeness3/5

    The set covers core read/query operations across multiple domains, but there are notable gaps: scene entities can be created and inspected but not updated or deleted, physics only offers queries (no manipulation), and particle control is limited to configuration. This leaves some lifecycle operations incomplete.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables LLM-driven text game state management by exposing MCP tools for managing players, locations, items, entities, and abstract concepts.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      An MCP server enabling AI agents to author Unreal Engine 5 scenes directly, with tools for spawning actors, building PCG graphs, validating physics, generating terrain, and more through a single MCP connection.
      13
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Connects Claude Code to the Unity Editor via MCP, enabling AI-driven control of scenes, assets, components, UI, animations, and more through 91 tools.
      2
      MIT
    • A
      license
      C
      quality
      C
      maintenance
      Enables AI-driven game development by providing MCP tools to interact with the Godot editor, including scene editing, node manipulation, script attachment, and scene execution.
      28
      14 npm
      MIT