Skip to content

Commit e03abc8

Browse files
fix(mcp-server): resolve __dirname ReferenceError in ESM test context
In vitest (which runs TypeScript source as ESM), the CJS module-level __dirname variable is undefined. The bare reference threw a ReferenceError at module load time, failing all knowledge.test.ts tests. Use a try/catch so the ReferenceError is caught and the fallback derives the bundled knowledge path from process.cwd() (repo root in CI). The compiled esbuild CJS output is unaffected — __dirname remains valid there. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 2e705c4 commit e03abc8

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

packages/mcp-server/src/knowledge.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,18 @@ import path from "path";
1515
import yaml from "js-yaml";
1616
import type { KnowledgeConnector, KnowledgeEntry, FrameworkDefinition } from "./connectors/types.js";
1717

18+
// __dirname is a CJS module variable (available in the compiled esbuild CJS output).
19+
// In ESM contexts (vitest running TypeScript source) it is not defined — catch the
20+
// ReferenceError and fall back to a path relative to process.cwd() (repo root in CI).
21+
let _dirname: string;
22+
try {
23+
_dirname = __dirname; // works in compiled CJS (Node.js module scope)
24+
} catch {
25+
_dirname = path.join(process.cwd(), "packages/mcp-server/src");
26+
}
27+
1828
/** Bundled fallback — YAML files copied into dist/knowledge at build time. */
19-
export const BUNDLED_KNOWLEDGE = path.join(__dirname, "../knowledge");
29+
export const BUNDLED_KNOWLEDGE = path.join(_dirname, "../knowledge");
2030

2131
/** How long a successful load is considered fresh. */
2232
const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour

0 commit comments

Comments
 (0)