From b55cba1ac94387aac6b292d329a10cabf5ba4206 Mon Sep 17 00:00:00 2001 From: trevor Date: Fri, 13 Nov 2026 08:53:40 -0700 Subject: [PATCH 1/3] fix(mcp): resolve named engines using export conditions Resolve named MCP engine packages using ESM import conditions to match how the modules are loaded. --- .changeset/mcp-engine-import-conditions.md | 5 + packages/e2e/package.json | 1 + packages/e2e/src/mcp/default-engine.ts | 48 +++---- .../e2e/tests/integration/mcp-server.test.ts | 16 ++- .../e2e/tests/unit/mcp-default-engine.test.ts | 134 +++++++++++++++++- pnpm-lock.yaml | 8 ++ 6 files changed, 179 insertions(+), 33 deletions(-) create mode 100644 .changeset/mcp-engine-import-conditions.md diff --git a/.changeset/mcp-engine-import-conditions.md b/.changeset/mcp-engine-import-conditions.md new file mode 100644 index 0000000000..f8b2be5ea8 --- /dev/null +++ b/.changeset/mcp-engine-import-conditions.md @@ -0,0 +1,5 @@ +--- +"e2e": patch +--- + +When an engine package provides separate `import` and `require` entries, the MCP server now uses the `import` entry when opening a session without a config file. diff --git a/packages/e2e/package.json b/packages/e2e/package.json index 32abbed8b9..1e39447f83 100644 --- a/packages/e2e/package.json +++ b/packages/e2e/package.json @@ -100,6 +100,7 @@ "@oxc-project/runtime": "0.158.0", "@vitest/expect": "5.1.0", "commander": "15.1.0", + "exsolve": "1.2.0", "get-tsconfig": "4.14.3", "oxc-parser": "0.158.0", "oxc-transform": "0.158.0", diff --git a/packages/e2e/src/mcp/default-engine.ts b/packages/e2e/src/mcp/default-engine.ts index 4931780300..cb4f7534d3 100644 --- a/packages/e2e/src/mcp/default-engine.ts +++ b/packages/e2e/src/mcp/default-engine.ts @@ -7,15 +7,23 @@ * already on disk is loaded. */ -import { existsSync, readFileSync } from 'node:fs'; -import { createRequire, isBuiltin } from 'node:module'; +import { existsSync } from 'node:fs'; +import { isBuiltin } from 'node:module'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { resolveModuleURL } from 'exsolve'; import { ENGINE_SPI_VERSION } from '../engine/contract.ts'; import { isEngineHandle, type EngineHandle } from '../engine/index.ts'; import { ConfigurationError, errorMessage, isE2EError } from '../internal/errors.ts'; +/** Returns the Node export conditions used for dynamic imports. */ +function importConditions(): readonly string[] { + return process.features.require_module ? ['node', 'import', 'module-sync'] : ['node', 'import']; +} + +const engineConditions: readonly string[] = importConditions(); + /** npm's package name grammar with an optional subpath, so a path, a URL, or a `..` segment is never resolved. */ const PACKAGE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:\/[A-Za-z0-9][A-Za-z0-9._~-]*)*$/; const EXPORT_NAME = /^[A-Za-z_$][\w$]*$/; @@ -85,7 +93,7 @@ async function callFactory(ref: FactoryRef, lookup: EngineLookup, role: 'engine' const entry = resolveEntry(ref.package, lookup, role); let exports: Record; try { - exports = (await import(pathToFileURL(entry).href)) as Record; + exports = (await import(entry)) as Record; } catch (cause) { throw new ConfigurationError('INVALID_CONFIG', `package ${ref.package} (${entry}) failed to load: ${errorMessage(cause)}`, { cause }); } @@ -145,7 +153,7 @@ function describe(ref: FactoryRef): string { } /** - * The package's entry file, from the first place that has the package + * The package's entry URL, from the first place that has the package * installed. A package that is there but has no loadable entry is an error * of its own, never a reason to look further or to install it again. */ @@ -157,12 +165,13 @@ function resolveEntry(name: string, lookup: EngineLookup, role: 'engine' | 'opti if (directory === undefined) continue; try { // The file need not exist: it only says which node_modules directories to walk. - return createRequire(path.join(root, 'package.json')).resolve(name); + return resolveModuleURL(name, { from: pathToFileURL(path.join(root, 'package.json')), conditions: [...engineConditions], cache: false }); } catch (cause) { - // `require` conditions miss an entry a package exports to `import` alone. - const imported = (cause as NodeJS.ErrnoException).code === 'ERR_PACKAGE_PATH_NOT_EXPORTED' ? importEntry(directory, name.slice(installable.length)) : undefined; - if (imported !== undefined) return imported; - throw new ConfigurationError('INVALID_CONFIG', `package ${name} is installed at ${directory} but its entry cannot be resolved: ${errorMessage(cause)}`, { cause }); + throw new ConfigurationError( + 'INVALID_CONFIG', + `package ${name} is installed at ${directory} but its entry cannot be resolved (conditions: ${engineConditions.join(', ')}): ${errorMessage(cause)}. Check the package's exports and entry files`, + { cause }, + ); } } // An option is only read as a call by its shape, so the message says how it was read before it names a command. @@ -181,24 +190,3 @@ function installedAt(name: string, root: string): string | undefined { if (path.dirname(directory) === directory) return undefined; } } - -/** The file `subpath` (`''` for the main entry) of the package at `directory` exports to `import`, when its `exports` names one. */ -function importEntry(directory: string, subpath: string): string | undefined { - const manifest: unknown = JSON.parse(readFileSync(path.join(directory, 'package.json'), 'utf8')); - const exports = typeof manifest === 'object' && manifest !== null && 'exports' in manifest ? manifest.exports : undefined; - const key = `.${subpath}`; - const keyed = typeof exports === 'object' && exports !== null && !Array.isArray(exports) && Object.keys(exports).some((entry) => entry.startsWith('.')); - const target = importTarget(keyed ? (exports as Record)[key] : key === '.' ? exports : undefined); - return target === undefined ? undefined : path.join(directory, target); -} - -/** The first target an `import` of this `exports` value selects: a path, or the first matching condition's, in the order written. */ -function importTarget(value: unknown): string | undefined { - if (typeof value === 'string') return value; - if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined; - for (const [condition, target] of Object.entries(value)) { - const selected = condition === 'import' || condition === 'node' || condition === 'default' ? importTarget(target) : undefined; - if (selected !== undefined) return selected; - } - return undefined; -} diff --git a/packages/e2e/tests/integration/mcp-server.test.ts b/packages/e2e/tests/integration/mcp-server.test.ts index 32973f0fa4..b75a8bb394 100644 --- a/packages/e2e/tests/integration/mcp-server.test.ts +++ b/packages/e2e/tests/integration/mcp-server.test.ts @@ -552,7 +552,12 @@ describe('e2e mcp', { timeout: 120_000 }, () => { }); it('opens a session on a named engine in a directory with no config, and says how to get one otherwise', async () => { - const bare = createProject({ 'README.md': 'no config here\n' }); + const bare = createProject({ + 'README.md': 'no config here\n', + 'node_modules/dual-engine/package.json': JSON.stringify({ name: 'dual-engine', version: '0.0.0', type: 'module', exports: { import: './index.js', require: './index.cjs' } }), + 'node_modules/dual-engine/index.js': "export { web as default } from '@e2e-dev/web';\n", + 'node_modules/dual-engine/index.cjs': "throw new Error('the require entry was loaded');\n", + }); const other = new Client({ name: 'e2e-mcp-bare-test', version: '0.0.0' }); await other.connect(new StdioClientTransport({ command: process.execPath, args: [CLI, 'mcp'], cwd: bare.dir, env: { ...(process.env as Record), CI: '' }, stderr: 'ignore' })); const open = async (args: Record): Promise<{ text: string; isError: boolean }> => { @@ -574,6 +579,15 @@ describe('e2e mcp', { timeout: 120_000 }, () => { expect(opened.isError, opened.text).toBe(false); expect(opened.text).toMatch(/^Session \S+ open on target "web" \(platform web, engine web [^)]+\), headless; no config file: one target on @e2e-dev\/web, every other setting at its default\./); expect(opened.text).toContain('button "Increment"'); + const closed = (await other.callTool({ name: 'close_session', arguments: {} })) as { isError?: boolean }; + expect(closed.isError).not.toBe(true); + + const dual = await open({ engine: 'dual-engine', app: { url: app.url } }); + expect(dual.isError, dual.text).toBe(false); + expect(dual.text).toMatch(/^Session \S+ open on target "web" \(platform web, engine web [^)]+\), headless; no config file: one target on dual-engine, every other setting at its default\./); + expect(dual.text).toContain('button "Increment"'); + const closedDual = (await other.callTool({ name: 'close_session', arguments: {} })) as { isError?: boolean }; + expect(closedDual.isError).not.toBe(true); } finally { await other.close(); bare.cleanup(); diff --git a/packages/e2e/tests/unit/mcp-default-engine.test.ts b/packages/e2e/tests/unit/mcp-default-engine.test.ts index 3645f4570e..bb607355ff 100644 --- a/packages/e2e/tests/unit/mcp-default-engine.test.ts +++ b/packages/e2e/tests/unit/mcp-default-engine.test.ts @@ -1,4 +1,5 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -21,7 +22,7 @@ function install(dir: string, name: string, source: string, subpaths: Readonly { - root = mkdtempSync(path.join(os.tmpdir(), 'e2e-default-engine-')); + root = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'e2e-default-engine-'))); lookup = { cwd: path.join(root, 'project'), enginesDir: path.join(root, 'engines') }; mkdirSync(lookup.cwd); }); @@ -49,6 +50,39 @@ describe('loadEngine', () => { expect(await loadEngine({ package: 'esm-only/web' }, lookup)).toMatchObject({ name: 'from-subpath' }); }); + it.each([ + ['dual', 'import'], + ['dual/web', 'import'], + ['dual', 'require'], + ['dual/web', 'require'], + ])('loads the import entry of %s when %s is declared first', async (specifier, first) => { + const dir = path.join(lookup.cwd, 'node_modules', 'dual'); + mkdirSync(dir, { recursive: true }); + const entry = (base: string) => first === 'import' ? { import: `./${base}.js`, require: `./${base}.cjs` } : { require: `./${base}.cjs`, import: `./${base}.js` }; + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'dual', version: '0.0.0', type: 'module', exports: { '.': entry('index'), './web': entry('web') } })); + for (const base of ['index', 'web']) { + writeFileSync(path.join(dir, `${base}.js`), FACTORY.replace("'fake'", "'esm'")); + writeFileSync(path.join(dir, `${base}.cjs`), FACTORY.replace('export default', 'module.exports =').replace("'fake'", "'cjs'")); + } + expect(await loadEngine({ package: specifier }, lookup)).toMatchObject({ name: 'esm' }); + }); + + it.each([null, './missing.js', '../outside.js'])('rejects an import target of %s without bypassing it for require', async (target) => { + const dir = path.join(lookup.cwd, 'node_modules', 'broken'); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'broken', type: 'module', exports: { import: target, require: './index.cjs' } })); + writeFileSync(path.join(dir, 'index.cjs'), FACTORY.replace('export default', 'module.exports =')); + await expect(loadEngine({ package: 'broken' }, lookup)).rejects.toMatchObject({ code: 'INVALID_CONFIG', message: expect.stringContaining('but its entry cannot be resolved') }); + }); + + it('loads a legacy CommonJS package with a main entry', async () => { + const dir = path.join(lookup.cwd, 'node_modules', 'legacy'); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'legacy', version: '0.0.0', main: 'index.cjs' })); + writeFileSync(path.join(dir, 'index.cjs'), FACTORY.replace('export default', 'module.exports =').replace("'fake'", "'legacy'")); + expect(await loadEngine({ package: 'legacy' }, lookup)).toMatchObject({ name: 'legacy' }); + }); + it('makes the factory calls among the options first, so an engine gets a provider JSON cannot carry', async () => { install(lookup.cwd, 'engine', FACTORY); install(lookup.enginesDir, 'cloud', `export const devices = (options) => ({ name: 'cloud', region: options?.region, acquire: () => 'leased' });\n`); @@ -122,3 +156,99 @@ describe('loadEngine', () => { await expect(loadEngine({ package: 'old-contract' }, lookup)).rejects.toMatchObject({ code: 'INVALID_CONFIG', message: expect.stringContaining('engine contract 0') }); }); }); + +describe('loadEngine runtime export conditions', () => { + it.each([ + { label: 'the defaults', flags: [], expected: process.features.require_module ? 'native' : 'fallback' }, + { label: '--no-experimental-require-module', flags: ['--no-experimental-require-module'], expected: 'fallback' }, + ])('loads what native import resolves under $label', ({ flags, expected }) => { + const dir = path.join(lookup.cwd, 'node_modules', 'cond'); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'cond', type: 'module', exports: { 'module-sync': './native.js', default: './fallback.js' } })); + for (const name of ['native', 'fallback']) writeFileSync(path.join(dir, name + '.js'), FACTORY.replace('fake', name)); + const program = [ + 'const { loadEngine } = await import(process.argv[1]);', + 'const native = (await import("cond")).default({}).name;', + 'const loaded = (await loadEngine({ package: "cond" }, { cwd: process.cwd(), enginesDir: process.cwd() })).name;', + 'console.log(JSON.stringify({ native, loaded }));', + ].join('\n'); + const loader = new URL('../../src/mcp/default-engine.ts', import.meta.url).href; + const child = spawnSync(process.execPath, [...flags, '--input-type=module', '-e', program, '--', loader], { cwd: lookup.cwd, encoding: 'utf8' }); + expect(child.status, child.stderr).toBe(0); + expect(JSON.parse(child.stdout.trim())).toEqual({ native: expected, loaded: expected }); + }); +}); + +describe('loadEngine nested export conditions', () => { + const NESTED: [string, Record, string | null][] = [ + ['subpath/web', { '.': { import: './outer.js' }, './web': { node: { require: './inner.cjs' }, import: './other.js' } }, 'other'], + ['deep', { '.': { node: { default: { require: './inner.cjs' } }, import: './outer.js' } }, 'outer'], + ['array', { '.': { node: [{ require: './inner.cjs' }, { custom: './other.js' }], import: './outer.js' } }, 'outer'], + ['inner-require', { '.': { node: { require: './inner.cjs' }, import: './outer.js' } }, 'outer'], + ['inner-null', { '.': { node: { require: null }, import: './outer.js' } }, 'outer'], + ['active-null', { '.': { node: { import: null }, default: './outer.js' } }, null], + ['null-array', { '.': { node: [null], import: './outer.js' } }, null], + ['empty-array', { '.': { node: [], import: './outer.js' } }, null], + ['blocked-subpath/web', { '.': { import: './outer.js' }, './web': null }, null], + ['require-only', { '.': { require: './inner.cjs' } }, null], + ]; + + const PROGRAM = [ + 'const { loadEngine } = await import(process.argv[1]);', + 'const spec = process.argv[2];', + 'const lookup = { cwd: process.cwd(), enginesDir: process.cwd() };', + 'const native = await import(spec).then((m) => m.default({}).name, (e) => ({ code: e.code }));', + 'const loaded = await loadEngine({ package: spec }, lookup).then((e) => e.name, (e) => ({ code: e.code, message: e.message }));', + 'console.log(JSON.stringify({ native, loaded }));', + ].join('\n'); + + it.each(NESTED)('loads %s as a native import does', (spec, exports, expected) => { + const name = spec.split('/')[0] ?? spec; + const dir = path.join(lookup.cwd, 'node_modules', name); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name, type: 'module', exports })); + writeFileSync(path.join(dir, 'outer.js'), FACTORY.replace('fake', 'outer')); + writeFileSync(path.join(dir, 'other.js'), FACTORY.replace('fake', 'other')); + writeFileSync(path.join(dir, 'inner.cjs'), FACTORY.replace('export default', 'module.exports =').replace('fake', 'inner')); + const loader = new URL('../../src/mcp/default-engine.ts', import.meta.url).href; + const child = spawnSync(process.execPath, ['--input-type=module', '-e', PROGRAM, '--', loader, spec], { cwd: lookup.cwd, encoding: 'utf8' }); + expect(child.status, child.stderr).toBe(0); + const { native, loaded } = JSON.parse(child.stdout.trim()) as { native: unknown; loaded: unknown }; + if (expected !== null) { + expect(native).toBe(expected); + expect(loaded).toBe(expected); + return; + } + expect(native).toMatchObject({ code: 'ERR_PACKAGE_PATH_NOT_EXPORTED' }); + expect(loaded).toMatchObject({ code: 'INVALID_CONFIG', message: expect.stringContaining('package ' + spec + ' is installed at ' + dir + ' but its entry cannot be resolved') }); + }); + + it('reports the first installed copy whose conditions block the entry, and looks no further for it', async () => { + const dir = path.join(lookup.cwd, 'node_modules', 'refused'); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'refused', type: 'module', exports: { '.': { node: { import: null }, default: './index.js' } } })); + writeFileSync(path.join(dir, 'index.js'), FACTORY); + install(lookup.enginesDir, 'refused', FACTORY); + await expect(loadEngine({ package: 'refused' }, lookup)).rejects.toMatchObject({ + code: 'INVALID_CONFIG', + message: expect.stringContaining('is installed at ' + dir + ' but its entry cannot be resolved'), + }); + }); + + it('resolves entries again after files or manifests change', async () => { + install(lookup.cwd, 'late', FACTORY, {}, 'import'); + rmSync(path.join(lookup.cwd, 'node_modules', 'late', 'index.js')); + await expect(loadEngine({ package: 'late' }, lookup)).rejects.toMatchObject({ code: 'INVALID_CONFIG' }); + writeFileSync(path.join(lookup.cwd, 'node_modules', 'late', 'index.js'), FACTORY.replace('fake', 'late')); + expect(await loadEngine({ package: 'late' }, lookup)).toMatchObject({ name: 'late' }); + + const dir = path.join(lookup.cwd, 'node_modules', 'swap'); + mkdirSync(dir, { recursive: true }); + for (const name of ['a', 'b']) writeFileSync(path.join(dir, name + '.js'), FACTORY.replace('fake', name)); + const manifest = (entry: string) => JSON.stringify({ name: 'swap', type: 'module', exports: { '.': { import: './' + entry + '.js' } } }); + writeFileSync(path.join(dir, 'package.json'), manifest('a')); + expect(await loadEngine({ package: 'swap' }, lookup)).toMatchObject({ name: 'a' }); + writeFileSync(path.join(dir, 'package.json'), manifest('b')); + expect(await loadEngine({ package: 'swap' }, lookup)).toMatchObject({ name: 'b' }); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c1f80bf64c..4714e81259 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -523,6 +523,9 @@ importers: commander: specifier: 15.1.0 version: 15.1.0 + exsolve: + specifier: 1.2.0 + version: 1.2.0 get-tsconfig: specifier: 4.14.3 version: 4.14.3 @@ -3755,6 +3758,9 @@ packages: exponential-backoff@3.1.3: resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==} + exsolve@1.2.0: + resolution: {integrity: sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg==} + extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} @@ -8431,6 +8437,8 @@ snapshots: exponential-backoff@3.1.3: {} + exsolve@1.2.0: {} + extend@3.0.2: {} fallow-type-aware@3.42.0: From 0a6bbadf8acf74b293b4ebcfab4d377e686cf366 Mon Sep 17 00:00:00 2001 From: trevor Date: Sat, 14 Nov 2026 09:11:30 -0700 Subject: [PATCH 2/3] fix(mcp): match Node's default node-addons condition --- packages/e2e/src/mcp/default-engine.ts | 16 ++++++++-------- .../e2e/tests/unit/mcp-default-engine.test.ts | 1 + 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/e2e/src/mcp/default-engine.ts b/packages/e2e/src/mcp/default-engine.ts index cb4f7534d3..eb3b7a277a 100644 --- a/packages/e2e/src/mcp/default-engine.ts +++ b/packages/e2e/src/mcp/default-engine.ts @@ -17,12 +17,12 @@ import { ENGINE_SPI_VERSION } from '../engine/contract.ts'; import { isEngineHandle, type EngineHandle } from '../engine/index.ts'; import { ConfigurationError, errorMessage, isE2EError } from '../internal/errors.ts'; -/** Returns the Node export conditions used for dynamic imports. */ -function importConditions(): readonly string[] { - return process.features.require_module ? ['node', 'import', 'module-sync'] : ['node', 'import']; -} - -const engineConditions: readonly string[] = importConditions(); +const ENGINE_CONDITIONS = [ + 'node', + 'import', + ...(process.features.require_module ? ['module-sync'] : []), + 'node-addons', +]; /** npm's package name grammar with an optional subpath, so a path, a URL, or a `..` segment is never resolved. */ const PACKAGE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:\/[A-Za-z0-9][A-Za-z0-9._~-]*)*$/; @@ -165,11 +165,11 @@ function resolveEntry(name: string, lookup: EngineLookup, role: 'engine' | 'opti if (directory === undefined) continue; try { // The file need not exist: it only says which node_modules directories to walk. - return resolveModuleURL(name, { from: pathToFileURL(path.join(root, 'package.json')), conditions: [...engineConditions], cache: false }); + return resolveModuleURL(name, { from: pathToFileURL(path.join(root, 'package.json')), conditions: ENGINE_CONDITIONS, cache: false }); } catch (cause) { throw new ConfigurationError( 'INVALID_CONFIG', - `package ${name} is installed at ${directory} but its entry cannot be resolved (conditions: ${engineConditions.join(', ')}): ${errorMessage(cause)}. Check the package's exports and entry files`, + `package ${name} is installed at ${directory} but its entry cannot be resolved (conditions: ${ENGINE_CONDITIONS.join(', ')}): ${errorMessage(cause)}. Check the package's exports and entry files`, { cause }, ); } diff --git a/packages/e2e/tests/unit/mcp-default-engine.test.ts b/packages/e2e/tests/unit/mcp-default-engine.test.ts index bb607355ff..d332617a09 100644 --- a/packages/e2e/tests/unit/mcp-default-engine.test.ts +++ b/packages/e2e/tests/unit/mcp-default-engine.test.ts @@ -190,6 +190,7 @@ describe('loadEngine nested export conditions', () => { ['null-array', { '.': { node: [null], import: './outer.js' } }, null], ['empty-array', { '.': { node: [], import: './outer.js' } }, null], ['blocked-subpath/web', { '.': { import: './outer.js' }, './web': null }, null], + ['node-addons', { '.': { 'node-addons': './other.js', import: './outer.js' } }, 'other'], ['require-only', { '.': { require: './inner.cjs' } }, null], ]; From 5b466791cc34a83541fe249e89929d9e50751f0f Mon Sep 17 00:00:00 2001 From: trevor Date: Sat, 14 Nov 2026 13:11:21 -0700 Subject: [PATCH 3/3] fix(mcp): detect effective node-addons condition --- packages/e2e/package.json | 6 ++++++ packages/e2e/src/mcp/default-engine.ts | 2 +- packages/e2e/tests/unit/mcp-default-engine.test.ts | 14 ++++++++------ 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/packages/e2e/package.json b/packages/e2e/package.json index 1e39447f83..4e4aed9517 100644 --- a/packages/e2e/package.json +++ b/packages/e2e/package.json @@ -73,6 +73,12 @@ "default": "./dist/oauth/opencode-console.js" } }, + "imports": { + "#e2e-node-addons": { + "node-addons": "fs", + "default": "path" + } + }, "bin": { "e2e": "./dist/cli/bin.js" }, diff --git a/packages/e2e/src/mcp/default-engine.ts b/packages/e2e/src/mcp/default-engine.ts index eb3b7a277a..1301dab77c 100644 --- a/packages/e2e/src/mcp/default-engine.ts +++ b/packages/e2e/src/mcp/default-engine.ts @@ -21,7 +21,7 @@ const ENGINE_CONDITIONS = [ 'node', 'import', ...(process.features.require_module ? ['module-sync'] : []), - 'node-addons', + ...(import.meta.resolve('#e2e-node-addons') === 'node:fs' ? ['node-addons'] : []), ]; /** npm's package name grammar with an optional subpath, so a path, a URL, or a `..` segment is never resolved. */ diff --git a/packages/e2e/tests/unit/mcp-default-engine.test.ts b/packages/e2e/tests/unit/mcp-default-engine.test.ts index d332617a09..1126cc0b65 100644 --- a/packages/e2e/tests/unit/mcp-default-engine.test.ts +++ b/packages/e2e/tests/unit/mcp-default-engine.test.ts @@ -159,12 +159,14 @@ describe('loadEngine', () => { describe('loadEngine runtime export conditions', () => { it.each([ - { label: 'the defaults', flags: [], expected: process.features.require_module ? 'native' : 'fallback' }, - { label: '--no-experimental-require-module', flags: ['--no-experimental-require-module'], expected: 'fallback' }, - ])('loads what native import resolves under $label', ({ flags, expected }) => { + { label: 'the defaults', condition: 'module-sync', flags: [], env: {}, expected: 'native' }, + { label: '--no-experimental-require-module', condition: 'module-sync', flags: ['--no-experimental-require-module'], env: {}, expected: 'fallback' }, + { label: '--no-addons', condition: 'node-addons', flags: ['--no-addons'], env: {}, expected: 'fallback' }, + { label: 'NODE_OPTIONS=--no-addons', condition: 'node-addons', flags: [], env: { NODE_OPTIONS: '--no-addons' }, expected: 'fallback' }, + ])('loads what native import resolves under $label', ({ condition, flags, env, expected }) => { const dir = path.join(lookup.cwd, 'node_modules', 'cond'); mkdirSync(dir, { recursive: true }); - writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'cond', type: 'module', exports: { 'module-sync': './native.js', default: './fallback.js' } })); + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'cond', type: 'module', exports: { [condition]: './native.js', default: './fallback.js' } })); for (const name of ['native', 'fallback']) writeFileSync(path.join(dir, name + '.js'), FACTORY.replace('fake', name)); const program = [ 'const { loadEngine } = await import(process.argv[1]);', @@ -173,7 +175,7 @@ describe('loadEngine runtime export conditions', () => { 'console.log(JSON.stringify({ native, loaded }));', ].join('\n'); const loader = new URL('../../src/mcp/default-engine.ts', import.meta.url).href; - const child = spawnSync(process.execPath, [...flags, '--input-type=module', '-e', program, '--', loader], { cwd: lookup.cwd, encoding: 'utf8' }); + const child = spawnSync(process.execPath, [...flags, '--input-type=module', '-e', program, '--', loader], { cwd: lookup.cwd, encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '', ...env } }); expect(child.status, child.stderr).toBe(0); expect(JSON.parse(child.stdout.trim())).toEqual({ native: expected, loaded: expected }); }); @@ -212,7 +214,7 @@ describe('loadEngine nested export conditions', () => { writeFileSync(path.join(dir, 'other.js'), FACTORY.replace('fake', 'other')); writeFileSync(path.join(dir, 'inner.cjs'), FACTORY.replace('export default', 'module.exports =').replace('fake', 'inner')); const loader = new URL('../../src/mcp/default-engine.ts', import.meta.url).href; - const child = spawnSync(process.execPath, ['--input-type=module', '-e', PROGRAM, '--', loader, spec], { cwd: lookup.cwd, encoding: 'utf8' }); + const child = spawnSync(process.execPath, ['--input-type=module', '-e', PROGRAM, '--', loader, spec], { cwd: lookup.cwd, encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '' } }); expect(child.status, child.stderr).toBe(0); const { native, loaded } = JSON.parse(child.stdout.trim()) as { native: unknown; loaded: unknown }; if (expected !== null) {