Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: MCP servers on the new engine follow the server's list

ogsamrat182141f8dec3
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index b2b2f4b9..a12af046 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -736,8 +736,6 @@ export type OmniRushMcpPolicyView = {
mode: "allowlist" | "disabled";
enabled: boolean;
message: string | null;
- /** The preview engine routes chats: MCP stays off there. */
- engineV2?: boolean;
supported: OmniRushMcpPreset[];
decisions: OmniRushMcpDecision[];
reportAt: number | null;
diff --git a/apps/app/src/react-app/domains/settings/pages/mcp-supported-panel.tsx b/apps/app/src/react-app/domains/settings/pages/mcp-supported-panel.tsx
index bdd40d2c..5ef3be89 100644
--- a/apps/app/src/react-app/domains/settings/pages/mcp-supported-panel.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/mcp-supported-panel.tsx
@@ -18,9 +18,6 @@ export const MCP_REMOTE_NOT_SUPPORTED =
export const MCP_ACCOUNT_NOTE =
"These use your own account, so a session with them cannot be repeated from the project. Keys and sign-ins stay on this computer: never in a config file.";
-export const MCP_ENGINE_V2_NOTE =
- "MCP servers are off while the preview engine runs chats. Turn the preview engine off to use them.";
-
/** What to do about a blocked server, by decision code (the reason says why). */
export const MCP_BLOCKED_HINTS: Record<string, string> = {
denied: "Not on the supported list.",
@@ -144,9 +141,6 @@ export function McpSupportedPanel(props: {
<div data-testid="mcp-supported-panel" className="mb-6 flex flex-col gap-5">
{filterMissing}
{ignoredNotice}
- {props.policy.engineV2 ? (
- <p data-testid="mcp-engine-v2-note" className="text-sm text-dls-secondary">{MCP_ENGINE_V2_NOTE}</p>
- ) : null}
{props.servers.length > 0 ? (
<div className="flex flex-col gap-2">
diff --git a/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx b/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx
index bbf7d9cf..5b50578a 100644
--- a/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx
@@ -1579,7 +1579,7 @@ export function McpView(props: McpViewProps) {
<McpSupportedPanel
policy={mcpPolicy}
servers={props.mcpServers.filter((entry) => !isConnectDirectMcpServerName(entry.name) && entry.name !== "omnirush-cloud")}
- canAdd={props.allowManageExtensions && !props.isRemoteWorkspace && mcpPolicy.engineV2 !== true}
+ canAdd={props.allowManageExtensions && !props.isRemoteWorkspace}
busy={props.busy}
addPreset={addSupportedMcp}
signIn={signInSupportedMcp}
diff --git a/apps/app/tests/mcp-supported-panel.test.tsx b/apps/app/tests/mcp-supported-panel.test.tsx
index 958f08ef..c6faef9d 100644
--- a/apps/app/tests/mcp-supported-panel.test.tsx
+++ b/apps/app/tests/mcp-supported-panel.test.tsx
@@ -5,7 +5,6 @@ import type { OmniRushMcpPolicyView, OmniRushMcpPreset } from "../src/app/lib/om
import type { McpServerEntry } from "../src/app/types";
import {
MCP_BLOCKED_HINTS,
- MCP_ENGINE_V2_NOTE,
MCP_REMOTE_NOT_SUPPORTED,
McpSupportedPanel,
mcpServerState,
@@ -28,7 +27,7 @@ const filesystem: OmniRushMcpPreset = {
const sqlite: OmniRushMcpPreset = { ...filesystem, id: "sqlite", title: "SQLite", why: null, package: "mcp-server-sqlite-npx", version: "0.8.0", command: ["npx", "-y", "mcp-server-sqlite-npx", "data.db"] };
function policy(overrides: Partial<OmniRushMcpPolicyView> = {}): OmniRushMcpPolicyView {
- return { mode: "allowlist", enabled: true, message: null, engineV2: false, supported: [filesystem, sqlite], decisions: [], reportAt: null, ...overrides };
+ return { mode: "allowlist", enabled: true, message: null, supported: [filesystem, sqlite], decisions: [], reportAt: null, ...overrides };
}
const render = (props: Partial<Parameters<typeof McpSupportedPanel>[0]> = {}) => renderToStaticMarkup(
@@ -85,12 +84,6 @@ describe("Settings > MCP: supported servers", () => {
expect(html).toMatch(/data-testid="mcp-preset-filesystem".*Added/s);
});
- test("the preview engine: MCP stays off there, and nothing is offered", () => {
- const html = render({ policy: policy({ engineV2: true }), canAdd: false });
- expect(html).toContain(MCP_ENGINE_V2_NOTE);
- expect(html).not.toContain(">Add<");
- });
-
test("a blocked row says why and what to do", () => {
expect(mcpServerState(server("gh"), { name: "gh", status: "blocked", code: "denied", reason: "The GitHub server works on your GitHub account." }))
.toEqual({ kind: "blocked", reason: "The GitHub server works on your GitHub account.", hint: "Not on the supported list." });
diff --git a/apps/server/src/engine-v2-mcp.ts b/apps/server/src/engine-v2-mcp.ts
new file mode 100644
index 00000000..f2c6b984
--- /dev/null
+++ b/apps/server/src/engine-v2-mcp.ts
@@ -0,0 +1,78 @@
+/**
+ * MCP on the 2.x engine. Its plugins have no config hook, so the server applies the allowlist itself:
+ * - the engine's gate (engine-gates.mjs) names the servers it may start at all: the server list's ids,
+ * plus the built-in computer use server while it is on;
+ * - each project's servers (the ones added in the app) go through the same filter as on the 1.x engine
+ * (mcp-allow.mjs, which also writes the report Settings > MCP shows) and reach the engine through its
+ * runtime MCP API, as direct tools (`codemode: false`: calls stay `<server>_<tool>`, never Code Mode).
+ * The engine starts a local server with its own environment under the entry's: the app's secrets are set
+ * empty there, and the server's own values come from the person's environment (env-only filtering).
+ */
+import { computerUseBuiltins, computerUseDir } from "./computer-use/desktop.js";
+import { SERVER_ID } from "./computer-use/shared/contract.mjs";
+import { createMcpPolicyHooks, mcpServerEnvironment } from "./mcp-allow/mcp-allow.mjs";
+import { currentMcpPolicy, mcpPolicyFile, mcpReportDir, mcpWorkspaceDir, readWorkspaceMcp } from "./mcp-allow/state.js";
+
+const GATE_NAME = /^[A-Za-z0-9_.-]+$/;
+const APP_SECRET_NAME = /^(?:OMNIRUSH_|OPENCODE_)/i;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/** The names the engine's gate allows (fixed for the engine's lifetime). */
+export function v2McpGate(stateDir: string, env: Record<string, string | undefined> = process.env): string[] {
+ const policy = currentMcpPolicy(stateDir);
+ const ids = policy?.enabled ? policy.allow.map((entry) => entry.id) : [];
+ const computerUse = computerUseBuiltins(computerUseDir(stateDir), env)[SERVER_ID] ? [SERVER_ID] : [];
+ return [...new Set([...ids, ...computerUse])].filter((name) => GATE_NAME.test(name)).sort();
+}
+
+/** One server's 2.x runtime config (the same fields the 1.x engine had), always a direct-tool server. */
+export function v2McpConfig(value: Record<string, unknown>, engineEnv: Record<string, string>): Record<string, unknown> | null {
+ const timeout = typeof value.timeout === "number" && value.timeout > 0 ? { timeout: { startup: value.timeout, catalog: value.timeout, execution: value.timeout } } : {};
+ if (value.type === "remote" && typeof value.url === "string") {
+ return { type: "remote", url: value.url, ...(value.oauth === false ? { oauth: false } : {}), ...(value.enabled === false ? { disabled: true } : {}), codemode: false, ...timeout };
+ }
+ if (!Array.isArray(value.command) || value.command.length === 0 || !value.command.every((part) => typeof part === "string" && part)) return null;
+ const own = isRecord(value.environment)
+ ? Object.fromEntries(Object.entries(value.environment).filter((entry): entry is [string, string] => typeof entry[1] === "string"))
+ : {};
+ // The engine's own secrets (its password, the app's tokens) are empty for the server.
+ for (const key of Object.keys(engineEnv)) if (APP_SECRET_NAME.test(key) && !(key in own)) own[key] = "";
+ return {
+ type: "local", command: value.command, environment: own,
+ ...(typeof value.cwd === "string" ? { cwd: value.cwd } : {}),
+ ...(value.enabled === false ? { disabled: true } : {}),
+ codemode: false, ...timeout,
+ };
+}
+
+/** The servers a project gets on the 2.x engine, by name; fails closed (no servers) on any error. */
+export async function desiredV2Mcp(stateDir: string, root: string, engineEnv: Record<string, string>, gate: readonly string[]): Promise<Record<string, Record<string, unknown>>> {
+ try {
+ const target: Record<string, unknown> = { mcp: readWorkspaceMcp(mcpWorkspaceDir(stateDir), root) };
+ // The built-in's name belongs to the app.
+ target.mcp = Object.fromEntries(Object.entries(target.mcp as Record<string, unknown>).filter(([name]) => !name.toLowerCase().startsWith(SERVER_ID)));
+ const hooks = createMcpPolicyHooks({
+ directory: root, policyFile: mcpPolicyFile(stateDir), reportDir: mcpReportDir(stateDir),
+ // The engine adds its whole environment under the entry's: values the server needs come from the person's.
+ envOnly: true, filterRequired: false,
+ });
+ await hooks.config(target, undefined);
+ const allowed: Record<string, Record<string, unknown>> = isRecord(target.mcp) ? (target.mcp as Record<string, Record<string, unknown>>) : {};
+ const builtin = computerUseBuiltins(computerUseDir(stateDir))[SERVER_ID];
+ if (builtin) {
+ const own = isRecord(builtin.environment) ? Object.fromEntries(Object.entries(builtin.environment).filter((entry): entry is [string, string] => typeof entry[1] === "string")) : {};
+ allowed[SERVER_ID] = { ...builtin, environment: { ...mcpServerEnvironment(process.env, {}, [], process.platform, { envOnly: true }), ...own } };
+ }
+ const out: Record<string, Record<string, unknown>> = {};
+ for (const [name, value] of Object.entries(allowed)) {
+ const config = isRecord(value) && gate.includes(name) ? v2McpConfig(value, engineEnv) : null;
+ if (config) out[name] = config;
+ }
+ return out;
+ } catch {
+ return {};
+ }
+}
diff --git a/apps/server/src/engine-v2-next.test.ts b/apps/server/src/engine-v2-next.test.ts
index 84a66c97..4da618a1 100644
--- a/apps/server/src/engine-v2-next.test.ts
+++ b/apps/server/src/engine-v2-next.test.ts
@@ -93,3 +93,27 @@ test("the 1.x engine starts no chat and no turn", () => {
expect(startsV1Chat(method!, path!)).toBe(false);
}
});
+
+test("MCP on the 2.x engine: the gate lists the server list's ids, entries stay direct tools without the app's secrets", () => withDir(async (dir) => {
+ const { v2McpConfig, v2McpGate, desiredV2Mcp } = await import("./engine-v2-mcp.js");
+ const { writePolicyFile } = await import("./mcp-allow/mcp-allow.mjs");
+ const { mcpPolicyFile, writeWorkspaceMcp } = await import("./mcp-allow/state.js");
+ expect(v2McpGate(dir)).toEqual([]);
+ const engineEnv = { OPENCODE_PASSWORD: "pw", OMNIRUSH_POLICY_TOKEN: "tok", PATH: "/bin" };
+ expect(v2McpConfig({ type: "local", command: ["node", "s.js"], environment: { A: "1" }, timeout: 2000 }, engineEnv)).toEqual({
+ type: "local", command: ["node", "s.js"], environment: { A: "1", OPENCODE_PASSWORD: "", OMNIRUSH_POLICY_TOKEN: "" },
+ codemode: false, timeout: { startup: 2000, catalog: 2000, execution: 2000 },
+ });
+ expect(v2McpConfig({ type: "remote", url: "https://x.test/mcp", oauth: false, enabled: false }, engineEnv)).toEqual({ type: "remote", url: "https://x.test/mcp", oauth: false, disabled: true, codemode: false });
+ expect(v2McpConfig({ type: "local", command: [] }, engineEnv)).toBeNull();
+ writePolicyFile(mcpPolicyFile(dir), JSON.parse(await readFile(join(import.meta.dir, "mcp-allow", "mcp-policy.fixture.json"), "utf8")));
+ expect(v2McpGate(dir)).toContain("memory");
+ const root = join(dir, "proj");
+ writeWorkspaceMcp(dir, root, { memory: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-memory"] }, rogue: { type: "local", command: ["sh", "-c", "curl evil"] } });
+ const desired = await desiredV2Mcp(dir, root, engineEnv, v2McpGate(dir));
+ expect(Object.keys(desired)).toEqual(["memory"]);
+ expect(desired.memory).toMatchObject({ type: "local", codemode: false });
+ expect((desired.memory!.environment as Record<string, string>).OPENCODE_PASSWORD).toBe("");
+ // Not on the gate: left out.
+ expect(await desiredV2Mcp(dir, root, engineEnv, [])).toEqual({});
+}));
diff --git a/apps/server/src/engine-v2-preview.test.ts b/apps/server/src/engine-v2-preview.test.ts
index 3c838e7d..89f137b3 100644
--- a/apps/server/src/engine-v2-preview.test.ts
+++ b/apps/server/src/engine-v2-preview.test.ts
@@ -7,7 +7,6 @@ import { join, resolve } from "node:path";
import {
createEngineV2Preview,
mapRuntimeProvidersToV2Specs,
- mapRuntimeMcpToV2,
readEngineV2PreviewState,
resolveInitialEngineV2PreviewState,
writeEngineV2PreviewState,
@@ -45,18 +44,6 @@ test("native plugin skills do not block workspace skill synchronization", async
} finally { await rm(root, { recursive: true, force: true }); }
});
-test("maps enabled MCP transports without retaining unknown runtime fields", () => {
- expect(mapRuntimeMcpToV2({ type: "remote", url: "https://example.test/mcp", oauth: false,
- headers: { Authorization: "Bearer fixture", ignored: 3 }, timeout: 2000, enabled: true, privateMetadata: "omit" }))
- .toEqual({ type: "remote", url: "https://example.test/mcp", oauth: false,
- headers: { Authorization: "Bearer fixture" }, timeout: { startup: 2000, catalog: 2000, execution: 2000 } });
- expect(mapRuntimeMcpToV2({ type: "local", command: ["node", "fixture.mjs"], environment: { FIXTURE: "value" } }))
- .toEqual({ type: "local", command: ["node", "fixture.mjs"], environment: { FIXTURE: "value" } });
- for (const value of [null, { type: "remote", url: "file:///secret" }, { type: "local", command: [] },
- { type: "remote", url: "https://example.test/mcp", enabled: false },
- { type: "remote", url: "https://example.test/mcp", disabled: true }]) expect(mapRuntimeMcpToV2(value)).toBeUndefined();
-});
-
function testConfig(root: string): ServerConfig {
return {
host: "127.0.0.1",
diff --git a/apps/server/src/engine-v2-preview.ts b/apps/server/src/engine-v2-preview.ts
index 07a9e7b1..4d169522 100644
--- a/apps/server/src/engine-v2-preview.ts
+++ b/apps/server/src/engine-v2-preview.ts
@@ -21,7 +21,9 @@ import type { EnvService } from "./env-file.js";
import { selectPrimaryCredentialEnvName } from "./managed-provider-auth.js";
import { isReleaseBuild } from "./release-guard.js";
import { webSearchSetting } from "./web-search.js";
+import { desiredV2Mcp, v2McpGate } from "./engine-v2-mcp.js";
import { engineDataDir } from "./engine-data-home.js";
+import { computerUseEngineEnv } from "./computer-use/desktop.js";
import { engineV2Root, readMigratedSessions, seedV2StoreFromV1 } from "./engine-v2-migration.js";
import type { ServerConfig } from "./types.js";
@@ -29,6 +31,8 @@ const PREVIEW_STATE_FILE = "engine-v2-preview.json";
const UNSET_API_KEY = "omnirush-engine-v2-preview-unset";
/** opencode-plugins/omnirush-session-next.ts's id (server modules never import plugin files). */
export const OMNIRUSH_SESSION_PLUGIN_ID = "omnirush.session";
+/** How long a prompt waits for a project's MCP servers to connect. */
+const MCP_READY_TIMEOUT_MS = 15_000;
// A cold sidecar can return HTTP 503 while its model catalog initializes for 17–20 seconds.
const CATALOG_MIRROR_TIMEOUT_MS = 60_000;
@@ -253,32 +257,6 @@ function catalogModelIds(payload: unknown, mirroredProviderIds: string[]): strin
return [...ids].sort((left, right) => left.localeCompare(right));
}
-/** Translate only fields supported by the pinned v2 MCP API. */
-export function mapRuntimeMcpToV2(value: unknown): Record<string, unknown> | undefined {
- if (!isRecord(value)) return undefined;
- if (value.enabled === false || value.disabled === true) return undefined;
- const shared = {
- ...(typeof value.codemode === "boolean" ? { codemode: value.codemode } : {}),
- ...(typeof value.timeout === "number" && value.timeout > 0
- ? { timeout: { startup: value.timeout, catalog: value.timeout, execution: value.timeout } } : {}),
- };
- const strings = (input: unknown) => isRecord(input)
- ? Object.fromEntries(Object.entries(input).filter((entry): entry is [string, string] => typeof entry[1] === "string")) : {};
- if (value.type === "local" && Array.isArray(value.command)
- && value.command.length > 0 && value.command.every((part) => typeof part === "string" && part.trim())) {
- return { type: "local", command: value.command, environment: strings(value.environment),
- ...(typeof value.cwd === "string" ? { cwd: value.cwd } : {}), ...shared };
- }
- if (value.type !== "remote" || typeof value.url !== "string" || !/^https?:\/\//i.test(value.url)) return undefined;
- const oauth = isRecord(value.oauth) ? {
- ...(typeof value.oauth.clientId === "string" ? { client_id: value.oauth.clientId } : {}),
- ...(typeof value.oauth.clientSecret === "string" ? { client_secret: value.oauth.clientSecret } : {}),
- ...(typeof value.oauth.scope === "string" ? { scope: value.oauth.scope } : {}),
- } : value.oauth === false ? false : undefined;
- return { type: "remote", url: value.url, headers: strings(value.headers),
- ...(oauth === undefined ? {} : { oauth }), ...shared };
-}
-
/**
* Chats bind to the gateway only through the session plugin's headers, and a 2.x plugin that
* fails to load only warns: no chat starts in a location where it is not active.
@@ -335,26 +313,39 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
const active = sidecar;
if (!active) throw new Error("OmniRush v2 is not running");
if (mcpCleaned.has(directory)) return;
-
- // The v2 daemon can discover MCPs from project/global files without a
- // runtime-DB write. Enumerate the live location and remove every entry;
- // this is intentionally removal-only because MCP is globally disabled.
+ // The allowed servers (engine-v2-mcp.ts) through the engine's runtime MCP API; every other one goes.
+ const desired = await desiredV2Mcp(runtimeStorageDir(config), directory, active.env, active.mcpGate);
const current = await active.fetchJson("/api/mcp", { directory, timeoutMs: 10_000 });
if (current.status !== 200 || !isRecord(current.json) || !Array.isArray(current.json.data)) {
throw new Error("OmniRush v2 MCP status is unavailable");
}
- const entries = current.json.data;
- const names = entries.flatMap((entry) => (
- isRecord(entry) && typeof entry.name === "string" && entry.name.trim()
- ? [entry.name]
- : []
+ const names = current.json.data.flatMap((entry) => (
+ isRecord(entry) && typeof entry.name === "string" && entry.name.trim() ? [entry.name] : []
));
- await Promise.all(names.map(async (name) => {
+ await Promise.all(names.filter((name) => !Object.hasOwn(desired, name)).map(async (name) => {
const result = await active.fetchJson(`/api/experimental/mcp/${encodeURIComponent(name)}`, {
method: "DELETE", directory, timeoutMs: 15_000,
});
if (result.status !== 204 && result.status !== 404) throw new Error(`OmniRush v2 MCP removal failed (${result.status})`);
}));
+ await Promise.all(Object.entries(desired).map(async ([name, serverConfig]) => {
+ const result = await active.fetchJson(`/api/experimental/mcp/${encodeURIComponent(name)}`, {
+ method: "PUT", directory, body: { config: serverConfig }, timeoutMs: 15_000,
+ });
+ if (result.status < 200 || result.status >= 300) throw new Error(`OmniRush v2 MCP setup failed (${result.status})`);
+ }));
+ // The first prompt waits (bounded) for the servers to connect, or its turn would have no MCP tools.
+ const deadline = Date.now() + MCP_READY_TIMEOUT_MS;
+ while (Object.keys(desired).length > 0 && Date.now() < deadline) {
+ const status = await active.fetchJson("/api/mcp", { directory, timeoutMs: 5_000 });
+ const servers = isRecord(status.json) && Array.isArray(status.json.data) ? status.json.data : [];
+ const waiting = Object.keys(desired).some((name) => {
+ const server = servers.find((entry) => isRecord(entry) && entry.name === name);
+ return !isRecord(server) || (isRecord(server.status) && server.status.status === "pending");
+ });
+ if (!waiting) break;
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ }
mcpCleaned.add(directory);
})();
mcpInFlight.set(directory, pending);
@@ -471,6 +462,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
env: { ...opencodeModelsEnv, OMNIRUSH_SERVER_URL: `http://127.0.0.1:${config.port}`, OMNIRUSH_POLICY_TOKEN: managedDesktopPolicy(config).evaluationToken },
permissions: async () => executionRules((await readGlobalRuntimeOpencodeConfig(config)).managedPolicy?.execution),
webSearch: () => webSearchSetting({ env: process.env, stateDir: runtimeStorageDir(config) }).enabled,
+ mcpGate: v2McpGate(runtimeStorageDir(config), { ...process.env, ...computerUseEngineEnv(runtimeStorageDir(config)) }),
});
sidecar = managed;
if (!enabled || !allowRunning) {
diff --git a/apps/server/src/managed-opencode-v2.ts b/apps/server/src/managed-opencode-v2.ts
index 7f646d0d..655888fc 100644
--- a/apps/server/src/managed-opencode-v2.ts
+++ b/apps/server/src/managed-opencode-v2.ts
@@ -43,6 +43,8 @@ export interface ManagedOpencodeV2ServerOptions {
permissions?: () => Promise<EnginePermissionRule[]>;
/** Whether the server's web-search switch is on (web-search.ts): the stock websearch tool then searches. */
webSearch?: () => boolean;
+ /** The MCP servers the engine's gate allows (engine-v2-mcp.ts); none when absent. */
+ mcpGate?: string[];
}
export interface OpencodeV2Health {
@@ -56,6 +58,9 @@ export interface ManagedOpencodeV2Server {
username: string;
password: string;
childPid: number | undefined;
+ /** The environment the engine runs with (MCP servers inherit it under their own). */
+ readonly env: Record<string, string>;
+ readonly mcpGate: string[];
readonly exitCode: number | null;
readonly stdout: string;
readonly stderr: string;
@@ -95,12 +100,12 @@ export async function pluginDirectories(root: string, modules: string[]): Promis
}
/**
- * The engine's environment with its gates last (engine-gates.mjs): only the gateway provider and no MCP
- * server (MCP stays off on this engine until its allowlist is wired). The engine fails open without the
- * gate variables, so the spawn is refused when they are missing.
+ * The engine's environment with its gates last (engine-gates.mjs): only the gateway provider and the
+ * listed MCP servers. The engine fails open without the gate variables, so the spawn is refused when
+ * they are missing.
*/
-export function engineV2SpawnEnv(env: Record<string, string>): Record<string, string> {
- return assertEngineGates({ ...env, ...gateEnv({ provider: "omnirush", mcp: [] }) });
+export function engineV2SpawnEnv(env: Record<string, string>, mcp: readonly string[] = []): Record<string, string> {
+ return assertEngineGates({ ...env, ...gateEnv({ provider: "omnirush", mcp }) });
}
export function assertEngineGates(env: Record<string, string | undefined>): Record<string, string> {
@@ -178,7 +183,7 @@ export async function createManagedOpencodeV2Server(
...(opencodeModelsUrl === undefined ? {} : { OPENCODE_MODELS_URL: opencodeModelsUrl }),
...(disableModelsFetch === undefined ? {} : { OPENCODE_DISABLE_MODELS_FETCH: disableModelsFetch }),
...providerLockEnv(providerLock).set,
- });
+ }, options.mcpGate ?? []);
const child = spawn(bin, ["serve", "--hostname", hostname, "--port", String(port)], {
env,
stdio: ["ignore", "pipe", "pipe"],
@@ -314,6 +319,8 @@ export async function createManagedOpencodeV2Server(
username,
password,
childPid: child.pid,
+ env,
+ mcpGate: [...(options.mcpGate ?? [])],
get exitCode() {
return child.exitCode;
},
diff --git a/apps/server/src/mcp.ts b/apps/server/src/mcp.ts
index 54a9106f..4ba688a8 100644
--- a/apps/server/src/mcp.ts
+++ b/apps/server/src/mcp.ts
@@ -591,45 +591,6 @@ export async function listMcpFromRuntimeSnapshot(
return items;
}
-/**
- * Read only MCP names from static project/global config and the supplied
- * runtime snapshot. The names are used at an engine boundary; configs and
- * credentials never leave the server.
- */
-export async function configuredMcpNames(
- workspaceRoot: string,
- runtimeConfig: RuntimeOpencodeConfig = {},
-): Promise<string[]> {
- const [project, global] = await Promise.all([
- readJsoncFile(opencodeConfigPath(workspaceRoot), {} as Record<string, unknown>, {
- allowInvalid: true,
- maxBytes: DIAGNOSTIC_STATIC_CONFIG_MAX_BYTES,
- }),
- readJsoncFile(resolveGlobalOpenCodeConfigPath(), {} as Record<string, unknown>, {
- allowInvalid: true,
- maxBytes: DIAGNOSTIC_STATIC_CONFIG_MAX_BYTES,
- }),
- ]);
- return [...new Set([
- ...Object.keys(getMcpConfig(project.data)),
- ...Object.keys(getMcpConfig(global.data)),
- ...Object.keys(runtimeMcpMap(runtimeConfig)),
- ])].sort();
-}
-
-/** The preview engine (v2) cannot apply the server's MCP list: MCP stays off there. */
-export const MCP_ENGINE_V2_MESSAGE =
- "MCP servers are off with the preview engine. Turn the preview engine off to use this project's MCP servers, or remove them.";
-
-export async function assertNoConfiguredMcp(
- workspaceRoot: string,
- runtimeConfig: RuntimeOpencodeConfig = {},
-): Promise<void> {
- const names = await configuredMcpNames(workspaceRoot, runtimeConfig);
- if (names.length === 0) return;
- throw new ApiError(403, "mcp_disabled", MCP_ENGINE_V2_MESSAGE, { servers: names });
-}
-
/**
* Diagnostics-only passive inventory. It returns every configured layer and
* collision metadata without claiming which entry is effective: OpenCode's
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index b3751592..6bd9cc81 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -49,7 +49,7 @@ import { LatestTrailingWorkQueue } from "./latest-trailing-work-queue.js";
import { buildEngineAuthProbeHeader } from "./engine-registry.js";
import { addPlugin, listPlugins, normalizePluginSpec, removePlugin } from "./plugins.js";
import { sanitizePortableOpencodeConfig } from "./portable-opencode.js";
-import { addMcp, assertNoConfiguredMcp, listMcp, removeMcp, setMcpEnabled } from "./mcp.js";
+import { addMcp, listMcp, removeMcp, setMcpEnabled } from "./mcp.js";
import { buildOmniRushV2Instructions, waitForOmniRushV2Skills, OMNIRUSH_V2_INSTRUCTION_KEY } from "./opencode-v2-instructions.js";
import {
callMcpAppTool,
@@ -1666,8 +1666,9 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
proxyService = "opencode";
proxyBaseUrl = connection.url;
await engineV2Preview.ensureWorkspaceReady(workspace.path);
- // Reconcile through v2's runtime MCP API before the next call. The
- // ordinary connection routes remain authoritative; v1 is untouched.
+ // The project's allowed MCP servers reach the engine before the next call (engine-v2-mcp.ts);
+ // a write first refreshes the app-added entries the filter reads.
+ if (request.method !== "GET" && request.method !== "HEAD") await writeWorkspaceMcpFile(config, workspace);
await engineV2Preview.syncWorkspaceMcp(workspace.id, workspace.path);
const send = () => proxyOpencodeV2Request({
config,
@@ -2043,8 +2044,7 @@ export async function proxyOpencodeV2Request(input: {
if (/^\/api\/config(?:\/|$)/.test(decodedPath)) {
throw new ApiError(403, "engine_config_private", "Engine configuration is private");
}
- // The preview engine cannot apply the server's MCP list: MCP stays off
- // there (its servers are removed before each request; engine-v2-preview.ts).
+ // MCP servers follow the server's list (engine-v2-mcp.ts): the engine's own MCP routes stay closed.
if (/^(?:\/api)?\/mcp(?:\/|$)/.test(decodedPath) && method !== "GET" && method !== "HEAD") {
throw new ApiError(403, "engine_mcp_managed", "Manage connections through OmniRush.ai");
}
@@ -2053,10 +2053,6 @@ export async function proxyOpencodeV2Request(input: {
const promptDispatch = isUploadV2PromptDispatch(method, routePath);
const collectible = input.workspace.workspaceType !== "remote";
if (promptDispatch && collectible) {
- await assertNoConfiguredMcp(
- input.workspace.path,
- await readRuntimeOpencodeConfig(input.config, input.workspace.id),
- );
if (uploadDispatchRefused(input.config, input.workspace)) {
// Drain the unread body so the client's keep-alive connection stays usable.
await input.request.arrayBuffer().catch(() => undefined);
@@ -5460,7 +5456,6 @@ function createRoutes(
mode: mcpPolicyForConfig(config),
enabled,
message: enabled ? policy?.message ?? null : mcpDisabledMessage(config),
- engineV2: engineV2Preview.status().chatRouting === true,
supported: enabled && policy ? policy.allow.map(mcpPreset) : [],
decisions,
reportAt: report?.at ?? null,