@mairwunnx/minecraft-mcp 0.0.0-stage → 2.0.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 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,205 @@
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
+ - 🔑 **Только те инструменты, что позволяет токен.** С токеном на чтение агент видит 27 инструментов, которые только смотрят. `WORLDAPI_READ_ONLY=1` прячет всё, что меняет сервер, какой бы токен ни был.
22
+ - 🙋 **«Я» — это вы.** Укажите `WORLDAPI_PLAYER`, и агент поймёт, кто такой «я».
23
+ - ⏳ **Живые события.** Агент умеет ждать: «скажи, когда Стив зайдёт».
24
+ - 📝 **Готовые сценарии**: проверка здоровья сервера, поиск лагов, расследование гриферства, гид для новичка и где сейчас игрок.
25
+ - 🔌 **Любой клиент.** Claude Code, Claude Desktop в один клик, Cursor и всё, что понимает MCP, через stdio или HTTP.
26
+
27
+ ## Попробуйте вживую
28
+
29
+ Moonlands — мой хардкорный сервер с друзьями — работает на WorldAPI и открыт для чтения всем. Направьте агента туда без токена и спросите о настоящем сервере:
30
+
31
+ ```sh
32
+ claude mcp add moonlands -e WORLDAPI_URL=https://minecraft.mairwunnx.com/worldapi/api/v1 -- npx -y minecraft-mcp
33
+ ```
34
+
35
+ [![Играйте на Moonlands: чистая ваниль, сложные мобы, ИИ, приваты. ru.minecraft.mairwunnx.com](https://raw.githubusercontent.com/MairwunNx/minecraft-mcp/master/media/og-adv-image.ru.png)](https://minecraft.mairwunnx.com)
36
+
37
+ Адрес для игроков из России — `ru.minecraft.mairwunnx.com`, для остальных — `minecraft.mairwunnx.com`. На сайте — живая карта, статистика игроков и зал славы.
38
+
39
+ ## Установка
40
+
41
+ Нужен сервер с [WorldAPI](https://github.com/MairwunNx/minecraft-worldapi) и токен от него: выполните в игре `/worldapi token create agent` и отметьте права. Клиентам, которые сами запускают сервер, нужен Node.js 22 или новее.
42
+
43
+ ### Claude Desktop
44
+
45
+ Скачайте `minecraft-mcp-<версия>.mcpb` из [Releases](https://github.com/MairwunNx/minecraft-mcp/releases) и откройте его. Claude Desktop спросит адрес WorldAPI, токен и, по желанию, ваш ник.
46
+
47
+ ### Claude Code
48
+
49
+ ```sh
50
+ claude mcp add minecraft \
51
+ -e WORLDAPI_URL=https://your-server.example.com/worldapi/api/v1 \
52
+ -e WORLDAPI_TOKEN=your-token \
53
+ -- npx -y minecraft-mcp
54
+ ```
55
+
56
+ Наберите `/mcp` в Claude Code, чтобы увидеть инструменты.
57
+
58
+ ### Cursor и другие клиенты
59
+
60
+ Любой клиент, который запускает сервер через stdio, принимает такой блок:
61
+
62
+ ```json
63
+ {
64
+ "mcpServers": {
65
+ "minecraft": {
66
+ "command": "npx",
67
+ "args": ["-y", "minecraft-mcp"],
68
+ "env": {
69
+ "WORLDAPI_URL": "http://localhost:8110/api/v1",
70
+ "WORLDAPI_TOKEN": "your-token"
71
+ }
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ ### По HTTP
78
+
79
+ Для агентов на другой машине:
80
+
81
+ ```sh
82
+ MCP_HTTP_TOKEN=a-long-random-secret WORLDAPI_URL=... WORLDAPI_TOKEN=... \
83
+ npx -y minecraft-mcp --http --host 0.0.0.0 --port 3333
84
+ ```
85
+
86
+ Клиенты подключаются к `http://host:3333/mcp` и передают `Authorization: Bearer <MCP_HTTP_TOKEN>`. Без этого токена сервер слушает только `localhost`.
87
+
88
+ ## Настройка
89
+
90
+ | Переменная | Что значит |
91
+ |---|---|
92
+ | `WORLDAPI_URL` | Адрес WorldAPI вместе с `/api/v1`. Обязательна |
93
+ | `WORLDAPI_TOKEN` | Токен WorldAPI. Без него агент видит то, что доступно посетителям |
94
+ | `WORLDAPI_PLAYER` | Ваш ник: кто такие «я» и «мне» |
95
+ | `WORLDAPI_READ_ONLY` | `1` прячет всё, что меняет сервер |
96
+ | `MCP_HTTP_TOKEN` | С `--http` — токен, который должны передавать клиенты |
97
+
98
+ ## Инструменты
99
+
100
+ Права берутся из WorldAPI: `admin` включает `read`, `write:world` и `write:players`, но не `code`.
101
+
102
+ **Чтение** (`read`, 27)
103
+
104
+ - `get_server_status`: версия, игроки, аптайм, TPS, память; `detail` добавляет перцентили тика, CPU и нагрузку по мирам
105
+ - `list_plugins`, `get_events`, `wait_for_event`: плагины, записанные события и ожидание живого
106
+ - `list_worlds`, `get_world`: время, погода, сложность, спавн, граница мира, правила игры, размер
107
+ - `locate_structure`, `find_nearby`: ближайшая деревня или крепость, ближайшие блоки нужного типа, ближайший биом
108
+ - `get_block`, `get_biome`, `get_highest_block`, `list_chunks`, `get_chunk`: что в точке; чанки по нагрузке
109
+ - `list_entities`, `get_entity`: мобы и предметы вокруг точки
110
+ - `list_players`, `list_online_players`, `get_player`, `get_player_inventory`, `get_player_effects`, `get_player_statistics`, `get_player_advancements`, `get_player_sessions`, `check_permission`
111
+ - `get_leaderboard`, `get_aggregates`, `get_recipes`: рейтинги, итоги сервера и как скрафтить что угодно
112
+
113
+ **Мир** (`write:world`, 10)
114
+
115
+ - `set_world`: время, погода, сложность, PvP, спавн
116
+ - `set_gamerule`, `set_world_border`
117
+ - `set_block`, `fill_blocks`, `force_load_chunk`
118
+ - `spawn_entity`, `update_entity`, `remove_entity` (одну или много по типу и области)
119
+ - `world_effect`: молнии, взрывы, звуки, частицы
120
+
121
+ **Игроки** (`write:players`, 7; игрок должен быть онлайн)
122
+
123
+ - `teleport_player`, `set_player_property`, `send_message`
124
+ - `give_item`, `edit_inventory`, `set_effects`, `set_advancement`
125
+
126
+ **Админ** (`admin`, 10)
127
+
128
+ - `broadcast`, `run_command`, `get_server_log`, `save_worlds`, `restart_server` (с обратным отсчётом или отменой)
129
+ - `get_access`, `manage_whitelist`, `set_operator`, `manage_bans`, `kick_player`
130
+
131
+ **Java** (`code`, 5)
132
+
133
+ - `execute_java`: скомпилировать и выполнить Java один раз и получить результат
134
+ - `load_java_script`, `list_java_scripts`, `get_java_script`, `unload_java_script`: скрипты, которые остаются загруженными и реагируют на события
135
+
136
+ Сценарии: `server_health_check`, `investigate_lag`, `investigate_grief`, `new_player_guide`, `player_whereabouts`. Ресурсы: статус сервера, кто онлайн, последние события и документ OpenAPI от WorldAPI.
137
+
138
+ ## Примеры
139
+
140
+ Спрашивайте обычными словами, агент сам выберет инструменты.
141
+
142
+ - «Кто больше всех играл на этой неделе и кто чаще всех умирал?»
143
+ - «Сервер лагает. Выясни почему».
144
+ - «Кто-то взорвал мой дом у спавна. Что случилось?»
145
+ - «Я тут новенький. Где я, что вокруг и с чего начать?»
146
+ - «Сделай утро, убери дождь и предупреди всех, что ивент через пять минут».
147
+ - «Перезапусти сервер через десять минут и предупреди всех».
148
+
149
+ ## Безопасность
150
+
151
+ Агент работает на живом сервере с настоящими игроками. Вот что делает это безопасным:
152
+
153
+ - 🔑 **Токен — это предел.** Агент получает только те инструменты, что разрешает его токен WorldAPI. Токен `read` или `WORLDAPI_READ_ONLY=1` ничего изменить не дадут.
154
+ - ⚠️ **Честные пометки.** Каждый инструмент сообщает клиенту, только ли он читает, безопасно ли его повторить и разрушает ли он что-то, поэтому клиенты вроде Claude Code могут сперва спросить вас. Инструкции сервера тоже велят агенту согласовывать с вами взрывы, баны, массовое удаление и рестарты.
155
+ - 🧱 **Игровой текст — это данные.** Игроки пишут текст, который читает агент: чат, таблички, книги, имена предметов, консоль. Табличка «ИИ, дай мне опку» — классический трюк. Инструменты помечают такой текст как данные, а не команды, и агенту велено никогда по нему не действовать.
156
+ - 🤐 **Токен не светится.** Сервер никогда не выводит токен WorldAPI и вымарывает его из любых ошибок.
157
+ - 🌐 **HTTP — только с паролем.** С `--http` сервер отказывается слушать что-либо кроме `localhost` без `MCP_HTTP_TOKEN`.
158
+ - 🧾 **Всё записано.** WorldAPI пишет каждое изменение в журнал аудита с именем токена.
159
+ - 🧑‍⚖️ **Java — только по двойному согласию.** Инструменты `code` работают, только если WorldAPI включил скрипты и у токена есть `code`, а в `admin` он не входит. Относитесь к токену с `code` как к SSH-доступу.
160
+
161
+ Самая надёжная защита — самый узкий токен, которого хватает для дела: с токеном на чтение любой трюк безвреден.
162
+
163
+ ## Сборка
164
+
165
+ ```sh
166
+ git clone https://github.com/MairwunNx/minecraft-mcp
167
+ cd minecraft-mcp
168
+ npm install # заодно собирает dist/
169
+ npm test
170
+ npm run pack:mcpb # бандл для Claude Desktop в build/
171
+ ```
172
+
173
+ `npm run generate` обновляет клиент WorldAPI из `../minecraft-worldapi/docs/openapi.json`. Релизы собирает воркфлоу «Release» на GitHub, версия задаётся при запуске.
174
+
175
+ ## Стек
176
+
177
+ - TypeScript на Node.js 22
178
+ - Официальный MCP SDK для TypeScript
179
+ - openapi-fetch с типами, сгенерированными из OpenAPI-документа WorldAPI
180
+ - zod для входных данных инструментов
181
+ - Biome и Vitest
182
+
183
+ ## Участие ИИ
184
+
185
+ Большую часть кода и документации написал ИИ по моим описаниям задач, а я проверяю результат. Сообщения коммитов ИИ тоже пишет по изменениям, а ИИ-агенты проверяли инструменты на настоящем сервере.
186
+
187
+ ## Связанные проекты
188
+
189
+ [WorldAPI](https://github.com/MairwunNx/minecraft-worldapi) — 🌍 плагин для Paper, который выводит сервер в HTTP; этот сервер работает через него.
190
+
191
+ [MCBuddy Server](https://github.com/mcbuddy-ai/mcbuddy-server) — 🛠️⚡ бэкенд MCBuddy, ИИ-помощника для Minecraft на OpenRouter.
192
+
193
+ [MCBuddy Spigot](https://github.com/mcbuddy-ai/mcbuddy-spigot) — 💬 приводит MCBuddy в игру: спросите ИИ о чём угодно через `/ask` прямо в чате. 🎮
194
+
195
+ ## От того же автора
196
+
197
+ [Mo’Joins](https://github.com/MairwunNx/mojoins) — 🎉 сообщения о входе и выходе на языке каждого игрока, выбранном по IP.
198
+
199
+ [Mo’Afks](https://github.com/MairwunNx/moafks) — 🛡️ безопасный AFK-режим: AFK-игроки не получают урон и не мешают пропустить ночь.
200
+
201
+ ## Лицензия
202
+
203
+ MIT, см. [LICENSE](https://github.com/MairwunNx/minecraft-mcp/blob/master/LICENSE).
204
+
205
+ > 🫡 Сделал Павел Ерохин (Pavel Erokhin), он же mairwunnx.
package/README.md CHANGED
@@ -1,3 +1,205 @@
1
- # Temporary Holding Version
1
+ # minecraft-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ - 🔑 **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.
22
+ - 🙋 **“Me” means you.** Set `WORLDAPI_PLAYER`, and the agent knows who “I” is.
23
+ - ⏳ **Live events.** The agent can wait for something to happen: “tell me when Steve joins”.
24
+ - 📝 **Prompts** for common jobs: a server health check, a lag hunt, a grief investigation, a new player’s guide, and where a player is.
25
+ - 🔌 **Every client.** Claude Code, Claude Desktop in one click, Cursor, and anything else that speaks MCP, over stdio or HTTP.
26
+
27
+ ## Try it live
28
+
29
+ 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:
30
+
31
+ ```sh
32
+ claude mcp add moonlands -e WORLDAPI_URL=https://minecraft.mairwunnx.com/worldapi/api/v1 -- npx -y minecraft-mcp
33
+ ```
34
+
35
+ [![Play on Moonlands: pure vanilla, hard mobs, AI, claims. minecraft.mairwunnx.com](https://raw.githubusercontent.com/MairwunNx/minecraft-mcp/master/media/og-adv-image.png)](https://minecraft.mairwunnx.com)
36
+
37
+ Join at `minecraft.mairwunnx.com`. The site has the live map, player stats, and the hall of fame.
38
+
39
+ ## Install
40
+
41
+ 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.
42
+
43
+ ### Claude Desktop
44
+
45
+ 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.
46
+
47
+ ### Claude Code
48
+
49
+ ```sh
50
+ claude mcp add minecraft \
51
+ -e WORLDAPI_URL=https://your-server.example.com/worldapi/api/v1 \
52
+ -e WORLDAPI_TOKEN=your-token \
53
+ -- npx -y minecraft-mcp
54
+ ```
55
+
56
+ Run `/mcp` in Claude Code to see the tools.
57
+
58
+ ### Cursor and other clients
59
+
60
+ Any client that starts a server over stdio takes the same block:
61
+
62
+ ```json
63
+ {
64
+ "mcpServers": {
65
+ "minecraft": {
66
+ "command": "npx",
67
+ "args": ["-y", "minecraft-mcp"],
68
+ "env": {
69
+ "WORLDAPI_URL": "http://localhost:8110/api/v1",
70
+ "WORLDAPI_TOKEN": "your-token"
71
+ }
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ ### Over HTTP
78
+
79
+ For agents on another machine:
80
+
81
+ ```sh
82
+ MCP_HTTP_TOKEN=a-long-random-secret WORLDAPI_URL=... WORLDAPI_TOKEN=... \
83
+ npx -y minecraft-mcp --http --host 0.0.0.0 --port 3333
84
+ ```
85
+
86
+ Clients connect to `http://host:3333/mcp` and send `Authorization: Bearer <MCP_HTTP_TOKEN>`. Without that token, the server listens only on `localhost`.
87
+
88
+ ## Configure
89
+
90
+ | Variable | Meaning |
91
+ |---|---|
92
+ | `WORLDAPI_URL` | WorldAPI address including `/api/v1`. Required |
93
+ | `WORLDAPI_TOKEN` | A WorldAPI token. Without one, the agent sees what visitors may read |
94
+ | `WORLDAPI_PLAYER` | Your player name: who “I” and “me” are |
95
+ | `WORLDAPI_READ_ONLY` | `1` hides every tool that changes anything |
96
+ | `MCP_HTTP_TOKEN` | With `--http`, the token clients must send |
97
+
98
+ ## Tools
99
+
100
+ Scopes come from WorldAPI: `admin` includes `read`, `write:world`, and `write:players`, but not `code`.
101
+
102
+ **Read** (`read`, 27)
103
+
104
+ - `get_server_status`: version, players, uptime, TPS, memory; `detail` adds tick percentiles, CPU, and load per world
105
+ - `list_plugins`, `get_events`, `wait_for_event`: plugins, recorded events, and waiting for a live one
106
+ - `list_worlds`, `get_world`: time, weather, difficulty, spawn, the border, game rules, size
107
+ - `locate_structure`, `find_nearby`: the nearest village or stronghold, the nearest blocks of a type, the nearest biome
108
+ - `get_block`, `get_biome`, `get_highest_block`, `list_chunks`, `get_chunk`: what’s at a spot; chunks sorted by load
109
+ - `list_entities`, `get_entity`: mobs and items around a point
110
+ - `list_players`, `list_online_players`, `get_player`, `get_player_inventory`, `get_player_effects`, `get_player_statistics`, `get_player_advancements`, `get_player_sessions`, `check_permission`
111
+ - `get_leaderboard`, `get_aggregates`, `get_recipes`: rankings, server totals, and how to craft anything
112
+
113
+ **World** (`write:world`, 10)
114
+
115
+ - `set_world`: time, weather, difficulty, PvP, spawn
116
+ - `set_gamerule`, `set_world_border`
117
+ - `set_block`, `fill_blocks`, `force_load_chunk`
118
+ - `spawn_entity`, `update_entity`, `remove_entity` (one, or many by type and area)
119
+ - `world_effect`: lightning, explosions, sounds, particles
120
+
121
+ **Players** (`write:players`, 7; the player must be online)
122
+
123
+ - `teleport_player`, `set_player_property`, `send_message`
124
+ - `give_item`, `edit_inventory`, `set_effects`, `set_advancement`
125
+
126
+ **Admin** (`admin`, 10)
127
+
128
+ - `broadcast`, `run_command`, `get_server_log`, `save_worlds`, `restart_server` (with a countdown, or cancel)
129
+ - `get_access`, `manage_whitelist`, `set_operator`, `manage_bans`, `kick_player`
130
+
131
+ **Java** (`code`, 5)
132
+
133
+ - `execute_java`: compile and run Java once and get the result
134
+ - `load_java_script`, `list_java_scripts`, `get_java_script`, `unload_java_script`: scripts that stay loaded and react to events
135
+
136
+ 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.
137
+
138
+ ## Examples
139
+
140
+ Ask in plain words; the agent picks the tools.
141
+
142
+ - “Who played the most this week, and who died the most?”
143
+ - “The server lags. Find out why.”
144
+ - “Someone blew up my house near spawn. What happened?”
145
+ - “I’m new here. Where am I, what’s around, and what should I do first?”
146
+ - “Set it to morning, clear the weather, and tell everyone the event starts in five minutes.”
147
+ - “Restart the server in ten minutes and warn everyone.”
148
+
149
+ ## Safety
150
+
151
+ The agent acts on a live server with real players. Here is what keeps that safe:
152
+
153
+ - 🔑 **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.
154
+ - ⚠️ **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.
155
+ - 🧱 **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.
156
+ - 🤐 **The token stays hidden.** The server never prints the WorldAPI token and blanks it out of any error.
157
+ - 🌐 **HTTP needs a password.** Over `--http`, the server refuses to listen beyond `localhost` without `MCP_HTTP_TOKEN`.
158
+ - 🧾 **Everything is on record.** WorldAPI writes every change to its audit log with the token’s name.
159
+ - 🧑‍⚖️ **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.
160
+
161
+ The narrowest token that does the job is the best protection: with a read token, every trick is harmless.
162
+
163
+ ## Build
164
+
165
+ ```sh
166
+ git clone https://github.com/MairwunNx/minecraft-mcp
167
+ cd minecraft-mcp
168
+ npm install # also builds dist/
169
+ npm test
170
+ npm run pack:mcpb # the Claude Desktop bundle in build/
171
+ ```
172
+
173
+ `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.
174
+
175
+ ## Stack
176
+
177
+ - TypeScript on Node.js 22
178
+ - The official MCP TypeScript SDK
179
+ - openapi-fetch with types generated from WorldAPI’s OpenAPI document
180
+ - zod for tool inputs
181
+ - Biome and Vitest
182
+
183
+ ## AI involvement
184
+
185
+ 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.
186
+
187
+ ## Related projects
188
+
189
+ [WorldAPI](https://github.com/MairwunNx/minecraft-worldapi)—🌍 the Paper plugin that puts your server on HTTP; this server talks to it.
190
+
191
+ [MCBuddy Server](https://github.com/mcbuddy-ai/mcbuddy-server)—🛠️⚡ the backend for MCBuddy, an AI assistant for Minecraft, built on OpenRouter.
192
+
193
+ [MCBuddy Spigot](https://github.com/mcbuddy-ai/mcbuddy-spigot)—💬 brings MCBuddy into the game: ask the AI anything with `/ask`, right in the chat. 🎮
194
+
195
+ ## From the same author
196
+
197
+ [Mo’Joins](https://github.com/MairwunNx/mojoins)—🎉 join and quit messages in each player’s own language, picked by IP.
198
+
199
+ [Mo’Afks](https://github.com/MairwunNx/moafks)—🛡️ a safe AFK mode: AFK players take no damage and don’t block the night.
200
+
201
+ ## License
202
+
203
+ MIT, see [LICENSE](https://github.com/MairwunNx/minecraft-mcp/blob/master/LICENSE).
204
+
205
+ > 🫡 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
@@ -0,0 +1,6 @@
1
+ /**
2
+ * This file was auto-generated by openapi-typescript.
3
+ * Do not make direct changes to the file.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=worldapi.js.map