item-namespace.test.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join, resolve } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createEngine, type ItemDef } from "@nengine/core";
  6. import { createEngineNamespaces, McpGateway } from "../src/index.js";
  7. const TIME_YAML = [
  8. "id: default",
  9. "dayLengthTicks: 480",
  10. "seasons:",
  11. " - { name: spring, dayCount: 28 }",
  12. "start: { day: 1, season: spring }",
  13. "",
  14. ].join("\n");
  15. const FARM_YAML = [
  16. "id: farm",
  17. "width: 2",
  18. "height: 2",
  19. 'tilesetRef: "tiles"',
  20. "spawn: { x: 0, y: 0 }",
  21. "layers:",
  22. " - name: ground",
  23. " data:",
  24. " - [a, b]",
  25. " - [b, a]",
  26. "",
  27. ].join("\n");
  28. interface Setup {
  29. engine: ReturnType<typeof createEngine>;
  30. gateway: McpGateway;
  31. tmp: string;
  32. close: () => Promise<void>;
  33. }
  34. async function setup(): Promise<Setup> {
  35. const tmp = await mkdtemp(join(tmpdir(), "farm-item-"));
  36. await mkdir(join(tmp, "maps"), { recursive: true });
  37. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  38. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  39. const engine = createEngine({ contentDir: tmp });
  40. const gateway = new McpGateway();
  41. for (const namespace of createEngineNamespaces(engine, { gateway })) {
  42. gateway.register(namespace);
  43. }
  44. await engine.start();
  45. return {
  46. engine,
  47. gateway,
  48. tmp,
  49. close: async () => {
  50. await engine.stop();
  51. await rm(tmp, { recursive: true, force: true });
  52. },
  53. };
  54. }
  55. async function callText(gateway: McpGateway, name: string, args: Record<string, unknown> = {}): Promise<{
  56. ok: boolean;
  57. text: string;
  58. }> {
  59. const result = await gateway.callTool(name, args);
  60. return { ok: result.isError !== true, text: result.content[0]?.text ?? "" };
  61. }
  62. const HOE_DEF: ItemDef = { id: "hoe", name: "Hoe", kind: "tool", stackable: false, rarity: "common" };
  63. describe("item namespace", () => {
  64. it("item.create writes content/items/<id>.yaml, registers live, and persists across restart", async () => {
  65. const { engine, gateway, tmp, close } = await setup();
  66. try {
  67. const created = await callText(gateway, "item.create", { def: HOE_DEF });
  68. expect(created.ok).toBe(true);
  69. expect(JSON.parse(created.text) as ItemDef).toEqual(HOE_DEF);
  70. expect(engine.registry.get<ItemDef>("item", "hoe")).toEqual(HOE_DEF);
  71. const file = await readFile(join(tmp, "items", "hoe.yaml"), "utf8");
  72. expect(file).toContain("id: hoe");
  73. expect(file).toContain("kind: tool");
  74. await engine.stop();
  75. const reloaded = createEngine({ contentDir: tmp });
  76. await reloaded.start();
  77. try {
  78. expect(reloaded.registry.get<ItemDef>("item", "hoe")).toEqual(HOE_DEF);
  79. } finally {
  80. await reloaded.stop();
  81. }
  82. } finally {
  83. await close();
  84. }
  85. });
  86. it("item.validate accepts a valid def and rejects an invalid one", async () => {
  87. const { gateway, close } = await setup();
  88. try {
  89. const valid = await callText(gateway, "item.validate", { def: HOE_DEF });
  90. expect(valid.ok).toBe(true);
  91. expect(JSON.parse(valid.text)).toEqual(HOE_DEF);
  92. const invalid = await callText(gateway, "item.validate", {
  93. def: { id: "nope", name: "Nope", kind: "not-a-kind", stackable: false },
  94. });
  95. expect(invalid.ok).toBe(false);
  96. expect(invalid.text).toMatch(/Invalid enum value/);
  97. expect(invalid.text).toMatch(/kind/);
  98. } finally {
  99. await close();
  100. }
  101. });
  102. it("item.create rejects an invalid def and does not write or register", async () => {
  103. const { engine, gateway, tmp, close } = await setup();
  104. try {
  105. const bad = await callText(gateway, "item.create", {
  106. def: { id: "broken", name: "Broken", kind: "tool", stackable: "yes" },
  107. });
  108. expect(bad.ok).toBe(false);
  109. expect(engine.registry.get("item", "broken")).toBeUndefined();
  110. await expect(readFile(join(tmp, "items", "broken.yaml"))).rejects.toThrow();
  111. } finally {
  112. await close();
  113. }
  114. });
  115. it("duplicate item.create overwrites the existing definition", async () => {
  116. const { engine, gateway, tmp, close } = await setup();
  117. try {
  118. await callText(gateway, "item.create", { def: HOE_DEF });
  119. const recreated = await callText(gateway, "item.create", {
  120. def: { id: "hoe", name: "Copper Hoe", kind: "tool", stackable: false, price: 800, rarity: "uncommon" },
  121. });
  122. expect(recreated.ok).toBe(true);
  123. const current = engine.registry.get<ItemDef>("item", "hoe");
  124. expect(current?.name).toBe("Copper Hoe");
  125. expect(current?.price).toBe(800);
  126. const file = await readFile(join(tmp, "items", "hoe.yaml"), "utf8");
  127. expect(file).toContain("name: Copper Hoe");
  128. } finally {
  129. await close();
  130. }
  131. });
  132. it("item.update merges a patch, validates, rewrites the file, and re-registers", async () => {
  133. const { engine, gateway, tmp, close } = await setup();
  134. try {
  135. await callText(gateway, "item.create", { def: HOE_DEF });
  136. const updated = await callText(gateway, "item.update", { id: "hoe", patch: { price: 700 } });
  137. expect(updated.ok).toBe(true);
  138. const def = JSON.parse(updated.text) as ItemDef;
  139. expect(def).toEqual({ id: "hoe", name: "Hoe", kind: "tool", stackable: false, rarity: "common", price: 700 });
  140. const file = await readFile(join(tmp, "items", "hoe.yaml"), "utf8");
  141. expect(file).toContain("price: 700");
  142. const missing = await callText(gateway, "item.update", { id: "nope", patch: { price: 1 } });
  143. expect(missing.ok).toBe(false);
  144. expect(missing.text).toMatch(/item not found: nope/);
  145. const badPatch = await callText(gateway, "item.update", { id: "hoe", patch: { kind: "bogus" } });
  146. expect(badPatch.ok).toBe(false);
  147. expect(badPatch.text).toMatch(/Invalid enum value/);
  148. expect(engine.registry.get<ItemDef>("item", "hoe")?.price).toBe(700);
  149. } finally {
  150. await close();
  151. }
  152. });
  153. it("item.list returns one-line summaries", async () => {
  154. const { gateway, close } = await setup();
  155. try {
  156. await callText(gateway, "item.create", { def: HOE_DEF });
  157. await callText(gateway, "item.create", {
  158. def: { id: "parsnip-seed", name: "Parsnip Seed", kind: "seed", stackable: true },
  159. });
  160. const listed = await callText(gateway, "item.list");
  161. expect(listed.ok).toBe(true);
  162. expect(JSON.parse(listed.text)).toEqual({
  163. items: [
  164. { id: "hoe", name: "Hoe", kind: "tool" },
  165. { id: "parsnip-seed", name: "Parsnip Seed", kind: "seed" },
  166. ],
  167. });
  168. } finally {
  169. await close();
  170. }
  171. });
  172. it("item.get returns the full def; unknown id is an error result", async () => {
  173. const { gateway, close } = await setup();
  174. try {
  175. await callText(gateway, "item.create", { def: HOE_DEF });
  176. const got = await callText(gateway, "item.get", { itemId: "hoe" });
  177. expect(got.ok).toBe(true);
  178. expect(JSON.parse(got.text)).toEqual(HOE_DEF);
  179. const missing = await callText(gateway, "item.get", { itemId: "nope" });
  180. expect(missing.ok).toBe(false);
  181. expect(missing.text).toMatch(/item not found: nope/);
  182. } finally {
  183. await close();
  184. }
  185. });
  186. it("item.query_inventory and item.give read and mutate the player inventory", async () => {
  187. const { engine, gateway, close } = await setup();
  188. try {
  189. await callText(gateway, "item.create", { def: HOE_DEF });
  190. const empty = await callText(gateway, "item.query_inventory");
  191. expect(JSON.parse(empty.text)).toEqual({ inventory: {} });
  192. const gave = await callText(gateway, "item.give", { itemId: "hoe", qty: 3 });
  193. expect(JSON.parse(gave.text)).toEqual({ itemId: "hoe", qty: 3, total: 3 });
  194. const after = await callText(gateway, "item.query_inventory");
  195. expect(JSON.parse(after.text)).toEqual({ inventory: { hoe: 3 } });
  196. const second = await callText(gateway, "item.give", { itemId: "hoe", qty: 2 });
  197. expect(JSON.parse(second.text)).toEqual({ itemId: "hoe", qty: 2, total: 5 });
  198. expect(engine.world.get("player")?.inventory).toEqual({ hoe: 5 });
  199. const unknown = await callText(gateway, "item.give", { itemId: "nope", qty: 1 });
  200. expect(unknown.ok).toBe(false);
  201. expect(unknown.text).toMatch(/unknown item: nope/);
  202. const badQty = await callText(gateway, "item.give", { itemId: "hoe", qty: 0 });
  203. expect(badQty.ok).toBe(false);
  204. expect(badQty.text).toMatch(/positive integer/);
  205. } finally {
  206. await close();
  207. }
  208. });
  209. it("resources: item://catalog and item://{id}; missing id rejects", async () => {
  210. const { engine, gateway, close } = await setup();
  211. try {
  212. await callText(gateway, "item.create", { def: HOE_DEF });
  213. const catalog = await gateway.readResource("item://catalog");
  214. expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ items: [HOE_DEF] });
  215. const single = await gateway.readResource("item://hoe");
  216. expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(HOE_DEF);
  217. await expect(gateway.readResource("item://missing")).rejects.toThrow(/item not found: missing/);
  218. expect(engine.registry.get("item", "missing")).toBeUndefined();
  219. } finally {
  220. await close();
  221. }
  222. });
  223. it("serves the item.create-prompt prompt", async () => {
  224. const { gateway, close } = await setup();
  225. try {
  226. const prompt = await gateway.getPrompt("item.create-prompt", {});
  227. const text = prompt.messages[0]?.content.text ?? "";
  228. expect(text).toContain("kind");
  229. expect(text).toContain("stackable");
  230. expect(text).toContain("item.validate");
  231. expect(text).toContain("content/items/<id>.yaml");
  232. } finally {
  233. await close();
  234. }
  235. });
  236. });