Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mcp-engine-import-conditions.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 7 additions & 0 deletions packages/e2e/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down Expand Up @@ -100,6 +106,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",
Expand Down
48 changes: 18 additions & 30 deletions packages/e2e/src/mcp/default-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 '@e2e-dev/core/lib/engine/contract';
import { isEngineHandle, type EngineHandle } from '@e2e-dev/core/lib/engine/index';
import { ConfigurationError, errorMessage, isE2EError } from '@e2e-dev/core/lib/internal/errors';

const ENGINE_CONDITIONS = [
'node',
'import',
...(process.features.require_module ? ['module-sync'] : []),
...(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. */
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$]*$/;
Expand Down Expand Up @@ -85,7 +93,7 @@ async function callFactory(ref: FactoryRef, lookup: EngineLookup, role: 'engine'
const entry = resolveEntry(ref.package, lookup, role);
let exports: Record<string, unknown>;
try {
exports = (await import(pathToFileURL(entry).href)) as Record<string, unknown>;
exports = (await import(entry)) as Record<string, unknown>;
} catch (cause) {
throw new ConfigurationError('INVALID_CONFIG', `package ${ref.package} (${entry}) failed to load: ${errorMessage(cause)}`, { cause });
}
Expand Down Expand Up @@ -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.
*/
Expand All @@ -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: ENGINE_CONDITIONS, 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: ${ENGINE_CONDITIONS.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.
Expand All @@ -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<string, unknown>)[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;
}
16 changes: 15 additions & 1 deletion packages/e2e/tests/integration/mcp-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>), CI: '' }, stderr: 'ignore' }));
const open = async (args: Record<string, unknown>): Promise<{ text: string; isError: boolean }> => {
Expand All @@ -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();
Expand Down
137 changes: 135 additions & 2 deletions packages/e2e/tests/unit/mcp-default-engine.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -21,7 +22,7 @@ function install(dir: string, name: string, source: string, subpaths: Readonly<R
}

beforeEach(() => {
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);
});
Expand Down Expand Up @@ -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`);
Expand Down Expand Up @@ -122,3 +156,102 @@ 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', 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: { [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]);',
'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', env: { ...process.env, NODE_OPTIONS: '', ...env } });
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, unknown>, 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],
['node-addons', { '.': { 'node-addons': './other.js', import: './outer.js' } }, 'other'],
['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', 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) {
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' });
});
});
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading