Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(mcp): a search that cannot see a file says so, and a tool names its arguments

yhhb556fcd86d3e
diff --git a/desktop/electron/projectFs.ts b/desktop/electron/projectFs.ts
index d8aa0347a..e45d64c7a 100644
--- a/desktop/electron/projectFs.ts
+++ b/desktop/electron/projectFs.ts
@@ -230,6 +230,44 @@ export function pathMatchesGlob(rel: string, glob: string): boolean {
const re = new RegExp(`^${pattern}$`);
return re.test(rel) || (!glob.includes('/') && re.test(rel.split('/').pop() ?? ''));
}
+/** The staged SDK types, which the content walk skips because they sit under a dot dir. */
+const SDK_TYPES_REL = '.esengine/sdk';
+
+/**
+ * What a code search reaches: the project's own files, then the staged SDK types.
+ *
+ * The dot rule that keeps `.esengine` out of the Content Browser was excluding it
+ * from search too — and search exists FOR that directory: the doc above names the
+ * 50k-line `.d.ts` as the thing nobody should have to page a hundred lines at a
+ * time, and it was the one file the walk could not see. `read_project_file` and
+ * `lookup_symbol` both hand out paths inside it, so "no matches" for a symbol
+ * those two had just named read as "it does not exist" — and the next twelve
+ * calls were blind offsets into the file the search would have pointed at.
+ * Project files come first so a hit in the user's own code still leads.
+ */
+async function* searchable(root: string): AsyncGenerator<string> {
+ yield* walkVisible(root, root);
+ const sdk = path.resolve(root, SDK_TYPES_REL);
+ if (existsSync(sdk)) {
+ for await (const abs of walkFiles(sdk)) yield toRel(root, abs);
+ }
+}
+
+/**
+ * A generated re-export line: `export { a as Foo, b as Bar, … }` — hundreds of
+ * aliases on one line, in five near-identical index files.
+ *
+ * It matches EVERY symbol anyone searches for and says nothing about any of
+ * them: the declaration is in another file, and the alias soup around the hit
+ * is a different file's alphabet (one reader took `d4 as GpAxis` from the
+ * wrong barrel and spent four calls on the wrong function). Clipped to 400
+ * characters it is also unreadable. The declaration is still found — it is a
+ * line in the file the barrel re-exports from.
+ */
+function isReExportBarrel(line: string): boolean {
+ return line.length > 400 && /^export\s+(type\s+)?\{/.test(line);
+}
+
export async function searchInRoot(
root: string,
opts: { query: string; regex?: boolean; glob?: string; maxResults?: number },
@@ -241,7 +279,7 @@ export async function searchInRoot(
? new RegExp(query, 'i')
: new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
const out: FileMatch[] = [];
- for await (const rel of walkVisible(root, root)) {
+ for await (const rel of searchable(root)) {
if (opts.glob && !pathMatchesGlob(rel, opts.glob)) continue;
let text: string;
try {
@@ -255,7 +293,9 @@ export async function searchInRoot(
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
if (!re.test(lines[i])) continue;
- out.push({ file: rel, line: i + 1, text: lines[i].trim().slice(0, 400) });
+ const line = lines[i].trim();
+ if (isReExportBarrel(line)) continue;
+ out.push({ file: rel, line: i + 1, text: line.slice(0, 400) });
if (out.length >= max) return out;
}
}
diff --git a/desktop/electron/scriptService.ts b/desktop/electron/scriptService.ts
index 99fac6c1d..9de0c8da2 100644
--- a/desktop/electron/scriptService.ts
+++ b/desktop/electron/scriptService.ts
@@ -214,6 +214,61 @@ class ProjectScripts {
return text.slice(from, end).replace(/\s+/g, ' ').trim().slice(0, 800);
}
+ /** The innermost class/interface a position falls inside, if any. */
+ private enclosingType(
+ source: ts.SourceFile,
+ start: number,
+ ): ts.ClassDeclaration | ts.InterfaceDeclaration | undefined {
+ let found: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined;
+ const visit = (node: ts.Node): void => {
+ if (start < node.getStart(source) || start >= node.getEnd()) return;
+ if (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node)) found = node;
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ return found;
+ }
+
+ /**
+ * A type rendered as WHAT YOU CAN CALL ON IT: its public members, signatures only.
+ *
+ * The declaration text is the wrong answer for a class, and silently so. Every
+ * real class opens with its private state, so the first 800 characters of
+ * `AudioAPI` are a dozen `private readonly` fields and a comment — the asker
+ * learns nothing and cannot even tell they were cut off. The one question a
+ * class is ever asked is which methods it has, and the members answer it in
+ * less space than the fields wasted.
+ */
+ private memberSummary(source: ts.SourceFile, start: number): string | null {
+ const node = this.enclosingType(source, start);
+ if (!node?.name) return null;
+ const hidden = (m: ts.ClassElement | ts.TypeElement): boolean => {
+ const mods = ts.canHaveModifiers(m) ? ts.getModifiers(m) ?? [] : [];
+ if (mods.some((x) => x.kind === ts.SyntaxKind.PrivateKeyword
+ || x.kind === ts.SyntaxKind.ProtectedKeyword)) return true;
+ const name = m.name ? m.name.getText(source) : '';
+ // `_id` / `world_` are the two spellings the engine uses for "not yours".
+ return !name || name.startsWith('_') || name.endsWith('_');
+ };
+ const rendered: string[] = [];
+ let dropped = 0;
+ for (const m of node.members as ts.NodeArray<ts.ClassElement | ts.TypeElement>) {
+ if (hidden(m)) continue;
+ if (rendered.length >= 40) { dropped++; continue; }
+ const body = (m as ts.MethodDeclaration).body;
+ const text = body
+ ? m.getText(source).slice(0, body.getStart(source) - m.getStart(source))
+ : m.getText(source);
+ rendered.push(text.replace(/\s+/g, ' ').trim().replace(/[;,]$/, ''));
+ }
+ if (!rendered.length) return null;
+ const kind = ts.isClassDeclaration(node) ? 'class' : 'interface';
+ const heritage = node.heritageClauses?.map((h) => h.getText(source).replace(/\s+/g, ' ')).join(' ');
+ const head = `${kind} ${node.name.getText(source)}${heritage ? ` ${heritage}` : ''}`;
+ const tail = dropped ? `; … ${dropped} more` : '';
+ return `${head} { ${rendered.join('; ')}${tail} }`.slice(0, 2400);
+ }
+
lookup(name: string, limit = 8): SymbolInfo[] {
this.rescan();
const items = this.service.getNavigateToItems(name, 64, undefined, false, true);
@@ -233,11 +288,16 @@ class ProjectScripts {
// IS complete it is better than raw source — it carries the owning type
// ("(method) InputState.isMouseButtonPressed(button: number): boolean").
const useQuick = quick.includes('(') || quick.includes(':');
+ // A class or interface answers with its members, whatever quickInfo said:
+ // for `AudioAPI` quickInfo is "class AudioAPI", and the declaration text
+ // is its private fields.
+ const members = source && (item.kind === 'class' || item.kind === 'interface')
+ ? this.memberSummary(source, item.textSpan.start) : null;
const declared = source ? this.declarationText(source, item.textSpan.start) : '';
out.push({
name: item.name,
kind: item.kind,
- signature: (useQuick ? quick : declared) || quick || `${item.kind} ${item.name}`,
+ signature: members || (useQuick ? quick : declared) || quick || `${item.kind} ${item.name}`,
doc: info?.documentation?.length ? ts.displayPartsToString(info.documentation) : undefined,
file: path.relative(this.root, item.fileName),
line,
diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjs
index ac33589bb..708a9040d 100644
--- a/desktop/shared/toolCatalog.mjs
+++ b/desktop/shared/toolCatalog.mjs
@@ -452,7 +452,8 @@ export const TOOLS = [
schema: obj({ name: { type: ['string', 'array'] }, limit: { type: 'number' } }, ['name']), op: 'lookup_symbol' },
{ name: 'search_project_files',
description: 'Lines matching `query` across the project (case-insensitive substring, or a regular expression with `regex: true`); `glob` filters paths — `*.ts`, `src/**`, `src/*.ts`, or a plain substring like ".ts". '
- + 'Each hit is { file, line, text }. The door between list_project_files and reading a file whole.',
+ + 'Each hit is { file, line, text }. The door between list_project_files and reading a file whole. '
+ + 'It searches the STAGED SDK TYPES too (`.esengine/sdk/**.d.ts`), so `query: "interface PrefabOverride"` finds the declaration and its line — that is the way to locate a type lookup_symbol did not answer, rather than paging the .d.ts by offset.',
schema: obj({
query: { type: 'string' }, regex: { type: 'boolean' },
glob: { type: 'string' }, maxResults: { type: 'number' },
@@ -543,8 +544,9 @@ export const TOOLS = [
+ '**`find(NAME)`** — an ARRAY of `{ entity, data }`, one per entity carrying that component (`.length`, `[0]`, `for..of` and `.map` all work; `.total` is the count, `.truncatedAt` is set when a limit cut it short, and returning the array itself serialises as a plain list); '
+ '**`get(ENTITY, NAME)`** — one entity\'s component data, or null when it does not have it; '
+ '**`set(ENTITY, NAME, PATCH)`** — write fields of one component, for staging the situation you want to watch; '
- + '**`resource(NAME)`** — the live value of a resource (a score, a phase — state belonging to no entity); '
- + '**`step(FRAMES, DT)`** — advance the game deterministically (the loop is throttled while the editor window is unfocused, so this is how anything moves); '
+ + '**`resource(NAME)`** — the live value of a resource (a score, a phase — state belonging to no entity), and **`setResource(NAME, PATCH)`** to write its fields, which is how you stage a game state (`setResource("GameState", { lives: 1 })`) without playing up to it; '
+ + '**`await step(FRAMES, DT)`** — advance the game deterministically (the loop is throttled while the editor window is unfocused, so this is how anything moves). '
+ + 'AWAIT it: it is async, and unawaited it returns a promise while everything you read after it is still the state from BEFORE the step. '
+ '`componentNames()` lists what `find` accepts, `resource` on an unknown name answers with the available ones, and `app` / `getComponent` are there for what these do not cover. '
+ 'Reach for find/get/resource first — they answer "what does the game think is going on right now", which is the question. Do NOT hand-roll a frame advance through app internals; `step` is the supported one. '
+ 'Use play_input, not synthetic DOM events, to drive input. frame picks the realm in multiplayer previews (0 = host).',
@@ -616,9 +618,30 @@ function typeMatches(spec, val) {
: true);
}
-/** Light validation: required args present + declared scalar types match. */
+/**
+ * Light validation: required args present, declared scalar types match, and
+ * NOTHING ELSE came along.
+ *
+ * The unknown-argument check is the one that saves a file. An argument nobody
+ * declared used to be dropped in silence, so a caller who assumed a parameter
+ * existed got a successful reply proving it did — `write_project_file` handed an
+ * `offset` (which `read_project_file` really does take) answered `{ok:true}` to
+ * what the caller believed was an append, and had overwritten four hundred lines
+ * with the fragment. Say which arguments exist instead; the caller is one round
+ * trip from right, rather than one call from a truncated file.
+ */
function validate(schema, raw) {
const input = raw ?? {};
+ const declared = Object.keys(schema.properties ?? {});
+ // `_`-prefixed keys are protocol metadata some MCP clients attach, not arguments.
+ const unknown = Object.keys(input).filter((k) => !k.startsWith('_') && !declared.includes(k));
+ if (unknown.length) {
+ throw new Error(
+ `unknown argument${unknown.length > 1 ? 's' : ''}: ${unknown.map((k) => `\`${k}\``).join(', ')}`
+ + ` — this tool takes ${declared.length ? declared.map((k) => `\`${k}\``).join(', ') : 'no arguments'}`
+ + '. It was IGNORED, not applied.',
+ );
+ }
for (const req of schema.required ?? []) {
if (input[req] === undefined) {
// Name what DID arrive. A caller that wrote `file` for `path` reads "missing
diff --git a/desktop/tests/agent-kernel.test.ts b/desktop/tests/agent-kernel.test.ts
index 4d0b08b12..c5daf2070 100644
--- a/desktop/tests/agent-kernel.test.ts
+++ b/desktop/tests/agent-kernel.test.ts
@@ -552,14 +552,14 @@ describe('looking before reporting', () => {
// The gomoku turn: 71 calls, every write compiling, every diagnostic clean,
// and the board half off camera — because nothing in the loop ever put a
// picture in front of it.
- const s = fakeSession([asks(call('add_entity', { name: 'Board' })), ends(), ends()]);
+ const s = fakeSession([asks(call('add_entity')), ends(), ends()]);
await runTurn(deps(s), 'build me a board', null, new AbortController().signal);
expect(s.context.some((c) => c.includes('capture_viewport'))).toBe(true);
});
it('says nothing to a turn that already looked', async () => {
const s = fakeSession([
- asks(call('add_entity', { name: 'Board' })),
+ asks(call('add_entity')),
asks(call('capture_viewport')),
ends(),
]);
@@ -578,7 +578,7 @@ describe('looking before reporting', () => {
it('asks once, not every round', async () => {
// A second ask is an argument. The model may have a reason not to look, and
// a loop that insists cannot be ended by the model at all.
- const s = fakeSession([asks(call('add_entity', { name: 'B' })), ends(), ends(), ends()]);
+ const s = fakeSession([asks(call('add_entity')), ends(), ends(), ends()]);
await runTurn(deps(s), 'build', null, new AbortController().signal);
expect(s.context.filter((c) => c.includes('capture_viewport')).length).toBe(1);
});
diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.ts
index ea2a6a9b9..184fc7cd6 100644
--- a/desktop/tests/editor-mcp-tools.test.ts
+++ b/desktop/tests/editor-mcp-tools.test.ts
@@ -78,6 +78,27 @@ describe('editor MCP tool registry', () => {
expect(driver).not.toHaveBeenCalled();
});
+ // An argument nobody declared used to be dropped in silence, so a caller who
+ // assumed a parameter existed got `{ok:true}` proving it did — and
+ // `write_project_file` with an `offset` (which read_project_file really takes)
+ // overwrote the file it was meant to append to.
+ it('runTool refuses an argument the tool does not declare, naming the ones it does', async () => {
+ const driver = vi.fn();
+ const write = TOOLS.find((t: { name: string }) => t.name === 'write_project_file');
+ const res = await runTool(write, driver, { path: 'src/a.ts', content: 'x', offset: 40 });
+ expect(res.isError).toBe(true);
+ expect(res.content[0].text).toContain('offset');
+ expect(res.content[0].text).toContain('`path`');
+ expect(driver).not.toHaveBeenCalled();
+ });
+
+ it('runTool lets protocol metadata through', async () => {
+ const driver = vi.fn(async () => ({}));
+ const tree = TOOLS.find((t: { name: string }) => t.name === 'get_scene_tree');
+ const res = await runTool(tree, driver, { _meta: { progressToken: 1 } });
+ expect(res.isError).toBeUndefined();
+ });
+
it('runTool wraps a driver throw as an error result', async () => {
const driver = vi.fn(async () => { throw new Error('boom'); });
const tree = TOOLS.find((t: { name: string }) => t.name === 'get_scene_tree');
diff --git a/desktop/tests/project-fs.test.ts b/desktop/tests/project-fs.test.ts
index 06f5412ac..8f66c67a1 100644
--- a/desktop/tests/project-fs.test.ts
+++ b/desktop/tests/project-fs.test.ts
@@ -19,6 +19,7 @@ import {
duplicateInRoot,
statInRoot,
readSliceInRoot,
+ searchInRoot,
snapshotForTrash,
restoreTrashed,
} from '../electron/projectFs';
@@ -89,6 +90,57 @@ describe('content visibility (contentPolicy)', () => {
});
});
+describe('searchInRoot', () => {
+ beforeEach(() => {
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'src', 'systems.ts'), 'const s = defineSystem([]);\n');
+ mkdirSync(path.join(root, '.esengine', 'sdk', 'shared'), { recursive: true });
+ writeFileSync(
+ path.join(root, '.esengine', 'sdk', 'shared', 'app.d.ts'),
+ 'interface PrefabOverride {\n prefabEntityId: string;\n}\n',
+ );
+ mkdirSync(path.join(root, 'node_modules', 'dep'), { recursive: true });
+ writeFileSync(path.join(root, 'node_modules', 'dep', 'i.ts'), 'interface PrefabOverride {}\n');
+ });
+
+ it('finds the project\'s own source', async () => {
+ const hits = await searchInRoot(root, { query: 'defineSystem' });
+ expect(hits.map((h) => h.file)).toEqual(['src/systems.ts']);
+ expect(hits[0].line).toBe(1);
+ });
+
+ // The SDK types are what this tool exists for, and the dot-dir rule that keeps
+ // them out of the Content Browser was hiding them here too — so a search for a
+ // declaration the compiler had just named came back empty, which reads as "no
+ // such type" and sends the caller back to paging the .d.ts by line offset.
+ it('reaches the staged SDK types under .esengine/sdk', async () => {
+ const hits = await searchInRoot(root, { query: 'interface PrefabOverride' });
+ expect(hits.map((h) => h.file)).toContain('.esengine/sdk/shared/app.d.ts');
+ });
+
+ it('still stays out of node_modules', async () => {
+ const hits = await searchInRoot(root, { query: 'interface PrefabOverride' });
+ expect(hits.some((h) => h.file.startsWith('node_modules/'))).toBe(false);
+ });
+
+ it('skips the generated re-export barrels', async () => {
+ // One line of several hundred aliases matches every query and points at
+ // nothing; the declaration it re-exports is still found in its own file.
+ writeFileSync(
+ path.join(root, '.esengine', 'sdk', 'index.d.ts'),
+ `export { ${Array.from({ length: 60 }, (_, i) => `a${i} as Sym${i}, x${i} as PrefabOverride${i}`).join(', ')} } from './shared/app.js';\n`,
+ );
+ const hits = await searchInRoot(root, { query: 'PrefabOverride' });
+ expect(hits.map((h) => h.file)).toEqual(['.esengine/sdk/shared/app.d.ts']);
+ });
+
+ it('puts the project ahead of the SDK', async () => {
+ writeFileSync(path.join(root, 'src', 'own.ts'), 'interface PrefabOverride {}\n');
+ const hits = await searchInRoot(root, { query: 'interface PrefabOverride' });
+ expect(hits[0].file).toBe('src/own.ts');
+ });
+});
+
describe('isIgnoredPath (watcher noise filter)', () => {
it('ignores the editor cache + heavy dirs (no refresh loop)', () => {
// `.esengine` is where we write assets.json — refreshing on it would loop.
diff --git a/desktop/tests/script-service.test.ts b/desktop/tests/script-service.test.ts
index bdea528f9..a274a4cbe 100644
--- a/desktop/tests/script-service.test.ts
+++ b/desktop/tests/script-service.test.ts
@@ -140,6 +140,18 @@ describe('the project script service', () => {
}
});
+ // A class is only ever asked what you can CALL on it, and the declaration text
+ // answered with its private field block — the first 800 characters of AudioAPI
+ // are a dozen `private readonly`s, so "how do I play a sound" came back empty
+ // and the asker fell back to paging the .d.ts by line offset.
+ it('answers a class with its public members', () => {
+ if (!existsSync(SDK_TYPES)) return;
+ const hit = lookupScriptSymbol('AudioAPI', 2).find((h) => h.name === 'AudioAPI');
+ expect(!!hit).toBe(true);
+ expect(hit!.signature).toContain('playSFX');
+ expect(hit!.signature).not.toMatch(/private/);
+ });
+
it('knows which paths it has an opinion about', () => {
expect([isScriptPath('src/a.ts'), isScriptPath('assets/a.png'), isScriptPath('a.json')])
.toEqual([true, false, false]);