docs: present Shacraft Core and its documentation in English

This commit is contained in:
Emil
2026-09-14 17:58:30 +03:00
parent b6ba064339
commit 26748912c6
18 changed files with 643 additions and 620 deletions
+30 -30
View File
@@ -1,14 +1,14 @@
# Shacraft MCP
`shacraft-mcp` — отдельный процесс с настоящим MCP поверх stdio и JSON-RPC 2.0. Он обращается к авторизованному Control API работающего сервера и не открывает файлы миров напрямую. Сервер хранит и проверяет ревизии, лимиты и долговечность операций.
`shacraft-mcp` is a separate process implementing MCP over stdio and JSON-RPC 2.0. It calls the running server's authorized Control API rather than opening world files directly. The server stores and validates revisions, limits, and operation durability.
```sh
cargo run -p shacraft-mcp -- --server http://127.0.0.1:4000 --data data
```
По умолчанию токен читается из `data/control.token`. Параметр `--token-file /absolute/path/control.token` переопределяет путь. Токен читается при управляющем вызове, поэтому MCP можно запустить раньше сервера. В стандартный вывод пишутся только JSON-RPC-сообщения, одна строка на сообщение; диагностика и CLI-ошибки идут в stderr. Не запускайте через командную обёртку, которая печатает посторонний текст в stdout.
By default, the token is read from `data/control.token`. The `--token-file /absolute/path/control.token` argument overrides this path. The token is read when a control call is made, so MCP can start before the server. Standard output contains only JSON-RPC messages, one per line; diagnostics and CLI errors go to stderr. Do not launch it through a shell wrapper that prints unrelated text to stdout.
Пример записи в конфигурации MCP-клиента (пути заменяются своими абсолютными):
Example MCP client configuration (replace the paths with your own absolute paths):
```json
{
@@ -21,57 +21,57 @@ cargo run -p shacraft-mcp -- --server http://127.0.0.1:4000 --data data
}
```
## Протокол
## Protocol
Поддерживаются версии `2025-11-25`, `2025-06-18`, `2025-03-26`, `2024-11-05`. Сервер возвращает запрошенную поддерживаемую версию или новейшую поддерживаемую. Клиент начинает с `initialize`, затем посылает `notifications/initialized`. До этого доступны только `initialize` и `ping`. Уведомления не вызывают ответов; неизвестные методы запросов получают JSON-RPC-ошибку. Ошибки аргументов и выполнения известных инструментов возвращаются в `result.content` с `isError: true`.
Supported versions are `2025-11-25`, `2025-06-18`, `2025-03-26`, and `2024-11-05`. The server returns the requested version if supported, or its newest supported version otherwise. The client starts with `initialize`, followed by `notifications/initialized`. Before that, only `initialize` and `ping` are available. Notifications receive no response; unknown request methods receive a JSON-RPC error. Argument and execution errors for known tools are returned in `result.content` with `isError: true`.
Реализованы `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, `prompts/get` и `ping`. Списки небольшие и возвращаются целиком. Подписки, асинхронные задачи и уведомления о смене списков не объявляются. Выполнение последовательное; уведомление об отмене не прерывает уже выполняющийся HTTP-запрос. Сетевой тайм-аут ограничен 20 секундами (установление соединения — 3 секунды).
Implemented methods are `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, `prompts/get`, and `ping`. Lists are small and returned in full. Subscriptions, asynchronous tasks, and list-change notifications are not advertised. Execution is sequential; a cancellation notification does not interrupt an HTTP request already in progress. The network timeout is 20 seconds, with a 3-second connection timeout.
Строка запроса и HTTP-ответ ограничены 8 МиБ. Слишком длинная входная строка отбрасывается до перевода строки, после чего поток продолжает разбираться. HTTP-редиректы отключены: bearer-токен не передаётся перенаправленному адресу.
Request lines and HTTP responses are limited to 8 MiB. An oversized input line is discarded through its terminating newline, after which stream parsing resumes. HTTP redirects are disabled so the bearer token is not forwarded to a redirected address.
## Инструменты и рабочий процесс
## Tools and workflow
- `world_list`, `world_create`, `world_read`: осмотр миров и создание пустого мира или экземпляра закреплённого шаблона.
- `catalog_search`: точные состояния, runtime ID, формы и сведения о покрытии реализации.
- `world_edit`, `world_undo`, `world_reset`: атомарные правки, консервативная отмена последней операции и возврат к базе.
- `build_plan`, `build_commit`: предварительный расчёт ограниченной постройки из box/line/cylinder и последующая фиксация плана.
- `entity_list`, `entity_spawn`, `entity_update`, `entity_delete`: сохранённые сущности мира и их свойства.
- `arena_configure`, `arena_start`: сохраняемые правила Spleef (время, минимум игроков, высота выбывания, точки появления, материал пола) и запуск матча. Правила нельзя менять во время начавшегося раунда; материал пола задаёт разрешённые для разрушения блоки, но не перестраивает карту.
- `metrics`: измеренный RSS и отдельные оценки полезных данных кэша.
- `camera_capture`: изометрическое изображение мира в формате MCP image plus metadata. Это диагностическая проекция сервера, не снимок WebGL-камеры игрока.
- `world_list`, `world_create`, `world_read`: inspect worlds and create an empty world or an instance of a pinned template.
- `catalog_search`: exact states, runtime IDs, shapes, and implementation coverage information.
- `world_edit`, `world_undo`, `world_reset`: atomic edits, conservative undo of the latest operation, and reset to the base.
- `build_plan`, `build_commit`: preview a bounded structure made of box/line/cylinder primitives, then commit the plan.
- `entity_list`, `entity_spawn`, `entity_update`, `entity_delete`: persistent world entities and their properties.
- `arena_configure`, `arena_start`: persistent Spleef rules (timing, minimum players, elimination height, spawn points, floor material) and match start. Rules cannot change while a round is in progress; the floor material determines which blocks may be broken but does not rebuild the map.
- `metrics`: measured RSS and separate cache payload estimates.
- `camera_capture`: an isometric world image returned as an MCP image plus metadata. This is a server diagnostic projection, not a frame from the player's WebGL camera.
Полные JSON Schema доступны через `tools/list`. Имена инструментов соответствуют Control API с заменой первого `_` на точку, например `world_edit` → `world.edit`.
Complete JSON Schemas are available through `tools/list`. Tool names correspond to Control API names with the first `_` replaced by a dot, for example `world_edit` → `world.edit`.
Для строительства сначала прочитайте ревизию и площадку через `world_list`/`world_read`, найдите точные материалы через `catalog_search`, сформируйте `build_plan`, оцените границы и объём, затем выполните `build_commit` с уникальным `operation_id` в пределах авторизованного запроса. После фиксации проверьте `camera_capture`. При конфликте перечитайте мир и сформируйте новый план. Тот же ключ операции используйте только при повторе идентичного запроса.
To build, first read the revision and site through `world_list`/`world_read`, find exact materials through `catalog_search`, create a `build_plan`, inspect its bounds and volume, then call `build_commit` with a unique `operation_id` within the user's authorized scope. After committing, verify the result with `camera_capture`. On conflict, reread the world and create a new plan. Reuse an operation key only to retry an identical request.
Отмена требует текущую ревизию и `target_operation` исходной правки. Последующие изменения и reset могут сделать отмену недоступной; инструмент не должен перезаписывать их молча.
Undo requires the current revision and the original edit's `target_operation`. Later changes and reset may make undo unavailable; the tool must not silently overwrite them.
## Ресурсы и prompt
## Resources and prompt
Ресурсы `shacraft://server/status`, `shacraft://catalog/blocks`, `shacraft://catalog/entities`, `shacraft://packages` читают публичные сведения сервера. Ресурс блоков даёт начальную ограниченную страницу; полный каталог доступен поиском и пагинацией инструмента.
The resources `shacraft://server/status`, `shacraft://catalog/blocks`, `shacraft://catalog/entities`, and `shacraft://packages` read public server information. The block resource provides an initial bounded page; use tool search and pagination to access the full catalog.
Prompt `construct` принимает строки `world` и `request` и описывает последовательность осмотра, планирования, правки и визуальной проверки. Он не расширяет пользовательское разрешение на действие.
The `construct` prompt accepts `world` and `request` strings and describes the inspection, planning, editing, and visual verification sequence. It does not expand the user's authorization.
Проверки: `cargo test -p shacraft-mcp`. Unit-тесты проверяют переходы жизненного цикла, согласование версии, отсутствие ответов на уведомления, ошибки аргументов и токена, недопустимые JSON-RPC ID, восстановление после слишком большой строки и схемы строительных операций. Сквозные тесты с настоящим сервером выполняются дополнительно.
Run checks with `cargo test -p shacraft-mcp`. Unit tests cover lifecycle transitions, version negotiation, notifications receiving no responses, argument and token errors, invalid JSON-RPC IDs, recovery after an oversized line, and build-operation schemas. Additional end-to-end tests use a real server.
Основание протокола: официальные [lifecycle](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle), [stdio transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) и [tools](https://modelcontextprotocol.io/specification/2025-11-25/server/tools).
Protocol references: the official [lifecycle](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle), [stdio transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports), and [tools](https://modelcontextprotocol.io/specification/2025-11-25/server/tools) specifications.
## Проверка настоящим MCP SDK
## Verification with the real MCP SDK
После запуска отдельного тестового сервера:
After starting a separate test server:
```sh
node crates/shacraft-mcp/tests/sdk-smoke.mjs --data /absolute/path/test-server-data
```
Скрипт использует `@modelcontextprotocol/sdk` (проверен с 1.30.0), выполняет согласование протокола, читает все ресурсы, вызывает prompt, делает правку/повтор/конфликт/отмену, план/фиксацию, получает PNG, проверяет CRUD сущностей и reset. Он создаёт отдельный мир с префиксом `mcp_sdk_`. Путь к установленному SDK задаётся через `SHACRAFT_MCP_SDK`; в локальной среде поддерживается соседний `minecraft-builder-mcp/bridge/node_modules`. Это независимая проверка протокола, не зависимость исполняемого MCP от Minecraft Builder.
The script uses `@modelcontextprotocol/sdk` (verified with 1.30.0), negotiates the protocol, reads every resource, invokes the prompt, exercises edit/replay/conflict/undo and plan/commit, receives a PNG, and checks entity CRUD and reset. It creates a separate world prefixed with `mcp_sdk_`. Set `SHACRAFT_MCP_SDK` to the installed SDK path; the local environment also supports a sibling `minecraft-builder-mcp/bridge/node_modules` directory. This independently verifies the protocol; the MCP executable does not depend on Minecraft Builder.
Для воспроизводимой проверки с автоматически запущенным отдельным сервером:
For a reproducible check with an automatically started separate server:
```sh
node scripts/check_mcp.mjs --binary target/release/shacraft-server --mcp-binary target/release/shacraft-mcp --port 4002 --output artifacts/mcp-sdk.json
```
Обёртка создаёт временный каталог данных, использует настоящий SDK и закрывает тестовый сервер. Рабочий сервер на порту 4000 не затрагивается. `--sdk` или `SHACRAFT_MCP_SDK` задают путь к уже установленному SDK; результат записывается JSON-файлом, включая ошибку при неуспешной проверке.
The wrapper creates a temporary data directory, uses the real SDK, and stops the test server. It does not affect the working server on port 4000. `--sdk` or `SHACRAFT_MCP_SDK` specifies the path to an already installed SDK; results are written to a JSON file, including the error if verification fails.
Связанный сквозной тест `scripts/check_server.mjs` проверяет HTTP/WebSocket-клиенты, действия, экземпляры миров, полный матч и восстановление после реального `SIGKILL`: подтверждённые блоки, сущности и правила арены должны пережить перезапуск того же каталога данных. Временные тестовые данные сохраняются для разбора.
The related end-to-end test, `scripts/check_server.mjs`, checks HTTP/WebSocket clients, actions, world instances, a complete match, and recovery after a real `SIGKILL`: acknowledged blocks, entities, and arena rules must survive restarting with the same data directory. Temporary test data is retained for investigation.