client-surface.test.ts 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. import { resolve } from "node:path";
  2. import { describe, expect, it } from "vitest";
  3. import { createEngine, type InventorySystem, type PlantingSystem, type TimeSystem } from "@nengine/core";
  4. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  5. import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
  6. import { createNengineMcpServer, createGateway } from "../src/server.js";
  7. const repoRoot = resolve(process.cwd(), "../..");
  8. const contentDir = resolve(repoRoot, "content");
  9. const modsDir = resolve(repoRoot, "mods");
  10. interface Harness {
  11. engine: ReturnType<typeof createEngine>;
  12. client: Client;
  13. close: () => Promise<void>;
  14. }
  15. async function setup(): Promise<Harness> {
  16. const engine = createEngine({ contentDir, modsDir });
  17. await engine.start();
  18. const gateway = createGateway(engine);
  19. const server = createNengineMcpServer(engine, gateway);
  20. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  21. await server.connect(serverTransport);
  22. const client = new Client({ name: "client-surface-test", version: "0.0.1" });
  23. await client.connect(clientTransport);
  24. return {
  25. engine,
  26. client,
  27. close: async () => {
  28. await client.close();
  29. await server.close();
  30. await engine.stop();
  31. },
  32. };
  33. }
  34. function textOf(result: { content: { type: string; text?: string }[] }): string {
  35. return result.content.find((block) => block.type === "text")?.text ?? "";
  36. }
  37. function contentsOf(result: { contents: { text?: string }[] }): string {
  38. return result.contents[0]?.text ?? "";
  39. }
  40. function jsonOf(text: string): Record<string, any> {
  41. return JSON.parse(text) as Record<string, any>;
  42. }
  43. describe("apps/mcp-server client surface (gateway-backed, in-memory)", () => {
  44. it("handshake: initialize + server version", async () => {
  45. const { client, close } = await setup();
  46. try {
  47. expect(client.getServerVersion()).toMatchObject({ name: "nengine-mcp-server", version: "0.1.0" });
  48. } finally {
  49. await close();
  50. }
  51. });
  52. it("tools surface: exactly 116 tools, all with object inputSchema", async () => {
  53. const { client, close } = await setup();
  54. try {
  55. const tools = await client.listTools();
  56. const names = tools.tools.map((tool) => tool.name).sort();
  57. expect(names).toEqual(
  58. [
  59. "animal.create",
  60. "animal.entities",
  61. "animal.feed",
  62. "animal.get",
  63. "animal.list",
  64. "animal.spawn",
  65. "animal.stage",
  66. "animal.update",
  67. "animal.validate",
  68. "animation.create",
  69. "animation.get",
  70. "animation.list",
  71. "animation.update",
  72. "animation.validate",
  73. "behavior.condition.validate",
  74. "behavior.fire",
  75. "behavior.statemachine.create",
  76. "behavior.statemachine.get",
  77. "behavior.statemachine.list",
  78. "behavior.statemachine.status",
  79. "behavior.statemachine.transition",
  80. "behavior.statemachine.update",
  81. "behavior.statemachine.validate",
  82. "behavior.trigger.create",
  83. "behavior.trigger.get",
  84. "behavior.trigger.list",
  85. "behavior.trigger.update",
  86. "behavior.trigger.validate",
  87. "crop.create",
  88. "crop.get",
  89. "crop.harvest",
  90. "crop.list",
  91. "crop.sow",
  92. "crop.stage",
  93. "crop.till",
  94. "crop.update",
  95. "crop.validate",
  96. "crop.water",
  97. "dialogue.choose",
  98. "dialogue.create",
  99. "dialogue.get",
  100. "dialogue.list",
  101. "dialogue.start",
  102. "dialogue.update",
  103. "dialogue.validate",
  104. "item.create",
  105. "item.get",
  106. "item.give",
  107. "item.list",
  108. "item.query_inventory",
  109. "item.update",
  110. "item.validate",
  111. "map.get",
  112. "map.list",
  113. "mod.list",
  114. "mod.reload",
  115. "mod.status",
  116. "npc.get",
  117. "npc.list",
  118. "npc.move",
  119. "npc.path",
  120. "npc.spawn",
  121. "npc.teleport",
  122. "particle.create",
  123. "particle.get",
  124. "particle.list",
  125. "particle.update",
  126. "particle.validate",
  127. "placement.building.create",
  128. "placement.building.get",
  129. "placement.building.list",
  130. "placement.building.update",
  131. "placement.building.validate",
  132. "placement.list",
  133. "placement.occupies",
  134. "placement.place",
  135. "placement.remove",
  136. "player.intent",
  137. "rng.get",
  138. "rng.set",
  139. "save.migrate",
  140. "save.restore",
  141. "save.snapshot",
  142. "save.validate",
  143. "server.disable_subsystem",
  144. "server.enable_subsystem",
  145. "server.info",
  146. "server.status",
  147. "shader.create",
  148. "shader.get",
  149. "shader.list",
  150. "shader.update",
  151. "shader.validate",
  152. "shop.buy",
  153. "shop.create",
  154. "shop.get",
  155. "shop.list",
  156. "shop.sell",
  157. "shop.update",
  158. "shop.validate",
  159. "sound.create",
  160. "sound.get",
  161. "sound.list",
  162. "sound.update",
  163. "sound.validate",
  164. "sprite.create",
  165. "sprite.get",
  166. "sprite.list",
  167. "sprite.update",
  168. "sprite.validate",
  169. "time.advance",
  170. "time.get",
  171. "time.set",
  172. "time.tick",
  173. "weather.get",
  174. "weather.set",
  175. ].sort(),
  176. );
  177. expect(tools.tools).toHaveLength(116);
  178. for (const tool of tools.tools) {
  179. expect(tool.inputSchema).toMatchObject({ type: "object" });
  180. }
  181. } finally {
  182. await close();
  183. }
  184. });
  185. it("server.info: identity, content counts, subsystems enabled, time state", async () => {
  186. const { client, close } = await setup();
  187. try {
  188. const info = jsonOf(textOf(await client.callTool({ name: "server.info", arguments: {} })));
  189. expect(info.engine).toBe("nengine");
  190. expect(info.version).toBe("0.1.0");
  191. expect(info.content).toEqual({
  192. animal: ["chicken"],
  193. behavior: ["season-welcome", "spring-gift"],
  194. building: ["fence", "shed"],
  195. crop: ["parsnip"],
  196. dialogue: ["welcome"],
  197. map: ["farm"],
  198. time: ["default"],
  199. item: ["egg", "hoe", "parsnip-seed", "parsnip"],
  200. shop: ["general-store"],
  201. statemachine: ["chicken-egg", "daily-routine", "spring-quest"],
  202. weather: ["default"],
  203. });
  204. expect(info.subsystems.map((s: { name: string }) => s.name).sort()).toEqual([
  205. "animal",
  206. "animation",
  207. "behavior",
  208. "crop",
  209. "dialogue",
  210. "item",
  211. "map",
  212. "mod",
  213. "npc",
  214. "particle",
  215. "placement",
  216. "player",
  217. "rng",
  218. "save",
  219. "server",
  220. "shader",
  221. "shop",
  222. "sound",
  223. "sprite",
  224. "time",
  225. "weather",
  226. ]);
  227. expect(info.subsystems.every((s: { enabled: boolean }) => s.enabled === true)).toBe(true);
  228. expect(info.time).toEqual({ day: 1, season: "spring", tickInDay: 0 });
  229. } finally {
  230. await close();
  231. }
  232. });
  233. it("server.status: {subsystems:[...]} with all namespaces", async () => {
  234. const { client, close } = await setup();
  235. try {
  236. const status = jsonOf(textOf(await client.callTool({ name: "server.status", arguments: {} })));
  237. expect(status.subsystems.map((s: { name: string }) => s.name).sort()).toEqual([
  238. "animal",
  239. "animation",
  240. "behavior",
  241. "crop",
  242. "dialogue",
  243. "item",
  244. "map",
  245. "mod",
  246. "npc",
  247. "particle",
  248. "placement",
  249. "player",
  250. "rng",
  251. "save",
  252. "server",
  253. "shader",
  254. "shop",
  255. "sound",
  256. "sprite",
  257. "time",
  258. "weather",
  259. ]);
  260. } finally {
  261. await close();
  262. }
  263. });
  264. it("server.enable_subsystem/disable_subsystem drive namespace availability through the real server", async () => {
  265. const { client, close } = await setup();
  266. try {
  267. const before = await client.listTools();
  268. expect(before.tools.some((t) => t.name === "time.get")).toBe(true);
  269. expect(before.tools.some((t) => t.name === "server.enable_subsystem")).toBe(true);
  270. const disabled = jsonOf(
  271. textOf(await client.callTool({ name: "server.disable_subsystem", arguments: { name: "time" } })),
  272. );
  273. expect(disabled).toEqual({ name: "time", enabled: false });
  274. const after = await client.listTools();
  275. expect(after.tools.some((t) => t.name === "time.get")).toBe(false);
  276. expect(after.tools.some((t) => t.name === "server.info")).toBe(true);
  277. const resources = await client.listResources();
  278. expect(resources.resources.some((r) => r.uri === "time://state")).toBe(false);
  279. const info = jsonOf(textOf(await client.callTool({ name: "server.info", arguments: {} })));
  280. expect(info.subsystems.find((s: { name: string }) => s.name === "time")).toEqual({
  281. name: "time",
  282. enabled: false,
  283. });
  284. const rejected = await client.callTool({ name: "time.get", arguments: {} });
  285. expect(rejected.isError).toBe(true);
  286. expect(textOf(rejected)).toMatch(/namespace "time" is disabled/);
  287. const guard = await client.callTool({ name: "server.disable_subsystem", arguments: { name: "server" } });
  288. expect(guard.isError).toBe(true);
  289. expect(textOf(guard)).toMatch(/server\.disable_subsystem: cannot disable the server subsystem/);
  290. const unknown = await client.callTool({ name: "server.enable_subsystem", arguments: { name: "nope" } });
  291. expect(unknown.isError).toBe(true);
  292. expect(textOf(unknown)).toMatch(/server\.enable_subsystem: unknown subsystem: nope/);
  293. const blank = await client.callTool({ name: "server.disable_subsystem", arguments: { name: "" } });
  294. expect(blank.isError).toBe(true);
  295. expect(textOf(blank)).toMatch(/server\.disable_subsystem: name must be a non-empty string/);
  296. const enabled = jsonOf(
  297. textOf(await client.callTool({ name: "server.enable_subsystem", arguments: { name: "time" } })),
  298. );
  299. expect(enabled).toEqual({ name: "time", enabled: true });
  300. const restored = await client.listTools();
  301. expect(restored.tools.some((t) => t.name === "time.get")).toBe(true);
  302. const get = jsonOf(textOf(await client.callTool({ name: "time.get", arguments: {} })));
  303. expect(get).toEqual({ day: 1, season: "spring", tickInDay: 0 });
  304. } finally {
  305. await close();
  306. }
  307. });
  308. it("item: seeded catalog, list/get, inventory give + query", async () => {
  309. const { client, close } = await setup();
  310. try {
  311. const catalog = jsonOf(contentsOf(await client.readResource({ uri: "item://catalog" })));
  312. expect(catalog.items).toHaveLength(4);
  313. const seed = catalog.items.find((i: { id: string }) => i.id === "parsnip-seed");
  314. expect(seed).toMatchObject({ id: "parsnip-seed", name: "Parsnip Seed", kind: "seed", stackable: true });
  315. const list = jsonOf(textOf(await client.callTool({ name: "item.list", arguments: {} })));
  316. expect(list.items).toEqual([
  317. { id: "egg", name: "Egg", kind: "material" },
  318. { id: "hoe", name: "Hoe", kind: "tool" },
  319. { id: "parsnip-seed", name: "Parsnip Seed", kind: "seed" },
  320. { id: "parsnip", name: "Parsnip", kind: "material" },
  321. ]);
  322. const got = jsonOf(textOf(await client.callTool({ name: "item.get", arguments: { itemId: "hoe" } })));
  323. expect(got).toMatchObject({ id: "hoe", kind: "tool" });
  324. const gave = jsonOf(textOf(await client.callTool({ name: "item.give", arguments: { itemId: "hoe", qty: 2 } })));
  325. expect(gave).toEqual({ itemId: "hoe", qty: 2, total: 2 });
  326. const inventory = jsonOf(textOf(await client.callTool({ name: "item.query_inventory", arguments: {} })));
  327. expect(inventory).toEqual({ inventory: { hoe: 2 } });
  328. const missing = await client.callTool({ name: "item.get", arguments: { itemId: "nope" } });
  329. expect(missing.isError).toBe(true);
  330. expect(textOf(missing)).toMatch(/item not found: nope/);
  331. const unknownGive = await client.callTool({ name: "item.give", arguments: { itemId: "nope", qty: 1 } });
  332. expect(unknownGive.isError).toBe(true);
  333. expect(textOf(unknownGive)).toMatch(/unknown item: nope/);
  334. } finally {
  335. await close();
  336. }
  337. });
  338. it("crop: seeded catalog, list/get, plot water/stage debug tools", async () => {
  339. const { engine, client, close } = await setup();
  340. try {
  341. const catalog = jsonOf(contentsOf(await client.readResource({ uri: "crop://catalog" })));
  342. expect(catalog.crops).toHaveLength(1);
  343. const parsnip = catalog.crops.find((c: { id: string }) => c.id === "parsnip");
  344. expect(parsnip).toMatchObject({
  345. id: "parsnip",
  346. seedItem: "parsnip-seed",
  347. stages: [
  348. { name: "sprout", days: 2, waterRequired: true },
  349. { name: "grown", days: 2, waterRequired: true },
  350. { name: "mature", days: 1, waterRequired: false },
  351. ],
  352. seasons: ["spring"],
  353. drops: [{ itemId: "parsnip", qty: 1 }],
  354. });
  355. const list = jsonOf(textOf(await client.callTool({ name: "crop.list", arguments: {} })));
  356. expect(list.crops).toEqual([{ id: "parsnip", seedItem: "parsnip-seed", stageCount: 3 }]);
  357. const got = jsonOf(textOf(await client.callTool({ name: "crop.get", arguments: { cropId: "parsnip" } })));
  358. expect(got).toMatchObject({ id: "parsnip", seedItem: "parsnip-seed" });
  359. const missing = await client.callTool({ name: "crop.get", arguments: { cropId: "nope" } });
  360. expect(missing.isError).toBe(true);
  361. expect(textOf(missing)).toMatch(/crop not found: nope/);
  362. const inv = engine.systems.get<InventorySystem>("inventory");
  363. inv!.give("parsnip-seed", 5);
  364. const planting = engine.systems.get<PlantingSystem>("planting");
  365. planting!.till(6, 6);
  366. planting!.sow(6, 6, "parsnip-seed");
  367. const watered = jsonOf(textOf(await client.callTool({ name: "crop.water", arguments: { x: 6, y: 6 } })));
  368. expect(watered).toEqual({ plotId: "plot:6:6", x: 6, y: 6, watered: true });
  369. const staged = jsonOf(textOf(await client.callTool({ name: "crop.stage", arguments: { x: 6, y: 6, stageIndex: 2 } })));
  370. expect(staged).toEqual({
  371. plotId: "plot:6:6",
  372. x: 6,
  373. y: 6,
  374. cropItemId: "parsnip",
  375. stageIndex: 2,
  376. stage: "mature",
  377. });
  378. const singleCrop = jsonOf(contentsOf(await client.readResource({ uri: "crop://parsnip" })));
  379. expect(singleCrop.id).toBe("parsnip");
  380. } finally {
  381. await close();
  382. }
  383. });
  384. it("crop: till → sow → harvest debug tools drive the full farming loop through MCP", async () => {
  385. const { engine, client, close } = await setup();
  386. try {
  387. const inv = engine.systems.get<InventorySystem>("inventory");
  388. inv!.give("parsnip-seed", 5);
  389. const tilled = jsonOf(textOf(await client.callTool({ name: "crop.till", arguments: { x: 7, y: 7 } })));
  390. expect(tilled).toEqual({ plotId: "plot:7:7", x: 7, y: 7, tilled: true });
  391. const byPlotId = jsonOf(textOf(await client.callTool({ name: "crop.till", arguments: { plotId: "plot:8:8" } })));
  392. expect(byPlotId).toEqual({ plotId: "plot:8:8", x: 8, y: 8, tilled: true });
  393. const sown = jsonOf(
  394. textOf(await client.callTool({ name: "crop.sow", arguments: { x: 7, y: 7, seedItemId: "parsnip-seed" } })),
  395. );
  396. expect(sown).toEqual({ plotId: "plot:7:7", x: 7, y: 7, cropItemId: "parsnip", seedItemId: "parsnip-seed" });
  397. expect(inv!.count("parsnip-seed")).toBe(4);
  398. engine.world.create({ id: "plot:6:6", type: "plot", x: 6, y: 6, tilled: false, watered: false });
  399. const untilled = await client.callTool({ name: "crop.sow", arguments: { x: 6, y: 6, seedItemId: "parsnip-seed" } });
  400. expect(untilled.isError).toBe(true);
  401. expect(textOf(untilled)).toMatch(/not tilled/);
  402. const staged = jsonOf(textOf(await client.callTool({ name: "crop.stage", arguments: { x: 7, y: 7, stageIndex: 2 } })));
  403. expect(staged).toMatchObject({ stageIndex: 2, stage: "mature" });
  404. const harvested = jsonOf(textOf(await client.callTool({ name: "crop.harvest", arguments: { x: 7, y: 7 } })));
  405. expect(harvested).toEqual({
  406. plotId: "plot:7:7",
  407. x: 7,
  408. y: 7,
  409. cropItemId: "parsnip",
  410. drops: [{ itemId: "parsnip", qty: 1 }],
  411. });
  412. expect(inv!.count("parsnip")).toBe(1);
  413. const empty = await client.callTool({ name: "crop.harvest", arguments: { x: 8, y: 8 } });
  414. expect(empty.isError).toBe(true);
  415. expect(textOf(empty)).toMatch(/has no crop/);
  416. const missingSeed = await client.callTool({ name: "crop.sow", arguments: { x: 7, y: 7 } });
  417. expect(missingSeed.isError).toBe(true);
  418. expect(textOf(missingSeed)).toMatch(/missing required arguments: seedItemId/);
  419. } finally {
  420. await close();
  421. }
  422. });
  423. it("shop: seeded def, list/get, buy/sell debug transactions", async () => {
  424. const { engine, client, close } = await setup();
  425. try {
  426. const catalog = jsonOf(contentsOf(await client.readResource({ uri: "shop://catalog" })));
  427. expect(catalog.shops).toHaveLength(1);
  428. const store = catalog.shops.find((s: { id: string }) => s.id === "general-store");
  429. expect(store).toMatchObject({
  430. id: "general-store",
  431. buys: [{ itemId: "parsnip", price: 30 }],
  432. sells: [
  433. { itemId: "hoe", price: 500 },
  434. { itemId: "parsnip-seed", price: 20, stock: 99 },
  435. ],
  436. });
  437. const list = jsonOf(textOf(await client.callTool({ name: "shop.list", arguments: {} })));
  438. expect(list.shops).toEqual([{ id: "general-store", buyCount: 1, sellCount: 2 }]);
  439. const got = jsonOf(textOf(await client.callTool({ name: "shop.get", arguments: { shopId: "general-store" } })));
  440. expect(got).toMatchObject({ id: "general-store" });
  441. const missing = await client.callTool({ name: "shop.get", arguments: { shopId: "nope" } });
  442. expect(missing.isError).toBe(true);
  443. expect(textOf(missing)).toMatch(/shop not found: nope/);
  444. const player = engine.world.get("player");
  445. if (!player) throw new Error("player entity not seeded");
  446. player.gold = 100;
  447. const bought = jsonOf(
  448. textOf(await client.callTool({ name: "shop.buy", arguments: { shopId: "general-store", itemId: "parsnip-seed", qty: 2 } })),
  449. );
  450. expect(bought).toEqual({ shopId: "general-store", itemId: "parsnip-seed", qty: 2, total: 40, gold: 60 });
  451. const inv = engine.systems.get<InventorySystem>("inventory");
  452. expect(inv!.count("parsnip-seed")).toBe(2);
  453. const broke = await client.callTool({ name: "shop.buy", arguments: { shopId: "general-store", itemId: "hoe", qty: 1 } });
  454. expect(broke.isError).toBe(true);
  455. expect(textOf(broke)).toMatch(/insufficient gold/);
  456. inv!.give("parsnip", 3);
  457. const sold = jsonOf(
  458. textOf(await client.callTool({ name: "shop.sell", arguments: { shopId: "general-store", itemId: "parsnip", qty: 2 } })),
  459. );
  460. expect(sold).toEqual({ shopId: "general-store", itemId: "parsnip", qty: 2, total: 60, gold: 120 });
  461. expect(inv!.count("parsnip")).toBe(1);
  462. const short = await client.callTool({ name: "shop.sell", arguments: { shopId: "general-store", itemId: "parsnip", qty: 9 } });
  463. expect(short.isError).toBe(true);
  464. expect(textOf(short)).toMatch(/insufficient parsnip/);
  465. const singleShop = jsonOf(contentsOf(await client.readResource({ uri: "shop://general-store" })));
  466. expect(singleShop.id).toBe("general-store");
  467. } finally {
  468. await close();
  469. }
  470. });
  471. it("behavior: seeded triggers, list/get, condition validate, fire debug, resource and prompt", async () => {
  472. const { engine, client, close } = await setup();
  473. try {
  474. const resource = jsonOf(contentsOf(await client.readResource({ uri: "behavior://triggers" })));
  475. expect(resource.triggers).toHaveLength(2);
  476. const springGift = resource.triggers.find((t: { id: string }) => t.id === "spring-gift");
  477. expect(springGift).toMatchObject({
  478. id: "spring-gift",
  479. when: { op: "gte", path: "time.day", value: 5 },
  480. fire: [{ action: "give-item", itemId: "parsnip-seed", qty: 1 }],
  481. });
  482. const list = jsonOf(textOf(await client.callTool({ name: "behavior.trigger.list", arguments: {} })));
  483. expect(list.triggers).toEqual([
  484. { id: "season-welcome", actionCount: 2 },
  485. { id: "spring-gift", actionCount: 1 },
  486. ]);
  487. const got = jsonOf(textOf(await client.callTool({ name: "behavior.trigger.get", arguments: { triggerId: "spring-gift" } })));
  488. expect(got).toMatchObject({ id: "spring-gift", when: { op: "gte", path: "time.day", value: 5 } });
  489. const missing = await client.callTool({ name: "behavior.trigger.get", arguments: { triggerId: "nope" } });
  490. expect(missing.isError).toBe(true);
  491. expect(textOf(missing)).toMatch(/trigger not found: nope/);
  492. const validCondition = jsonOf(
  493. textOf(await client.callTool({
  494. name: "behavior.condition.validate",
  495. arguments: { condition: { and: [{ op: "gte", path: "time.day", value: 5 }, { op: "exists", path: "payload.itemId" }] } },
  496. })),
  497. );
  498. expect(validCondition).toEqual({ ok: true });
  499. const invalidCondition = jsonOf(
  500. textOf(await client.callTool({ name: "behavior.condition.validate", arguments: { condition: { op: "gte", path: "time.day" } } })),
  501. );
  502. expect(invalidCondition.ok).toBe(false);
  503. expect(Array.isArray(invalidCondition.errors)).toBe(true);
  504. const time = engine.systems.get<TimeSystem>("time");
  505. time!.set(5, "spring");
  506. const fired = jsonOf(textOf(await client.callTool({ name: "behavior.fire", arguments: { triggerId: "spring-gift" } })));
  507. expect(fired).toEqual({ triggerId: "spring-gift", fired: true });
  508. const inv = engine.systems.get<InventorySystem>("inventory");
  509. expect(inv!.count("parsnip-seed")).toBe(1);
  510. const notFired = jsonOf(textOf(await client.callTool({ name: "behavior.fire", arguments: { triggerId: "season-welcome" } })));
  511. expect(notFired).toEqual({ triggerId: "season-welcome", fired: false });
  512. const unknown = await client.callTool({ name: "behavior.fire", arguments: { triggerId: "nope" } });
  513. expect(unknown.isError).toBe(true);
  514. expect(textOf(unknown)).toMatch(/unknown trigger: nope/);
  515. const prompt = await client.getPrompt({ name: "behavior.trigger-prompt", arguments: {} });
  516. const promptText = String(prompt.messages[0]?.content.text);
  517. expect(promptText).toContain("give-item");
  518. expect(promptText).toContain("behavior.trigger.validate");
  519. expect(promptText).toContain("content/behaviors/<id>.yaml");
  520. } finally {
  521. await close();
  522. }
  523. });
  524. it("statemachine: seeded definitions, list/get/status/transition, resource and prompt", async () => {
  525. const { engine, client, close } = await setup();
  526. try {
  527. const resource = jsonOf(contentsOf(await client.readResource({ uri: "behavior://statemachines" })));
  528. expect(resource.statemachines).toHaveLength(3);
  529. const routine = resource.statemachines.find((m: { id: string }) => m.id === "daily-routine");
  530. expect(routine).toMatchObject({
  531. id: "daily-routine",
  532. initial: "sleeping",
  533. states: [{ id: "sleeping" }, { id: "working" }, { id: "resting" }],
  534. });
  535. const list = jsonOf(textOf(await client.callTool({ name: "behavior.statemachine.list", arguments: {} })));
  536. expect(list.statemachines).toEqual([
  537. { id: "chicken-egg", stateCount: 2, transitionCount: 2 },
  538. { id: "daily-routine", stateCount: 3, transitionCount: 1 },
  539. { id: "spring-quest", stateCount: 3, transitionCount: 2 },
  540. ]);
  541. const got = jsonOf(textOf(await client.callTool({ name: "behavior.statemachine.get", arguments: { machineId: "spring-quest" } })));
  542. expect(got).toMatchObject({ id: "spring-quest", initial: "inactive" });
  543. const missing = await client.callTool({ name: "behavior.statemachine.get", arguments: { machineId: "nope" } });
  544. expect(missing.isError).toBe(true);
  545. expect(textOf(missing)).toMatch(/machine not found: nope/);
  546. const before = jsonOf(
  547. textOf(await client.callTool({ name: "behavior.statemachine.status", arguments: { machineId: "spring-quest" } })),
  548. );
  549. expect(before).toEqual({ machineId: "spring-quest", state: "inactive", started: false });
  550. const time = engine.systems.get<TimeSystem>("time");
  551. time!.set(3, "spring");
  552. time!.advance(480);
  553. const after = jsonOf(
  554. textOf(await client.callTool({ name: "behavior.statemachine.status", arguments: { machineId: "spring-quest" } })),
  555. );
  556. expect(after).toEqual({ machineId: "spring-quest", state: "active", started: true });
  557. const forced = jsonOf(
  558. textOf(await client.callTool({ name: "behavior.statemachine.transition", arguments: { machineId: "spring-quest", to: "complete" } })),
  559. );
  560. expect(forced).toEqual({ machineId: "spring-quest", from: "active", to: "complete", transitioned: true });
  561. const player = engine.world.get("player");
  562. expect(player?.questProgress).toMatchObject({ "spring-quest": "complete" });
  563. const prompt = await client.getPrompt({ name: "behavior.statemachine-prompt", arguments: {} });
  564. const promptText = String(prompt.messages[0]?.content.text);
  565. expect(promptText).toContain("onSchedule");
  566. expect(promptText).toContain("behavior.statemachine.validate");
  567. expect(promptText).toContain("content/statemachines/<id>.yaml");
  568. } finally {
  569. await close();
  570. }
  571. });
  572. it("map.list: {maps:[...]} summaries", async () => {
  573. const { client, close } = await setup();
  574. try {
  575. const list = jsonOf(textOf(await client.callTool({ name: "map.list", arguments: {} })));
  576. expect(list.maps).toEqual([{ id: "farm", width: 12, height: 12, tilesetRef: "farm-tiles" }]);
  577. } finally {
  578. await close();
  579. }
  580. });
  581. it("map.get: full definition, layer layout, spawn, player entity", async () => {
  582. const { client, close } = await setup();
  583. try {
  584. const map = jsonOf(textOf(await client.callTool({ name: "map.get", arguments: { mapId: "farm" } })));
  585. expect(map.id).toBe("farm");
  586. expect(map.width).toBe(12);
  587. expect(map.height).toBe(12);
  588. expect(map.tilesetRef).toBe("farm-tiles");
  589. const ground = map.layers[0];
  590. expect(ground.name).toBe("ground");
  591. expect(ground.data).toHaveLength(12);
  592. expect(ground.data[0]).toHaveLength(12);
  593. expect(ground.data[0][0]).toBe("water");
  594. expect(ground.data[4][4]).toBe("tilled");
  595. expect(ground.data[0][10]).toBe("grass");
  596. expect(map.spawn).toEqual({ x: 2, y: 2 });
  597. expect(map.player).toMatchObject({ id: "player", type: "player", x: 2, y: 2 });
  598. } finally {
  599. await close();
  600. }
  601. });
  602. it("map.get: defaults to first map; missing mapId is an error result", async () => {
  603. const { client, close } = await setup();
  604. try {
  605. const first = jsonOf(textOf(await client.callTool({ name: "map.get", arguments: {} })));
  606. expect(first.id).toBe("farm");
  607. const missing = await client.callTool({ name: "map.get", arguments: { mapId: "nope" } });
  608. expect(missing.isError).toBe(true);
  609. expect(textOf(missing)).toMatch(/map not found: nope/);
  610. } finally {
  611. await close();
  612. }
  613. });
  614. it("time: get initial, advance across day, set, advance across season", async () => {
  615. const { client, close } = await setup();
  616. try {
  617. const initial = jsonOf(textOf(await client.callTool({ name: "time.get", arguments: {} })));
  618. expect(initial).toEqual({ day: 1, season: "spring", tickInDay: 0 });
  619. const day2 = jsonOf(textOf(await client.callTool({ name: "time.advance", arguments: { ticks: 480 } })));
  620. expect(day2).toEqual({ day: 2, season: "spring", tickInDay: 0 });
  621. const day28 = jsonOf(textOf(await client.callTool({ name: "time.set", arguments: { day: 28, season: "spring" } })));
  622. expect(day28).toEqual({ day: 28, season: "spring", tickInDay: 0 });
  623. const summer = jsonOf(textOf(await client.callTool({ name: "time.advance", arguments: { ticks: 480 } })));
  624. expect(summer).toEqual({ day: 1, season: "summer", tickInDay: 0 });
  625. } finally {
  626. await close();
  627. }
  628. });
  629. it("time.tick runs a full simulation step (drives growth + emits time-tick; defaults to 1 tick)", async () => {
  630. const { engine, client, close } = await setup();
  631. try {
  632. const stepped = jsonOf(textOf(await client.callTool({ name: "time.tick", arguments: { ticks: 120 } })));
  633. expect(stepped).toEqual({ day: 1, season: "spring", tickInDay: 120 });
  634. const defaulted = jsonOf(textOf(await client.callTool({ name: "time.tick", arguments: {} })));
  635. expect(defaulted).toEqual({ day: 1, season: "spring", tickInDay: 121 });
  636. const inv = engine.systems.get<InventorySystem>("inventory");
  637. inv!.give("parsnip-seed", 5);
  638. const planting = engine.systems.get<PlantingSystem>("planting");
  639. planting!.till(6, 6);
  640. planting!.sow(6, 6, "parsnip-seed");
  641. planting!.water(6, 6);
  642. const day2 = jsonOf(textOf(await client.callTool({ name: "time.tick", arguments: { ticks: 359 } })));
  643. expect(day2).toEqual({ day: 2, season: "spring", tickInDay: 0 });
  644. const plot = engine.world.get("plot:6:6") as { daysInStage?: number };
  645. expect(plot.daysInStage).toBe(1);
  646. const invalid = await client.callTool({ name: "time.tick", arguments: { ticks: 0 } });
  647. expect(invalid.isError).toBe(true);
  648. expect(textOf(invalid)).toMatch(/ticks must be a positive integer/);
  649. } finally {
  650. await close();
  651. }
  652. });
  653. it("error paths: unknown tool, missing args, negative ticks", async () => {
  654. const { client, close } = await setup();
  655. try {
  656. const unknown = await client.callTool({ name: "nope.nothing", arguments: {} });
  657. expect(unknown.isError).toBe(true);
  658. expect(textOf(unknown)).toMatch(/tool not found: nope.nothing/);
  659. const missing = await client.callTool({ name: "time.advance", arguments: {} });
  660. expect(missing.isError).toBe(true);
  661. expect(textOf(missing)).toMatch(/missing required arguments: ticks/);
  662. const negative = await client.callTool({ name: "time.advance", arguments: { ticks: -5 } });
  663. expect(negative.isError).toBe(true);
  664. expect(textOf(negative)).toMatch(/ticks must be a positive integer/);
  665. } finally {
  666. await close();
  667. }
  668. });
  669. it("resources: 34 template URIs, all readable, live state reflected", async () => {
  670. const { client, close } = await setup();
  671. try {
  672. await client.callTool({ name: "time.advance", arguments: { ticks: 480 } });
  673. await client.callTool({ name: "time.set", arguments: { day: 28, season: "spring" } });
  674. await client.callTool({ name: "time.advance", arguments: { ticks: 480 } });
  675. const resources = await client.listResources();
  676. expect(resources.resources.map((r) => r.uri).sort()).toEqual(
  677. ["animal://{id}", "animal://catalog", "animation://{id}", "animation://catalog", "behavior://statemachines", "behavior://triggers", "crop://{id}", "crop://catalog", "dialogue://{id}", "dialogue://catalog", "item://{id}", "item://catalog", "map://{mapId}", "mod://{id}", "npc://{npcId}", "particle://{id}", "particle://catalog", "placement://{id}", "placement://buildings", "placement://placed", "player://state", "rng://state", "save://state", "server://status", "shader://{id}", "shader://catalog", "shop://{shopId}", "shop://catalog", "sound://{id}", "sound://catalog", "sprite://{id}", "sprite://catalog", "time://state", "weather://state"].sort(),
  678. );
  679. const status = jsonOf(contentsOf(await client.readResource({ uri: "server://status" })));
  680. expect(status.engine).toBe("nengine");
  681. const map = jsonOf(contentsOf(await client.readResource({ uri: "map://farm" })));
  682. expect(map.id).toBe("farm");
  683. const time = jsonOf(contentsOf(await client.readResource({ uri: "time://state" })));
  684. expect(time).toEqual({ day: 1, season: "summer", tickInDay: 0 });
  685. } finally {
  686. await close();
  687. }
  688. });
  689. it("resources: missing template param rejects with a server error", async () => {
  690. const { client, close } = await setup();
  691. try {
  692. await expect(client.readResource({ uri: "map://missing" })).rejects.toThrow(/map not found: missing/);
  693. } finally {
  694. await close();
  695. }
  696. });
  697. it("prompts: 15 authoring prompts, get returns guidance; missing prompt rejects", async () => {
  698. const { client, close } = await setup();
  699. try {
  700. const prompts = await client.listPrompts();
  701. expect(prompts.prompts.map((p) => p.name).sort()).toEqual([
  702. "animal.create-prompt",
  703. "animation.create-prompt",
  704. "behavior.statemachine-prompt",
  705. "behavior.trigger-prompt",
  706. "crop.create-prompt",
  707. "dialogue.create-prompt",
  708. "item.create-prompt",
  709. "particle.create-prompt",
  710. "placement.create-prompt",
  711. "save.authoring-prompt",
  712. "server.orient",
  713. "shader.create-prompt",
  714. "shop.create-prompt",
  715. "sound.create-prompt",
  716. "sprite.create-prompt",
  717. ]);
  718. const orient = await client.getPrompt({ name: "server.orient", arguments: {} });
  719. const text = orient.messages[0]?.content;
  720. expect(text).toMatchObject({ type: "text" });
  721. expect(String(text?.text)).toContain("nEngine MCP server");
  722. expect(String(text?.text)).toContain("time.advance");
  723. expect(String(text?.text)).toContain("content/maps/<id>.yaml");
  724. const itemPrompt = await client.getPrompt({ name: "item.create-prompt", arguments: {} });
  725. expect(String(itemPrompt.messages[0]?.content.text)).toContain("item.validate");
  726. expect(String(itemPrompt.messages[0]?.content.text)).toContain("content/items/<id>.yaml");
  727. const cropPrompt = await client.getPrompt({ name: "crop.create-prompt", arguments: {} });
  728. expect(String(cropPrompt.messages[0]?.content.text)).toContain("crop.validate");
  729. expect(String(cropPrompt.messages[0]?.content.text)).toContain("content/crops/<id>.yaml");
  730. expect(String(cropPrompt.messages[0]?.content.text)).toContain("waterRequired");
  731. const shopPrompt = await client.getPrompt({ name: "shop.create-prompt", arguments: {} });
  732. expect(String(shopPrompt.messages[0]?.content.text)).toContain("shop.validate");
  733. expect(String(shopPrompt.messages[0]?.content.text)).toContain("content/shops/<id>.yaml");
  734. expect(String(shopPrompt.messages[0]?.content.text)).toContain("stock");
  735. await expect(client.getPrompt({ name: "nope", arguments: {} })).rejects.toThrow();
  736. } finally {
  737. await close();
  738. }
  739. });
  740. it("save: snapshot/validate/restore/migrate, save://state resource, and authoring prompt", async () => {
  741. const { engine, client, close } = await setup();
  742. try {
  743. const snapshot = jsonOf(textOf(await client.callTool({ name: "save.snapshot", arguments: {} })));
  744. expect(snapshot.format).toBe("nengine-save");
  745. expect(snapshot.version).toBe(1);
  746. expect(typeof snapshot.savedAt).toBe("string");
  747. const entities = snapshot.world as { id: string; type: string; x: number; y: number; width: number; height: number }[];
  748. expect(entities.find((e) => e.id === "farm")).toMatchObject({ type: "map", width: 12, height: 12 });
  749. expect(entities.find((e) => e.id === "player")).toMatchObject({ type: "player", x: 2, y: 2 });
  750. const valid = jsonOf(textOf(await client.callTool({ name: "save.validate", arguments: { snapshot } })));
  751. expect(valid).toEqual({ ok: true });
  752. const invalid = jsonOf(
  753. textOf(await client.callTool({ name: "save.validate", arguments: { snapshot: { format: "nengine-save" } } })),
  754. );
  755. expect(invalid.ok).toBe(false);
  756. expect(Array.isArray(invalid.errors)).toBe(true);
  757. const inv = engine.systems.get<InventorySystem>("inventory");
  758. inv!.give("parsnip-seed", 4);
  759. const planting = engine.systems.get<PlantingSystem>("planting");
  760. planting!.till(9, 9);
  761. const mutated = jsonOf(textOf(await client.callTool({ name: "save.snapshot", arguments: {} })));
  762. expect((mutated.world as { id: string }[]).some((e) => e.id === "plot:9:9")).toBe(true);
  763. const restored = jsonOf(
  764. textOf(await client.callTool({ name: "save.restore", arguments: { snapshot: mutated } })),
  765. );
  766. expect(restored).toEqual({ restored: 4 });
  767. const after = jsonOf(textOf(await client.callTool({ name: "save.snapshot", arguments: {} })));
  768. const afterEntities = after.world as { id: string; inventory?: Record<string, number> }[];
  769. expect(afterEntities.some((e) => e.id === "plot:9:9")).toBe(true);
  770. expect(afterEntities.find((e) => e.id === "player")?.inventory).toEqual({ "parsnip-seed": 4 });
  771. const badRestore = await client.callTool({ name: "save.restore", arguments: { snapshot: { format: "nengine-save" } } });
  772. expect(badRestore.isError).toBe(true);
  773. expect(textOf(badRestore)).toMatch(/invalid snapshot/);
  774. const migrated = jsonOf(
  775. textOf(await client.callTool({ name: "save.migrate", arguments: { snapshot, fromVersion: 1, toVersion: 2 } })),
  776. );
  777. expect(migrated.world).toEqual(snapshot.world);
  778. const state = jsonOf(contentsOf(await client.readResource({ uri: "save://state" })));
  779. expect(state.format).toBe("nengine-save");
  780. expect(state.version).toBe(1);
  781. const prompt = await client.getPrompt({ name: "save.authoring-prompt", arguments: {} });
  782. const promptText = String(prompt.messages[0]?.content.text);
  783. expect(promptText).toContain("nengine-save");
  784. expect(promptText).toContain("migration");
  785. expect(promptText).toContain("save.snapshot");
  786. } finally {
  787. await close();
  788. }
  789. });
  790. it("mod: list/status/reload over the real mods dir (example-mod), mod://{id} resource, no prompts", async () => {
  791. const { engine, client, close } = await setup();
  792. try {
  793. const list = jsonOf(textOf(await client.callTool({ name: "mod.list", arguments: {} })));
  794. expect(list.mods).toEqual([{ id: "example-mod", version: "0.1.0", loaded: true, hooks: ["onDayStart"] }]);
  795. const status = jsonOf(textOf(await client.callTool({ name: "mod.status", arguments: { id: "example-mod" } })));
  796. expect(status).toEqual({ id: "example-mod", version: "0.1.0", loaded: true, hooks: ["onDayStart"] });
  797. const missing = await client.callTool({ name: "mod.status", arguments: { id: "nope" } });
  798. expect(missing.isError).toBe(true);
  799. expect(textOf(missing)).toMatch(/mod not found: nope/);
  800. const singleMod = jsonOf(contentsOf(await client.readResource({ uri: "mod://example-mod" })));
  801. expect(singleMod).toMatchObject({ id: "example-mod", version: "0.1.0", loaded: true });
  802. const reloaded = jsonOf(textOf(await client.callTool({ name: "mod.reload", arguments: { id: "example-mod" } })));
  803. expect(reloaded.reloaded).toBe(true);
  804. expect(reloaded.mods).toEqual([{ id: "example-mod", version: "0.1.0", loaded: true, hooks: ["onDayStart"] }]);
  805. expect(engine.mods).toEqual([{ id: "example-mod", version: "0.1.0", loaded: true, hooks: ["onDayStart"] }]);
  806. const reloadAll = jsonOf(textOf(await client.callTool({ name: "mod.reload", arguments: {} })));
  807. expect(reloadAll.mods).toHaveLength(1);
  808. expect(reloadAll.mods[0].id).toBe("example-mod");
  809. const prompts = await client.listPrompts();
  810. expect(prompts.prompts.some((p) => p.name.startsWith("mod."))).toBe(false);
  811. } finally {
  812. await close();
  813. }
  814. });
  815. it("placement: seeded building defs, place/list/occupies/remove, resources and prompt", async () => {
  816. const { client, close } = await setup();
  817. try {
  818. const catalog = jsonOf(contentsOf(await client.readResource({ uri: "placement://buildings" })));
  819. expect(catalog.buildings.map((b: { id: string }) => b.id)).toEqual(["fence", "shed"]);
  820. const list = jsonOf(textOf(await client.callTool({ name: "placement.building.list", arguments: {} })));
  821. expect(list.buildings).toEqual([
  822. { id: "fence", name: "Fence", w: 1, h: 1, blocksMovement: true },
  823. { id: "shed", name: "Shed", w: 2, h: 2, blocksMovement: true },
  824. ]);
  825. const placed = jsonOf(
  826. textOf(await client.callTool({ name: "placement.place", arguments: { buildingId: "shed", x: 3, y: 3 } })),
  827. );
  828. expect(placed).toEqual({
  829. id: "building:shed:3:3",
  830. type: "building",
  831. buildingId: "shed",
  832. x: 3,
  833. y: 3,
  834. w: 2,
  835. h: 2,
  836. blocksMovement: true,
  837. });
  838. await client.callTool({ name: "placement.place", arguments: { buildingId: "fence", x: 0, y: 10 } });
  839. const all = jsonOf(textOf(await client.callTool({ name: "placement.list", arguments: {} })));
  840. expect(all.buildings).toHaveLength(2);
  841. const inside = jsonOf(textOf(await client.callTool({ name: "placement.occupies", arguments: { x: 4, y: 3 } })));
  842. expect(inside.id).toBe("building:shed:3:3");
  843. const outside = jsonOf(textOf(await client.callTool({ name: "placement.occupies", arguments: { x: 11, y: 11 } })));
  844. expect(outside).toBeNull();
  845. const onWater = await client.callTool({ name: "placement.place", arguments: { buildingId: "fence", x: 0, y: 0 } });
  846. expect(onWater.isError).toBe(true);
  847. expect(textOf(onWater)).toMatch(/tile \(0,0\) is not buildable for fence/);
  848. const overlap = await client.callTool({ name: "placement.place", arguments: { buildingId: "fence", x: 3, y: 3 } });
  849. expect(overlap.isError).toBe(true);
  850. expect(textOf(overlap)).toMatch(/overlaps existing building/);
  851. const removed = jsonOf(textOf(await client.callTool({ name: "placement.remove", arguments: { x: 3, y: 3 } })));
  852. expect(removed.id).toBe("building:shed:3:3");
  853. const missing = await client.callTool({ name: "placement.remove", arguments: { x: 3, y: 3 } });
  854. expect(missing.isError).toBe(true);
  855. expect(textOf(missing)).toMatch(/no building at \(3,3\)/);
  856. const placedResource = jsonOf(contentsOf(await client.readResource({ uri: "placement://placed" })));
  857. expect(placedResource.buildings).toHaveLength(1);
  858. const shedDef = jsonOf(contentsOf(await client.readResource({ uri: "placement://shed" })));
  859. expect(shedDef).toMatchObject({ id: "shed", footprint: { w: 2, h: 2 } });
  860. const prompt = await client.getPrompt({ name: "placement.create-prompt", arguments: {} });
  861. const promptText = String(prompt.messages[0]?.content.text);
  862. expect(promptText).toContain("buildable");
  863. expect(promptText).toContain("content/buildings/<id>.yaml");
  864. } finally {
  865. await close();
  866. }
  867. });
  868. it("npc: spawn/list/get/move/teleport, npc-move event, blocking by building, resource, no prompts", async () => {
  869. const { engine, client, close } = await setup();
  870. try {
  871. const spawned = jsonOf(textOf(await client.callTool({ name: "npc.spawn", arguments: { id: "leah", x: 2, y: 2 } })));
  872. expect(spawned).toEqual({ id: "leah", type: "npc", x: 2, y: 2 });
  873. const listed = jsonOf(textOf(await client.callTool({ name: "npc.list", arguments: {} })));
  874. expect(listed.npcs).toEqual([{ id: "leah", x: 2, y: 2 }]);
  875. const got = jsonOf(textOf(await client.callTool({ name: "npc.get", arguments: { npcId: "leah" } })));
  876. expect(got).toMatchObject({ id: "leah", type: "npc", x: 2, y: 2 });
  877. const moved = jsonOf(textOf(await client.callTool({ name: "npc.move", arguments: { npcId: "leah", x: 4, y: 4 } })));
  878. expect(moved).toEqual({ npcId: "leah", from: { x: 2, y: 2 }, to: { x: 4, y: 4 } });
  879. const unknown = await client.callTool({ name: "npc.move", arguments: { npcId: "ghost", x: 0, y: 0 } });
  880. expect(unknown.isError).toBe(true);
  881. expect(textOf(unknown)).toMatch(/unknown npc: ghost/);
  882. const onWater = await client.callTool({ name: "npc.move", arguments: { npcId: "leah", x: 0, y: 0 } });
  883. expect(onWater.isError).toBe(true);
  884. expect(textOf(onWater)).toMatch(/tile \(0,0\) is not walkable/);
  885. const bounds = await client.callTool({ name: "npc.move", arguments: { npcId: "leah", x: 12, y: 0 } });
  886. expect(bounds.isError).toBe(true);
  887. expect(textOf(bounds)).toMatch(/target out of bounds: \(12,0\)/);
  888. await client.callTool({ name: "placement.place", arguments: { buildingId: "shed", x: 8, y: 8 } });
  889. const blocked = await client.callTool({ name: "npc.move", arguments: { npcId: "leah", x: 8, y: 8 } });
  890. expect(blocked.isError).toBe(true);
  891. expect(textOf(blocked)).toMatch(/blocked by building building:shed:8:8 at \(8,8\)/);
  892. const teleported = jsonOf(
  893. textOf(await client.callTool({ name: "npc.teleport", arguments: { npcId: "leah", x: 0, y: 0 } })),
  894. );
  895. expect(teleported).toEqual({ npcId: "leah", from: { x: 4, y: 4 }, to: { x: 0, y: 0 } });
  896. const leah = jsonOf(contentsOf(await client.readResource({ uri: "npc://leah" })));
  897. expect(leah).toMatchObject({ id: "leah", type: "npc", x: 0, y: 0 });
  898. await expect(client.readResource({ uri: "npc://ghost" })).rejects.toThrow(/npc not found: ghost/);
  899. const prompts = await client.listPrompts();
  900. expect(prompts.prompts.some((p) => p.name.startsWith("npc."))).toBe(false);
  901. expect(engine.world.get("leah")).toMatchObject({ x: 0, y: 0 });
  902. } finally {
  903. await close();
  904. }
  905. });
  906. it("npc.path: A* path result, null reasons (blocked/out of bounds), and validation errors", async () => {
  907. const { client, close } = await setup();
  908. try {
  909. await client.callTool({ name: "npc.spawn", arguments: { id: "leah", x: 4, y: 4 } });
  910. const found = jsonOf(
  911. textOf(await client.callTool({ name: "npc.path", arguments: { npcId: "leah", to: { x: 6, y: 6 } } })),
  912. );
  913. expect(found).toEqual({
  914. npcId: "leah",
  915. from: { x: 4, y: 4 },
  916. to: { x: 6, y: 6 },
  917. path: [
  918. { x: 4, y: 4 },
  919. { x: 5, y: 4 },
  920. { x: 6, y: 4 },
  921. { x: 6, y: 5 },
  922. { x: 6, y: 6 },
  923. ],
  924. });
  925. const onWater = jsonOf(
  926. textOf(await client.callTool({ name: "npc.path", arguments: { npcId: "leah", to: { x: 0, y: 0 } } })),
  927. );
  928. expect(onWater).toEqual({ npcId: "leah", path: null, reason: "blocked" });
  929. const bounds = jsonOf(
  930. textOf(await client.callTool({ name: "npc.path", arguments: { npcId: "leah", to: { x: 12, y: 0 } } })),
  931. );
  932. expect(bounds).toEqual({ npcId: "leah", path: null, reason: "out of bounds" });
  933. const unknown = await client.callTool({ name: "npc.path", arguments: { npcId: "ghost", to: { x: 5, y: 5 } } });
  934. expect(unknown.isError).toBe(true);
  935. expect(textOf(unknown)).toMatch(/movement: unknown npc: ghost/);
  936. const blank = await client.callTool({ name: "npc.path", arguments: { npcId: "", to: { x: 5, y: 5 } } });
  937. expect(blank.isError).toBe(true);
  938. expect(textOf(blank)).toMatch(/npc\.path: npcId must be a non-empty string/);
  939. const badTo = await client.callTool({ name: "npc.path", arguments: { npcId: "leah", to: { x: 1.5, y: 0 } } });
  940. expect(badTo.isError).toBe(true);
  941. expect(textOf(badTo)).toMatch(/npc\.path: to must have integer x and y/);
  942. } finally {
  943. await close();
  944. }
  945. });
  946. it("animal: seeded def, list/get, spawn/feed/stage debug tools, resources and prompt", async () => {
  947. const { engine, client, close } = await setup();
  948. try {
  949. const catalog = jsonOf(contentsOf(await client.readResource({ uri: "animal://catalog" })));
  950. expect(catalog.animals).toHaveLength(1);
  951. const chicken = catalog.animals.find((a: { id: string }) => a.id === "chicken");
  952. expect(chicken).toMatchObject({
  953. id: "chicken",
  954. stages: [
  955. { name: "chick", days: 2, feedRequired: false },
  956. { name: "grown", days: 2, feedRequired: true },
  957. { name: "laying", days: 1, feedRequired: true },
  958. ],
  959. produces: [{ itemId: "egg", qty: 1 }],
  960. });
  961. const list = jsonOf(textOf(await client.callTool({ name: "animal.list", arguments: {} })));
  962. expect(list.animals).toEqual([{ id: "chicken", stageCount: 3 }]);
  963. const got = jsonOf(textOf(await client.callTool({ name: "animal.get", arguments: { animalId: "chicken" } })));
  964. expect(got).toMatchObject({ id: "chicken", produces: [{ itemId: "egg", qty: 1 }] });
  965. const missing = await client.callTool({ name: "animal.get", arguments: { animalId: "cow" } });
  966. expect(missing.isError).toBe(true);
  967. expect(textOf(missing)).toMatch(/animal not found: cow/);
  968. const spawned = jsonOf(textOf(await client.callTool({ name: "animal.spawn", arguments: { animalId: "chicken", x: 3, y: 3 } })));
  969. expect(spawned).toMatchObject({
  970. id: "animal:chicken:1",
  971. type: "animal",
  972. animalId: "chicken",
  973. x: 3,
  974. y: 3,
  975. stageIndex: 0,
  976. fed: false,
  977. });
  978. const fed = jsonOf(textOf(await client.callTool({ name: "animal.feed", arguments: { id: "animal:chicken:1" } })));
  979. expect(fed).toEqual({ id: "animal:chicken:1", animalId: "chicken", fed: true });
  980. const staged = jsonOf(
  981. textOf(await client.callTool({ name: "animal.stage", arguments: { id: "animal:chicken:1", stageIndex: 2 } })),
  982. );
  983. expect(staged).toEqual({
  984. id: "animal:chicken:1",
  985. animalId: "chicken",
  986. animalDefId: "chicken",
  987. stageIndex: 2,
  988. stage: "laying",
  989. });
  990. const entities = jsonOf(textOf(await client.callTool({ name: "animal.entities", arguments: {} })));
  991. expect(entities.animals).toHaveLength(1);
  992. expect(entities.animals[0].id).toBe("animal:chicken:1");
  993. const unknownSpawn = await client.callTool({ name: "animal.spawn", arguments: { animalId: "cow", x: 0, y: 0 } });
  994. expect(unknownSpawn.isError).toBe(true);
  995. expect(textOf(unknownSpawn)).toMatch(/unknown animal def: cow/);
  996. const singleAnimal = jsonOf(contentsOf(await client.readResource({ uri: "animal://chicken" })));
  997. expect(singleAnimal.id).toBe("chicken");
  998. await expect(client.readResource({ uri: "animal://ghost" })).rejects.toThrow(/animal not found: ghost/);
  999. const prompt = await client.getPrompt({ name: "animal.create-prompt", arguments: {} });
  1000. const promptText = String(prompt.messages[0]?.content.text);
  1001. expect(promptText).toContain("feedRequired");
  1002. expect(promptText).toContain("content/animals/<id>.yaml");
  1003. } finally {
  1004. await close();
  1005. }
  1006. });
  1007. it("player: intent drives the player entity, player://state reads it", async () => {
  1008. const { engine, client, close } = await setup();
  1009. try {
  1010. const state = jsonOf(contentsOf(await client.readResource({ uri: "player://state" })));
  1011. expect(state).toMatchObject({ id: "player", type: "player", x: 2, y: 2 });
  1012. const moved = jsonOf(
  1013. textOf(await client.callTool({ name: "player.intent", arguments: { action: "move", tile: { x: 3, y: 2 } } })),
  1014. );
  1015. expect(moved).toMatchObject({ action: "move", tile: { x: 3, y: 2 }, ok: true, detail: "moved to (3,2)" });
  1016. expect(engine.world.get("player")).toMatchObject({ x: 3, y: 2 });
  1017. const tilled = jsonOf(
  1018. textOf(await client.callTool({ name: "player.intent", arguments: { action: "interact", tile: { x: 5, y: 5 } } })),
  1019. );
  1020. expect(tilled).toMatchObject({ action: "interact", ok: true, detail: "tilled plot" });
  1021. expect(engine.world.get("plot:5:5")).toMatchObject({ type: "plot", x: 5, y: 5, tilled: true });
  1022. const onWater = await client.callTool({ name: "player.intent", arguments: { action: "move", tile: { x: 0, y: 0 } } });
  1023. expect(onWater.isError).toBe(true);
  1024. expect(textOf(onWater)).toMatch(/player\.intent: intent\.move: tile \(0,0\) is not walkable/);
  1025. const badAction = await client.callTool({
  1026. name: "player.intent",
  1027. arguments: { action: "dance", tile: { x: 1, y: 1 } },
  1028. });
  1029. expect(badAction.isError).toBe(true);
  1030. expect(textOf(badAction)).toMatch(
  1031. /player\.intent: action must be one of "move", "interact", "buy", "sell", "talk", "choose", "select-seed"/,
  1032. );
  1033. const badTile = await client.callTool({
  1034. name: "player.intent",
  1035. arguments: { action: "move", tile: { x: -1, y: 0 } },
  1036. });
  1037. expect(badTile.isError).toBe(true);
  1038. expect(textOf(badTile)).toMatch(/player\.intent: tile x and y must be non-negative integers/);
  1039. const movedState = jsonOf(contentsOf(await client.readResource({ uri: "player://state" })));
  1040. expect(movedState).toMatchObject({ x: 3, y: 2 });
  1041. } finally {
  1042. await close();
  1043. }
  1044. });
  1045. it("player.intent buy/sell/talk/choose/select-seed drive the extended actions through the real server", async () => {
  1046. const { engine, client, close } = await setup();
  1047. try {
  1048. const player = engine.world.get("player");
  1049. if (!player) throw new Error("player entity not seeded");
  1050. player.gold = 100;
  1051. const inv = engine.systems.get<InventorySystem>("inventory");
  1052. if (!inv) throw new Error("inventory system not booted");
  1053. const noActive = await client.callTool({ name: "player.intent", arguments: { action: "choose", index: 0 } });
  1054. expect(noActive.isError).toBe(true);
  1055. expect(textOf(noActive)).toMatch(/no active dialogue/);
  1056. const bought = jsonOf(
  1057. textOf(
  1058. await client.callTool({
  1059. name: "player.intent",
  1060. arguments: { action: "buy", shopId: "general-store", itemId: "parsnip-seed", qty: 2 },
  1061. }),
  1062. ),
  1063. );
  1064. expect(bought.detail).toEqual({ shopId: "general-store", itemId: "parsnip-seed", qty: 2, total: 40, gold: 60 });
  1065. expect(inv.count("parsnip-seed")).toBe(2);
  1066. const missingItem = await client.callTool({ name: "player.intent", arguments: { action: "buy", shopId: "general-store" } });
  1067. expect(missingItem.isError).toBe(true);
  1068. expect(textOf(missingItem)).toMatch(/buy requires itemId/);
  1069. const missingShop = await client.callTool({ name: "player.intent", arguments: { action: "buy", itemId: "parsnip-seed" } });
  1070. expect(missingShop.isError).toBe(true);
  1071. expect(textOf(missingShop)).toMatch(/buy requires shopId/);
  1072. const badQty = await client.callTool({
  1073. name: "player.intent",
  1074. arguments: { action: "buy", shopId: "general-store", itemId: "parsnip-seed", qty: 0 },
  1075. });
  1076. expect(badQty.isError).toBe(true);
  1077. expect(textOf(badQty)).toMatch(/qty must be a positive integer/);
  1078. inv.give("parsnip", 3);
  1079. const sold = jsonOf(
  1080. textOf(
  1081. await client.callTool({
  1082. name: "player.intent",
  1083. arguments: { action: "sell", shopId: "general-store", itemId: "parsnip", qty: 1 },
  1084. }),
  1085. ),
  1086. );
  1087. expect(sold.detail).toEqual({ shopId: "general-store", itemId: "parsnip", qty: 1, total: 30, gold: 90 });
  1088. expect(inv.count("parsnip")).toBe(2);
  1089. const broke = await client.callTool({
  1090. name: "player.intent",
  1091. arguments: { action: "buy", shopId: "general-store", itemId: "hoe", qty: 1 },
  1092. });
  1093. expect(broke.isError).toBe(true);
  1094. expect(textOf(broke)).toMatch(/insufficient gold/);
  1095. engine.world.create({ id: "npc:clerk", type: "npc", x: 3, y: 3, dialogue: "welcome" });
  1096. const talked = jsonOf(
  1097. textOf(await client.callTool({ name: "player.intent", arguments: { action: "talk", npcId: "npc:clerk" } })),
  1098. );
  1099. expect(talked.detail).toMatchObject({ dialogueId: "welcome", nodeId: "hello" });
  1100. const chosen = jsonOf(
  1101. textOf(await client.callTool({ name: "player.intent", arguments: { action: "choose", index: 0 } })),
  1102. );
  1103. expect(chosen.detail).toMatchObject({ dialogueId: "welcome", nodeId: "seed-tip" });
  1104. const outOfRange = await client.callTool({ name: "player.intent", arguments: { action: "choose", index: 9 } });
  1105. expect(outOfRange.isError).toBe(true);
  1106. expect(textOf(outOfRange)).toMatch(/choice index out of range/);
  1107. const selected = jsonOf(
  1108. textOf(
  1109. await client.callTool({ name: "player.intent", arguments: { action: "select-seed", seedItemId: "parsnip-seed" } }),
  1110. ),
  1111. );
  1112. expect(selected.detail).toEqual({ selectedSeed: "parsnip-seed" });
  1113. expect(engine.world.get("player")).toMatchObject({ selectedSeed: "parsnip-seed" });
  1114. const notASeed = await client.callTool({ name: "player.intent", arguments: { action: "select-seed", seedItemId: "hoe" } });
  1115. expect(notASeed.isError).toBe(true);
  1116. expect(textOf(notASeed)).toMatch(/hoe is not a seed item/);
  1117. } finally {
  1118. await close();
  1119. }
  1120. });
  1121. it("rng: get/set the engine RNG, determinism through MCP, rng://state resource, no prompts", async () => {
  1122. const { engine, client, close } = await setup();
  1123. try {
  1124. const initial = jsonOf(textOf(await client.callTool({ name: "rng.get", arguments: {} })));
  1125. expect(initial.seed).toEqual(engine.rng.state().seed);
  1126. expect(initial.calls).toBe(0);
  1127. engine.rng.next();
  1128. const afterDraw = jsonOf(textOf(await client.callTool({ name: "rng.get", arguments: {} })));
  1129. expect(afterDraw.calls).toBe(1);
  1130. const set = jsonOf(textOf(await client.callTool({ name: "rng.set", arguments: { seed: 2026 } })));
  1131. expect(set).toEqual({ seed: 2026, calls: 0 });
  1132. const first = engine.rng.next();
  1133. const second = engine.rng.next();
  1134. expect(first).toBeGreaterThanOrEqual(0);
  1135. expect(second).toBeGreaterThanOrEqual(0);
  1136. const state = jsonOf(contentsOf(await client.readResource({ uri: "rng://state" })));
  1137. expect(state).toEqual({ seed: 2026, calls: 2 });
  1138. const badSeed = await client.callTool({ name: "rng.set", arguments: { seed: Infinity } });
  1139. expect(badSeed.isError).toBe(true);
  1140. expect(textOf(badSeed)).toMatch(/seed must be a finite number/);
  1141. const prompts = await client.listPrompts();
  1142. expect(prompts.prompts.some((p) => p.name.startsWith("rng."))).toBe(false);
  1143. } finally {
  1144. await close();
  1145. }
  1146. });
  1147. it("animation.*: lifecycle validate + empty catalog over the root content dir (no writes)", async () => {
  1148. const { client, close } = await setup();
  1149. try {
  1150. const animationList = jsonOf(textOf(await client.callTool({ name: "animation.list", arguments: {} })));
  1151. expect(animationList).toEqual({ animations: [] });
  1152. const missingAnimation = await client.callTool({ name: "animation.get", arguments: { animationId: "player" } });
  1153. expect(missingAnimation.isError).toBe(true);
  1154. expect(textOf(missingAnimation)).toMatch(/animation not found: player/);
  1155. const validAnimation = jsonOf(
  1156. textOf(await client.callTool({
  1157. name: "animation.validate",
  1158. arguments: {
  1159. def: {
  1160. id: "player",
  1161. initial: "idle",
  1162. states: [
  1163. { id: "idle", spriteRef: "player", loop: true },
  1164. { id: "walk", spriteRef: "player-walk", fps: 8 },
  1165. ],
  1166. },
  1167. },
  1168. })),
  1169. );
  1170. expect(validAnimation).toEqual({
  1171. id: "player",
  1172. initial: "idle",
  1173. states: [
  1174. { id: "idle", spriteRef: "player", loop: true },
  1175. { id: "walk", spriteRef: "player-walk", fps: 8 },
  1176. ],
  1177. });
  1178. const badAnimation = await client.callTool({
  1179. name: "animation.validate",
  1180. arguments: { def: { id: "bad", initial: "nope", states: [{ id: "idle", spriteRef: "player" }] } },
  1181. });
  1182. expect(badAnimation.isError).toBe(true);
  1183. expect(textOf(badAnimation)).toMatch(/initial state must be a declared state/);
  1184. const animationCatalog = jsonOf(contentsOf(await client.readResource({ uri: "animation://catalog" })));
  1185. expect(animationCatalog).toEqual({ animations: [] });
  1186. await expect(client.readResource({ uri: "animation://missing" })).rejects.toThrow(/animation not found: missing/);
  1187. const animationPrompt = await client.getPrompt({ name: "animation.create-prompt", arguments: {} });
  1188. expect(String(animationPrompt.messages[0]?.content.text)).toContain("content/animations/<id>.yaml");
  1189. } finally {
  1190. await close();
  1191. }
  1192. });
  1193. it("particle.* and shader.*: lifecycle validate + empty catalogs over the root content dir (no writes)", async () => {
  1194. const { client, close } = await setup();
  1195. try {
  1196. const particleList = jsonOf(textOf(await client.callTool({ name: "particle.list", arguments: {} })));
  1197. expect(particleList).toEqual({ particles: [] });
  1198. const missingParticle = await client.callTool({ name: "particle.get", arguments: { particleId: "dust" } });
  1199. expect(missingParticle.isError).toBe(true);
  1200. expect(textOf(missingParticle)).toMatch(/particle not found: dust/);
  1201. const validParticle = jsonOf(
  1202. textOf(await client.callTool({ name: "particle.validate", arguments: { def: { id: "dust", colors: ["#d7ccc8"] } } })),
  1203. );
  1204. expect(validParticle).toEqual({ id: "dust", colors: ["#d7ccc8"] });
  1205. const badParticle = await client.callTool({
  1206. name: "particle.validate",
  1207. arguments: { def: { id: "bad", colors: ["green"] } },
  1208. });
  1209. expect(badParticle.isError).toBe(true);
  1210. expect(textOf(badParticle)).toMatch(/colors/);
  1211. const shaderList = jsonOf(textOf(await client.callTool({ name: "shader.list", arguments: {} })));
  1212. expect(shaderList).toEqual({ shaders: [] });
  1213. const missingShader = await client.callTool({ name: "shader.get", arguments: { shaderId: "rain-tint" } });
  1214. expect(missingShader.isError).toBe(true);
  1215. expect(textOf(missingShader)).toMatch(/shader not found: rain-tint/);
  1216. const validShader = jsonOf(
  1217. textOf(await client.callTool({ name: "shader.validate", arguments: { def: { id: "rain-tint", filter: "grayscale", params: { factor: 0.7 } } } })),
  1218. );
  1219. expect(validShader).toEqual({ id: "rain-tint", filter: "grayscale", params: { factor: 0.7 } });
  1220. const badShader = await client.callTool({ name: "shader.validate", arguments: { def: { id: "bad", filter: "vignette" } } });
  1221. expect(badShader.isError).toBe(true);
  1222. expect(textOf(badShader)).toMatch(/filter/);
  1223. const particleCatalog = jsonOf(contentsOf(await client.readResource({ uri: "particle://catalog" })));
  1224. expect(particleCatalog).toEqual({ particles: [] });
  1225. const shaderCatalog = jsonOf(contentsOf(await client.readResource({ uri: "shader://catalog" })));
  1226. expect(shaderCatalog).toEqual({ shaders: [] });
  1227. await expect(client.readResource({ uri: "particle://missing" })).rejects.toThrow(/particle not found: missing/);
  1228. await expect(client.readResource({ uri: "shader://missing" })).rejects.toThrow(/shader not found: missing/);
  1229. const particlePrompt = await client.getPrompt({ name: "particle.create-prompt", arguments: {} });
  1230. expect(String(particlePrompt.messages[0]?.content.text)).toContain("content/particles/<id>.yaml");
  1231. const shaderPrompt = await client.getPrompt({ name: "shader.create-prompt", arguments: {} });
  1232. expect(String(shaderPrompt.messages[0]?.content.text)).toContain("content/shaders/<id>.yaml");
  1233. } finally {
  1234. await close();
  1235. }
  1236. });
  1237. });