Spaces:
Running
Running
File size: 7,923 Bytes
6ed91fb e183811 270f46d 6ed91fb e183811 6ed91fb 270f46d 6ed91fb 270f46d 6ed91fb 270f46d 6ed91fb e183811 6ed91fb e183811 6ed91fb e183811 6ed91fb 270f46d 6ed91fb 270f46d 6ed91fb 270f46d 6ed91fb | 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 | import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { basename, extname } from "node:path";
import { getMap, objectCoordMode, serializeMap } from "../builder.js";
import { isHosted } from "../context.js";
import { publishMap } from "../downloads.js";
import { mapsRoot, resolveUserPath } from "../paths.js";
import { reachabilityWarnings, walkWorld } from "../reachability.js";
import { worldOf } from "../world.js";
import { saveMapFile, stringifyMap } from "../tmj.js";
import { asText } from "./util.js";
/** Structural check of the Tiled JSON. The game engine that imports the map should re-validate. */
function validateTiledShape(json: unknown): string[] {
const errors: string[] = [];
if (!json || typeof json !== "object") return ["The root of the map JSON must be an object."];
const o = json as Record<string, unknown>;
for (const k of ["width", "height", "tilewidth", "tileheight", "orientation", "layers"]) {
if (!(k in o)) errors.push(`Missing required field: ${k}`);
}
if (typeof o.width !== "number" || (o.width as number) <= 0) errors.push("Invalid width");
if (typeof o.height !== "number" || (o.height as number) <= 0) errors.push("Invalid height");
if (o.orientation !== "isometric" && o.orientation !== "orthogonal") {
errors.push(`Unsupported orientation: ${String(o.orientation)}`);
}
if (!Array.isArray(o.layers)) errors.push("layers must be an array");
return errors;
}
export function registerExportTools(server: McpServer): void {
server.registerTool(
"validate_map",
{
title: "Validate a map",
description:
"Checks the map before export: Tiled structure (errors) and gameplay sanity (warnings): at least one player spawn, no object or spawn on a wall or outside the painted ground, no spawn inside an obstacle prop, no door left inside a wall, and walking reachability: every object and floor area can be reached on foot from where the player starts or arrives (walls, obstacle props, unpainted cells and buildings block; objects and spawns do not; no diagonal moves; a map transition must be stepped on, anything else can be used from a side cell), following map links like validate_world. Returns { ok, errors, warnings }.",
inputSchema: { mapId: z.string() },
annotations: { readOnlyHint: true, openWorldHint: false },
},
async ({ mapId }) => {
const state = getMap(mapId);
const errors = validateTiledShape(serializeMap(mapId));
const warnings: string[] = [];
const hasRole = (role: string) =>
state.spawns.objects.some((o) => o.properties?.some((p) => p.name === "role" && p.value === role));
// A map entered through a transition (an interior) starts the player on an arrival point.
if (!hasRole("player") && !hasRole("arrival")) {
warnings.push("No 'player' spawn: the map is not playable until one is placed (place_spawn_player).");
}
for (const [key, who] of state.occupied) {
if (who.type === "building") continue; // footprint cells, checked by place_building
const [x, y] = key.split(",").map(Number);
const i = y * state.width + x;
const onWall = state.walls.data[i] !== 0;
const onGround = state.ground.data[i] !== 0;
if (who.type === "door" || who.type === "exit") {
if (onWall) warnings.push(`Door "${who.name}" at (${x}, ${y}) is still inside a wall: erase the wall tile (erase_tile layer=walls).`);
continue;
}
const deco = state.decorations.data[i];
const onObstacle = !!deco && state.theme.tiles[deco - state.tileset.firstgid]?.tileType === "OBSTACLE";
if (onWall) warnings.push(`"${who.name}" (${who.type}) at (${x}, ${y}) stands on a wall.`);
else if (!onGround) warnings.push(`"${who.name}" (${who.type}) at (${x}, ${y}) stands outside the painted ground.`);
// A chest or lever on a prop is used from the next cell; a spawn inside one could never move.
else if (onObstacle && who.type.endsWith(" spawn")) warnings.push(`"${who.name}" (${who.type}) at (${x}, ${y}) stands inside an obstacle prop and could never move: erase the prop (erase_tile layer=decorations) or move the spawn.`);
}
// Walking reachability, following links into the rest of the map's world.
const walk = walkWorld(worldOf(mapId)).get(state.id);
if (walk) warnings.push(...reachabilityWarnings(walk));
return asText({ ok: errors.length === 0, errors, warnings, objectCoordinates: objectCoordMode() });
},
);
server.registerTool(
"export_json",
{
title: "Export as Tiled JSON",
description:
"Returns the full Tiled JSON (.tmj content) of a map as text, each tile layer's data on one line. Sprite paths are written as './assets/<theme>/<role>.png' relative to the repository root; use save_to_disk to get a file whose sprite paths resolve from where it is saved. Large maps make long answers: prefer save_to_disk or save_world above 64x64.",
inputSchema: { mapId: z.string() },
annotations: { readOnlyHint: true, openWorldHint: false },
},
async ({ mapId }) => ({ content: [{ type: "text" as const, text: stringifyMap(serializeMap(mapId)) }] }),
);
if (isHosted()) {
// The hosted server never writes to its own disk: the caller gets a download link instead.
server.registerTool(
"save_to_disk",
{
title: "Save (download link)",
description:
"Hosted server: packs the map into a .zip holding the .tmj file and the sprites it uses (including sprites generated in this session), laid out to open directly in Tiled, and returns a download link plus a link to the bare .tmj. Links expire after one hour. Only the file name of path is used; folders are ignored.",
inputSchema: {
mapId: z.string(),
path: z.string().min(1).describe("File name ending in .tmj or .json, e.g. 'crypt-chapel.tmj'"),
},
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
},
async ({ mapId, path }) => {
const name = basename(path.replace(/\\/g, "/"));
const ext = extname(name).toLowerCase();
if (ext !== ".tmj" && ext !== ".json") {
throw new Error(`The file name must end in .tmj or .json (got '${path}').`);
}
getMap(mapId);
return asText({ ok: true, ...publishMap(mapId, name) });
},
);
return;
}
server.registerTool(
"save_to_disk",
{
title: "Save to disk",
description:
"Writes the map to a .tmj file that opens directly in the Tiled editor. A relative path is resolved against the maps folder (the repository's maps/ by default, or TILED_MAPS_DIR); an absolute path is used as is. Missing folders are created and an existing file is overwritten. Sprite paths inside the file are rewritten relative to its location so Tiled finds the PNGs. For maps linked by place_building or link_maps, use save_world so the linked files land side by side under the names their links use.",
inputSchema: {
mapId: z.string(),
path: z
.string()
.min(1)
.describe("File path ending in .tmj or .json, e.g. 'crypt-chapel.tmj' (goes to the maps folder) or an absolute path"),
},
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
},
async ({ mapId, path }) => {
const ext = extname(path).toLowerCase();
if (ext !== ".tmj" && ext !== ".json") {
throw new Error(`The file name must end in .tmj or .json (got '${path}').`);
}
getMap(mapId);
const target = resolveUserPath(path, mapsRoot());
const saved = await saveMapFile(mapId, target);
return asText({ ok: true, ...saved });
},
);
}
|