emptysock-mcp
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Переменная | Обязательно | Описание |
| Нет | Bearer-токен для аутентифицированных вызовов к API движка |
| Нет | Обязательный Bearer-токен для запросов на SSE-транспорте. Оставьте пустым, чтобы отключить аутентификацию. |
| Нет | Абсолютный путь, который инструменты сохранения могут читать/записывать. По умолчанию — рабочая директория процесса. В продакшене задавайте явно. |
Никогда не коммитьте
.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
Инструмент | Описание |
| Путь A* между двумя 2D-точками мира по загруженной навмеше. Возвращает упорядоченные путевые точки или |
| Ближайший проходимый узел навмеша к заданной точке мира. |
Пример — поиск пути:
{
"from": { "x": 0, "y": 0 },
"to": { "x": 100, "y": 50 },
"mapId": "level1"
}Physics
Инструмент | Описание |
| Запускает луч в 2D-физическом пространстве; возвращает первую задетую сущность, точку попадания и нормаль. |
| Запускает луч в 3D-физическом пространстве (Rapier3D); возвращает первое попадание. |
| Все идентификаторы сущностей, чьи 2D-коллайдеры пересекают окружность. |
| Текущая позиция, скорость и угловая скорость физического тела по идентификатору сущности. |
Пример — перекрытие окружности:
{
"center": { "x": 50, "y": 50 },
"radius": 20,
"layerMask": 3
}Scene
Инструмент | Описание |
| Все идентификаторы сущностей, активных в сцене. |
| Тег, состояние активности и список компонентов для конкретной сущности. |
| Сериализованное состояние конкретного компонента на сущности. |
Пример — получение компонента:
{
"sceneId": "gameplay",
"entityId": "player-001",
"componentType": "Transform"
}Save
Все инструменты сохранения изолированы в SAVE_BASE_DIR. Обход пути (.., абсолютные пути) отклоняется на уровне схемы и повторно на этапе разрешения.
Инструмент | Описание |
| Читает слот сохранения с диска и возвращает его JSON-данные. |
| Записывает JSON-объект в именованный слот сохранения. |
| Удаляет слот сохранения. |
| Перечисляет все доступные слоты сохранения. |
Пример — запись:
{
"slot": "autosave",
"data": { "level": 3, "score": 4200, "checkpoint": "bridge" }
}Имена слотов — только алфавитно-цифровые символы, дефисы и подчёркивания (например, slot1, autosave, new-game-plus).
Actor
Инструмент | Описание |
| Ставит сообщение в очередь входящих сообщений конкретного актора. Обрабатывается при следующем сбросе ActorSystem. |
| Рассылает сообщение всем зарегистрированным акторам. |
| Количество ожидающих сообщений во входящих актора. |
Пример — отправка сообщения:
{
"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/. Они покрывают валидацию входных данных, диспетчеризацию инструментов и инварианты безопасности (обход пути, инъекция шелл-метасимволов, неизвестные имена инструментов).
Добавление инструмента
Создайте
src/tools/<domain>.ts— экспортируйте запись массиваtoolDefи функциюhandler.Зарегистрируйте оба в
src/tools/index.tsчерез вызовregister()вbuildRegistry().Добавьте запись в
api-reference.jsonвemptysock-engine.Добавьте файл навыка в
eleferrets/emptysock-ai-skills.
Используйте общие помощники в src/lib/:
parse(schema, raw)— Zod-разбор, который выбрасываетMcpError(InvalidParams)при сбоеSafeRelPath,SafeId,Vec2,Vec3,GameNum— переиспользуемые Zod-схемыtextResponse(data)— формирует стандартный текстовый ответ MCPwrapError(err)— логирует в stderr и повторно выбрасывает какMcpError(InternalError)
Модель безопасности
Угроза | Меры защиты |
Некорректные аргументы | Zod |
Обход пути | Схема |
Шелл-инъекция | Никаких |
Утечка учётных данных | Секреты только из |
Чрезмерно большой вход | Длины строк ограничены для каждого поля схемы |
Неизвестные инструменты |
|
Available Tools
21 toolsactor_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
Scored across 21 tools
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.
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.
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.
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
Related MCP Connectors
Make games with AI: one MCP server that connects your agent to Unity, Unreal and Godot editors.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to control Unreal E…
Nifty's MCP server — exposes tasks, projects, messages, and files as tools for AI agents.
Persistent memory, knowledge graph, task management and more for AI agents via MCP.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables LLM-driven text game state management by exposing MCP tools for managing players, locations, items, entities, and abstract concepts.MIT
- AlicenseNot gradedqualityBmaintenanceAn 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.13MIT
- AlicenseNot gradedqualityDmaintenanceConnects Claude Code to the Unity Editor via MCP, enabling AI-driven control of scenes, assets, components, UI, animations, and more through 91 tools.2MIT
- AlicenseCqualityCmaintenanceEnables AI-driven game development by providing MCP tools to interact with the Godot editor, including scene editing, node manipulation, script attachment, and scene execution.2814 npmMIT