threenative-engine-mcp 0.2.10 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -73,13 +73,13 @@ interface IEngineTool {
73
73
  readonly properties: Record<string, {
74
74
  readonly description?: string;
75
75
  readonly enum?: readonly string[];
76
- readonly type: "string" | "object";
76
+ readonly type: "string" | "object" | "number";
77
77
  }>;
78
78
  readonly required: readonly string[];
79
79
  readonly additionalProperties: false;
80
80
  };
81
81
  }
82
- declare const ENGINE_MCP_TOOL_NAMES: readonly ["engine_search_capabilities", "engine_capability_detail", "engine_search_references", "engine_reference_detail", "engine_save_reference"];
82
+ declare const ENGINE_MCP_TOOL_NAMES: readonly ["engine_search_capabilities", "engine_capability_detail", "engine_search_references", "engine_reference_detail", "engine_save_reference", "engine_watch_reference"];
83
83
  /** Chosen by the current-manifest threshold sweep: the highest recalled candidate at 0.27. */
84
84
  declare const RELEVANCE_FLOOR = 0.27;
85
85
  declare function defaultManifestPath(cwd?: string): string;
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { realpathSync, readFileSync, existsSync, mkdirSync, rmSync, writeFileSync, appendFileSync, renameSync, readdirSync } from 'fs';
3
- import path2 from 'path';
2
+ import { realpathSync, readFileSync, existsSync, mkdirSync, rmSync, writeFileSync, appendFileSync, mkdtempSync, renameSync, readdirSync } from 'fs';
3
+ import path from 'path';
4
4
  import { createInterface } from 'readline';
5
5
  import { fileURLToPath } from 'url';
6
+ import { execFile } from 'child_process';
6
7
  import { createHash } from 'crypto';
7
8
  import os from 'os';
9
+ import { promisify } from 'util';
8
10
  import { gunzipSync } from 'zlib';
9
11
 
10
12
  var DEFAULT_REFERENCES_URL = "https://github.com/ThreeNativeHQ/threenative-reverse-engineer-mcp/releases/latest/download/";
@@ -18,12 +20,12 @@ function referencesBaseUrl() {
18
20
  function referencesCacheDir() {
19
21
  const override = process.env.THREENATIVE_REFERENCES_CACHE?.trim();
20
22
  const source = createHash("sha256").update(referencesBaseUrl()).digest("hex").slice(0, 16);
21
- if (override) return path2.join(path2.resolve(override), source);
22
- const cacheHome = process.env.XDG_CACHE_HOME?.trim() || path2.join(os.homedir(), ".cache");
23
- return path2.join(cacheHome, "threenative", "refs", source);
23
+ if (override) return path.join(path.resolve(override), source);
24
+ const cacheHome = process.env.XDG_CACHE_HOME?.trim() || path.join(os.homedir(), ".cache");
25
+ return path.join(cacheHome, "threenative", "refs", source);
24
26
  }
25
27
  function localReferencesDir(cwd = process.cwd()) {
26
- return path2.join(cwd, ".threenative", "refs");
28
+ return path.join(cwd, ".threenative", "refs");
27
29
  }
28
30
  function fail(where, reason) {
29
31
  throw new Error(`TN_REFERENCES_MALFORMED: ${where}: ${reason}`);
@@ -61,7 +63,7 @@ function line(value, where) {
61
63
  }
62
64
  function sourcePath(value, where) {
63
65
  const result = text(value, where);
64
- if (path2.isAbsolute(result) || result.split("/").includes("..") || !/^[a-zA-Z0-9_./-]+$/u.test(result))
66
+ if (path.isAbsolute(result) || result.split("/").includes("..") || !/^[a-zA-Z0-9_./-]+$/u.test(result))
65
67
  fail(where, "expected a safe relative source path");
66
68
  return result;
67
69
  }
@@ -275,7 +277,7 @@ function referenceStubs(game) {
275
277
  ];
276
278
  }
277
279
  async function cachedAsset(name, parse, timeout = FETCH_TIMEOUT_MS) {
278
- const file = path2.join(referencesCacheDir(), name);
280
+ const file = path.join(referencesCacheDir(), name);
279
281
  const etagFile = `${file}.etag`;
280
282
  let response;
281
283
  try {
@@ -301,7 +303,7 @@ async function cachedAsset(name, parse, timeout = FETCH_TIMEOUT_MS) {
301
303
  throw new Error(`TN_REFERENCES_UNAVAILABLE: ${name}: ${String(error)}`);
302
304
  }
303
305
  const parsed = parse(body);
304
- mkdirSync(path2.dirname(file), { recursive: true });
306
+ mkdirSync(path.dirname(file), { recursive: true });
305
307
  atomicWrite(file, body);
306
308
  const etag = response.headers.get("etag");
307
309
  if (etag === null) rmSync(etagFile, { force: true });
@@ -332,17 +334,17 @@ function loadLocalReferenceGames(cwd = process.cwd()) {
332
334
  if (!existsSync(directory)) return [];
333
335
  return readdirSync(directory).filter((file) => file.endsWith(".json")).sort().map((file) => {
334
336
  const game = validateReferenceGame(
335
- parseJson(readFileSync(path2.join(directory, file)), file),
336
- path2.join(".threenative", "refs", file)
337
+ parseJson(readFileSync(path.join(directory, file)), file),
338
+ path.join(".threenative", "refs", file)
337
339
  );
338
- if (game.id !== path2.basename(file, ".json"))
340
+ if (game.id !== path.basename(file, ".json"))
339
341
  fail(file, `id '${game.id}' differs from filename`);
340
342
  return game;
341
343
  });
342
344
  }
343
345
  function loadReferenceGame(gameId, cwd = process.cwd()) {
344
346
  id(gameId, "game id");
345
- const file = path2.join(localReferencesDir(cwd), `${gameId}.json`);
347
+ const file = path.join(localReferencesDir(cwd), `${gameId}.json`);
346
348
  if (existsSync(file)) {
347
349
  const local = validateReferenceGame(parseJson(readFileSync(file), file), file);
348
350
  if (local.id !== gameId) fail(file, `id '${local.id}' differs from requested '${gameId}'`);
@@ -394,7 +396,7 @@ function saveReferenceGame(value, cwd = process.cwd()) {
394
396
  "cards"
395
397
  ]);
396
398
  const gameId = id(incoming.id, "reference.id");
397
- const file = path2.join(localReferencesDir(cwd), `${gameId}.json`);
399
+ const file = path.join(localReferencesDir(cwd), `${gameId}.json`);
398
400
  const previous = existsSync(file) ? validateReferenceGame(parseJson(readFileSync(file), file), file) : void 0;
399
401
  if (previous !== void 0 && previous.sha !== incoming.sha)
400
402
  fail(
@@ -418,10 +420,10 @@ function saveReferenceGame(value, cwd = process.cwd()) {
418
420
  },
419
421
  "reference"
420
422
  );
421
- mkdirSync(path2.dirname(file), { recursive: true });
423
+ mkdirSync(path.dirname(file), { recursive: true });
422
424
  atomicWrite(file, `${JSON.stringify(merged, null, 2)}
423
425
  `);
424
- const relative = path2.relative(cwd, file);
426
+ const relative = path.relative(cwd, file);
425
427
  const title = `Reference cards: ${merged.title} (${merged.nodes.length} nodes, ${merged.cards.length} cards)`;
426
428
  return {
427
429
  contribution: {
@@ -431,6 +433,54 @@ function saveReferenceGame(value, cwd = process.cwd()) {
431
433
  saved: relative
432
434
  };
433
435
  }
436
+ var WATCH_TOOLS = [
437
+ ["yt-dlp", "install it with `pipx install yt-dlp`"],
438
+ ["ffmpeg", "install it with `sudo apt install ffmpeg` or `brew install ffmpeg`"]
439
+ ];
440
+ var WATCH_TIMEOUT_MS = 3e5;
441
+ function onPath(name) {
442
+ return [
443
+ ...(process.env.PATH ?? "").split(path.delimiter),
444
+ path.join(os.homedir(), ".local", "bin")
445
+ ].filter((directory) => directory.length > 0).some((directory) => existsSync(path.join(directory, name)));
446
+ }
447
+ async function watchReference(options) {
448
+ for (const [name, install] of WATCH_TOOLS)
449
+ if (!onPath(name))
450
+ throw new Error(`TN_WATCH_TOOL_MISSING: ${name} is not on PATH: ${install}.`);
451
+ const url = new URL("watch.mjs", referencesBaseUrl()).href;
452
+ try {
453
+ await cachedAsset("watch.mjs", (body) => body, GAME_FETCH_TIMEOUT_MS);
454
+ } catch (error) {
455
+ throw new Error(`TN_WATCH_UNAVAILABLE: cannot fetch ${url}: ${String(error)}`);
456
+ }
457
+ const out = mkdtempSync(path.join(os.tmpdir(), "threenative-watch-"));
458
+ const flags = Object.entries({
459
+ "--duration": options.duration,
460
+ "--frames": options.frames,
461
+ "--at": options.at,
462
+ "--pick": options.pick,
463
+ "--from": options.from
464
+ }).flatMap(([flag, value]) => value === void 0 ? [] : [flag, String(value)]);
465
+ try {
466
+ await promisify(execFile)(
467
+ process.execPath,
468
+ [path.join(referencesCacheDir(), "watch.mjs"), options.query, ...flags, "--out", out],
469
+ { maxBuffer: 16 * 1024 * 1024, timeout: WATCH_TIMEOUT_MS }
470
+ );
471
+ } catch (error) {
472
+ rmSync(out, { recursive: true, force: true });
473
+ const stderr = String(error.stderr ?? "").trim();
474
+ throw new Error(`TN_WATCH_FAILED: ${stderr || String(error)}`);
475
+ }
476
+ const watch = JSON.parse(readFileSync(path.join(out, "watch.json"), "utf8"));
477
+ return {
478
+ sheet: watch.sheet === null ? null : path.join(out, watch.sheet),
479
+ frames: watch.frames.map((frame) => path.join(out, frame.path)),
480
+ watch,
481
+ guidance: "Read the sheet first: every frame in order. Then aim with pick, from or at. Reference only: borrow the mechanic, never commit the frames."
482
+ };
483
+ }
434
484
 
435
485
  // src/index.ts
436
486
  var ENGINE_MCP_TOOL_NAMES = [
@@ -438,7 +488,8 @@ var ENGINE_MCP_TOOL_NAMES = [
438
488
  "engine_capability_detail",
439
489
  "engine_search_references",
440
490
  "engine_reference_detail",
441
- "engine_save_reference"
491
+ "engine_save_reference",
492
+ "engine_watch_reference"
442
493
  ];
443
494
  var DEFAULT_MANIFEST_FILE = "capabilities.json";
444
495
  var STOP_WORDS = /* @__PURE__ */ new Set([
@@ -486,6 +537,7 @@ var STOP_WORDS = /* @__PURE__ */ new Set([
486
537
  "is",
487
538
  "it",
488
539
  "its",
540
+ "keep",
489
541
  "let",
490
542
  "made",
491
543
  "make",
@@ -557,29 +609,29 @@ var STOP_WORDS = /* @__PURE__ */ new Set([
557
609
  var MAX_COMPLETE_REQUEST_RESULTS = 15;
558
610
  var MAX_SITUATION_RESULTS = 5;
559
611
  var RELEVANCE_FLOOR = 0.27;
560
- var AUTHORING_INSTRUCTIONS = "Invoke threenative-capabilities to route authoring. New games: steps 1-8 \u2014 prompt, matching starter kit (minimal fallback), mechanics references PLUS built-in capabilities, core-mechanics plan via prd-creator, required textures, execute, mechanics playtest, reference-image visual judge. Existing games: steps 5-7 only \u2014 required textures, execute and mechanics playtest using existing context; no kit selection, rediscovery, whole-game replanning or added step 8. In both routes, execute plan with subagents focused on specific areas: bounded tasks, file ownership, then coordinator integration before step 7 mechanics playtests. Follow binding capability constraints. References borrow mechanics only: no code, level layouts, character names or art; cite pinned file:line sources.";
612
+ var AUTHORING_INSTRUCTIONS = "Follow the Authoring flow in the game's AGENTS.md (the threenative-capabilities skill holds the detail): search capabilities and references before the first new src/ file, for a new game and for every change to an existing game. Follow binding capability constraints. Execute with subagents focused on specific areas: bounded tasks, file ownership, then coordinator integration before mechanics playtests. References borrow mechanics only: no code, level layouts, character names or art; cite pinned file:line sources.";
561
613
  var GENERIC_GUIDANCE = "No installed engine capability matches this situation. Decompose it into concrete mechanics and write the game-owned behavior in your project's src/; inspect the relevant template AGENTS.md before adding a package.";
562
614
  function defaultManifestPath(cwd = process.cwd()) {
563
615
  const override = process.env.THREENATIVE_CAPABILITIES_MANIFEST;
564
- if (override !== void 0 && override.trim().length > 0) return path2.resolve(cwd, override);
565
- for (let directory = path2.resolve(cwd); ; directory = path2.dirname(directory)) {
566
- const nodeModules = path2.join(directory, "node_modules");
567
- const installed = path2.join(nodeModules, "@threenative", "core", "capabilities.json");
616
+ if (override !== void 0 && override.trim().length > 0) return path.resolve(cwd, override);
617
+ for (let directory = path.resolve(cwd); ; directory = path.dirname(directory)) {
618
+ const nodeModules = path.join(directory, "node_modules");
619
+ const installed = path.join(nodeModules, "@threenative", "core", "capabilities.json");
568
620
  if (existsSync(installed)) {
569
- const relative = path2.relative(realpathSync(directory), realpathSync(nodeModules));
570
- if (relative !== ".." && !relative.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative))
621
+ const relative = path.relative(realpathSync(directory), realpathSync(nodeModules));
622
+ if (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
571
623
  return installed;
572
624
  }
573
- const parent = path2.dirname(directory);
625
+ const parent = path.dirname(directory);
574
626
  if (parent === directory) break;
575
627
  }
576
- for (let directory = path2.dirname(fileURLToPath(import.meta.url)); ; directory = path2.dirname(directory)) {
577
- const repository = path2.join(directory, "packages", "core", "capabilities.json");
628
+ for (let directory = path.dirname(fileURLToPath(import.meta.url)); ; directory = path.dirname(directory)) {
629
+ const repository = path.join(directory, "packages", "core", "capabilities.json");
578
630
  if (existsSync(repository)) return repository;
579
- const parent = path2.dirname(directory);
631
+ const parent = path.dirname(directory);
580
632
  if (parent === directory) break;
581
633
  }
582
- return path2.resolve(cwd, DEFAULT_MANIFEST_FILE);
634
+ return path.resolve(cwd, DEFAULT_MANIFEST_FILE);
583
635
  }
584
636
  function manifestError(file, reason) {
585
637
  return new Error(`TN_ENGINE_CAPABILITIES_MANIFEST: ${file}: ${reason}`);
@@ -651,8 +703,9 @@ function suffixStripped(token) {
651
703
  if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss")) return token.slice(0, -1);
652
704
  return token;
653
705
  }
706
+ var STOP_WORD_STEMS = new Set([...STOP_WORDS].map(stem));
654
707
  function capabilitySituationTokens(value) {
655
- return value.toLocaleLowerCase().split(/[^a-z0-9]+/u).filter((token) => token.length > 1 && !STOP_WORDS.has(token)).map(stem);
708
+ return value.toLocaleLowerCase().split(/[^a-z0-9]+/u).filter((token) => token.length > 1 && !STOP_WORDS.has(token)).map(stem).filter((token) => !STOP_WORD_STEMS.has(token));
656
709
  }
657
710
  var tokens = capabilitySituationTokens;
658
711
  function tokenWeights(entries) {
@@ -817,10 +870,11 @@ var REVERSE_ENGINEER = /\breverse[\s-]?engineer|\bdecomp|\bdisassembl/iu;
817
870
  var REFERENCE_TOOLS = [
818
871
  "engine_search_references",
819
872
  "engine_reference_detail",
820
- "engine_save_reference"
873
+ "engine_save_reference",
874
+ "engine_watch_reference"
821
875
  ];
822
876
  function withReferenceTools(situation, response) {
823
- if (!REVERSE_ENGINEER.test(situation)) return response;
877
+ if (!REVERSE_ENGINEER.test(situation)) return { referenceTools: REFERENCE_TOOLS, ...response };
824
878
  return {
825
879
  referenceTools: REFERENCE_TOOLS,
826
880
  ...response,
@@ -963,19 +1017,43 @@ var TOOL_DEFINITIONS = [
963
1017
  },
964
1018
  required: ["game"]
965
1019
  }
1020
+ },
1021
+ {
1022
+ name: "engine_watch_reference",
1023
+ description: "Watch what you reverse engineer: see a game mechanic before you build it. Searches YouTube for gameplay of a reference game, download one short segment and slice frames plus one contact sheet into a tmp folder. Returns sheet (read it first), frames and watch.json (video, segment, frame times). Needs yt-dlp and ffmpeg. Frames are reference only: never commit them.",
1024
+ annotations: { destructiveHint: false, openWorldHint: true, readOnlyHint: true },
1025
+ inputSchema: {
1026
+ type: "object",
1027
+ additionalProperties: false,
1028
+ properties: {
1029
+ query: {
1030
+ type: "string",
1031
+ description: "Game and mechanic, e.g. 'super mario 64 triple jump'."
1032
+ },
1033
+ duration: { type: "number", description: "Seconds of gameplay to sample (default 90)." },
1034
+ frames: { type: "number", description: "Frames to slice from the segment (default 12)." },
1035
+ at: { type: "string", description: "Exact timestamps, comma separated, e.g. '12,35,61'." },
1036
+ pick: { type: "number", description: "Search result index (default 0, the top one)." },
1037
+ from: {
1038
+ type: "string",
1039
+ description: "Segment start: seconds, mm:ss or NN% (default 10%)."
1040
+ }
1041
+ },
1042
+ required: ["query"]
1043
+ }
966
1044
  }
967
1045
  ];
968
1046
  function toolDefinitions() {
969
1047
  return TOOL_DEFINITIONS;
970
1048
  }
971
- var DEFAULT_LOG_FILE = path2.join(".threenative", "engine-mcp.log");
1049
+ var DEFAULT_LOG_FILE = path.join(".threenative", "engine-mcp.log");
972
1050
  var logBroken = false;
973
1051
  function logToolCall(entry) {
974
1052
  if (logBroken) return;
975
1053
  const target = process.env.THREENATIVE_ENGINE_MCP_LOG ?? DEFAULT_LOG_FILE;
976
1054
  if (target === "off") return;
977
1055
  try {
978
- mkdirSync(path2.dirname(path2.resolve(target)), { recursive: true });
1056
+ mkdirSync(path.dirname(path.resolve(target)), { recursive: true });
979
1057
  appendFileSync(target, `${JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
980
1058
  `);
981
1059
  } catch (error) {
@@ -1084,17 +1162,13 @@ async function handleToolCall(params, manifestFile) {
1084
1162
  tool: name,
1085
1163
  verdict: response.verdict
1086
1164
  });
1087
- return toolText(
1088
- response.verdict === "none" ? {
1089
- ...response,
1090
- references: await searchReferences(argumentsValue.situation, 3).catch(
1091
- (error) => ({
1092
- results: [],
1093
- guidance: `references unavailable: ${String(error)}`
1094
- })
1095
- )
1096
- } : response
1097
- );
1165
+ return toolText({
1166
+ ...response,
1167
+ references: await searchReferences(argumentsValue.situation, 3).catch((error) => ({
1168
+ results: [],
1169
+ guidance: `references unavailable: ${String(error)}`
1170
+ }))
1171
+ });
1098
1172
  }
1099
1173
  if (name === "engine_capability_detail") {
1100
1174
  if (typeof argumentsValue.symbol !== "string")
@@ -1153,6 +1227,27 @@ async function handleToolCall(params, manifestFile) {
1153
1227
  logToolCall({ tool: name, saved: saved.saved });
1154
1228
  return toolText(saved);
1155
1229
  }
1230
+ if (name === "engine_watch_reference") {
1231
+ const { query, duration, frames, at, pick, from } = argumentsValue;
1232
+ if (typeof query !== "string" || !query.trim())
1233
+ throw new Error("engine_watch_reference requires a non-empty string 'query'.");
1234
+ for (const [key, value] of Object.entries({ duration, frames, pick }))
1235
+ if (value !== void 0 && typeof value !== "number")
1236
+ throw new Error(`engine_watch_reference '${key}' must be a number when given.`);
1237
+ for (const [key, value] of Object.entries({ at, from }))
1238
+ if (value !== void 0 && typeof value !== "string")
1239
+ throw new Error(`engine_watch_reference '${key}' must be a string when given.`);
1240
+ const result = await watchReference({
1241
+ query,
1242
+ ...typeof duration === "number" ? { duration } : {},
1243
+ ...typeof frames === "number" ? { frames } : {},
1244
+ ...typeof at === "string" ? { at } : {},
1245
+ ...typeof pick === "number" ? { pick } : {},
1246
+ ...typeof from === "string" ? { from } : {}
1247
+ });
1248
+ logToolCall({ tool: name, query, sheet: result.sheet });
1249
+ return toolText(result);
1250
+ }
1156
1251
  throw new Error(`Unknown engine MCP tool '${String(name)}'.`);
1157
1252
  }
1158
1253
  async function handleLine(line2, manifestFile) {
@@ -1171,7 +1266,7 @@ async function handleLine(line2, manifestFile) {
1171
1266
  capabilities: { tools: { listChanged: false } },
1172
1267
  instructions: AUTHORING_INSTRUCTIONS,
1173
1268
  protocolVersion: "2025-06-18",
1174
- serverInfo: { name: "threenative-engine-mcp", version: "0.2.10" }
1269
+ serverInfo: { name: "threenative-engine-mcp", version: "0.2.12" }
1175
1270
  });
1176
1271
  }
1177
1272
  if (request.method === "tools/list") {
@@ -1226,7 +1321,7 @@ function runServer(manifestFile = defaultManifestPath()) {
1226
1321
  });
1227
1322
  }
1228
1323
  var entryPath = process.argv[1];
1229
- if (entryPath !== void 0 && realpathSync(path2.resolve(entryPath)) === realpathSync(fileURLToPath(import.meta.url))) {
1324
+ if (entryPath !== void 0 && realpathSync(path.resolve(entryPath)) === realpathSync(fileURLToPath(import.meta.url))) {
1230
1325
  try {
1231
1326
  runServer();
1232
1327
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "threenative-engine-mcp",
3
- "version": "0.2.10",
3
+ "version": "0.2.12",
4
4
  "license": "MIT",
5
5
  "description": "Offline MCP capability discovery for ThreeNative authoring agents.",
6
6
  "keywords": [
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "repository": {
20
20
  "type": "git",
21
- "url": "git+https://github.com/ThreeNativeHQ/threenative.git",
21
+ "url": "git+https://github.com/ThreeNativeHQ/threenative-engine.git",
22
22
  "directory": "packages/engine-mcp"
23
23
  },
24
24
  "type": "module",