-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-mcp-sidecar-node.js
More file actions
1751 lines (1695 loc) · 71.4 KB
/
run-mcp-sidecar-node.js
File metadata and controls
1751 lines (1695 loc) · 71.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const fs = require("fs");
const os = require("os");
const path = require("path");
const http = require("http");
const DEFAULT_BRIDGE_URL = "http://127.0.0.1:7766";
const PROTOCOL_VERSION = "2025-03-26";
const DEBUG_LOG_PATH = path.join(os.homedir(), ".codex", "gemini-minecraft-mcp.log");
function debugLog(line) {
try {
fs.mkdirSync(path.dirname(DEBUG_LOG_PATH), { recursive: true });
fs.appendFileSync(DEBUG_LOG_PATH, `${new Date().toISOString()} ${line}\n`, "utf8");
} catch {
// ignore
}
}
function parseArgs(argv) {
const parsed = {};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("--")) continue;
const key = arg.slice(2);
let value = "true";
if (i + 1 < argv.length && !argv[i + 1].startsWith("--")) {
value = argv[i + 1];
i += 1;
}
parsed[key] = value;
}
return parsed;
}
function firstNonBlank(...values) {
for (const value of values) {
if (value != null && String(value).trim()) {
return String(value).trim();
}
}
return "";
}
function safeJoin(base, ...segments) {
try {
return path.join(base, ...segments);
} catch {
return null;
}
}
function discoverGlobalSettingsPaths(projectRoot) {
const paths = [];
const addRoot = (root) => {
if (!root) return;
const one = safeJoin(root, "run", "ai-settings", "global.json");
const two = safeJoin(root, "run", "run", "ai-settings", "global.json");
if (one) paths.push(one);
if (two) paths.push(two);
};
addRoot(projectRoot);
addRoot(process.cwd());
let current = path.resolve(__dirname);
for (let i = 0; i < 6; i += 1) {
addRoot(current);
const parent = path.dirname(current);
if (parent === current) break;
current = parent;
}
return [...new Set(paths)];
}
function readTokenFromGlobalSettings(filePath) {
try {
const raw = fs.readFileSync(filePath, "utf8");
const data = JSON.parse(raw);
return typeof data.mcpToken === "string" ? data.mcpToken.trim() : "";
} catch {
return "";
}
}
function resolveBridgeToken(explicitToken, tokenFile, projectRoot) {
if (explicitToken) return explicitToken.trim();
if (tokenFile) {
const token = readTokenFromGlobalSettings(tokenFile);
if (token) return token;
}
for (const filePath of discoverGlobalSettingsPaths(projectRoot)) {
const token = readTokenFromGlobalSettings(filePath);
if (token) return token;
}
return "";
}
function trimTrailingSlash(url) {
return url.replace(/\/+$/, "");
}
function objectSchema() {
return { type: "object", additionalProperties: true, properties: {} };
}
function primitive(type, description) {
return { type, description };
}
function schema(...entries) {
const obj = objectSchema();
const required = [];
for (const [key, type, requiredFlag, description] of entries) {
obj.properties[key] = primitive(type, description);
if (requiredFlag) required.push(key);
}
if (required.length) obj.required = required;
return obj;
}
function commandsSchema() {
const obj = objectSchema();
obj.properties.commands = {
type: "array",
items: {
anyOf: [
{ type: "string" },
{
type: "object",
additionalProperties: false,
properties: {
command: primitive("string", "Minecraft command string."),
delayTicks: primitive("integer", "Optional delay in ticks before this command executes, relative to the previous command."),
delayMs: primitive("number", "Optional delay in milliseconds before this command executes, relative to the previous command."),
},
required: ["command"],
},
],
},
};
obj.required = ["commands"];
return obj;
}
function highlightSchema() {
const obj = objectSchema();
const item = objectSchema();
item.properties = {
x: primitive("number", "World x coordinate."),
y: primitive("number", "World y coordinate."),
z: primitive("number", "World z coordinate."),
label: primitive("string", "Optional label."),
color: primitive("string", "Named color or hex code."),
durationMs: primitive("integer", "Highlight duration in milliseconds."),
};
item.required = ["x", "y", "z"];
obj.properties.highlights = { type: "array", items: item };
obj.required = ["highlights"];
return obj;
}
const TOOLS = {
minecraft_help: {
description: "Get a detailed guide for using this Minecraft MCP server, including workflow, build-plans, and when to use each major tool.",
inputSchema: schema(
["topic", "string", false, "Optional topic such as workflow, build-plan, commands, vision, or tools."],
["task", "string", false, "Optional current task so the guide can be framed around it."]
),
localHandler: (argumentsObject = {}) => {
const topic = typeof argumentsObject.topic === "string" ? argumentsObject.topic.trim().toLowerCase() : "";
const task = typeof argumentsObject.task === "string" ? argumentsObject.task.trim() : "";
let guide = buildAgentWorkflowGuide();
if (topic === "build" || topic === "build-plan" || topic === "buildplan") {
guide = buildBuildPlanGuide();
} else if (topic === "buildsite" || topic === "terrain" || topic === "site") {
guide = buildBuildsiteGuide();
} else if (topic === "commands" || topic === "raw-commands") {
guide = buildCommandsGuide();
} else if (topic === "vision" || topic === "capture") {
guide = buildVisionGuide();
} else if (topic === "tools" || topic === "catalog") {
guide = "# Tool Catalog\n\n" + buildToolCatalogText();
}
return {
topic: topic || "workflow",
task,
guide,
};
},
},
minecraft_describe_tool: {
description: "Explain exactly how to use one Minecraft MCP tool, including argument expectations, when to use it, and examples.",
inputSchema: schema(["name", "string", true, "Tool name to explain."]),
localHandler: (argumentsObject = {}) => {
const name = typeof argumentsObject.name === "string" ? argumentsObject.name.trim() : "";
return describeTool(name);
},
},
minecraft_session: {
description: "Get the current Minecraft bridge and active-player session.",
method: "GET",
path: "/v1/session",
inputSchema: objectSchema(),
},
minecraft_inventory: {
description: "Read the active player's inventory summary.",
method: "POST",
path: "/v1/tools/inventory",
inputSchema: objectSchema(),
},
minecraft_nearby_entities: {
description: "List nearby entities around the active player.",
method: "POST",
path: "/v1/tools/nearby",
inputSchema: objectSchema(),
},
minecraft_scan_blocks: {
description: "Scan for nearby blocks matching a block id or tag.",
method: "POST",
path: "/v1/tools/blocks",
inputSchema: schema(
["target", "string", true, "Block id or #tag."],
["radius", "integer", false, "Optional scan radius."]
),
},
minecraft_scan_containers: {
description: "Scan nearby containers and summarize their contents.",
method: "POST",
path: "/v1/tools/containers",
inputSchema: schema(
["filter", "string", false, "Optional block filter."],
["radius", "integer", false, "Optional scan radius."]
),
},
minecraft_blockdata: {
description: "Inspect a block entity by coordinates or nearest matching container.",
method: "POST",
path: "/v1/tools/blockdata",
inputSchema: schema(
["target", "string", false, "Optional block filter."],
["radius", "integer", false, "Optional search radius."],
["x", "integer", false, "Absolute block x."],
["y", "integer", false, "Absolute block y."],
["z", "integer", false, "Absolute block z."]
),
},
minecraft_players: {
description: "List online players and their positions.",
method: "POST",
path: "/v1/tools/players",
inputSchema: objectSchema(),
},
minecraft_stats: {
description: "Read the active player's health, food, armor, XP, and effects.",
method: "POST",
path: "/v1/tools/stats",
inputSchema: objectSchema(),
},
minecraft_buildsite: {
description: "Summarize terrain around the active player for build planning, including relative ground range, headroom clear percent, water columns, and top surface blocks.",
method: "POST",
path: "/v1/tools/buildsite",
inputSchema: schema(["radius", "integer", false, "Optional scan radius."]),
},
minecraft_recipe_lookup: {
description: "Look up crafting recipes for an item.",
method: "POST",
path: "/v1/tools/recipe",
inputSchema: schema(["item", "string", true, "Item id to resolve."]),
},
minecraft_smelt_lookup: {
description: "Look up smelting and other cooking recipes for an item.",
method: "POST",
path: "/v1/tools/smelt",
inputSchema: schema(["item", "string", true, "Item id to resolve."]),
},
minecraft_item_lookup: {
description: "Inspect the tooltip of an inventory slot, mainhand, or offhand item.",
method: "POST",
path: "/v1/tools/lookup",
inputSchema: schema(["target", "string", false, "mainhand, offhand, or slot N"]),
},
minecraft_item_components: {
description: "Inspect item components for an inventory slot, mainhand, or offhand item.",
method: "POST",
path: "/v1/tools/nbt",
inputSchema: schema(["target", "string", false, "mainhand, offhand, or slot N"]),
},
minecraft_batch_status: {
description: "Get the status of the latest or a specific delayed MCP command batch.",
method: "POST",
path: "/v1/tools/batch_status",
inputSchema: schema(["batchId", "string", false, "Optional delayed batch id. If omitted, uses the latest batch for the active player."]),
},
minecraft_capture_view: {
description: "Capture the active player's current view as a PNG screenshot and return it as base64.",
method: "POST",
path: "/v1/actions/capture_view",
inputSchema: objectSchema(),
},
minecraft_preview_build_plan: {
description: "Compile and validate a structured voxel build plan without executing it, including v2 semantic steps like hollow_cuboid, columns, windows, roof, repeat, and scatter. Returns previewCommands, planId, resolvedOrigin, issues, repairs, rotation, and phase data.",
method: "POST",
path: "/v1/actions/preview_build_plan",
inputSchema: {
type: "object",
description: "Either provide build_plan explicitly or pass the build_plan object as the root arguments object. Supports version=2 plans, coordMode=player|absolute|anchor, explicit origin, offset, anchors, snapToGround, flattenTerrain, clearVegetation, autoFix, clear, cuboids, blocks, and typed semantic steps.",
additionalProperties: true,
properties: {
build_plan: { type: "object", additionalProperties: true },
coordMode: { type: "string", enum: ["player", "absolute", "anchor"] },
origin: { type: "object", additionalProperties: true },
offset: { type: "object", additionalProperties: true },
anchor: { type: "string" },
autoFix: { type: "boolean" },
snapToGround: { type: "boolean" },
flattenTerrain: { type: "boolean" },
clearVegetation: { type: "boolean" },
options: { type: "object", additionalProperties: true },
},
},
},
minecraft_highlight: {
description: "Render x-ray highlights in the world for the active player.",
method: "POST",
path: "/v1/actions/highlight",
inputSchema: highlightSchema(),
},
minecraft_execute_build_plan: {
description: "Compile and execute a structured voxel build plan using the mod's planner, including v2 semantic steps, terrain options, anchor origins, support diagnostics, preview parity via planId, and undo-aware batching.",
method: "POST",
path: "/v1/actions/execute_build_plan",
inputSchema: {
type: "object",
description: "Either provide build_plan explicitly, pass the build_plan object as the root arguments object, or send executePlanId/planId from minecraft_preview_build_plan to execute the exact cached preview unchanged. Supports the v2 semantic build vocabulary and terrain flags.",
additionalProperties: true,
properties: {
build_plan: { type: "object", additionalProperties: true },
executePlanId: { type: "string" },
planId: { type: "string" },
coordMode: { type: "string", enum: ["player", "absolute", "anchor"] },
origin: { type: "object", additionalProperties: true },
offset: { type: "object", additionalProperties: true },
anchor: { type: "string" },
autoFix: { type: "boolean" },
snapToGround: { type: "boolean" },
flattenTerrain: { type: "boolean" },
clearVegetation: { type: "boolean" },
options: { type: "object", additionalProperties: true },
},
},
},
minecraft_execute_commands: {
description: "Execute validated Minecraft commands through the mod's existing command pipeline, including optional delayed sequencing for cinematic batches.",
method: "POST",
path: "/v1/actions/execute_commands",
inputSchema: commandsSchema(),
},
minecraft_undo_last_batch: {
description: "Undo the last MCP or AI command/build batch for the active player.",
method: "POST",
path: "/v1/actions/undo",
inputSchema: objectSchema(),
},
};
function buildToolCatalogText() {
return Object.entries(TOOLS)
.map(([name, tool]) => {
const properties = Object.keys(tool.inputSchema?.properties || {});
const args = properties.length ? properties.join(", ") : "none";
return `- ${name}: ${tool.description}\n arguments: ${args}`;
})
.join("\n");
}
function buildAgentWorkflowGuide() {
return [
"# Gemini Minecraft MCP Agent Guide",
"",
"Use this server as a Minecraft capability backend. The external agent does the reasoning; this server provides grounded world reads, safe build execution, screenshots, and undo.",
"",
"## Core rules",
"",
"- Prefer discovery before action. Read the world state first, then decide.",
"- Use `minecraft_execute_build_plan` for multi-block structures. Do not emit long raw command lists when a structured build plan is more natural.",
"- Use `minecraft_execute_commands` for one-off commands like `give`, `say`, `time set`, or small targeted edits.",
"- Use `minecraft_undo_last_batch` immediately after a bad command/build rather than trying to manually reverse a mistake.",
"- For visual tasks, use `minecraft_capture_view` to inspect what the player sees before making aesthetic judgments.",
"- In singleplayer, mutation tools only work while the integrated server is actively ticking. If a mutation call reports server unavailable, keep the world in focus or open it to LAN and retry.",
"- Do not assume `y=0` means ground. All build-plan coordinates are relative to the player origin, not auto-snapped to terrain.",
"- Do not infer planner semantics from error strings alone. Use `minecraft_describe_tool` or `minecraft_help` first when the build contract matters.",
"",
"## Recommended workflow",
"",
"### General world reasoning",
"1. Call `minecraft_session` to confirm the active world, dimension, and coordinates.",
"2. Use read tools as needed: inventory, nearby entities, block scans, containers, player stats, recipes, and item lookups.",
"3. If the task depends on what is visible on screen, call `minecraft_capture_view`.",
"4. Choose the smallest mutation necessary: highlight, commands, or structured build plan.",
"",
"### Building structures",
"1. Call `minecraft_buildsite` with a radius that matches the requested structure size.",
"2. Read `minDy`, `maxDy`, `clearPercent`, `waterColumns`, and `surfaceCounts` before choosing build height and footprint.",
"3. Produce a compact `build_plan` using relative coordinates with the player as the origin.",
"4. Prefer cuboids over many single blocks.",
"5. Use `steps` when the build needs a foundation first or when terrain is uneven.",
"6. Use `rotate` only when orientation matters.",
"7. Call `minecraft_preview_build_plan` before the real build when the terrain, support, or footprint is uncertain.",
"8. Execute with `minecraft_execute_build_plan`.",
"9. If the result is wrong, inspect with `minecraft_capture_view` or another read tool, then revise or undo.",
"",
"### Timed command sequences",
"1. Use `minecraft_execute_commands` with either plain strings or objects like `{ \"command\": \"say beat\", \"delayTicks\": 20 }`.",
"2. Delays are relative to the previous command.",
"3. For longer sequences, inspect the returned `batchId` and poll `minecraft_batch_status` until it completes.",
"4. Delayed batches are for real Minecraft commands only, not skill or settings commands.",
"",
"## Build-plan guidance",
"",
"- Coordinates should be relative to the player unless you have a strong reason to anchor elsewhere.",
"- Favor `cuboids` for floors, walls, roofs, and shells.",
"- Use `blocks` for details like doors, beds, torches, chests, stairs, or decorative accents.",
"- Include `clear` only when needed.",
"- Use `steps` for larger builds that benefit from phases like foundation -> walls -> roof -> details.",
"- If `minecraft_buildsite` reports negative `minDy`/`maxDy`, the nearby ground is below the player's feet. Lower the build or move the player before building.",
"",
"## Interpreting `minecraft_buildsite`",
"",
"- `minDy` and `maxDy` are surface deltas relative to the player's current block Y.",
"- Example: if the player is at world y=64 and `maxDy=-9`, then the highest nearby sampled ground is around world y=55.",
"- `clearPercent` is the percentage of sampled columns that have open headroom above the detected surface. Low values mean the area is obstructed or underground.",
"- `surfaceCounts` is a top-surface sample, not a full material histogram of the whole volume.",
"- `waterColumns > 0` means the sampled area includes water on the surface and may need relocation or clearing.",
"- Never treat `y=0` in a build plan as 'ground level' unless you intentionally positioned the player so that their block Y matches the intended structure base.",
"",
"## Planner safety envelope",
"",
"- Relative X/Z coordinates are clamped into `[-32, 32]`.",
"- Relative Y coordinates are clamped into `[-24, 24]`.",
"- If the planner clamps a point or bounds, it reports a repair like `was clamped into the safe build window`.",
"- Large or off-center plans should be moved closer to the player or broken into smaller phased plans.",
"",
"## Support and foundations",
"",
"- The planner checks the lowest occupied columns in the compiled build and looks for solid terrain below them.",
"- If a build is close to grounded, the planner can auto-add support pillars using `minecraft:stone_bricks`.",
"- Auto-foundation is capped at 24 columns. Beyond that, the build is rejected and the agent should revise the plan.",
"- If there is no solid terrain below some columns at all, the planner rejects the build and tells the agent to add a foundation, lower the build, or use `steps`.",
"- The safest fix for uneven terrain is usually a first phase that lays an explicit foundation at the correct relative Y.",
"",
"## Result fields from `minecraft_execute_build_plan`",
"",
"- `success`: whether execution completed.",
"- `applied`: number of compiled Minecraft commands that were actually executed.",
"- `repairs`: planner repairs or normalizations that were applied before execution.",
"- `outputs`: command output strings from Minecraft.",
"- `error`: machine-readable failure summary if the action failed.",
"- `undoAvailable`: whether `minecraft_undo_last_batch` can revert the result.",
"- `summary`: final build summary string.",
"- `appliedRotation`: normalized rotation that was actually used (`0`, `90`, `180`, or `270`).",
"- `phaseCount`: number of compiled build phases with direct operations.",
"",
"## Previewing first",
"",
"- `minecraft_preview_build_plan` runs the same planner and command validation without mutating the world.",
"- Use it when the agent is unsure about terrain alignment, clamping, rotation, or support pillars.",
"- The preview returns `previewCommands` so the agent can inspect exactly what would run before committing.",
"",
"## When to use vision",
"",
"- To inspect the player’s current viewpoint.",
"- To judge terrain fit, doorway alignment, roof shape, or visual mistakes after a build.",
"- To read what is on screen when the needed information is not already exposed by another tool.",
"",
"## Tool catalog",
"",
buildToolCatalogText(),
"",
].join("\n");
}
function buildCommandsGuide() {
return [
"# Raw Commands Guide",
"",
"Use `minecraft_execute_commands` for one-off commands and small targeted actions.",
"",
"## Good use cases",
"- `give @s minecraft:apple 1`",
"- `say hello`",
"- `time set day`",
"- one or two small world edits where a build plan would be excessive",
"",
"## Avoid using raw commands when",
"- building a house, tower, wall, interior, or other multi-block structure",
"- you can describe the intent more clearly as floors, walls, roofs, or detail blocks",
"",
"For normal structures, prefer `minecraft_execute_build_plan` instead.",
"",
"## Command payload shape",
"",
"```json",
"{",
" \"commands\": [",
" \"give @s minecraft:apple 1\"",
" ]",
"}",
"```",
"",
"Delayed sequencing is also supported:",
"",
"```json",
"{",
" \"commands\": [",
" { \"command\": \"say intro\", \"delayTicks\": 0 },",
" { \"command\": \"say beat\", \"delayTicks\": 20 },",
" { \"command\": \"say finale\", \"delayMs\": 1500 }",
" ]",
"}",
"```",
"",
"When delays are present, the result includes `pending=true` and a `batchId`. Poll `minecraft_batch_status` until it completes.",
"",
"## Normalization",
"",
"- Literal `\\uXXXX` Unicode escapes are decoded before execution, so color codes like `\\u00a7` work without manual repair.",
"- `effect give ... 0` is normalized to a minimum duration of `1` so the command does not fail on Minecraft's duration floor.",
"",
].join("\n");
}
function buildVisionGuide() {
return [
"# Vision Guide",
"",
"Use `minecraft_capture_view` when the task depends on what the player currently sees.",
"",
"## Good use cases",
"- judge whether a build looks correct",
"- inspect terrain fit before finalizing a structure",
"- read visible UI or signs when the needed data is not already exposed by another tool",
"",
"## Return shape",
"- `mimeType`",
"- `lookAt`",
"- `byteLength`",
"- `imageBase64`",
"- `imagePath`",
"- `summary`",
"",
"The capture is also persisted to a PNG file on disk so external tooling can inspect it directly if needed.",
"",
].join("\n");
}
function buildBuildsiteGuide() {
return [
"# Buildsite Guide",
"",
"Use `minecraft_buildsite` before planning terrain-sensitive structures such as houses, towers, shrines, farms, bridges, or anything that needs to sit on real ground.",
"",
"## Returned fields",
"",
"- `radius`: actual scan radius used by the server.",
"- `minDy`: lowest detected surface Y relative to the player's current block Y.",
"- `maxDy`: highest detected surface Y relative to the player's current block Y.",
"- `clearPercent`: percent of sampled columns with open headroom above the surface.",
"- `waterColumns`: sampled columns whose surface block is water.",
"- `totalColumns`: number of sampled columns.",
"- `surfaceCounts`: top surface sample, usually the four most common surface blocks.",
"",
"## How to read it",
"",
"- If both `minDy` and `maxDy` are negative, the surrounding surface is below the player. A build plan with `y=0` will float unless you lower it.",
"- If both are positive, the player is below surrounding ground or inside terrain. Move the player or raise the structure.",
"- If the range crosses zero, the area is mixed or uneven. Use a foundation phase or choose a flatter spot.",
"- Low `clearPercent` means the site is obstructed, roofed over, forested, underground, or otherwise tight.",
"",
"## Agent rule",
"",
"Never convert `buildsite` directly into world coordinates and then ignore it. Use it to decide the relative Y of the first foundation or floor cuboid before calling `minecraft_execute_build_plan`.",
"",
].join("\n");
}
function buildExampleUsageForTool(name) {
switch (name) {
case "minecraft_session":
return "{ }";
case "minecraft_buildsite":
return '{ "radius": 16 }';
case "minecraft_batch_status":
return "{ }";
case "minecraft_preview_build_plan":
return '{ "summary": "Preview small oak hut", "cuboids": [{"name":"floor","block":"oak_planks","from":{"x":0,"y":0,"z":0},"to":{"x":4,"y":0,"z":4}}] }';
case "minecraft_capture_view":
return "{ }";
case "minecraft_execute_commands":
return '{ "commands": ["give @s minecraft:apple 1", {"command":"say beat","delayTicks":20}] }';
case "minecraft_execute_build_plan":
return '{ "summary": "Small oak hut", "cuboids": [{"name":"floor","block":"oak_planks","from":{"x":0,"y":0,"z":0},"to":{"x":4,"y":0,"z":4}}] }';
case "minecraft_help":
return '{ "topic": "build-plan", "task": "build a small house" }';
case "minecraft_describe_tool":
return '{ "name": "minecraft_execute_build_plan" }';
default:
return "{}";
}
}
function buildWhenToUseForTool(name) {
switch (name) {
case "minecraft_batch_status":
return "Use after a delayed execute_commands call so the agent can tell whether the batch is still running, completed, or failed.";
case "minecraft_preview_build_plan":
return "Use before committing a structure when grounding, clamping, support pillars, or final command shape is uncertain.";
case "minecraft_execute_build_plan":
return "Use for real structures: huts, houses, towers, walls, interiors, platforms, statues, and other multi-block builds.";
case "minecraft_execute_commands":
return "Use for one-off commands, compact command batches, or timed command sequences where a full build plan would be overkill.";
case "minecraft_capture_view":
return "Use when the task depends on the player’s visible viewpoint or when you need visual confirmation.";
case "minecraft_buildsite":
return "Use before planning a structure so the agent knows terrain shape, surface composition, relative surface height, and headroom.";
case "minecraft_help":
return "Use when the agent is unsure how this MCP server is intended to be used.";
case "minecraft_describe_tool":
return "Use when the agent is unsure about one specific tool’s semantics or payload shape.";
default:
return "Use when you need the structured Minecraft capability described by the tool.";
}
}
function buildPitfallsForTool(name) {
switch (name) {
case "minecraft_batch_status":
return [
"This only applies to delayed MCP command batches.",
"If no batchId is provided, it reports the latest batch for the active player.",
];
case "minecraft_preview_build_plan":
return [
"Do not treat preview success as proof the final result is visually perfect; it only proves the planner and command validation succeeded.",
"Preview does not mutate the world and does not create an undo batch.",
];
case "minecraft_execute_build_plan":
return [
"Do not send prose instead of geometry.",
"Do not use raw command strings inside the build plan.",
"For most structures, prefer cuboids over many single blocks.",
"Do not assume `y=0` is ground; it is relative to the player origin.",
"Do not ignore clamping repairs. If the plan was clamped, move it closer or make it smaller.",
"If support-pillar errors appear, add an explicit foundation phase or lower the build instead of retrying the same floating plan.",
];
case "minecraft_buildsite":
return [
"Do not treat `minDy` or `maxDy` as absolute world Y values.",
"Do not assume high `clearPercent` means the terrain is flat; it only describes headroom above sampled surface columns.",
];
case "minecraft_execute_commands":
return [
"Do not use this as a substitute for a normal house or tower build plan.",
"Keep the command batch compact and deliberate.",
"Delayed batches support real Minecraft commands only. Do not use delayed skill or setting commands.",
];
case "minecraft_capture_view":
return [
"It captures what the client currently sees, not an arbitrary detached camera angle.",
];
default:
return [];
}
}
function describeTool(name) {
const tool = TOOLS[name];
if (!tool) {
throw new Error(`Unknown tool: ${name}`);
}
const properties = Object.entries(tool.inputSchema?.properties || {}).map(([key, value]) => ({
name: key,
type: value?.type || "unknown",
description: value?.description || "",
required: (tool.inputSchema?.required || []).includes(key),
}));
return {
name,
description: tool.description,
whenToUse: buildWhenToUseForTool(name),
arguments: properties,
exampleArguments: buildExampleUsageForTool(name),
pitfalls: buildPitfallsForTool(name),
responseFields: buildResponseFieldsForTool(name),
workflowNotes: buildWorkflowNotesForTool(name),
relatedResources:
name === "minecraft_execute_build_plan"
? ["minecraft://guide/agent-workflow", "minecraft://guide/build-plan", "minecraft://guide/buildsite", "minecraft_build_planner"]
: name === "minecraft_buildsite"
? ["minecraft://guide/agent-workflow", "minecraft://guide/buildsite", "minecraft://guide/build-plan", "minecraft_agent_guide"]
: ["minecraft://guide/agent-workflow", "minecraft_agent_guide"],
};
}
function buildResponseFieldsForTool(name) {
switch (name) {
case "minecraft_buildsite":
return [
{ name: "radius", description: "Actual scan radius used." },
{ name: "minDy", description: "Lowest detected surface Y relative to the player's block Y." },
{ name: "maxDy", description: "Highest detected surface Y relative to the player's block Y." },
{ name: "clearPercent", description: "Percent of sampled columns with open headroom above the surface." },
{ name: "waterColumns", description: "How many sampled columns had water as the surface block." },
{ name: "totalColumns", description: "Total sampled columns." },
{ name: "surfaceCounts", description: "Most common sampled surface blocks and counts." },
];
case "minecraft_batch_status":
return [
{ name: "success", description: "Whether the status lookup succeeded." },
{ name: "batchId", description: "Delayed batch identifier." },
{ name: "pending", description: "Whether the batch is still running." },
{ name: "completed", description: "Whether the batch has finished." },
{ name: "totalCommands", description: "Total scheduled commands." },
{ name: "applied", description: "Commands successfully applied so far." },
{ name: "failed", description: "Commands failed so far." },
{ name: "nextIndex", description: "Next command index to execute." },
{ name: "outputs", description: "Collected command outputs." },
{ name: "error", description: "Combined failure summary, if any." },
{ name: "undoAvailable", description: "Whether the completed batch can be undone." },
{ name: "summary", description: "Human-readable batch state." },
];
case "minecraft_execute_commands":
return [
{ name: "success", description: "Whether the command execution or scheduling request succeeded." },
{ name: "applied", description: "Commands executed immediately or scheduled in the batch." },
{ name: "outputs", description: "Immediate command outputs for non-delayed execution." },
{ name: "error", description: "Failure summary if validation or execution failed." },
{ name: "undoAvailable", description: "Whether the resulting mutation can be undone." },
{ name: "summary", description: "Execution or scheduling summary." },
{ name: "pending", description: "True when a delayed batch was scheduled and is still running." },
{ name: "batchId", description: "Returned when a delayed batch was scheduled." },
{ name: "previewCommands", description: "Validated command list, especially useful for delayed batches." },
];
case "minecraft_preview_build_plan":
return [
{ name: "success", description: "Whether the preview compiled and validated successfully." },
{ name: "applied", description: "How many commands would execute if the build were committed." },
{ name: "repairs", description: "Planner repairs or clamping notices." },
{ name: "error", description: "Failure summary if the preview failed." },
{ name: "summary", description: "Planner summary of the build." },
{ name: "appliedRotation", description: "Final normalized rotation." },
{ name: "phaseCount", description: "Number of compiled direct-operation phases." },
{ name: "resolvedOrigin", description: "Exact world origin the planner actually used." },
{ name: "issues", description: "Structured floating/grounding issues with cuboid names, gaps, and suggestedY." },
{ name: "autoFixAvailable", description: "Whether the planner believes a safe grounding fix exists." },
{ name: "planId", description: "Cached preview id that execute can reuse unchanged via executePlanId." },
{ name: "previewCommands", description: "The exact validated Minecraft commands that would run." },
];
case "minecraft_execute_build_plan":
return [
{ name: "success", description: "Whether the build executed successfully." },
{ name: "applied", description: "Number of compiled Minecraft commands executed." },
{ name: "repairs", description: "Planner repairs, clamping notices, or support messages." },
{ name: "outputs", description: "Minecraft command outputs." },
{ name: "error", description: "Failure summary if execution failed." },
{ name: "undoAvailable", description: "Whether the result can be rolled back with minecraft_undo_last_batch." },
{ name: "summary", description: "Planner summary of what was built or attempted." },
{ name: "appliedRotation", description: "Final normalized rotation used: 0, 90, 180, or 270." },
{ name: "phaseCount", description: "How many direct-operation phases the planner compiled." },
{ name: "resolvedOrigin", description: "Exact world origin the planner actually used." },
{ name: "issues", description: "Structured floating/grounding issues for failed or revised builds." },
{ name: "autoFixAvailable", description: "Whether the planner believed a safe grounding fix was available." },
{ name: "planId", description: "Preview cache id if the build was executed from a cached preview." },
];
default:
return [];
}
}
function buildWorkflowNotesForTool(name) {
switch (name) {
case "minecraft_buildsite":
return [
"Use this before finalizing any structure that needs to rest on real terrain.",
"Read `minDy` and `maxDy` before deciding the base Y of the plan.",
"If the ground range is below zero, lower the plan or move the player to the intended build level.",
];
case "minecraft_batch_status":
return [
"Use this after a delayed `minecraft_execute_commands` call returns a `batchId`.",
"Poll until `pending` becomes false before assuming the full sequence finished.",
];
case "minecraft_preview_build_plan":
return [
"Use this after minecraft_buildsite and before minecraft_execute_build_plan when the structure may float or get clamped.",
"If preview returns support-pillar or clamping repairs, revise the build before executing it.",
"If preview succeeds and the command list looks reasonable, then use minecraft_execute_build_plan with the same payload.",
];
case "minecraft_execute_build_plan":
return [
"Start with minecraft_session, then minecraft_buildsite, then produce the plan.",
"For uneven terrain, use `steps` with a foundation phase before walls or roofs.",
"If the result contains clamping or support-pillar repairs, revise the plan rather than blindly retrying the same geometry.",
];
default:
return [];
}
}
function buildBuildPlanGuide() {
return [
"# Build Plan Contract",
"",
"The `minecraft_execute_build_plan` tool accepts the same build-plan contract used by the in-mod voxel planner.",
"If you can describe a structure as floors, walls, roofs, shells, or a handful of detail blocks, prefer this tool over raw `minecraft_execute_commands`.",
"",
"## When To Use This Tool",
"",
"- Use `minecraft_execute_build_plan` for huts, houses, towers, interiors, platforms, walls, statues, or any other multi-block structure.",
"- Use `minecraft_execute_commands` for one-off commands like `give`, `say`, `time set`, or tiny targeted edits where a build plan would be overkill.",
"- If you are unsure about terrain fit, call `minecraft_buildsite` first and then produce the plan.",
"",
"## Root Shape",
"",
"You may pass either:",
"- a root object that already is the build plan",
"- or an object with a top-level `build_plan` field",
"",
"Both of these are valid:",
"",
"```json",
"{",
" \"summary\": \"Small hut\",",
" \"cuboids\": [ ... ]",
"}",
"```",
"",
"```json",
"{",
" \"build_plan\": {",
" \"summary\": \"Small hut\",",
" \"cuboids\": [ ... ]",
" }",
"}",
"```",
"",
"## Common Top-Level Fields",
"",
"- `label` or `summary`: short description of the structure",
"- `version`: schema version. `2` enables the richer semantic build-plan style.",
"- `coordMode`: `player`, `absolute`, or `anchor`",
"- `origin`: explicit origin. In `absolute` mode it is a real world origin.",
"- `offset`: optional extra relative shift applied after the base origin",
"- `anchor`: anchor reference such as `last_build:door` when `coordMode=anchor`",
"- `autoFix`: whether the planner may auto-lower near-ground builds and add limited support repair",
"- `snapToGround`: opt-in origin grounding adjustment",
"- `flattenTerrain`: opt-in flattening of the footprint to origin Y",
"- `clearVegetation`: opt-in clearing of replaceable plants in the footprint",
"- `rotate`: `0`, `90`, `180`, `270`, `cw`, or `ccw`",
"- `options.rotation`: v2 rotation field if you keep metadata under `options`",
"- `options.phaseReorder`: default false. If false, step order is sacred.",
"- `palette`: aliases for block ids, useful for custom mod blocks",
"- `anchors`: named relative points created by the build for later attachment",
"- `clear`: volumes to clear before building",
"- `cuboids`: bulk structural geometry",
"- `blocks`: single-block details",
"- `steps`: phased sub-plans for larger structures",
"- Semantic step `type`s: `cuboid`, `hollow_cuboid`, `columns`, `blocks`, `windows`, `roof`, `fill`, `repeat`, `scatter`",
"",
"## Coordinate Rules",
"",
"- `coordMode=player` means the plan is relative to the active player.",
"- `coordMode=absolute` means `origin` is an explicit world coordinate and cuboid/block coordinates are relative to that absolute origin.",
"- `coordMode=anchor` means the planner resolves a previously remembered anchor reference such as `last_build:door` or `Some Label:door` and uses that as the base origin.",
"- If `coordMode=absolute` is used without `origin`, the planner rejects the plan.",
"- Positive `x` is east, positive `y` is up, positive `z` is south.",
"- Keep small test structures close to the origin, for example between `-8` and `8` on x/z.",
"- The planner clamps X/Z into `[-32, 32]` and Y into `[-24, 24]`. If you exceed that window, the plan is repaired and reported as clamped.",
"- Absolute `origin` is not clamped into the player's safe window. Relative cuboid/block coordinates still are.",
"",
"## Aligning The Build With Real Terrain",
"",
"- `minecraft_buildsite` returns `minDy` and `maxDy` relative to the player's block Y.",
"- Example: player at world y=64 and `maxDy=-9` means the highest nearby sampled ground is roughly world y=55.",
"- In that situation, a plan with its floor at relative `y=0` starts nine blocks above nearby surface and will likely trigger support repairs or failure.",
"- Best practice: move the player to the intended build level or lower the foundation/floor phase to match the surface you actually want to build on.",
"- If `clearPercent` is low, do not brute-force retries. Either choose another spot, clear space explicitly, or use a phased plan.",
"- If you want a structure at a stable world location, prefer `coordMode=absolute` with an explicit `origin` rather than relying on wherever the player happens to be standing.",
"",
"## Accepted Geometry Forms",
"",
"The planner is intentionally flexible. For cuboids and clear volumes it accepts several equivalent shapes:",
"- `from` + `to`",
"- `start` + `end`",
"- `start` + `size`",
"- `location` + `size`",
"- `location` + `dimensions`",
"- direct `x`, `y`, `z`, `width`, `height`, `depth` style fields",
"",
"For single-block details it accepts:",
"- `pos`",
"- `location`",
"- direct `x`, `y`, `z` fields",
"",
"Block ids may be provided as:",
"- `block`",
"- `material`",
"- `id`",
"- full vanilla-style blockstate strings like `minecraft:oak_stairs[facing=east,half=top]`",
"",
"Block properties may be provided as:",
"- `properties`",
"- `state`",
"",
"## Semantic Step Vocabulary",
"",
"- `cuboid`: solid rectangular fill",
"- `hollow_cuboid`: shell-only room or wall box",
"- `columns`: repeat vertical pillars at listed x/z positions",
"- `blocks`: individual entries with exact block ids and optional block states",
"- `windows`: semantic glass replacement regions",
"- `roof`: declarative roof generator for `flat`, `pyramid`, `gable`, `hip`, or `dome`-style output",
"- `repeat`: repeated posts or details using `start`, `step`, and `count`",
"- `scatter`: decorative random surface placement in a bounded region",
"",
"## Good Planning Habits",
"",
"- Keep plans compact and structural.",
"- Prefer a handful of cuboids over dozens of raw commands.",
"- Use blocks for doors, beds, torches, stairs, and fine details.",
"- If terrain is uneven, inspect with `minecraft_buildsite` first.",
"- If the structure is larger, use `steps` so the plan reads like phases instead of one giant blob.",
"- Treat `clear` as a surgical pre-build removal step, not a vague instruction to hollow things out automatically.",
"- Prefer `hollow_cuboid` for rooms instead of solid-fill-then-air tricks.",
"- Prefer `roof` for small structures if you want the planner to own the roof geometry.",
"",
"## Minimal Valid Plan",
"",
"At least one of these must be present with valid content:",
"- `clear`",
"- `cuboids`",
"- `blocks`",
"- `steps` containing valid sub-plans",
"",
"An empty object is not valid.",
"",
"## `clear` Volumes",
"",
"- `clear` is for removing space before building.",
"- A clear volume uses bounds but no block id.",
"- Use the same bounds formats as cuboids: `from/to`, `start/end`, `start + size`, `location + size`, or `location + dimensions`.",
"- Clear volumes execute before cuboids and blocks in the same plan phase.",
"",
"Example:",
"",
"```json",
"{",
" \"summary\": \"Clear a small room before building\",",
" \"clear\": [",
" {\"name\":\"room_clear\",\"from\":{\"x\":0,\"y\":1,\"z\":0},\"to\":{\"x\":4,\"y\":3,\"z\":4}}",
" ],",
" \"cuboids\": [",
" {\"name\":\"floor\",\"block\":\"stone_bricks\",\"from\":{\"x\":0,\"y\":0,\"z\":0},\"to\":{\"x\":4,\"y\":0,\"z\":4}}",
" ]",
"}",
"```",
"",
"## Recommended Small-House Example",
"",
"This is a good default pattern for a simple house because it is compact, valid, and easy for the planner to compile:",
"",
"## Example",
"",
"```json",
"{",
" \"summary\": \"Small oak hut\",",
" \"cuboids\": [",
" {\"name\":\"floor\",\"block\":\"oak_planks\",\"from\":{\"x\":0,\"y\":0,\"z\":0},\"to\":{\"x\":4,\"y\":0,\"z\":4}},",
" {\"name\":\"walls\",\"block\":\"oak_planks\",\"start\":{\"x\":0,\"y\":1,\"z\":0},\"size\":{\"x\":5,\"y\":3,\"z\":5},\"hollow\":true}",
" ],",
" \"blocks\": [",
" {\"name\":\"door\",\"block\":\"oak_door\",\"pos\":{\"x\":2,\"y\":1,\"z\":0},\"properties\":{\"facing\":\"south\"}}",
" ]",
"}",
"```",
"",
"## Example With Wrapper",
"",
"```json",
"{",
" \"build_plan\": {",
" \"summary\": \"Small oak hut\",",
" \"cuboids\": [",
" {\"name\":\"floor\",\"block\":\"oak_planks\",\"from\":{\"x\":0,\"y\":0,\"z\":0},\"to\":{\"x\":4,\"y\":0,\"z\":4}},",
" {\"name\":\"walls\",\"block\":\"oak_planks\",\"start\":{\"x\":0,\"y\":1,\"z\":0},\"size\":{\"x\":5,\"y\":3,\"z\":5},\"hollow\":true}",
" ],",
" \"blocks\": [",