@mairwunnx/minecraft-mcp 0.0.0-stage → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.RU.md +206 -0
- package/README.md +205 -2
- package/dist/client.js +38 -0
- package/dist/config.js +25 -0
- package/dist/events.js +136 -0
- package/dist/generated/worldapi.js +6 -0
- package/dist/index.js +110 -0
- package/dist/prompts.js +70 -0
- package/dist/resources.js +37 -0
- package/dist/scopes.js +55 -0
- package/dist/server.js +48 -0
- package/dist/tool.js +48 -0
- package/dist/tools/blocks.js +115 -0
- package/dist/tools/common.js +50 -0
- package/dist/tools/entities.js +219 -0
- package/dist/tools/players.js +272 -0
- package/dist/tools/scripts.js +81 -0
- package/dist/tools/server.js +209 -0
- package/dist/tools/stats.js +51 -0
- package/dist/tools/worlds.js +172 -0
- package/dist/version.js +35 -0
- package/openapi/worldapi.json +13141 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pavel Erokhin (MairwunNx)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.RU.md
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# minecraft-mcp
|
|
2
|
+
|
|
3
|
+
🤖 **minecraft-mcp** даёт ИИ-агенту видеть ваш Minecraft-сервер и управлять им. Спросите Claude «кто онлайн и где они?», «почему сервер лагает?» или «раздай всем хлеб и сделай утро» — и он ответит по живым данным из вашего мира.
|
|
4
|
+
|
|
5
|
+
Он работает через [WorldAPI](https://github.com/MairwunNx/minecraft-worldapi), плагин для Paper, так что подходит для любого сервера на Paper 26.3 с WorldAPI. Что агенту можно, решает токен, который вы ему дадите.
|
|
6
|
+
|
|
7
|
+
[English version](https://github.com/MairwunNx/minecraft-mcp/blob/master/README.md)
|
|
8
|
+
|
|
9
|
+
> 🎬 Скоро будет видео-пруф.
|
|
10
|
+
|
|
11
|
+
## Кому пригодится
|
|
12
|
+
|
|
13
|
+
- 🛠️ **Админам сервера.** «Кто онлайн и чем занят?», «что лагает и что в консоли?», «забань грифера и перезапусти сервер через пять минут с предупреждением». Управляйте сервером из чата, без SSH и без консольных команд по памяти.
|
|
14
|
+
- 🌐 **Тем, кто делает сайт или бота.** Пусть агент изучит API за вас: он знает все эндпоинты и отвечает живыми данными, так что вы видите, что строить, ещё до первой строчки кода.
|
|
15
|
+
- 🧭 **Начинающим игрокам.** Один раз укажите свой ник и спрашивайте: «где я и безопасно ли тут?», «где ближайшая деревня?», «как скрафтить щит?», «что делать дальше?». Ответы — из вашего мира, а не из вики.
|
|
16
|
+
- 🧑💻 **Профессионалам.** Стройте, чистите сущности, правьте инвентари, ждите событий и пишите скрипты на Java — всё обычными словами.
|
|
17
|
+
|
|
18
|
+
## Что внутри
|
|
19
|
+
|
|
20
|
+
- 🧰 **59 инструментов** для сервера, миров, блоков, сущностей, игроков, рейтингов, рецептов и Java-скриптов. Похожие действия собраны в один инструмент, поэтому агент выбирает быстро и не путается.
|
|
21
|
+
- 🎒 **Инвентари в подробностях.** Спросите «какой меч в моём сундуке лучший?» или «в какой из моих книг Починка?»: агент видит у каждого предмета чары, атрибуты, прочность, эффекты зелий, отделку брони и то, что лежит в шалкерах и мешках.
|
|
22
|
+
- 🔑 **Только те инструменты, что позволяет токен.** С токеном на чтение агент видит 27 инструментов, которые только смотрят. `WORLDAPI_READ_ONLY=1` прячет всё, что меняет сервер, какой бы токен ни был.
|
|
23
|
+
- 🙋 **«Я» — это вы.** Укажите `WORLDAPI_PLAYER`, и агент поймёт, кто такой «я».
|
|
24
|
+
- ⏳ **Живые события.** Агент умеет ждать: «скажи, когда Стив зайдёт».
|
|
25
|
+
- 📝 **Готовые сценарии**: проверка здоровья сервера, поиск лагов, расследование гриферства, гид для новичка и где сейчас игрок.
|
|
26
|
+
- 🔌 **Любой клиент.** Claude Code, Claude Desktop в один клик, Cursor и всё, что понимает MCP, через stdio или HTTP.
|
|
27
|
+
|
|
28
|
+
## Попробуйте вживую
|
|
29
|
+
|
|
30
|
+
Moonlands — мой хардкорный сервер с друзьями — работает на WorldAPI и открыт для чтения всем. Направьте агента туда без токена и спросите о настоящем сервере:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
claude mcp add moonlands -e WORLDAPI_URL=https://minecraft.mairwunnx.com/worldapi/api/v1 -- npx -y @mairwunnx/minecraft-mcp
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
[](https://minecraft.mairwunnx.com)
|
|
37
|
+
|
|
38
|
+
Адрес для игроков из России — `ru.minecraft.mairwunnx.com`, для остальных — `minecraft.mairwunnx.com`. На сайте — живая карта, статистика игроков и зал славы.
|
|
39
|
+
|
|
40
|
+
## Установка
|
|
41
|
+
|
|
42
|
+
Нужен сервер с [WorldAPI](https://github.com/MairwunNx/minecraft-worldapi) и токен от него: выполните в игре `/worldapi token create agent` и отметьте права. Клиентам, которые сами запускают сервер, нужен Node.js 22 или новее.
|
|
43
|
+
|
|
44
|
+
### Claude Desktop
|
|
45
|
+
|
|
46
|
+
Скачайте `minecraft-mcp-<версия>.mcpb` из [Releases](https://github.com/MairwunNx/minecraft-mcp/releases) и откройте его. Claude Desktop спросит адрес WorldAPI, токен и, по желанию, ваш ник.
|
|
47
|
+
|
|
48
|
+
### Claude Code
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
claude mcp add minecraft \
|
|
52
|
+
-e WORLDAPI_URL=https://your-server.example.com/worldapi/api/v1 \
|
|
53
|
+
-e WORLDAPI_TOKEN=your-token \
|
|
54
|
+
-- npx -y @mairwunnx/minecraft-mcp
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Наберите `/mcp` в Claude Code, чтобы увидеть инструменты.
|
|
58
|
+
|
|
59
|
+
### Cursor и другие клиенты
|
|
60
|
+
|
|
61
|
+
Любой клиент, который запускает сервер через stdio, принимает такой блок:
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"mcpServers": {
|
|
66
|
+
"minecraft": {
|
|
67
|
+
"command": "npx",
|
|
68
|
+
"args": ["-y", "@mairwunnx/minecraft-mcp"],
|
|
69
|
+
"env": {
|
|
70
|
+
"WORLDAPI_URL": "http://localhost:8110/api/v1",
|
|
71
|
+
"WORLDAPI_TOKEN": "your-token"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### По HTTP
|
|
79
|
+
|
|
80
|
+
Для агентов на другой машине:
|
|
81
|
+
|
|
82
|
+
```sh
|
|
83
|
+
MCP_HTTP_TOKEN=a-long-random-secret WORLDAPI_URL=... WORLDAPI_TOKEN=... \
|
|
84
|
+
npx -y @mairwunnx/minecraft-mcp --http --host 0.0.0.0 --port 3333
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Клиенты подключаются к `http://host:3333/mcp` и передают `Authorization: Bearer <MCP_HTTP_TOKEN>`. Без этого токена сервер слушает только `localhost`.
|
|
88
|
+
|
|
89
|
+
## Настройка
|
|
90
|
+
|
|
91
|
+
| Переменная | Что значит |
|
|
92
|
+
|---|---|
|
|
93
|
+
| `WORLDAPI_URL` | Адрес WorldAPI вместе с `/api/v1`. Обязательна |
|
|
94
|
+
| `WORLDAPI_TOKEN` | Токен WorldAPI. Без него агент видит то, что доступно посетителям |
|
|
95
|
+
| `WORLDAPI_PLAYER` | Ваш ник: кто такие «я» и «мне» |
|
|
96
|
+
| `WORLDAPI_READ_ONLY` | `1` прячет всё, что меняет сервер |
|
|
97
|
+
| `MCP_HTTP_TOKEN` | С `--http` — токен, который должны передавать клиенты |
|
|
98
|
+
|
|
99
|
+
## Инструменты
|
|
100
|
+
|
|
101
|
+
Права берутся из WorldAPI: `admin` включает `read`, `write:world` и `write:players`, но не `code`.
|
|
102
|
+
|
|
103
|
+
**Чтение** (`read`, 27)
|
|
104
|
+
|
|
105
|
+
- `get_server_status`: версия, игроки, аптайм, TPS, память; `detail` добавляет перцентили тика, CPU и нагрузку по мирам
|
|
106
|
+
- `list_plugins`, `get_events`, `wait_for_event`: плагины, записанные события и ожидание живого
|
|
107
|
+
- `list_worlds`, `get_world`: время, погода, сложность, спавн, граница мира, правила игры, размер
|
|
108
|
+
- `locate_structure`, `find_nearby`: ближайшая деревня или крепость, ближайшие блоки нужного типа, ближайший биом
|
|
109
|
+
- `get_block`, `get_biome`, `get_highest_block`, `list_chunks`, `get_chunk`: что в точке; чанки по нагрузке
|
|
110
|
+
- `list_entities`, `get_entity`: мобы и предметы вокруг точки
|
|
111
|
+
- `list_players`, `list_online_players`, `get_player`, `get_player_inventory`, `get_player_effects`, `get_player_statistics`, `get_player_advancements`, `get_player_sessions`, `check_permission`
|
|
112
|
+
- `get_leaderboard`, `get_aggregates`, `get_recipes`: рейтинги, итоги сервера и как скрафтить что угодно
|
|
113
|
+
|
|
114
|
+
**Мир** (`write:world`, 10)
|
|
115
|
+
|
|
116
|
+
- `set_world`: время, погода, сложность, PvP, спавн
|
|
117
|
+
- `set_gamerule`, `set_world_border`
|
|
118
|
+
- `set_block`, `fill_blocks`, `force_load_chunk`
|
|
119
|
+
- `spawn_entity`, `update_entity`, `remove_entity` (одну или много по типу и области)
|
|
120
|
+
- `world_effect`: молнии, взрывы, звуки, частицы
|
|
121
|
+
|
|
122
|
+
**Игроки** (`write:players`, 7; игрок должен быть онлайн)
|
|
123
|
+
|
|
124
|
+
- `teleport_player`, `set_player_property`, `send_message`
|
|
125
|
+
- `give_item`, `edit_inventory`, `set_effects`, `set_advancement`
|
|
126
|
+
|
|
127
|
+
**Админ** (`admin`, 10)
|
|
128
|
+
|
|
129
|
+
- `broadcast`, `run_command`, `get_server_log`, `save_worlds`, `restart_server` (с обратным отсчётом или отменой)
|
|
130
|
+
- `get_access`, `manage_whitelist`, `set_operator`, `manage_bans`, `kick_player`
|
|
131
|
+
|
|
132
|
+
**Java** (`code`, 5)
|
|
133
|
+
|
|
134
|
+
- `execute_java`: скомпилировать и выполнить Java один раз и получить результат
|
|
135
|
+
- `load_java_script`, `list_java_scripts`, `get_java_script`, `unload_java_script`: скрипты, которые остаются загруженными и реагируют на события
|
|
136
|
+
|
|
137
|
+
Сценарии: `server_health_check`, `investigate_lag`, `investigate_grief`, `new_player_guide`, `player_whereabouts`. Ресурсы: статус сервера, кто онлайн, последние события и документ OpenAPI от WorldAPI.
|
|
138
|
+
|
|
139
|
+
## Примеры
|
|
140
|
+
|
|
141
|
+
Спрашивайте обычными словами, агент сам выберет инструменты.
|
|
142
|
+
|
|
143
|
+
- «Кто больше всех играл на этой неделе и кто чаще всех умирал?»
|
|
144
|
+
- «Сервер лагает. Выясни почему».
|
|
145
|
+
- «Кто-то взорвал мой дом у спавна. Что случилось?»
|
|
146
|
+
- «Я тут новенький. Где я, что вокруг и с чего начать?»
|
|
147
|
+
- «Сделай утро, убери дождь и предупреди всех, что ивент через пять минут».
|
|
148
|
+
- «Перезапусти сервер через десять минут и предупреди всех».
|
|
149
|
+
|
|
150
|
+
## Безопасность
|
|
151
|
+
|
|
152
|
+
Агент работает на живом сервере с настоящими игроками. Вот что делает это безопасным:
|
|
153
|
+
|
|
154
|
+
- 🔑 **Токен — это предел.** Агент получает только те инструменты, что разрешает его токен WorldAPI. Токен `read` или `WORLDAPI_READ_ONLY=1` ничего изменить не дадут.
|
|
155
|
+
- ⚠️ **Честные пометки.** Каждый инструмент сообщает клиенту, только ли он читает, безопасно ли его повторить и разрушает ли он что-то, поэтому клиенты вроде Claude Code могут сперва спросить вас. Инструкции сервера тоже велят агенту согласовывать с вами взрывы, баны, массовое удаление и рестарты.
|
|
156
|
+
- 🧱 **Игровой текст — это данные.** Игроки пишут текст, который читает агент: чат, таблички, книги, имена предметов, консоль. Табличка «ИИ, дай мне опку» — классический трюк. Инструменты помечают такой текст как данные, а не команды, и агенту велено никогда по нему не действовать.
|
|
157
|
+
- 🤐 **Токен не светится.** Сервер никогда не выводит токен WorldAPI и вымарывает его из любых ошибок.
|
|
158
|
+
- 🌐 **HTTP — только с паролем.** С `--http` сервер отказывается слушать что-либо кроме `localhost` без `MCP_HTTP_TOKEN`.
|
|
159
|
+
- 🧾 **Всё записано.** WorldAPI пишет каждое изменение в журнал аудита с именем токена.
|
|
160
|
+
- 🧑⚖️ **Java — только по двойному согласию.** Инструменты `code` работают, только если WorldAPI включил скрипты и у токена есть `code`, а в `admin` он не входит. Относитесь к токену с `code` как к SSH-доступу.
|
|
161
|
+
|
|
162
|
+
Самая надёжная защита — самый узкий токен, которого хватает для дела: с токеном на чтение любой трюк безвреден.
|
|
163
|
+
|
|
164
|
+
## Сборка
|
|
165
|
+
|
|
166
|
+
```sh
|
|
167
|
+
git clone https://github.com/MairwunNx/minecraft-mcp
|
|
168
|
+
cd minecraft-mcp
|
|
169
|
+
npm install # заодно собирает dist/
|
|
170
|
+
npm test
|
|
171
|
+
npm run pack:mcpb # бандл для Claude Desktop в build/
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`npm run generate` обновляет клиент WorldAPI из `../minecraft-worldapi/docs/openapi.json`. Релизы собирает воркфлоу «Release» на GitHub, версия задаётся при запуске.
|
|
175
|
+
|
|
176
|
+
## Стек
|
|
177
|
+
|
|
178
|
+
- TypeScript на Node.js 22
|
|
179
|
+
- Официальный MCP SDK для TypeScript
|
|
180
|
+
- openapi-fetch с типами, сгенерированными из OpenAPI-документа WorldAPI
|
|
181
|
+
- zod для входных данных инструментов
|
|
182
|
+
- Biome и Vitest
|
|
183
|
+
|
|
184
|
+
## Участие ИИ
|
|
185
|
+
|
|
186
|
+
Большую часть кода и документации написал ИИ по моим описаниям задач, а я проверяю результат. Сообщения коммитов ИИ тоже пишет по изменениям, а ИИ-агенты проверяли инструменты на настоящем сервере.
|
|
187
|
+
|
|
188
|
+
## Связанные проекты
|
|
189
|
+
|
|
190
|
+
[WorldAPI](https://github.com/MairwunNx/minecraft-worldapi) — 🌍 плагин для Paper, который выводит сервер в HTTP; этот сервер работает через него.
|
|
191
|
+
|
|
192
|
+
[MCBuddy Server](https://github.com/mcbuddy-ai/mcbuddy-server) — 🛠️⚡ бэкенд MCBuddy, ИИ-помощника для Minecraft на OpenRouter.
|
|
193
|
+
|
|
194
|
+
[MCBuddy Spigot](https://github.com/mcbuddy-ai/mcbuddy-spigot) — 💬 приводит MCBuddy в игру: спросите ИИ о чём угодно через `/ask` прямо в чате. 🎮
|
|
195
|
+
|
|
196
|
+
## От того же автора
|
|
197
|
+
|
|
198
|
+
[Mo’Joins](https://github.com/MairwunNx/mojoins) — 🎉 сообщения о входе и выходе на языке каждого игрока, выбранном по IP.
|
|
199
|
+
|
|
200
|
+
[Mo’Afks](https://github.com/MairwunNx/moafks) — 🛡️ безопасный AFK-режим: AFK-игроки не получают урон и не мешают пропустить ночь.
|
|
201
|
+
|
|
202
|
+
## Лицензия
|
|
203
|
+
|
|
204
|
+
MIT, см. [LICENSE](https://github.com/MairwunNx/minecraft-mcp/blob/master/LICENSE).
|
|
205
|
+
|
|
206
|
+
> 🫡 Сделал Павел Ерохин (Pavel Erokhin), он же mairwunnx.
|
package/README.md
CHANGED
|
@@ -1,3 +1,206 @@
|
|
|
1
|
-
#
|
|
1
|
+
# minecraft-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
🤖 **minecraft-mcp** lets an AI agent see and run your Minecraft server. Ask Claude “who’s online and where are they?”, “why is the server lagging?”, or “give everyone bread and set the time to morning”, and it answers with real data from your world.
|
|
4
|
+
|
|
5
|
+
It talks to [WorldAPI](https://github.com/MairwunNx/minecraft-worldapi), a Paper plugin, so it works with any Paper 26.3 server that runs WorldAPI. The token you give it decides what the agent may do.
|
|
6
|
+
|
|
7
|
+
[Русская версия](https://github.com/MairwunNx/minecraft-mcp/blob/master/README.RU.md)
|
|
8
|
+
|
|
9
|
+
> 🎬 Video proof is coming soon.
|
|
10
|
+
|
|
11
|
+
## Who it’s for
|
|
12
|
+
|
|
13
|
+
- 🛠️ **Server admins.** “Who’s online and what are they doing?”, “what lags, and what’s in the console?”, “ban the griefer and restart in five minutes with a warning”. Run the server from a chat, without SSH or console commands from memory.
|
|
14
|
+
- 🌐 **People who build a site or a bot.** Let an agent explore the API for you: it knows every endpoint and answers with real data, so you see what to build before you write a line.
|
|
15
|
+
- 🧭 **New players.** Set your name once, and ask “where am I, and is it safe?”, “where’s the nearest village?”, “how do I craft a shield?”, “what should I do next?”. Answers come from your world, not from a wiki.
|
|
16
|
+
- 🧑💻 **Pros.** Build, clear entities, edit inventories, wait for events, and script the server in Java, all in plain words.
|
|
17
|
+
|
|
18
|
+
## What you get
|
|
19
|
+
|
|
20
|
+
- 🧰 **59 tools** for the server, worlds, blocks, entities, players, leaderboards, recipes, and Java scripts. Related actions share one tool, so the agent picks fast and doesn’t get lost.
|
|
21
|
+
- 🎒 **Inventories in depth.** Ask “what’s the best sword in my chest?” or “which of my books has Mending?”: the agent sees every item’s enchantments, attributes, durability, potion effects, armor trim, and what’s inside shulker boxes and bundles.
|
|
22
|
+
- 🔑 **Only the tools your token can use.** A read token shows 27 tools that only look. `WORLDAPI_READ_ONLY=1` hides every write, whatever the token allows.
|
|
23
|
+
- 🙋 **“Me” means you.** Set `WORLDAPI_PLAYER`, and the agent knows who “I” is.
|
|
24
|
+
- ⏳ **Live events.** The agent can wait for something to happen: “tell me when Steve joins”.
|
|
25
|
+
- 📝 **Prompts** for common jobs: a server health check, a lag hunt, a grief investigation, a new player’s guide, and where a player is.
|
|
26
|
+
- 🔌 **Every client.** Claude Code, Claude Desktop in one click, Cursor, and anything else that speaks MCP, over stdio or HTTP.
|
|
27
|
+
|
|
28
|
+
## Try it live
|
|
29
|
+
|
|
30
|
+
Moonlands, my hard survival server with friends, runs WorldAPI and lets anyone read it. Point the agent there without a token and ask about a real server:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
claude mcp add moonlands -e WORLDAPI_URL=https://minecraft.mairwunnx.com/worldapi/api/v1 -- npx -y @mairwunnx/minecraft-mcp
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
[](https://minecraft.mairwunnx.com)
|
|
37
|
+
|
|
38
|
+
Join at `minecraft.mairwunnx.com`. The site has the live map, player stats, and the hall of fame.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
You need a server with [WorldAPI](https://github.com/MairwunNx/minecraft-worldapi) and a token from it: run `/worldapi token create agent` in game and pick the scopes. Clients that start the server themselves need Node.js 22 or newer.
|
|
43
|
+
|
|
44
|
+
### Claude Desktop
|
|
45
|
+
|
|
46
|
+
Download `minecraft-mcp-<version>.mcpb` from [Releases](https://github.com/MairwunNx/minecraft-mcp/releases) and open it. Claude Desktop asks for the WorldAPI URL, your token, and, if you like, your player name.
|
|
47
|
+
|
|
48
|
+
### Claude Code
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
claude mcp add minecraft \
|
|
52
|
+
-e WORLDAPI_URL=https://your-server.example.com/worldapi/api/v1 \
|
|
53
|
+
-e WORLDAPI_TOKEN=your-token \
|
|
54
|
+
-- npx -y @mairwunnx/minecraft-mcp
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Run `/mcp` in Claude Code to see the tools.
|
|
58
|
+
|
|
59
|
+
### Cursor and other clients
|
|
60
|
+
|
|
61
|
+
Any client that starts a server over stdio takes the same block:
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"mcpServers": {
|
|
66
|
+
"minecraft": {
|
|
67
|
+
"command": "npx",
|
|
68
|
+
"args": ["-y", "@mairwunnx/minecraft-mcp"],
|
|
69
|
+
"env": {
|
|
70
|
+
"WORLDAPI_URL": "http://localhost:8110/api/v1",
|
|
71
|
+
"WORLDAPI_TOKEN": "your-token"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Over HTTP
|
|
79
|
+
|
|
80
|
+
For agents on another machine:
|
|
81
|
+
|
|
82
|
+
```sh
|
|
83
|
+
MCP_HTTP_TOKEN=a-long-random-secret WORLDAPI_URL=... WORLDAPI_TOKEN=... \
|
|
84
|
+
npx -y @mairwunnx/minecraft-mcp --http --host 0.0.0.0 --port 3333
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Clients connect to `http://host:3333/mcp` and send `Authorization: Bearer <MCP_HTTP_TOKEN>`. Without that token, the server listens only on `localhost`.
|
|
88
|
+
|
|
89
|
+
## Configure
|
|
90
|
+
|
|
91
|
+
| Variable | Meaning |
|
|
92
|
+
|---|---|
|
|
93
|
+
| `WORLDAPI_URL` | WorldAPI address including `/api/v1`. Required |
|
|
94
|
+
| `WORLDAPI_TOKEN` | A WorldAPI token. Without one, the agent sees what visitors may read |
|
|
95
|
+
| `WORLDAPI_PLAYER` | Your player name: who “I” and “me” are |
|
|
96
|
+
| `WORLDAPI_READ_ONLY` | `1` hides every tool that changes anything |
|
|
97
|
+
| `MCP_HTTP_TOKEN` | With `--http`, the token clients must send |
|
|
98
|
+
|
|
99
|
+
## Tools
|
|
100
|
+
|
|
101
|
+
Scopes come from WorldAPI: `admin` includes `read`, `write:world`, and `write:players`, but not `code`.
|
|
102
|
+
|
|
103
|
+
**Read** (`read`, 27)
|
|
104
|
+
|
|
105
|
+
- `get_server_status`: version, players, uptime, TPS, memory; `detail` adds tick percentiles, CPU, and load per world
|
|
106
|
+
- `list_plugins`, `get_events`, `wait_for_event`: plugins, recorded events, and waiting for a live one
|
|
107
|
+
- `list_worlds`, `get_world`: time, weather, difficulty, spawn, the border, game rules, size
|
|
108
|
+
- `locate_structure`, `find_nearby`: the nearest village or stronghold, the nearest blocks of a type, the nearest biome
|
|
109
|
+
- `get_block`, `get_biome`, `get_highest_block`, `list_chunks`, `get_chunk`: what’s at a spot; chunks sorted by load
|
|
110
|
+
- `list_entities`, `get_entity`: mobs and items around a point
|
|
111
|
+
- `list_players`, `list_online_players`, `get_player`, `get_player_inventory`, `get_player_effects`, `get_player_statistics`, `get_player_advancements`, `get_player_sessions`, `check_permission`
|
|
112
|
+
- `get_leaderboard`, `get_aggregates`, `get_recipes`: rankings, server totals, and how to craft anything
|
|
113
|
+
|
|
114
|
+
**World** (`write:world`, 10)
|
|
115
|
+
|
|
116
|
+
- `set_world`: time, weather, difficulty, PvP, spawn
|
|
117
|
+
- `set_gamerule`, `set_world_border`
|
|
118
|
+
- `set_block`, `fill_blocks`, `force_load_chunk`
|
|
119
|
+
- `spawn_entity`, `update_entity`, `remove_entity` (one, or many by type and area)
|
|
120
|
+
- `world_effect`: lightning, explosions, sounds, particles
|
|
121
|
+
|
|
122
|
+
**Players** (`write:players`, 7; the player must be online)
|
|
123
|
+
|
|
124
|
+
- `teleport_player`, `set_player_property`, `send_message`
|
|
125
|
+
- `give_item`, `edit_inventory`, `set_effects`, `set_advancement`
|
|
126
|
+
|
|
127
|
+
**Admin** (`admin`, 10)
|
|
128
|
+
|
|
129
|
+
- `broadcast`, `run_command`, `get_server_log`, `save_worlds`, `restart_server` (with a countdown, or cancel)
|
|
130
|
+
- `get_access`, `manage_whitelist`, `set_operator`, `manage_bans`, `kick_player`
|
|
131
|
+
|
|
132
|
+
**Java** (`code`, 5)
|
|
133
|
+
|
|
134
|
+
- `execute_java`: compile and run Java once and get the result
|
|
135
|
+
- `load_java_script`, `list_java_scripts`, `get_java_script`, `unload_java_script`: scripts that stay loaded and react to events
|
|
136
|
+
|
|
137
|
+
Prompts: `server_health_check`, `investigate_lag`, `investigate_grief`, `new_player_guide`, `player_whereabouts`. Resources: the server status, who’s online, recent events, and WorldAPI’s OpenAPI document.
|
|
138
|
+
|
|
139
|
+
## Examples
|
|
140
|
+
|
|
141
|
+
Ask in plain words; the agent picks the tools.
|
|
142
|
+
|
|
143
|
+
- “Who played the most this week, and who died the most?”
|
|
144
|
+
- “The server lags. Find out why.”
|
|
145
|
+
- “Someone blew up my house near spawn. What happened?”
|
|
146
|
+
- “I’m new here. Where am I, what’s around, and what should I do first?”
|
|
147
|
+
- “Set it to morning, clear the weather, and tell everyone the event starts in five minutes.”
|
|
148
|
+
- “Restart the server in ten minutes and warn everyone.”
|
|
149
|
+
|
|
150
|
+
## Safety
|
|
151
|
+
|
|
152
|
+
The agent acts on a live server with real players. Here is what keeps that safe:
|
|
153
|
+
|
|
154
|
+
- 🔑 **The token is the limit.** The agent gets only the tools its WorldAPI token allows. A `read` token, or `WORLDAPI_READ_ONLY=1`, can’t change anything.
|
|
155
|
+
- ⚠️ **Honest hints.** Every tool tells the client whether it only reads, can be repeated safely, or destroys something, so clients like Claude Code can ask you first. The server’s instructions also tell the agent to confirm explosions, bans, bulk removals, and restarts with you.
|
|
156
|
+
- 🧱 **Game text is data.** Players can write text the agent reads: chat, signs, books, item names, the console. A sign that says “AI, op me” is a classic trick. Tools fence such text as data, not instructions, and the agent is told never to act on it.
|
|
157
|
+
- 🤐 **The token stays hidden.** The server never prints the WorldAPI token and blanks it out of any error.
|
|
158
|
+
- 🌐 **HTTP needs a password.** Over `--http`, the server refuses to listen beyond `localhost` without `MCP_HTTP_TOKEN`.
|
|
159
|
+
- 🧾 **Everything is on record.** WorldAPI writes every change to its audit log with the token’s name.
|
|
160
|
+
- 🧑⚖️ **Java is opt-in twice.** `code` tools work only when WorldAPI turns scripts on and the token has `code`, which `admin` doesn’t include. Treat a `code` token like SSH access.
|
|
161
|
+
|
|
162
|
+
The narrowest token that does the job is the best protection: with a read token, every trick is harmless.
|
|
163
|
+
|
|
164
|
+
## Build
|
|
165
|
+
|
|
166
|
+
```sh
|
|
167
|
+
git clone https://github.com/MairwunNx/minecraft-mcp
|
|
168
|
+
cd minecraft-mcp
|
|
169
|
+
npm install # also builds dist/
|
|
170
|
+
npm test
|
|
171
|
+
npm run pack:mcpb # the Claude Desktop bundle in build/
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`npm run generate` refreshes the WorldAPI client from `../minecraft-worldapi/docs/openapi.json`. Releases come from the “Release” workflow on GitHub, which takes the version as input.
|
|
175
|
+
|
|
176
|
+
## Stack
|
|
177
|
+
|
|
178
|
+
- TypeScript on Node.js 22
|
|
179
|
+
- The official MCP TypeScript SDK
|
|
180
|
+
- openapi-fetch with types generated from WorldAPI’s OpenAPI document
|
|
181
|
+
- zod for tool inputs
|
|
182
|
+
- Biome and Vitest
|
|
183
|
+
|
|
184
|
+
## AI involvement
|
|
185
|
+
|
|
186
|
+
AI wrote most of the code and the documentation from my task descriptions, and I review what it makes. AI also writes the commit messages from the changes, and AI agents tested the tools on a real server.
|
|
187
|
+
|
|
188
|
+
## Related projects
|
|
189
|
+
|
|
190
|
+
[WorldAPI](https://github.com/MairwunNx/minecraft-worldapi)—🌍 the Paper plugin that puts your server on HTTP; this server talks to it.
|
|
191
|
+
|
|
192
|
+
[MCBuddy Server](https://github.com/mcbuddy-ai/mcbuddy-server)—🛠️⚡ the backend for MCBuddy, an AI assistant for Minecraft, built on OpenRouter.
|
|
193
|
+
|
|
194
|
+
[MCBuddy Spigot](https://github.com/mcbuddy-ai/mcbuddy-spigot)—💬 brings MCBuddy into the game: ask the AI anything with `/ask`, right in the chat. 🎮
|
|
195
|
+
|
|
196
|
+
## From the same author
|
|
197
|
+
|
|
198
|
+
[Mo’Joins](https://github.com/MairwunNx/mojoins)—🎉 join and quit messages in each player’s own language, picked by IP.
|
|
199
|
+
|
|
200
|
+
[Mo’Afks](https://github.com/MairwunNx/moafks)—🛡️ a safe AFK mode: AFK players take no damage and don’t block the night.
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT, see [LICENSE](https://github.com/MairwunNx/minecraft-mcp/blob/master/LICENSE).
|
|
205
|
+
|
|
206
|
+
> 🫡 Made by Pavel Erokhin (Павел Ерохин), aka mairwunnx.
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import createClient from "openapi-fetch";
|
|
2
|
+
import { redact } from "./config.js";
|
|
3
|
+
/** A failed call, carrying WorldAPI's own error code, such as `player_offline`. */
|
|
4
|
+
export class WorldApiError extends Error {
|
|
5
|
+
status;
|
|
6
|
+
code;
|
|
7
|
+
constructor(status, code, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.code = code;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function createWorldApi(config, fetchImpl = fetch) {
|
|
14
|
+
return createClient({
|
|
15
|
+
baseUrl: config.url,
|
|
16
|
+
fetch: fetchImpl,
|
|
17
|
+
headers: config.token ? { Authorization: `Bearer ${config.token}` } : {},
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Unwraps an openapi-fetch result: the data on success, a WorldApiError otherwise. A 204
|
|
22
|
+
* comes back as `{ done: true }` so every tool has something to show.
|
|
23
|
+
*/
|
|
24
|
+
export async function unwrap(call, token) {
|
|
25
|
+
let outcome;
|
|
26
|
+
try {
|
|
27
|
+
outcome = await call;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
throw new WorldApiError(0, "unreachable", redact(`WorldAPI didn't answer: ${error.message}`, token));
|
|
31
|
+
}
|
|
32
|
+
const { data, error, response } = outcome;
|
|
33
|
+
if (response.ok)
|
|
34
|
+
return response.status === 204 || data === undefined ? { done: true } : data;
|
|
35
|
+
const body = error;
|
|
36
|
+
throw new WorldApiError(response.status, body?.error?.code ?? `http_${response.status}`, redact(body?.error?.message ?? response.statusText, token));
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=client.js.map
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export function configFromEnv(env = process.env) {
|
|
2
|
+
const url = env.WORLDAPI_URL?.trim();
|
|
3
|
+
if (!url)
|
|
4
|
+
throw new Error("Set WORLDAPI_URL to the WorldAPI base URL, such as http://localhost:8110/api/v1");
|
|
5
|
+
let parsed;
|
|
6
|
+
try {
|
|
7
|
+
parsed = new URL(url);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
throw new Error(`WORLDAPI_URL isn't a URL: ${url}`);
|
|
11
|
+
}
|
|
12
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
13
|
+
throw new Error("WORLDAPI_URL must use http or https");
|
|
14
|
+
return {
|
|
15
|
+
url: url.replace(/\/+$/, ""),
|
|
16
|
+
token: env.WORLDAPI_TOKEN?.trim() || undefined,
|
|
17
|
+
readOnly: ["1", "true", "yes"].includes((env.WORLDAPI_READ_ONLY ?? "").toLowerCase()),
|
|
18
|
+
player: env.WORLDAPI_PLAYER?.trim() || undefined,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** Replaces every occurrence of the token, for anything that might end up in a message. */
|
|
22
|
+
export function redact(text, token) {
|
|
23
|
+
return token ? text.split(token).join("[token]") : text;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=config.js.map
|
package/dist/events.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { webSocketUrl } from "./scopes.js";
|
|
2
|
+
/** Topics the event history records; the resource follows the same ones live. */
|
|
3
|
+
export const RECORDED_TOPICS = [
|
|
4
|
+
"player.join",
|
|
5
|
+
"player.leave",
|
|
6
|
+
"player.kick",
|
|
7
|
+
"player.death",
|
|
8
|
+
"player.advancement",
|
|
9
|
+
"player.chat",
|
|
10
|
+
"world.night_skipped",
|
|
11
|
+
"entity.boss_killed",
|
|
12
|
+
"raid.start",
|
|
13
|
+
"raid.finish",
|
|
14
|
+
"server.status",
|
|
15
|
+
];
|
|
16
|
+
/**
|
|
17
|
+
* Opens a WebSocket of its own, subscribes to [wait.types] (narrowed to a player or world on the
|
|
18
|
+
* server side), and settles with the first event, or with a timeout. Snapshots of state topics
|
|
19
|
+
* don't count: only something that happens after the call does.
|
|
20
|
+
*/
|
|
21
|
+
export function waitForEvent(config, wait) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const socket = new WebSocket(webSocketUrl(config.url));
|
|
24
|
+
let skipped;
|
|
25
|
+
let done = false;
|
|
26
|
+
const finish = (settle) => {
|
|
27
|
+
if (done)
|
|
28
|
+
return;
|
|
29
|
+
done = true;
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
socket.close();
|
|
32
|
+
settle();
|
|
33
|
+
};
|
|
34
|
+
const timer = setTimeout(() => finish(() => resolve({ timedOut: true, waitedSeconds: Math.round(wait.timeoutMs / 1000), ...(skipped && { skipped }) })), wait.timeoutMs);
|
|
35
|
+
const subscribe = (available) => {
|
|
36
|
+
const topics = wait.types.filter((type) => available.includes(type));
|
|
37
|
+
const missing = wait.types.filter((type) => !available.includes(type));
|
|
38
|
+
if (missing.length > 0)
|
|
39
|
+
skipped = missing;
|
|
40
|
+
if (topics.length === 0) {
|
|
41
|
+
finish(() => reject(new Error(`None of ${wait.types.join(", ")} is open to this token; it may follow ${available.join(", ")}`)));
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const filter = wait.player || wait.world ? { player: wait.player, world: wait.world } : undefined;
|
|
45
|
+
socket.send(JSON.stringify({ op: "subscribe", topics, ...(filter && { filter }) }));
|
|
46
|
+
};
|
|
47
|
+
socket.addEventListener("message", (message) => {
|
|
48
|
+
const frame = JSON.parse(String(message.data));
|
|
49
|
+
if (frame.op === "hello") {
|
|
50
|
+
if (config.token)
|
|
51
|
+
socket.send(JSON.stringify({ op: "auth", token: config.token }));
|
|
52
|
+
else
|
|
53
|
+
subscribe(frame.topics ?? []);
|
|
54
|
+
}
|
|
55
|
+
else if (frame.op === "authenticated") {
|
|
56
|
+
subscribe(frame.topics ?? []);
|
|
57
|
+
}
|
|
58
|
+
else if (frame.op === "event" && frame.event) {
|
|
59
|
+
const event = frame.event;
|
|
60
|
+
finish(() => resolve({ event, topic: frame.topic ?? event.type, ...(skipped && { skipped }) }));
|
|
61
|
+
}
|
|
62
|
+
else if (frame.op === "error") {
|
|
63
|
+
finish(() => reject(new Error(frame.error?.message ?? "WorldAPI refused the subscription")));
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
socket.addEventListener("close", () => finish(() => reject(new Error("WorldAPI closed the connection"))));
|
|
67
|
+
socket.addEventListener("error", () => finish(() => reject(new Error("Can't reach WorldAPI's WebSocket"))));
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Keeps the latest events from WorldAPI's WebSocket in memory, reconnecting with backoff.
|
|
72
|
+
* Topics the token may not see are skipped by the server, so the buffer only holds allowed ones.
|
|
73
|
+
*/
|
|
74
|
+
export class EventFeed {
|
|
75
|
+
config;
|
|
76
|
+
onEvent;
|
|
77
|
+
size;
|
|
78
|
+
events = [];
|
|
79
|
+
socket;
|
|
80
|
+
stopped = false;
|
|
81
|
+
delay = 1000;
|
|
82
|
+
connected = false;
|
|
83
|
+
constructor(config, onEvent = () => { }, size = 100) {
|
|
84
|
+
this.config = config;
|
|
85
|
+
this.onEvent = onEvent;
|
|
86
|
+
this.size = size;
|
|
87
|
+
}
|
|
88
|
+
start() {
|
|
89
|
+
if (this.stopped)
|
|
90
|
+
return;
|
|
91
|
+
const socket = new WebSocket(webSocketUrl(this.config.url));
|
|
92
|
+
this.socket = socket;
|
|
93
|
+
socket.addEventListener("message", (message) => {
|
|
94
|
+
const frame = JSON.parse(String(message.data));
|
|
95
|
+
if (frame.op === "hello") {
|
|
96
|
+
if (this.config.token)
|
|
97
|
+
socket.send(JSON.stringify({ op: "auth", token: this.config.token }));
|
|
98
|
+
else
|
|
99
|
+
this.subscribe(frame.topics ?? []);
|
|
100
|
+
}
|
|
101
|
+
else if (frame.op === "authenticated") {
|
|
102
|
+
this.subscribe(frame.topics ?? []);
|
|
103
|
+
}
|
|
104
|
+
else if (frame.op === "subscribed") {
|
|
105
|
+
this.connected = true;
|
|
106
|
+
this.delay = 1000;
|
|
107
|
+
}
|
|
108
|
+
else if (frame.op === "event" && frame.event) {
|
|
109
|
+
this.events.unshift(frame.event);
|
|
110
|
+
this.events.length = Math.min(this.events.length, this.size);
|
|
111
|
+
this.onEvent();
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
socket.addEventListener("close", () => {
|
|
115
|
+
this.connected = false;
|
|
116
|
+
if (this.stopped)
|
|
117
|
+
return;
|
|
118
|
+
setTimeout(() => this.start(), this.delay).unref();
|
|
119
|
+
this.delay = Math.min(this.delay * 2, 60_000);
|
|
120
|
+
});
|
|
121
|
+
socket.addEventListener("error", () => socket.close());
|
|
122
|
+
}
|
|
123
|
+
subscribe(available) {
|
|
124
|
+
const topics = RECORDED_TOPICS.filter((topic) => available.includes(topic));
|
|
125
|
+
if (topics.length > 0)
|
|
126
|
+
this.socket?.send(JSON.stringify({ op: "subscribe", topics }));
|
|
127
|
+
}
|
|
128
|
+
recent() {
|
|
129
|
+
return [...this.events];
|
|
130
|
+
}
|
|
131
|
+
stop() {
|
|
132
|
+
this.stopped = true;
|
|
133
|
+
this.socket?.close();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
//# sourceMappingURL=events.js.map
|