Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(server): enforce deny-only MCP policy

Task Builder3f24f0b1a4dc
diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts
index 10c1a812..f0d25f5b 100644
--- a/apps/server/src/cli.ts
+++ b/apps/server/src/cli.ts
@@ -91,7 +91,6 @@ if (!config.opencodeBaseUrl && process.env.OMNIRUSH_MANAGE_OPENCODE === "1") {
OMNIRUSH_SERVER_URL: serverUrl,
OMNIRUSH_SERVER_TOKEN: config.token,
OMNIRUSH_POLICY_TOKEN: managedDesktopPolicy(config).evaluationToken,
- OMNIRUSH_MCP_POLICY: "disabled",
OPENCODE_CONFIG: runtimeConfigPath,
...opencodeModelsEnv,
};
diff --git a/apps/server/src/cloud-plugins.ts b/apps/server/src/cloud-plugins.ts
index 40e40719..3337f8e3 100644
--- a/apps/server/src/cloud-plugins.ts
+++ b/apps/server/src/cloud-plugins.ts
@@ -3,7 +3,7 @@ import { dirname, resolve } from "node:path";
import type { ServerConfig } from "./types.js";
import { ApiError } from "./errors.js";
import { parseFrontmatter, buildFrontmatter } from "./frontmatter.js";
-import { addMcp, removeMcp } from "./mcp.js";
+import { removeMcp } from "./mcp.js";
import { createWorkspaceKvStore, isRecord } from "./workspace-kv-store.js";
const OPENCODE_SKILL_NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
@@ -410,6 +410,10 @@ function mcpNoConfigWarning(title: string): string {
return `MCP component "${title}" could not be installed: no server config with a "url" or "command" was found.`;
}
+function mcpDisabledWarning(title: string): string {
+ return `MCP component "${title}" was skipped because MCP servers are disabled in OmniRush.ai.`;
+}
+
function mcpInactiveWarning(title: string): string {
return `MCP component "${title}" could not be installed because it is not active.`;
}
@@ -557,19 +561,7 @@ export async function installCloudPlugin(input: {
}
if (object.objectType === "mcp") {
- const configs = pluginMcpConfigsFromPayload(object, namespace);
- if (configs.length === 0) warnings.push(mcpNoConfigWarning(object.title));
- for (const config of configs) {
- await addMcp(input.serverConfig, input.workspaceId, config.name, config.config);
- files.push({
- configObjectId: object.id,
- versionId: version?.id ?? null,
- objectType: object.objectType,
- title: object.title,
- path: config.path,
- updatedAt: object.updatedAt,
- });
- }
+ warnings.push(mcpDisabledWarning(object.title));
continue;
}
diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts
index 453a6f34..a82acc7e 100644
--- a/apps/server/src/config.ts
+++ b/apps/server/src/config.ts
@@ -3,7 +3,6 @@ import { omnirushServerConfigPath } from "@omnirush/paths";
import type { ApprovalMode, ApprovalConfig, ServerConfig, WorkspaceConfig, LogFormat } from "./types.js";
import { buildWorkspaceInfos } from "./workspaces.js";
import { parseList, readJsonFile, shortId } from "./utils.js";
-import { resolveMcpPolicyFromEnvironment } from "./mcp-policy.js";
export interface CliArgs {
configPath?: string;
@@ -333,6 +332,5 @@ export async function resolveServerConfig(cli: CliArgs): Promise<ServerConfig> {
hostTokenSource,
logFormat,
logRequests,
- mcpPolicy: resolveMcpPolicyFromEnvironment(),
};
}
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index 21f17ea0..f3c88155 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -261,7 +261,6 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promi
OMNIRUSH_SERVER_URL: serverUrl,
OMNIRUSH_SERVER_TOKEN: config.token,
OMNIRUSH_POLICY_TOKEN: managedDesktopPolicy(config).evaluationToken,
- OMNIRUSH_MCP_POLICY: "disabled",
OPENCODE_CONFIG: runtimeConfigPath,
...opencodeModelsEnv,
};
diff --git a/apps/server/src/engine-plugin-bridge.e2e.test.ts b/apps/server/src/engine-plugin-bridge.e2e.test.ts
index c88823cb..ec2226c5 100644
--- a/apps/server/src/engine-plugin-bridge.e2e.test.ts
+++ b/apps/server/src/engine-plugin-bridge.e2e.test.ts
@@ -4,7 +4,11 @@ import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { createManagedOpencodeServer, type ManagedOpencodeServer } from "./managed-opencode.js";
-import { omnirushAnthropicToolSchemaPluginPath, omnirushTitleRecoveryPluginPath } from "./omnirush-extensions-plugin-path.js";
+import {
+ omnirushAnthropicToolSchemaPluginPath,
+ omnirushMcpPolicyPluginPath,
+ omnirushTitleRecoveryPluginPath,
+} from "./omnirush-extensions-plugin-path.js";
/**
* OmniRush plugins that patch the global fetch the engine sends model
@@ -15,8 +19,8 @@ import { omnirushAnthropicToolSchemaPluginPath, omnirushTitleRecoveryPluginPath
* reaches the provider, and a rejected optional title parameter
* (`reasoning_effort`, `temperature`, `top_p`) is retried without it, so the session
* still gets its title;
- * - Anthropic tool schemas: an MCP tool whose input schema has a top-level
- * `anyOf` reaches the Anthropic Messages API flattened.
+ * - MCP policy: a configured local MCP is removed before the supported
+ * engine exposes its inventory or sends provider tools.
*
* Skipped when the sidecar binary is not present (prepare:sidecar not run).
*/
@@ -108,7 +112,8 @@ describeMaybe("OmniRush fetch plugins on the bundled engine (mock provider)", ()
},
});
const base = `http://127.0.0.1:${provider.port}`;
- // A local MCP server with one tool whose input schema has a top-level anyOf.
+ // A local MCP server that must be rejected by the policy plugin before the
+ // supported engine can expose or execute its tool.
const mcpScript = join(data, "anyof-mcp.mjs");
writeFileSync(mcpScript, `import readline from "node:readline";
const rl = readline.createInterface({ input: process.stdin });
@@ -130,7 +135,11 @@ rl.on("line", (line) => {
anth: { name: "Anth", npm: "@ai-sdk/anthropic", options: { baseURL: `${base}/v1`, apiKey: "mock-key" }, models: { "claude-mock": { name: "Claude mock", tool_call: true, limit: { context: 100_000, output: 4_000 } } } },
},
mcp: { anyof: { type: "local", command: ["node", mcpScript], enabled: true } },
- plugin: [omnirushTitleRecoveryPluginPath(), omnirushAnthropicToolSchemaPluginPath()],
+ plugin: [
+ omnirushTitleRecoveryPluginPath(),
+ omnirushAnthropicToolSchemaPluginPath(),
+ omnirushMcpPolicyPluginPath(),
+ ],
}));
engine = await createManagedOpencodeServer({
bin: enginePath!,
@@ -181,19 +190,23 @@ rl.on("line", (line) => {
console.log("title requests: optional parameters", JSON.stringify(refused));
}, 90_000);
- test("an MCP tool with a top-level anyOf reaches the Anthropic API flattened", async () => {
+ test("a configured MCP never reaches the engine inventory or provider tools", async () => {
seen.length = 0;
- await waitFor(async () => {
- const status = (await (await engineFetch("/mcp")).json()) as Record<string, { status: string }>;
- return status.anyof?.status === "connected";
- }, "the MCP server");
+ const status = await waitFor(async () => {
+ const response = await engineFetch("/mcp");
+ if (!response.ok) return null;
+ return (await response.json()) as Record<string, unknown>;
+ }, "the engine MCP inventory");
+ expect(status.anyof).toBeUndefined();
+
await prompt({ providerID: "anth", modelID: "claude-mock" }, "Use the export tool.");
- const request = await waitFor(async () => seen.find((entry) => entry.path === "/v1/messages" && Array.isArray(entry.body.tools) && entry.body.tools.length > 0), "an Anthropic request with tools");
- const tool = (request.body.tools as Array<{ name: string; input_schema: Record<string, unknown> }>).find((entry) => entry.name.endsWith("export_batch"));
- expect(tool).toBeDefined();
- expect(tool!.input_schema.anyOf).toBeUndefined();
- expect(tool!.input_schema.type).toBe("object");
- expect(Object.keys(tool!.input_schema.properties as object).sort()).toEqual(["id", "name"]);
- for (const entry of seen) expect(entry.headers[HEADER]).toBeUndefined();
+ await waitFor(async () => seen.find((entry) => entry.path === "/v1/messages"), "an Anthropic request");
+ const requests = seen.filter((entry) => entry.path === "/v1/messages");
+ expect(requests.length).toBeGreaterThan(0);
+ for (const request of requests) {
+ const tools = Array.isArray(request.body.tools) ? request.body.tools : [];
+ expect(tools.some((entry) => typeof entry === "object" && entry !== null
+ && "name" in entry && typeof entry.name === "string" && entry.name.endsWith("export_batch"))).toBe(false);
+ }
}, 90_000);
});
diff --git a/apps/server/src/engine-v2-preview.test.ts b/apps/server/src/engine-v2-preview.test.ts
index 85793dc4..e0a7aa28 100644
--- a/apps/server/src/engine-v2-preview.test.ts
+++ b/apps/server/src/engine-v2-preview.test.ts
@@ -1,7 +1,8 @@
import { expect, test } from "bun:test";
+import { existsSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, resolve } from "node:path";
import {
createEngineV2Preview,
@@ -14,6 +15,10 @@ import {
import type { ServerConfig } from "./types.js";
import { buildOmniRushV2Instructions, waitForOmniRushV2Skills } from "./opencode-v2-instructions.js";
+const realV2Binary = process.env.OMNIRUSH_OPENCODE2_BIN?.trim()
+ || join(resolve(import.meta.dir, "../../.."), "apps/desktop/resources/sidecars/opencode-x86_64-unknown-linux-gnu");
+const realV2Test = existsSync(realV2Binary) ? test : test.skip;
+
test("v2 app guidance fits the native entry limit and uses the current native tools", () => {
for (const connected of [true, false]) {
const value = buildOmniRushV2Instructions(connected);
@@ -124,6 +129,57 @@ test("persists chat routing and includes it in preview status without starting t
}
});
+realV2Test("removes a configured MCP from the real v2 engine before admission", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-engine-v2-mcp-ban-"));
+ const previousBinary = process.env.OMNIRUSH_OPENCODE2_BIN;
+ await writeEngineV2PreviewState(testConfig(root), { enabled: true, chatRouting: false });
+ process.env.OMNIRUSH_OPENCODE2_BIN = realV2Binary;
+ const config = testConfig(root);
+ const preview = createEngineV2Preview({ config, deferStart: true });
+
+ try {
+ preview.start();
+ const deadline = Date.now() + 60_000;
+ let connection: ReturnType<typeof preview.connection>;
+ while (!(connection = preview.connection()) && Date.now() < deadline) {
+ if (preview.status().lastError) throw new Error(preview.status().lastError);
+ await Bun.sleep(100);
+ }
+ if (!connection) throw new Error("Timed out waiting for the real v2 engine");
+
+ const directory = encodeURIComponent(root);
+ const request = (path: string, init?: RequestInit) => fetch(
+ `${connection!.url}${path}${path.includes("?") ? "&" : "?"}location%5Bdirectory%5D=${directory}`,
+ {
+ ...init,
+ headers: {
+ authorization: `Basic ${Buffer.from(`${connection!.username}:${connection!.password}`).toString("base64")}`,
+ "content-type": "application/json",
+ ...(init?.headers ?? {}),
+ },
+ },
+ );
+ const configured = await request("/api/mcp/fixture", {
+ method: "PUT",
+ body: JSON.stringify({ config: { type: "remote", url: "https://example.invalid/mcp" } }),
+ });
+ expect(configured.status).toBe(204);
+
+ const before = await (await request("/api/mcp")).json() as { data?: Array<{ name?: string }> };
+ expect(before.data?.some((entry) => entry.name === "fixture")).toBe(true);
+
+ await preview.syncWorkspaceMcp("ws_1", root);
+
+ const after = await (await request("/api/mcp")).json() as { data?: Array<{ name?: string }> };
+ expect(after.data?.some((entry) => entry.name === "fixture")).toBe(false);
+ } finally {
+ await preview.stop();
+ if (previousBinary === undefined) delete process.env.OMNIRUSH_OPENCODE2_BIN;
+ else process.env.OMNIRUSH_OPENCODE2_BIN = previousBinary;
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
test("maps runtime provider fields and models to an OpenCode v2 spec", () => {
expect(mapRuntimeProvidersToV2Specs({
example: {
diff --git a/apps/server/src/engine-v2-preview.ts b/apps/server/src/engine-v2-preview.ts
index 0da47088..8c54f492 100644
--- a/apps/server/src/engine-v2-preview.ts
+++ b/apps/server/src/engine-v2-preview.ts
@@ -18,8 +18,6 @@ import {
isEngineGlobalRuntimeConfigId,
onRuntimeOpencodeConfigWrite,
readGlobalRuntimeOpencodeConfig,
- readEffectiveRuntimeOpencodeConfig,
- runtimeMcpMap,
runtimeProviderMap,
} from "./runtime-opencode-config-store.js";
import type { EnvService } from "./env-file.js";
@@ -320,7 +318,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
let mirrorDirty = false;
const workspaceReadiness = new Map<string, Promise<void>>();
let mirroredSpecs: OpencodeV2ProviderSpec[] = [];
- const workspaceMcp = new Map<string, Map<string, string>>();
+ const mcpCleaned = new Set<string>();
const mcpInFlight = new Map<string, Promise<void>>();
const mcpWorkspaces = new Map<string, string>();
@@ -333,66 +331,33 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
if (previous) await previous.catch(() => undefined);
const active = sidecar;
if (!active) throw new Error("OmniRush v2 is not running");
- const runtime = runtimeMcpMap(await readEffectiveRuntimeOpencodeConfig(config, workspaceId));
- const desired = new Map(Object.entries(runtime).flatMap(([name, value]) => {
- const mapped = mapRuntimeMcpToV2(value);
- return mapped ? [[name, mapped] as const] : [];
- }));
- const applied = workspaceMcp.get(directory) ?? new Map<string, string>();
- workspaceMcp.set(directory, applied);
- let changed = false;
- // Remove first so a failed replacement cannot leave an old credential or
- // revoked tool active. Only touch registrations owned by this mirror.
- for (const [name, fingerprint] of applied) {
- if (desired.has(name) && JSON.stringify(desired.get(name)) === fingerprint) continue;
+ 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.
+ 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]
+ : []
+ ));
+ await Promise.all(names.map(async (name) => {
const result = await active.fetchJson(`/api/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})`);
- applied.delete(name);
- changed = true;
- }
- for (const [name, mcpConfig] of desired) {
- const fingerprint = JSON.stringify(mcpConfig);
- if (applied.get(name) === fingerprint) continue;
- const result = await active.fetchJson(`/api/mcp/${encodeURIComponent(name)}`, {
- method: "PUT", body: { config: mcpConfig }, directory, timeoutMs: 30_000,
- });
- if (result.status !== 204) throw new Error(`OmniRush v2 MCP registration failed (${result.status})`);
- applied.set(name, fingerprint);
- changed = true;
- }
- if (changed) {
- const deadline = Date.now() + 30_000;
- while (true) {
- const result = await active.fetchJson("/api/mcp", { directory, timeoutMs: 5_000 });
- const entries = isRecord(result.json) ? result.json.data : undefined;
- if (result.status !== 200 || !Array.isArray(entries)) throw new Error("OmniRush v2 MCP status is unavailable");
- const pending = [...desired.keys()].some((name) => {
- const entry = entries.find((entry) => isRecord(entry) && entry.name === name);
- return !isRecord(entry) || !isRecord(entry.status) || entry.status.status === "pending";
- });
- if (!pending) break;
- if (Date.now() >= deadline) {
- // Retry readiness on the next request rather than cache an
- // acknowledged registration as usable before its tools exist.
- throw new Error("OmniRush v2 MCP connections did not settle");
- }
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- // The pinned beta batches MCP ToolsChanged events for 100ms after
- // connection startup. Admission must follow that registry refresh,
- // not merely the PUT acknowledgement or connected status.
- await new Promise((resolve) => setTimeout(resolve, 250));
- }
+ }));
+ mcpCleaned.add(directory);
})();
mcpInFlight.set(directory, pending);
try { await pending; }
catch (error) {
- // Retain ownership for removals, but never cache a failed readiness
- // attempt as an applied configuration.
- const applied = workspaceMcp.get(directory);
- if (applied) for (const name of applied.keys()) applied.set(name, "");
+ mcpCleaned.delete(directory);
throw error;
}
finally { if (mcpInFlight.get(directory) === pending) mcpInFlight.delete(directory); }
@@ -471,7 +436,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
const active = sidecar;
workspaceReadiness.clear();
sidecar = undefined;
- workspaceMcp.clear();
+ mcpCleaned.clear();
mcpWorkspaces.clear();
running = false;
version = undefined;
@@ -513,6 +478,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
// locations while a conversation is active. Request admission joins
// the same serialized reconciliation rather than racing it.
for (const [directory, id] of mcpWorkspaces) {
+ mcpCleaned.delete(directory);
if (global || id === workspaceId) void syncWorkspaceMcp(id, directory).catch((error) => {
if (sidecar) lastError = `MCP: ${errorMessage(error)}`;
});
diff --git a/apps/server/src/managed-opencode.ts b/apps/server/src/managed-opencode.ts
index 2af98e88..82638c57 100644
--- a/apps/server/src/managed-opencode.ts
+++ b/apps/server/src/managed-opencode.ts
@@ -180,6 +180,9 @@ async function startManagedOpencodeServer(
// The managed engine needs its own provider environment, but never the key
// that decrypts OmniRush.ai-owned OAuth credentials.
delete env.OMNIRUSH_ENCRYPTION_KEY;
+ // OPENCODE_PURE disables managed config/plugin loading in OpenCode 1.x;
+ // inheriting it would bypass the engine-side MCP fence.
+ delete env.OPENCODE_PURE;
const injectedEnv = Object.entries({
...engineEnvDefaults,
...(options.env ?? {}),
@@ -187,7 +190,7 @@ async function startManagedOpencodeServer(
OPENCODE_SERVER_USERNAME: username,
OPENCODE_SERVER_PASSWORD: password,
})
- .filter((entry): entry is [string, string] => typeof entry[1] === "string")
+ .filter((entry): entry is [string, string] => entry[0] !== "OPENCODE_PURE" && typeof entry[1] === "string")
.map(([name, value]) => ({
name,
value: SECRET_ENV_PATTERN.test(name) ? "<redacted>" : value,
@@ -223,7 +226,7 @@ async function startManagedOpencodeServer(
child.stdout?.on("data", (chunk) => {
output += chunk.toString();
for (const line of output.split("\n")) {
- if (!line.startsWith("opencode server listening")) continue;
+ if (!/^(?:opencode )?server listening\b/.test(line)) continue;
const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
if (!match?.[1]) return fail(new Error(`Failed to parse OmniRush server URL from: ${line}`));
done(match[1]);
diff --git a/apps/server/src/mcp-policy.test.ts b/apps/server/src/mcp-policy.test.ts
index 3b224524..6365340b 100644
--- a/apps/server/src/mcp-policy.test.ts
+++ b/apps/server/src/mcp-policy.test.ts
@@ -4,23 +4,16 @@ import {
assertMcpAllowed,
mcpAllowed,
mcpPolicyForConfig,
- resolveMcpPolicyFromEnvironment,
} from "./mcp-policy.js";
describe("MCP execution policy", () => {
- test("normal server environments deny MCP", () => {
- expect(resolveMcpPolicyFromEnvironment({})).toBe("disabled");
- expect(resolveMcpPolicyFromEnvironment({
- OMNIRUSH_MCP_POLICY: "enabled",
- })).toBe("disabled");
- });
-
- test("rejects resolved and legacy explicit policies while preserving bare fixtures", () => {
- expect(mcpPolicyForConfig({})).toBe("enabled");
+ test("fails closed for bare and legacy-shaped configurations", () => {
+ expect(mcpPolicyForConfig({})).toBe("disabled");
expect(mcpPolicyForConfig({ mcpPolicy: "enabled" })).toBe("disabled");
- expect(mcpAllowed({})).toBe(true);
+ expect(mcpAllowed({})).toBe(false);
expect(mcpAllowed({ mcpPolicy: "disabled" })).toBe(false);
expect(mcpAllowed({ mcpPolicy: "enabled" })).toBe(false);
+ expect(() => assertMcpAllowed({})).toThrow(ApiError);
expect(() => assertMcpAllowed({ mcpPolicy: "disabled" })).toThrow(ApiError);
expect(() => assertMcpAllowed({ mcpPolicy: "enabled" })).toThrow(ApiError);
});
diff --git a/apps/server/src/mcp-policy.ts b/apps/server/src/mcp-policy.ts
index 43cff22c..3c7a634b 100644
--- a/apps/server/src/mcp-policy.ts
+++ b/apps/server/src/mcp-policy.ts
@@ -1,30 +1,19 @@
import { ApiError } from "./errors.js";
-import type { ServerConfig } from "./types.js";
-/** MCP is disabled for resolved OmniRush.ai server configs. */
-export type McpPolicyMode = "disabled" | "enabled";
+/** MCP is disabled for every OmniRush.ai server configuration. */
+export type McpPolicyMode = "disabled";
export const MCP_DISABLED_MESSAGE =
"MCP servers are disabled in OmniRush.ai.";
-export function resolveMcpPolicyFromEnvironment(_env: NodeJS.ProcessEnv = process.env): McpPolicyMode {
+export function mcpPolicyForConfig(_config: unknown): McpPolicyMode {
return "disabled";
}
-/**
- * A missing field is retained for old in-memory embedders and test fixtures.
- * Persisted or resolved values are fail-closed, so an old explicit value
- * cannot re-enable MCP after a restart.
- */
-export function mcpPolicyForConfig(config: Pick<ServerConfig, "mcpPolicy">): McpPolicyMode {
- return Object.prototype.hasOwnProperty.call(config, "mcpPolicy") ? "disabled" : "enabled";
+export function mcpAllowed(_config: unknown): false {
+ return false;
}
-export function mcpAllowed(config: Pick<ServerConfig, "mcpPolicy">): boolean {
- return !Object.prototype.hasOwnProperty.call(config, "mcpPolicy");
-}
-
-export function assertMcpAllowed(config: Pick<ServerConfig, "mcpPolicy">): void {
- if (mcpAllowed(config)) return;
+export function assertMcpAllowed(_config: unknown): never {
throw new ApiError(403, "mcp_disabled", MCP_DISABLED_MESSAGE);
}
diff --git a/apps/server/src/mcp.ts b/apps/server/src/mcp.ts
index c7365afb..30411732 100644
--- a/apps/server/src/mcp.ts
+++ b/apps/server/src/mcp.ts
@@ -6,8 +6,7 @@ import { readJsoncFile } from "./jsonc.js";
import { opencodeConfigPath } from "./workspace-files.js";
import { validateMcpConfig, validateMcpName, validateUserMcpName } from "./validators.js";
import { ApiError } from "./errors.js";
-import { assertMcpAllowed, mcpAllowed } from "./mcp-policy.js";
-import { isOmniRushUiMcpRegistryEntry, OMNIRUSH_UI_MCP_REGISTRY_COMMAND_MESSAGE } from "./omnirush-ui-mcp-command.js";
+import { assertMcpAllowed, mcpAllowed, MCP_DISABLED_MESSAGE } from "./mcp-policy.js";
import {
readRuntimeOpencodeConfig,
runtimeMcpMap,
@@ -585,6 +584,41 @@ 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();
+}
+
+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_DISABLED_MESSAGE, { servers: names });
+}
+
/**
* Diagnostics-only passive inventory. It returns every configured layer and
* collision metadata without claiming which entry is effective: OpenCode's
@@ -681,7 +715,6 @@ export async function addMcp(
}
export async function removeMcp(serverConfig: ServerConfig, workspaceId: string, name: string): Promise<boolean> {
- assertMcpAllowed(serverConfig);
const runtimeConfig = await readRuntimeOpencodeConfig(serverConfig, workspaceId);
const mcpMap = { ...runtimeMcpMap(runtimeConfig) };
if (!Object.prototype.hasOwnProperty.call(mcpMap, name)) return false;
@@ -703,28 +736,14 @@ export async function setMcpEnabled(
name: string,
enabled: boolean,
): Promise<boolean> {
- assertMcpAllowed(serverConfig);
validateMcpName(name);
+ if (enabled) {
+ assertMcpAllowed(serverConfig);
+ }
const runtimeConfig = await readRuntimeOpencodeConfig(serverConfig, workspaceId);
const mcpMap = { ...runtimeMcpMap(runtimeConfig) };
if (!Object.prototype.hasOwnProperty.call(mcpMap, name)) return false;
- const current = mcpMap[name];
- if (!current || typeof current !== "object" || Array.isArray(current)) return false;
- if (isOmniRushUiMcpRegistryEntry(current)) {
- // Never re-enable a registry launch of omnirush-ui-mcp. Disabling one
- // removes it: the runtime store does not keep such entries and the
- // engine never receives them, so there is nothing left to toggle.
- if (enabled) throw new ApiError(400, "unsafe_mcp_command", OMNIRUSH_UI_MCP_REGISTRY_COMMAND_MESSAGE);
- delete mcpMap[name];
- await writeRuntimeOpencodeConfig(serverConfig, workspaceId, (currentConfig) => ({ ...currentConfig, mcp: mcpMap }));
- return true;
- }
- try {
- validateMcpConfig({ ...(current as Record<string, unknown>), enabled });
- } catch {
- return false;
- }
- mcpMap[name] = { ...(current as Record<string, unknown>), enabled };
+ delete mcpMap[name];
await writeRuntimeOpencodeConfig(serverConfig, workspaceId, (currentConfig) => ({ ...currentConfig, mcp: mcpMap }));
return true;
}
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.ts
index dfdd2408..64a88d58 100644
--- a/apps/server/src/omnirush-runtime-config.test.ts
+++ b/apps/server/src/omnirush-runtime-config.test.ts
@@ -81,7 +81,7 @@ async function readConfigFile(config: ServerConfig): Promise<Record<string, unkn
}
describe("omnirush runtime config file", () => {
- test("disabled policy omits MCP and adds an engine permission fence", () => {
+ test("permanent MCP ban omits MCP and adds an engine permission fence", () => {
const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot(
{ mcp: { posthog: { type: "remote", url: "https://mcp.example" } } },
undefined,
@@ -89,11 +89,12 @@ describe("omnirush runtime config file", () => {
undefined,
undefined,
undefined,
- "disabled",
);
expect(parsed.mcp).toEqual({});
expect(parsed.permission).toMatchObject({ "mcp.*": "deny" });
- expect(parsed.plugin).toContain(expect.stringContaining("omnirush-mcp-policy"));
+ const plugins = Array.isArray(parsed.plugin) ? parsed.plugin : [];
+ expect(plugins.some((plugin) => typeof plugin === "string" && plugin.includes("omnirush-mcp-policy"))).toBe(true);
+ expect(String(plugins.at(-1))).toContain("omnirush-mcp-policy");
});
test("managed browser restrictions use scalar actions in global and agent permissions", () => {
@@ -107,16 +108,16 @@ describe("omnirush runtime config file", () => {
});
// The built-in git workflow rules come first; the organization's execution
// rules are appended last so the engine's last-match-wins evaluation keeps them.
- const permission = { bash: { ...gitWorkflowPermissionRules(), "*": "deny", "curl *": "deny" }, webfetch: "deny", websearch: "deny" };
+ const permission = { bash: { ...gitWorkflowPermissionRules(), "*": "deny", "curl *": "deny" }, "mcp.*": "deny", webfetch: "deny", websearch: "deny" };
expect(parsed.permission).toEqual(permission);
expect(Object.keys((parsed.permission as { bash: Record<string, string> }).bash).slice(-2)).toEqual(["*", "curl *"]);
expect(parsed.agent).toMatchObject({ omnirush: { permission } });
expect(parsed.managedPolicy).toBeUndefined();
- expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}).permission).toEqual({ bash: gitWorkflowPermissionRules() });
+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}).permission).toEqual({ bash: gitWorkflowPermissionRules(), "mcp.*": "deny" });
});
test("full approval mode allows every permission category; the environment overrides the setting", () => {
- const permission = { bash: { "*": "allow" }, read: { "*": "allow" }, edit: "allow", webfetch: "allow", websearch: "allow", doom_loop: "allow", external_directory: "allow" };
+ const permission = { bash: { "*": "allow" }, read: { "*": "allow" }, edit: "allow", "mcp.*": "deny", webfetch: "allow", websearch: "allow", doom_loop: "allow", external_directory: "allow" };
const full = buildOmniRushRuntimeConfigObjectFromSnapshot(
{ approvals: { mode: "full" }, permission: { external_directory: { "/Users/sam/Docs": "allow" } } },
undefined,
@@ -145,12 +146,12 @@ describe("omnirush runtime config file", () => {
// OMNIRUSH_APPROVALS on the server process wins in both directions; the default stays guarded.
expect(buildOmniRushRuntimeConfigObjectFromSnapshot({ approvals: { mode: "full" } }, undefined, { OMNIRUSH_APPROVALS: "guarded" }).permission)
- .toEqual({ bash: gitWorkflowPermissionRules() });
+ .toEqual({ bash: gitWorkflowPermissionRules(), "mcp.*": "deny" });
expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, { OMNIRUSH_APPROVALS: "full" }).permission).toEqual(permission);
- expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, {}).permission).toEqual({ bash: gitWorkflowPermissionRules() });
+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, {}).permission).toEqual({ bash: gitWorkflowPermissionRules(), "mcp.*": "deny" });
});
- test("writes global-row MCPs and omnirush defaults into the file", async () => {
+ test("omits global-row MCPs while writing omnirush defaults into the file", async () => {
const { config } = await setup();
await writeGlobalRuntimeOpencodeConfig(config, (current) => ({
...current,
@@ -164,9 +165,7 @@ describe("omnirush runtime config file", () => {
expect(path).toBe(omnirushRuntimeConfigFilePath(config));
const parsed = await readConfigFile(config);
- const mcp = parsed.mcp as Record<string, Record<string, unknown>>;
- expect(mcp.posthog?.enabled).toBe(true);
- expect(mcp["omnirush-connect-stale"]).toBeUndefined();
+ expect(parsed.mcp).toEqual({});
expect(parsed.default_agent).toBe("omnirush");
expect(Array.isArray(parsed.plugin)).toBe(true);
if (!Array.isArray(parsed.plugin)) throw new Error("Expected runtime plugins");
@@ -326,7 +325,7 @@ describe("omnirush runtime config file", () => {
"ui-bundled": bundled,
},
});
- expect(built.mcp).toEqual({ "ui-bundled": bundled });
+ expect(built.mcp).toEqual({});
});
test("omnirush prompt states identity, repo memory, artifacts, and Connect routing once, without the removed Memory Bank", async () => {
@@ -392,12 +391,12 @@ describe("omnirush runtime config file", () => {
const prompt = (buildOmniRushRuntimeConfigObjectFromSnapshot({}).agent as Record<string, { prompt: string }>).omnirush!.prompt;
const section = prompt.slice(prompt.indexOf("## Sub-agent swarms"), prompt.indexOf("## Editing files"));
expect(section).toContain(`load the \`${OMNIRUSH_SWARM_SKILL_NAME}\` skill first`);
- expect(section).toContain("Before you start 3 or more sub-agents for one request");
- expect(section).toContain("the 1-2 sub-agents the work needs with the subagent tool and no board");
+ expect(section).toContain("Before you start 3 or more sub-agents for implementation work");
+ expect(section).toContain("For smaller implementation work, use 1-2 sub-agents directly when they help");
// No board mechanics on every request: no file name, no table, no layers.
expect(prompt).not.toContain("swarm.md");
expect(prompt).not.toContain("## Tasks");
- expect(section.length).toBeLessThan(400);
+ expect(section.length).toBeLessThan(500);
// The skill carries the procedure, with the board under .omnirush/.
expect(OMNIRUSH_SWARM_SKILL).toContain("`.omnirush/swarm.md`");
expect(OMNIRUSH_SWARM_SKILL).toContain("never a file in the project root");
@@ -411,7 +410,7 @@ describe("omnirush runtime config file", () => {
expect(OMNIRUSH_SWARM_SKILL).toContain("omnirush.ai does that when the turn ends");
const { data, body } = parseFrontmatter(omnirushSwarmSkillMarkdown());
expect(data.name).toBe(OMNIRUSH_SWARM_SKILL_NAME);
- expect(String(data.description)).toContain("Required before starting 3 or more sub-agents for one request");
+ expect(String(data.description)).toContain("Required before starting 3 or more sub-agents for implementation work");
expect(body.trim()).toBe(OMNIRUSH_SWARM_SKILL);
});
@@ -547,14 +546,9 @@ describe("omnirush runtime config file", () => {
}));
// The refresh is fire-and-forget; poll briefly for the rewrite.
- let mcp: Record<string, Record<string, unknown>> = {};
- for (let attempt = 0; attempt < 50; attempt += 1) {
- const parsed = await readConfigFile(config);
- mcp = (parsed.mcp ?? {}) as Record<string, Record<string, unknown>>;
- if (mcp.stripe) break;
- await new Promise((resolve) => setTimeout(resolve, 20));
- }
- expect(mcp.stripe?.enabled).toBe(false);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ const parsed = await readConfigFile(config);
+ expect(parsed.mcp).toEqual({});
});
test("workspace runtime writes do not rewrite the file", async () => {
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index 3dbfaa6d..4528ed2d 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -39,13 +39,10 @@ import {
isEngineGlobalRuntimeConfigId,
readGlobalRuntimeOpencodeConfig,
runtimeDisabledProviderList,
- runtimeMcpMap,
runtimeProviderMap,
runtimePluginList,
type RuntimeOpencodeConfig,
} from "./runtime-opencode-config-store.js";
-import { CONNECT_MCP_SERVER_NAME_PREFIX } from "./connect-mcp-server-catalog.js";
-import { isOmniRushUiMcpRegistryEntry } from "./omnirush-ui-mcp-command.js";
import { OMNIRUSH_AGENT_PROMPT } from "./omnirush-agent-prompt.js";
import { OMNIRUSH_SUBAGENT_DEPTH, OMNIRUSH_SWARM_SKILL_NAME, OMNIRUSH_SWARM_TOOL_NAME, omnirushSwarmSkillMarkdown } from "./omnirush-swarm.js";
import {
@@ -56,7 +53,6 @@ import {
type OmniRushModelCatalog,
} from "./omnirush-model-catalog.js";
import { writeFileAtomic } from "./atomic-write.js";
-import { mcpPolicyForConfig, type McpPolicyMode } from "./mcp-policy.js";
import {
OMNIRUSH_BEST_PRACTICES,
bestPracticesEnabled,
@@ -142,7 +138,6 @@ export async function buildOmniRushRuntimeConfigObject(
internalGateway && config ? await readOmniRushModelCatalog(config) : undefined,
config ? omnirushRuntimeSkillsDir(config) : undefined,
config ? omnirushBestPracticesSkillsDir(config) : undefined,
- config ? mcpPolicyForConfig(config) : "disabled",
);
}
@@ -172,12 +167,11 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
catalog: OmniRushModelCatalog = builtinOmniRushModelCatalog(),
skillsDir?: string,
bestPracticesDir?: string,
- mcpPolicy: McpPolicyMode = "disabled",
): Record<string, unknown> {
const disabledProviders = runtimeDisabledProviderList(runtimeConfig);
// OMNIRUSH_APPROVALS in the server environment wins over the persisted setting.
const permissions = legacyExecutionPermissions(runtimeConfig.managedPolicy?.execution, resolveApprovalMode(runtimeConfig, env).mode);
- const mcpPermission = mcpPolicy === "disabled" ? { "mcp.*": "deny" } : {};
+ const mcpPermission = { "mcp.*": "deny" };
const { managedPolicy: _managedPolicy, approvals: _approvals, bestPractices: _bestPractices, ...engineConfig } = runtimeConfig;
const enabled = bestPracticesEnabled(runtimeConfig);
const skillPaths = [
@@ -272,17 +266,15 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
omnirushReasoningEffortPluginPath(),
omnirushTitleRecoveryPluginPath(),
omnirushSwarmPluginPath(),
- omnirushMcpPolicyPluginPath(),
...runtimePluginList(runtimeConfig),
+ // This must be last: user/runtime plugins may not reintroduce MCP
+ // configuration or replace the deny rules.
+ omnirushMcpPolicyPluginPath(),
],
...(disabledProviders.length ? { disabled_providers: disabledProviders } : {}),
- // Registry launches of omnirush-ui-mcp are never delivered, whatever the
- // runtime DB holds: the MCP ships inside the desktop app, not on npm.
- mcp: mcpPolicy === "disabled"
- ? {}
- : Object.fromEntries(Object.entries(runtimeMcpMap(runtimeConfig))
- .filter(([name, entry]) => !name.startsWith(CONNECT_MCP_SERVER_NAME_PREFIX)
- && !isOmniRushUiMcpRegistryEntry(entry))),
+ // MCP is a permanently disabled capability. The policy plugin also
+ // strips project/global MCP entries that the engine discovers itself.
+ mcp: {},
...(Object.keys(provider).length ? { provider } : {}),
};
}
diff --git a/apps/server/src/omnirush-ui-mcp-guard.e2e.test.ts b/apps/server/src/omnirush-ui-mcp-guard.e2e.test.ts
index ea8f0716..9f2d0a60 100644
--- a/apps/server/src/omnirush-ui-mcp-guard.e2e.test.ts
+++ b/apps/server/src/omnirush-ui-mcp-guard.e2e.test.ts
@@ -119,8 +119,8 @@ async function seedRuntimeRow(config: ServerConfig, workspaceId: string, value:
}
}
-describe("registry launches of omnirush-ui-mcp", () => {
- test("POST /workspace/:id/mcp refuses one with 400 and nothing reaches the engine", async () => {
+describe("complete MCP ban at the HTTP and runtime boundaries", () => {
+ test("POST /workspace/:id/mcp refuses every configured server and nothing reaches the engine", async () => {
const { config, engine } = await fixture();
const { call } = await start(config, engine.baseUrl);
@@ -133,28 +133,28 @@ describe("registry launches of omnirush-ui-mcp", () => {
name: "omnirush-ui",
config: { type: "local", command, enabled: true },
});
- expect(response.status).toBe(400);
- expect(await response.json()).toMatchObject({ code: "unsafe_mcp_command" });
+ expect(response.status).toBe(403);
+ expect(await response.json()).toMatchObject({ code: "mcp_disabled" });
}
expect((await readRuntimeOpencodeConfig(config, "ws_1")).mcp).toBeUndefined();
expect(engine.pushedNames()).toEqual([]);
});
- test("PATCH /workspace/:id/config refuses one with 400 and stores nothing", async () => {
+ test("PATCH /workspace/:id/config refuses MCP config before it is stored", async () => {
const { config, engine } = await fixture();
const { call } = await start(config, engine.baseUrl);
const response = await call("PATCH", "/workspace/ws_1/config", {
opencode: { mcp: { "omnirush-ui": LEGACY, "user-tool": SAFE } },
});
- expect(response.status).toBe(400);
- expect(await response.json()).toMatchObject({ code: "unsafe_mcp_command" });
+ expect(response.status).toBe(403);
+ expect(await response.json()).toMatchObject({ code: "mcp_disabled" });
expect((await readRuntimeOpencodeConfig(config, "ws_1")).mcp).toBeUndefined();
- // The same patch without it goes through.
- const safe = await call("PATCH", "/workspace/ws_1/config", { opencode: { mcp: { "user-tool": SAFE } } });
- expect(safe.status).toBe(200);
- expect((await readRuntimeOpencodeConfig(config, "ws_1")).mcp).toEqual({ "user-tool": SAFE });
+ const provider = await call("PATCH", "/workspace/ws_1/config", {
+ opencode: { provider: { "user-provider": { npm: "@ai-sdk/openai" } } },
+ });
+ expect(provider.status).toBe(200);
});
test("enabling a stored one over HTTP is refused and not pushed", async () => {
@@ -163,12 +163,12 @@ describe("registry launches of omnirush-ui-mcp", () => {
const { call } = await start(config, engine.baseUrl);
const response = await call("POST", "/workspace/ws_1/mcp/omnirush-ui/enabled", { enabled: true });
- expect(response.status).toBe(400);
- expect(await response.json()).toMatchObject({ code: "unsafe_mcp_command" });
+ expect(response.status).toBe(403);
+ expect(await response.json()).toMatchObject({ code: "mcp_disabled" });
expect(engine.pushedNames()).toEqual([]);
});
- test("the dynamic engine push and the injected config file skip stored ones", async () => {
+ test("legacy stored rows are hidden from runtime delivery and injected config", async () => {
const { config, engine } = await fixture();
await seedRuntimeRow(config, "ws_1", { mcp: { "omnirush-ui": LEGACY, "user-tool": SAFE } });
await seedRuntimeRow(config, ENGINE_GLOBAL_RUNTIME_CONFIG_ID, {
@@ -177,15 +177,15 @@ describe("registry launches of omnirush-ui-mcp", () => {
await start(config, engine.baseUrl);
await syncAllWorkspacesRuntimeMcpToEngine(config);
- expect(engine.pushedNames().sort()).toEqual(["global-tool", "user-tool"]);
+ expect(engine.pushedNames()).toEqual([]);
- expect(Object.keys((await readEffectiveRuntimeOpencodeConfig(config, "ws_1")).mcp ?? {}).sort())
- .toEqual(["global-tool", "user-tool"]);
+ expect((await readEffectiveRuntimeOpencodeConfig(config, "ws_1")).mcp).toBeUndefined();
await writeOmniRushRuntimeConfigFile(config);
const injected = JSON.parse(await readFile(omnirushRuntimeConfigFilePath(config), "utf8")) as { mcp?: Record<string, unknown> };
- expect(Object.keys(injected.mcp ?? {})).toEqual(["global-tool"]);
+ expect(injected.mcp).toEqual({});
- // Filtered on delivery, not by a hidden write: the rows are unchanged.
+ // The raw legacy row remains readable only so removal/credential cleanup
+ // can repair it; runtime and engine boundaries never expose it.
expect((await readRuntimeOpencodeConfig(config, "ws_1")).mcp?.["omnirush-ui"]).toEqual(LEGACY);
});
});
diff --git a/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts b/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts
index c6a1b3b0..2d7ec3c1 100644
--- a/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts
+++ b/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts
@@ -1,23 +1,89 @@
+type ConfigTarget = {
+ mcp?: unknown;
+ permission?: unknown;
+ permissions?: unknown;
+ tools?: unknown;
+};
+
+type ToolBeforeInput = {
+ tool?: unknown;
+};
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function configTarget(input: unknown, output: unknown): ConfigTarget | null {
+ if (isRecord(output)) return output;
+ return isRecord(input) ? input : null;
+}
+
+function serverNamesFromConfig(value: unknown): string[] {
+ if (!isRecord(value) || !isRecord(value.mcp)) return [];
+ return Object.keys(value.mcp).filter((name) => name.trim().length > 0);
+}
+
+function normalizedServerName(name: string): string {
+ return name.replace(/[^a-zA-Z0-9_-]/g, "_");
+}
+
+function deniedPatterns(serverNames: Iterable<string>): string[] {
+ const patterns = new Set<string>(["mcp.*", "mcp:*", "mcp_*"]);
+ for (const name of serverNames) {
+ const normalized = normalizedServerName(name);
+ patterns.add(`${normalized}_*`);
+ patterns.add(`${normalized}___*`);
+ patterns.add(`mcp.${name}.*`);
+ patterns.add(`mcp:${name}:*`);
+ patterns.add(`tool.${normalized}_*`);
+ }
+ return [...patterns];
+}
+
+function withDenyRules(value: unknown, patterns: string[]): Record<string, unknown> {
+ const existing = isRecord(value) ? value : {};
+ return Object.fromEntries([
+ ...Object.entries(existing),
+ ...patterns.map((pattern) => [pattern, "deny"] as const),
+ ]);
+}
+
+function isDeniedMcpTool(tool: string, serverNames: Iterable<string>): boolean {
+ if (tool.startsWith("mcp_") || tool.startsWith("mcp.") || tool.startsWith("mcp:")) return true;
+ return [...serverNames].some((name) => {
+ const normalized = normalizedServerName(name);
+ return tool === normalized
+ || tool.startsWith(`${normalized}_`)
+ || tool.startsWith(`${normalized}___`);
+ });
+}
+
/**
- * Engine-side MCP fence. The HTTP/UI checks are useful for normal clients,
- * but an OpenCode config can also come from a workspace file or a direct
- * engine request. This hook removes those servers before the model sees
- * them for every server process, including locally configured engines.
+ * Engine-side MCP fence. HTTP checks protect OmniRush routes, while these
+ * hooks cover workspace/global config discovery inside a managed v1 engine.
+ * The config hook supports both OpenCode hook shapes, and the execution hook
+ * catches the actual `<server>_<tool>` IDs rather than relying on `mcp.*`.
*/
export default async function omnirushMcpPolicy() {
+ const serverNames = new Set<string>();
+ const applyFence = (input: unknown, output?: unknown): void => {
+ const target = configTarget(input, output);
+ if (!target) return;
+ for (const name of serverNamesFromConfig(target)) serverNames.add(name);
+ const patterns = deniedPatterns(serverNames);
+ target.mcp = {};
+ target.permission = withDenyRules(target.permission, patterns);
+ target.permissions = withDenyRules(target.permissions, patterns);
+ target.tools = withDenyRules(target.tools, patterns);
+ };
+
return {
- // OpenCode 1.x has shipped both config(config) and config(input, output)
- // hook shapes; accept either so the fence survives engine upgrades.
- config: async (input: unknown, output?: { mcp?: unknown; permission?: Record<string, unknown> }) => {
- const target = output && typeof output === "object"
- ? output
- : (input && typeof input === "object" ? input as { mcp?: unknown; permission?: Record<string, unknown> } : null);
- if (!target) return;
- target.mcp = {};
- target.permission = {
- ...(target.permission ?? {}),
- "mcp.*": "deny",
- };
+ config: async (input: unknown, output?: unknown) => {
+ applyFence(input, output);
+ },
+ "tool.execute.before": async (input: ToolBeforeInput) => {
+ if (typeof input.tool !== "string" || !isDeniedMcpTool(input.tool, serverNames)) return;
+ throw new Error("MCP tools are disabled in OmniRush.ai.");
},
};
}
diff --git a/apps/server/src/routes/cloud-mcp.ts b/apps/server/src/routes/cloud-mcp.ts
index 67875045..3be070f9 100644
--- a/apps/server/src/routes/cloud-mcp.ts
+++ b/apps/server/src/routes/cloud-mcp.ts
@@ -95,91 +95,15 @@ export function registerCloudMcpRoutes(options: RegisterCloudMcpRoutesOptions):
serverMetadata,
} = options;
- addRoute(routes, "GET", "/workspace/:id/mcp/omnirush-cloud/health", "client", async (ctx) => {
+ addRoute(routes, "GET", "/workspace/:id/mcp/omnirush-cloud/health", "client", async () => {
assertMcpAllowed(config);
- const workspace = await resolveWorkspace(config, ctx.params.id);
- assertExactWorkspace(ctx.params.id, workspace);
- const health = await readOmniRushCloudMcpHealth({
- config,
- workspace,
- directory: resolveOpencodeDirectory(workspace),
- providerModel: providerModelFromQuery(ctx.url),
- serverMetadata,
- probe: probeFromQuery(ctx.url),
- createWorkspaceOpencodeClient,
- refreshRegistrationFromLiveStatus,
- });
- return jsonResponse(health);
});
- addRoute(routes, "POST", "/workspace/:id/mcp/omnirush-cloud/engine-refresh", "client", async (ctx) => {
+ addRoute(routes, "POST", "/workspace/:id/mcp/omnirush-cloud/engine-refresh", "client", async () => {
assertMcpAllowed(config);
- ensureWritable(config);
- requireClientScope(ctx, "collaborator");
- const workspace = await resolveWorkspace(config, ctx.params.id);
- assertExactWorkspace(ctx.params.id, workspace);
- // The refresh needs no payload; an optional body may scope provider/model
- // and name the trigger for the delivery ledger. An absent/empty body is
- // fine, but malformed JSON stays a hard 400 — never silently ignored.
- const raw = (await ctx.request.text()).trim();
- let body: Record<string, unknown> = {};
- if (raw) {
- let parsed: unknown;
- try {
- parsed = JSON.parse(raw);
- } catch {
- throw new ApiError(400, "invalid_json", "Invalid JSON body");
- }
- if (!isRecord(parsed)) {
- throw new ApiError(400, "invalid_payload", "JSON object body is required");
- }
- body = parsed;
- }
- assertStrictBody(body, workspace);
- const result = await refreshOmniRushCloudMcpEngine({
- config,
- workspace,
- directory: resolveOpencodeDirectory(workspace),
- providerModel: providerModelFromBody(body),
- serverMetadata,
- createWorkspaceOpencodeClient,
- registerRuntimeMcp,
- refreshRegistrationFromLiveStatus,
- trigger: typeof body.trigger === "string" ? body.trigger : undefined,
- });
- return jsonResponse(result);
});
- addRoute(routes, "POST", "/workspace/:id/mcp/omnirush-cloud/reconcile", "client", async (ctx) => {
+ addRoute(routes, "POST", "/workspace/:id/mcp/omnirush-cloud/reconcile", "client", async () => {
assertMcpAllowed(config);
- ensureWritable(config);
- requireClientScope(ctx, "collaborator");
- const workspace = await resolveWorkspace(config, ctx.params.id);
- assertExactWorkspace(ctx.params.id, workspace);
- const body = await readJsonBody(ctx.request);
- if (!isRecord(body)) {
- throw new ApiError(400, "invalid_payload", "JSON object body is required");
- }
- assertStrictBody(body, workspace);
- // Reconcile persists the account-global desired config (it reconfigures
- // Connect for every workspace). Collaborator scope suffices only for
- // trusted endpoints; anything else needs the owner.
- const configBody = isRecord(body.config) ? body.config : body;
- const endpointUrl = typeof configBody.url === "string" ? configBody.url : "";
- if (!await isTrustedCloudMcpEndpointForGlobalPersist(endpointUrl)) {
- requireClientScope(ctx, "owner");
- }
- const health = await reconcileOmniRushCloudMcp({
- config,
- workspace,
- directory: resolveOpencodeDirectory(workspace),
- body,
- providerModel: providerModelFromBody(body),
- serverMetadata,
- createWorkspaceOpencodeClient,
- registerRuntimeMcp,
- refreshRegistrationFromLiveStatus,
- });
- return jsonResponse(health);
});
}
diff --git a/apps/server/src/runtime-opencode-config-store.test.ts b/apps/server/src/runtime-opencode-config-store.test.ts
index f9ca4758..9eee33d1 100644
--- a/apps/server/src/runtime-opencode-config-store.test.ts
+++ b/apps/server/src/runtime-opencode-config-store.test.ts
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { resolveApprovalMode } from "./approval-mode.js";
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
import { policyRequestActions } from "./managed-policy-rules.js";
-import { addMcp, listMcp, setMcpEnabled } from "./mcp.js";
+import { listMcp } from "./mcp.js";
import { buildOmniRushRuntimeConfig } from "./omnirush-runtime-config.js";
import { readOmniRushWorkspaceConfig } from "./omnirush-workspace-config-store.js";
import { addPlugin, listPlugins, removePlugin } from "./plugins.js";
@@ -105,14 +105,14 @@ describe("runtime OpenCode config store", () => {
try {
const first = await writeRuntimeOpencodeConfig(config, WORKSPACE_ID, (current) => ({
...current,
- mcp: { posthog: { type: "remote", url: "https://mcp.posthog.com/mcp", enabled: true } },
+ provider: { "fixture-provider": { npm: "@ai-sdk/openai" } },
}));
expect(first.changed).toBe(true);
expect(writes).toBe(1);
const second = await writeRuntimeOpencodeConfig(config, WORKSPACE_ID, (current) => ({
...current,
- mcp: { posthog: { type: "remote", url: "https://mcp.posthog.com/mcp", enabled: true } },
+ provider: { "fixture-provider": { npm: "@ai-sdk/openai" } },
}));
expect(second.changed).toBe(false);
expect(second.config).toEqual(first.config);
@@ -122,30 +122,33 @@ describe("runtime OpenCode config store", () => {
...current,
mcp: { posthog: { type: "remote", url: "https://mcp.posthog.com/mcp", enabled: false } },
}));
- expect(third.changed).toBe(true);
- expect(writes).toBe(2);
+ expect(third.changed).toBe(false);
+ expect(third.config).toEqual(first.config);
+ expect(writes).toBe(1);
} finally {
unsubscribe();
}
});
});
- test("stores MCP changes in the OmniRush.ai runtime DB without rewriting workspace files", async () => {
+ test("drops MCP writes without rewriting workspace files", async () => {
await withWorkspace(async ({ root, config }) => {
const opencodePath = join(root, "opencode.jsonc");
const opencode = '{\n "mcp": {\n "project": { "type": "remote", "url": "https://project.example/mcp" }\n }\n}\n';
await writeFile(opencodePath, opencode, "utf8");
- await addMcp(config, WORKSPACE_ID, "runtime", { type: "remote", url: "https://runtime.example/mcp", enabled: true });
- await setMcpEnabled(config, WORKSPACE_ID, "runtime", false);
+ const result = await writeRuntimeOpencodeConfig(config, WORKSPACE_ID, (current) => ({
+ ...current,
+ mcp: { runtime: { type: "remote", url: "https://runtime.example/mcp", enabled: true } },
+ }));
expect(await readFile(opencodePath, "utf8")).toBe(opencode);
await expectMissing(join(root, ".opencode", "omnirush.json"));
- expect((await readRuntimeOpencodeConfig(config, WORKSPACE_ID)).mcp?.runtime?.enabled).toBe(false);
+ expect(result.changed).toBe(true);
+ expect((await readRuntimeOpencodeConfig(config, WORKSPACE_ID)).mcp).toBeUndefined();
const items = await listMcp(config, WORKSPACE_ID, root);
- expect(items.map((item) => `${item.name}:${item.source}`)).toContain("project:config.project");
- expect(items.map((item) => `${item.name}:${item.source}`)).toContain("runtime:config.remote");
+ expect(items).toEqual([]);
});
});
@@ -167,7 +170,6 @@ describe("runtime OpenCode config store", () => {
const result = await listPlugins(config, WORKSPACE_ID, root, false);
expect(result.items.map((item) => item.spec)).toEqual(["project-plugin", "runtime-plugin"]);
- await addMcp(config, WORKSPACE_ID, "runtime", { type: "remote", url: "https://runtime.example/mcp", enabled: true });
const runtimeConfig = JSON.parse(await buildOmniRushRuntimeConfig(config)) as {
plugin?: string[];
mcp?: Record<string, Record<string, unknown>>;
@@ -181,13 +183,12 @@ describe("runtime OpenCode config store", () => {
test("malformed user opencode config does not block runtime config reads", async () => {
await withWorkspace(async ({ root, config }) => {
await writeFile(join(root, "opencode.jsonc"), '{ "mcp": {\n}\n}\n}\n', "utf8");
- await addMcp(config, WORKSPACE_ID, "runtime", { type: "remote", url: "https://runtime.example/mcp", enabled: true });
await addPlugin(config, "runtime-plugin");
const mcpItems = await listMcp(config, WORKSPACE_ID, root);
const pluginItems = await listPlugins(config, WORKSPACE_ID, root, false);
- expect(mcpItems.map((item) => item.name)).toEqual(["runtime"]);
+ expect(mcpItems).toEqual([]);
expect(pluginItems.items.map((item) => item.spec)).toEqual(["runtime-plugin"]);
});
});
@@ -246,7 +247,6 @@ describe("runtime OpenCode config store", () => {
plugin: ["plugin-a", "plugin-shared"],
disabled_providers: ["anthropic"],
permission: { external_directory: { "/folders/a": "allow" } },
- mcp: { notion: { type: "remote", url: "https://notion.example/mcp" } },
provider: { "user-lmstudio": { npm: "@ai-sdk/openai-compatible", options: { baseURL: "https://a.example/v1" } }, local: { npm: "stale-copy" } },
default_agent: "omnirush",
}));
@@ -281,13 +281,13 @@ describe("runtime OpenCode config store", () => {
options: { baseURL: "https://b.example/v1" },
});
- // Workspace rows are cleaned; mcp stays per-workspace (dynamic push owns delivery).
+ // Workspace rows are cleaned; MCP is omitted from all engine-visible rows.
const workspaceA = await readRuntimeOpencodeConfig(config, "ws_a");
expect(workspaceA.plugin).toBeUndefined();
expect(workspaceA.disabled_providers).toBeUndefined();
expect(workspaceA.permission).toBeUndefined();
expect(workspaceA.provider).toBeUndefined();
- expect(workspaceA.mcp?.notion?.url).toBe("https://notion.example/mcp");
+ expect(workspaceA.mcp).toBeUndefined();
expect(workspaceA.default_agent).toBe("omnirush");
expect(await readRuntimeOpencodeConfig(config, "ws_b")).toEqual({});
@@ -314,17 +314,13 @@ describe("runtime OpenCode config store", () => {
await withWorkspace(async ({ root, config }) => {
await mkdir(join(root, ".opencode"), { recursive: true });
await writeFile(join(root, ".opencode", "omnirush.json"), "{ invalid\n", "utf8");
- await addMcp(config, WORKSPACE_ID, "runtime", { type: "remote", url: "https://runtime.example/mcp" });
-
const server = await startServer(config) as Served;
try {
const response = await fetch(`http://127.0.0.1:${server.port}/workspace/${WORKSPACE_ID}/runtime-config`, {
headers: { authorization: `Bearer ${config.token}` },
});
expect(response.status).toBe(200);
- expect(await response.json()).toMatchObject({
- runtimeKeys: ["mcp"],
- });
+ expect(await response.json()).toMatchObject({ runtimeKeys: [] });
} finally {
await server.stop(true);
}
diff --git a/apps/server/src/runtime-opencode-config-store.ts b/apps/server/src/runtime-opencode-config-store.ts
index 21c15f87..6dbc1a3a 100644
--- a/apps/server/src/runtime-opencode-config-store.ts
+++ b/apps/server/src/runtime-opencode-config-store.ts
@@ -31,9 +31,6 @@ export type RuntimeOpencodeConfig = {
export const ENGINE_GLOBAL_RUNTIME_CONFIG_ID = "__omnirush_engine_global__";
-/** Reserved Connect MCP name; kept in sync with OMNIRUSH_CLOUD_MCP_NAME in cloud-mcp-health.ts. */
-const OMNIRUSH_CLOUD_MCP_RESERVED_NAME = "omnirush-cloud";
-
export function isEngineGlobalRuntimeConfigId(workspaceId: string): boolean {
return workspaceId === ENGINE_GLOBAL_RUNTIME_CONFIG_ID;
}
@@ -63,6 +60,12 @@ function normalizeRuntimeOpencodeConfig(value: unknown): RuntimeOpencodeConfig {
};
}
+/** Remove MCP before a runtime config crosses an engine or diagnostics boundary. */
+export function withoutMcpRuntimeConfig(config: RuntimeOpencodeConfig): RuntimeOpencodeConfig {
+ const { mcp: _mcp, ...rest } = config;
+ return rest;
+}
+
function parseRuntimeOpencodeConfig(configJson: string): RuntimeOpencodeConfig {
try {
return normalizeRuntimeOpencodeConfig(JSON.parse(configJson));
@@ -246,15 +249,6 @@ export function mergeRuntimeOpencodeConfigLayers(
...runtimeDisabledProviderList(base),
...runtimeDisabledProviderList(overlay),
]);
- const mcp = {
- ...runtimeMcpMap(base),
- ...runtimeMcpMap(overlay),
- };
- // The Connect MCP is account-scoped: the global row is authoritative, so a
- // stale legacy per-workspace copy must not shadow it. Mirrors
- // OMNIRUSH_CLOUD_MCP_NAME in cloud-mcp-health.ts (import would be cyclic).
- const globalCloudMcp = runtimeMcpMap(base)[OMNIRUSH_CLOUD_MCP_RESERVED_NAME];
- if (globalCloudMcp) mcp[OMNIRUSH_CLOUD_MCP_RESERVED_NAME] = globalCloudMcp;
const basePermission = isRecord(base.permission) ? base.permission : {};
const overlayPermission = isRecord(overlay.permission) ? overlay.permission : {};
const externalDirectory = {
@@ -279,7 +273,6 @@ export function mergeRuntimeOpencodeConfigLayers(
...(base.default_agent || overlay.default_agent ? { default_agent: overlay.default_agent ?? base.default_agent } : {}),
...(plugin.length ? { plugin } : {}),
...(disabledProviders.length ? { disabled_providers: disabledProviders } : {}),
- ...(Object.keys(mcp).length ? { mcp } : {}),
...(Object.keys(permission).length ? { permission } : {}),
...(Object.keys(provider).length ? { provider } : {}),
});
@@ -308,13 +301,13 @@ export async function readEffectiveRuntimeOpencodeConfig(
workspaceId: string,
): Promise<RuntimeOpencodeConfig> {
if (isEngineGlobalRuntimeConfigId(workspaceId)) {
- return withoutRegistryOmniRushUiMcp(await readRuntimeOpencodeConfig(config, workspaceId));
+ return withoutMcpRuntimeConfig(withoutRegistryOmniRushUiMcp(await readRuntimeOpencodeConfig(config, workspaceId)));
}
const [globalRuntime, workspaceRuntime] = await Promise.all([
readGlobalRuntimeOpencodeConfig(config),
readRuntimeOpencodeConfig(config, workspaceId),
]);
- return withoutRegistryOmniRushUiMcp(mergeRuntimeOpencodeConfigLayers(globalRuntime, workspaceRuntime));
+ return withoutMcpRuntimeConfig(withoutRegistryOmniRushUiMcp(mergeRuntimeOpencodeConfigLayers(globalRuntime, workspaceRuntime)));
}
/**
@@ -465,7 +458,7 @@ function inspectRuntimeConfigRow(
return { status: "invalid-row", config: {} };
}
}
- return { status: "available", config: normalizeRuntimeOpencodeConfig(parsed) };
+ return { status: "available", config: withoutMcpRuntimeConfig(normalizeRuntimeOpencodeConfig(parsed)) };
} catch {
return { status: "invalid-row", config: {} };
}
@@ -587,7 +580,11 @@ function updateRuntimeConfig(
const result = pending.catch(() => undefined).then(async () => {
const row = await runtimeOpencodeConfigStore.getRow(config, workspaceId);
const current = row?.value ?? {};
- const next = refuseRegistryOmniRushUiMcp(current, normalizeRuntimeOpencodeConfig(updater(current)));
+ // MCP is never persisted by a runtime write. Existing rows are allowed to
+ // be read by cleanup code, but the next write removes every registration.
+ const next = withoutMcpRuntimeConfig(
+ refuseRegistryOmniRushUiMcp(current, normalizeRuntimeOpencodeConfig(updater(current))),
+ );
const configJson = runtimeOpencodeConfigStore.serialize(next);
if (row?.valueJson === configJson) return { config: next, changed: false };
await runtimeOpencodeConfigStore.setSerialized(config, workspaceId, configJson, Date.now());
@@ -618,7 +615,6 @@ export function writeManagedDesktopPolicy(config: ServerConfig, policy: DesktopC
export function mergeOpencodeConfigs(
persisted: Record<string, unknown>,
runtime: RuntimeOpencodeConfig,
- mcpEnabled = true,
): Record<string, unknown> {
const persistedPermission = isRecord(persisted.permission) ? persisted.permission : {};
const persistedExternalDirectory = isRecord(persistedPermission.external_directory)
@@ -635,12 +631,7 @@ export function mergeOpencodeConfigs(
...(Array.isArray(persisted.disabled_providers) ? persisted.disabled_providers.filter((item) => typeof item === "string") : []),
...runtimeDisabledProviderList(runtime),
].filter((item, index, list) => list.indexOf(item) === index),
- mcp: mcpEnabled
- ? {
- ...(isRecord(persisted.mcp) ? persisted.mcp : {}),
- ...runtimeMcpMap(runtime),
- }
- : {},
+ mcp: {},
permission: {
...persistedPermission,
external_directory: {
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index c2f1aed1..9a7a2248 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -45,7 +45,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, listMcp, removeMcp, setMcpEnabled } from "./mcp.js";
+import { addMcp, assertNoConfiguredMcp, listMcp, removeMcp, setMcpEnabled } from "./mcp.js";
import { buildOmniRushV2Instructions, waitForOmniRushV2Skills, OMNIRUSH_V2_INSTRUCTION_KEY } from "./opencode-v2-instructions.js";
import {
callMcpAppTool,
@@ -164,6 +164,7 @@ import {
runtimeMcpMap,
runtimeProviderMap,
type RuntimeOpencodeConfig,
+ withoutMcpRuntimeConfig,
writeGlobalRuntimeOpencodeConfig,
writeRuntimeOpencodeConfig,
} from "./runtime-opencode-config-store.js";
@@ -1645,6 +1646,10 @@ 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);
@@ -1714,13 +1719,7 @@ export async function proxyOpencodeV2Request(input: {
if (method === "POST" && sessionId && /^\/api\/session\/[^/]+\/(?:prompt|command|generate)$/.test(routePath)) {
// Session ownership was verified above. Replace one native instruction
// entry immediately before admission; never append to conversation text.
- const mcpUrl = new URL(target);
- mcpUrl.pathname = "/api/mcp";
const internalHeaders = new Headers({ authorization: headers.get("authorization") ?? "", "content-type": "application/json" });
- const mcpResponse = await loopbackFetch(mcpUrl.toString(), { headers: internalHeaders, signal: AbortSignal.timeout(10_000) });
- const mcpPayload: unknown = mcpResponse.ok ? await mcpResponse.json() : null;
- const connectReady = isRecord(mcpPayload) && Array.isArray(mcpPayload.data) && mcpPayload.data.some((entry) =>
- isRecord(entry) && entry.name === "omnirush-cloud" && isRecord(entry.status) && entry.status.status === "connected");
const skillUrl = new URL(target);
skillUrl.pathname = "/api/skill";
await waitForOmniRushV2Skills(input.workspace.path, async () => {
@@ -1728,7 +1727,7 @@ export async function proxyOpencodeV2Request(input: {
if (!response.ok) throw new ApiError(502, "engine_skill_sync_failed", "Native skills are unavailable");
return response.json();
});
- const value = buildOmniRushV2Instructions(connectReady);
+ const value = buildOmniRushV2Instructions(false);
const instructionUrl = new URL(target);
instructionUrl.pathname = `/api/session/${encodeURIComponent(sessionId)}/instructions/entries/${OMNIRUSH_V2_INSTRUCTION_KEY}`;
const synced = await loopbackFetch(instructionUrl.toString(), {
@@ -2067,6 +2066,10 @@ export async function proxyOpencodeRequest(input: {
assertMcpAllowed(input.config);
}
if (workspace && workspace.workspaceType !== "remote" && isUploadPromptDispatch(method, proxyPath)) {
+ await assertNoConfiguredMcp(
+ workspace.path,
+ await readRuntimeOpencodeConfig(input.config, workspace.id),
+ );
if (uploadDispatchRefused(input.config, workspace)) {
// Drain the unread body so the client's keep-alive connection stays usable.
await input.request.arrayBuffer().catch(() => undefined);
@@ -3208,7 +3211,6 @@ function createRoutes(
const opencode = mergeOpencodeConfigs(
await readOpencodeConfig(workspace.path),
await readEffectiveRuntimeOpencodeConfig(config, workspace.id),
- mcpAllowed(config),
);
const lastAudit = await readLastAudit(workspace.path, workspace.id);
return jsonResponse({ opencode, omnirush, updatedAt: lastAudit?.timestamp ?? null });
@@ -3271,9 +3273,6 @@ function createRoutes(
const workspace = await resolveWorkspace(config, ctx.params.id);
const body = await readJsonBody(ctx.request);
const resolved = readCloudPluginResolved(body.resolved);
- if (resolved.memberships.some((membership) => membership.configObject?.objectType === "mcp")) {
- assertMcpAllowed(config);
- }
const marketplace = body.marketplace && typeof body.marketplace === "object" && !Array.isArray(body.marketplace)
? Object.fromEntries(Object.entries(body.marketplace))
: null;
@@ -3347,9 +3346,6 @@ function createRoutes(
const dryRun = body.dryRun === true;
const bundle = await resolveClaudePluginBundle({ url, ref });
- if (bundle.resolved.memberships.some((membership) => membership.configObject?.objectType === "mcp")) {
- assertMcpAllowed(config);
- }
if (dryRun) {
return jsonResponse({ preview: bundle.preview });
}
@@ -4020,7 +4016,7 @@ function createRoutes(
addRoute(routes, "GET", "/workspace/:id/runtime-config", "client", async (ctx) => {
const workspace = await resolveWorkspace(config, ctx.params.id);
- const runtime = await readRuntimeOpencodeConfig(config, workspace.id);
+ const runtime = withoutMcpRuntimeConfig(await readRuntimeOpencodeConfig(config, workspace.id));
const rawOpencode = await readRawOpencodeConfig(opencodeConfigPath(workspace.path));
const persistedOpencode = await readOpencodeConfig(workspace.path);
const globalOpencodePath = resolveOpencodeConfigFilePath("global", workspace.path);
@@ -4172,6 +4168,9 @@ function createRoutes(
if (opencode) {
const configPath = omnirushConfigPath(workspace.path);
const nextOpencode = ensurePlainObject(opencode);
+ if (Object.prototype.hasOwnProperty.call(nextOpencode, "mcp")) {
+ assertMcpAllowed(config);
+ }
const { permission, provider, ...topLevelUpdates } = nextOpencode;
const logicalUpdates: Record<string, unknown> = { ...topLevelUpdates };
@@ -4600,244 +4599,40 @@ function createRoutes(
addRoute(routes, "POST", "/workspace/:id/mcp-apps/resolve", "client", async (ctx) => {
assertMcpAllowed(config);
- requireClientScope(ctx, "viewer");
- const workspace = await resolveWorkspace(config, ctx.params.id);
- const body = await readJsonBody(ctx.request);
- const projectedToolName = typeof body.projectedToolName === "string" ? body.projectedToolName.trim() : "";
- const launch = body.launch && typeof body.launch === "object" && !Array.isArray(body.launch)
- ? body.launch as Record<string, unknown>
- : null;
- try {
- const app = launch && typeof launch.connectionId === "string"
- ? await resolveConnectMcpAppResource({
- serverConfig: config,
- workspaceId: workspace.id,
- workspaceRoot: workspace.path,
- launch: {
- connectionId: typeof launch.connectionId === "string" ? launch.connectionId : "",
- toolName: typeof launch.toolName === "string" ? launch.toolName : "",
- resourceUri: typeof launch.resourceUri === "string" ? launch.resourceUri : "",
- },
- })
- : launch
- ? await resolveSameServerMcpAppResource({
- serverConfig: config,
- workspaceId: workspace.id,
- workspaceRoot: workspace.path,
- projectedToolName,
- launch: {
- toolName: typeof launch.toolName === "string" ? launch.toolName : "",
- resourceUri: typeof launch.resourceUri === "string" ? launch.resourceUri : "",
- },
- })
- : await resolveMcpAppResource({
- serverConfig: config,
- workspaceId: workspace.id,
- workspaceRoot: workspace.path,
- projectedToolName,
- });
- return jsonResponse({ app });
- } catch (error) {
- rethrowMcpAppHostError(error);
- }
});
- addRoute(routes, "POST", "/workspace/:id/mcp-apps/call", "client", async (ctx) => {
+ addRoute(routes, "POST", "/workspace/:id/mcp-apps/call", "client", async () => {
assertMcpAllowed(config);
- requireClientScope(ctx, "viewer");
- const workspace = await resolveWorkspace(config, ctx.params.id);
- const body = await readJsonBody(ctx.request);
- const serverName = typeof body.serverName === "string" ? body.serverName.trim() : "";
- const name = typeof body.name === "string" ? body.name.trim() : "";
- const resourceUri = typeof body.resourceUri === "string" ? body.resourceUri.trim() : "";
- const args = body.arguments && typeof body.arguments === "object" && !Array.isArray(body.arguments)
- ? body.arguments as Record<string, unknown>
- : {};
- const approved = body.approved === true;
- if (!serverName || !name) throw new ApiError(400, "invalid_payload", "serverName and name are required");
- if (approved) requireClientScope(ctx, "collaborator");
- try {
- return jsonResponse(await callMcpAppTool({
- serverConfig: config,
- workspaceId: workspace.id,
- workspaceRoot: workspace.path,
- serverName,
- name,
- resourceUri,
- arguments: args,
- approved,
- }));
- } catch (error) {
- rethrowMcpAppHostError(error);
- }
});
- addRoute(routes, "POST", "/workspace/:id/mcp/managed", "client", async (ctx) => {
+ addRoute(routes, "POST", "/workspace/:id/mcp/managed", "client", async () => {
assertMcpAllowed(config);
- ensureWritable(config);
- requireClientScope(ctx, "collaborator");
- const workspace = await resolveWorkspace(config, ctx.params.id);
- const body = await readJsonBody(ctx.request);
- const name = String(body.name ?? "").trim();
- validateUserMcpName(name);
- const serverUrl = typeof body.url === "string" ? body.url.trim() : "";
- const oauth = body.oauth && typeof body.oauth === "object" && !Array.isArray(body.oauth)
- ? body.oauth as Record<string, unknown>
- : {};
- if (!serverUrl) throw new ApiError(400, "invalid_payload", "Managed MCP URL is required");
- const requestedScopes = Array.isArray(oauth.requestedScopes)
- ? oauth.requestedScopes.filter((scope): scope is string => typeof scope === "string" && scope.trim().length > 0)
- : [];
- if ((await listMcp(config, workspace.id, workspace.path)).some((item) => item.name === name)) {
- throw new ApiError(409, "mcp_exists", `MCP ${name} already exists in this workspace`);
- }
- await requireApproval(ctx, {
- workspaceId: workspace.id,
- action: "mcp.add",
- summary: `Add OmniRush.ai-managed MCP ${name}`,
- paths: [omnirushConfigPath(workspace.path)],
- });
- await createLocalManagedMcpConnection(config, {
- workspaceId: workspace.id,
- name,
- serverUrl,
- oauth: {
- applicationType: oauth.applicationType === "web" ? "web" : "native",
- requestedScopes,
- ...(typeof oauth.authorizationServerIssuer === "string" && oauth.authorizationServerIssuer.trim()
- ? { authorizationServerIssuer: oauth.authorizationServerIssuer.trim() }
- : {}),
- ...(typeof oauth.clientId === "string" && oauth.clientId.trim() ? { clientId: oauth.clientId.trim() } : {}),
- ...(typeof oauth.clientSecret === "string" && oauth.clientSecret.trim() ? { clientSecret: oauth.clientSecret.trim() } : {}),
- },
- });
- const result = await (async () => {
- try {
- return await startLocalManagedMcpAuthorization(config, workspace.id, name);
- } catch (error) {
- // Creation writes the encrypted connection and runtime facade before
- // OAuth discovery starts. If that first handshake fails, roll both back
- // so the failed Add request cannot leave a ghost connection behind.
- await deleteLocalManagedMcp(config, workspace.id, name).catch(() => undefined);
- if (error instanceof ApiError) throw error;
- const cause = (error instanceof Error ? error.message : String(error)).trim().slice(0, 300);
- throw new ApiError(
- 502,
- "managed_mcp_connection_failed",
- `OmniRush.ai could not start sign-in with this MCP server. Check the server URL, OAuth settings, and network connection, then try again.${cause ? ` (${cause})` : ""}`,
- cause ? { cause } : undefined,
- );
- }
- })();
- await syncRuntimeMcpToOpencodeEngine(config, workspace, [name], undefined, engineMcpServerState).catch(() => undefined);
- await recordAudit(workspace.path, {
- id: shortId(),
- workspaceId: workspace.id,
- actor: ctx.actor ?? { type: "remote" },
- action: "mcp.add",
- target: omnirushConfigPath(workspace.path),
- summary: `Added OmniRush.ai-managed MCP ${name}`,
- timestamp: Date.now(),
- });
- emitReloadEvent(ctx.reloadEvents, workspace, "mcp", { type: "mcp", name, action: "added" });
- return jsonResponse(result, 201);
});
- addRoute(routes, "GET", "/workspace/:id/mcp/:name/managed", "client", async (ctx) => {
+ addRoute(routes, "GET", "/workspace/:id/mcp/:name/managed", "client", async () => {
assertMcpAllowed(config);
- const workspace = await resolveWorkspace(config, ctx.params.id);
- return jsonResponse(await getLocalManagedMcpConnection(config, workspace.id, ctx.params.name ?? ""));
});
- addRoute(routes, "POST", "/workspace/:id/mcp/:name/managed/connect", "client", async (ctx) => {
+ addRoute(routes, "POST", "/workspace/:id/mcp/:name/managed/connect", "client", async () => {
assertMcpAllowed(config);
- ensureWritable(config);
- requireClientScope(ctx, "collaborator");
- const workspace = await resolveWorkspace(config, ctx.params.id);
- const name = String(ctx.params.name ?? "").trim();
- validateMcpName(name);
- const result = await startLocalManagedMcpAuthorization(config, workspace.id, name);
- await syncRuntimeMcpToOpencodeEngine(config, workspace, [name], undefined, engineMcpServerState).catch(() => undefined);
- return jsonResponse(result);
});
- addRoute(routes, "GET", "/mcp/oauth/callback", "none", async (ctx) => {
+ addRoute(routes, "GET", "/mcp/oauth/callback", "none", async () => {
assertMcpAllowed(config);
- const state = ctx.url.searchParams.get("state") ?? "";
- const code = ctx.url.searchParams.get("code") ?? "";
- if (!state || !code) throw new ApiError(400, "managed_mcp_oauth_callback_invalid", "OAuth callback is missing code or state");
- const { connection, workspaceId } = await completeLocalManagedMcpAuthorization(config, state, code, ctx.url.searchParams.get("iss") ?? undefined);
- const workspace = config.workspaces.find((item) => item.id === workspaceId);
- if (workspace) {
- await syncRuntimeMcpToOpencodeEngine(config, workspace, [connection.name], undefined, engineMcpServerState).catch(() => undefined);
- }
- return new Response(
- `<!doctype html><meta charset="utf-8"><title>Connected</title><main style="font:16px system-ui;padding:40px;max-width:560px"><h1>Connected</h1><p>${connection.name} is ready in OmniRush.ai. You can close this window.</p><script>setTimeout(()=>window.close(),1200)</script></main>`,
- { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } },
- );
});
- const managedGatewayHandler = async (ctx: RequestContext) => {
+ const managedGatewayHandler = async () => {
assertMcpAllowed(config);
- return handleLocalManagedMcpGateway(
- config,
- ctx.request,
- ctx.params.workspaceId ?? "",
- ctx.params.name ?? "",
- );
};
addRoute(routes, "POST", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);
addRoute(routes, "GET", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);
addRoute(routes, "DELETE", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);
- addRoute(routes, "POST", "/workspace/:id/mcp", "client", async (ctx) => {
+ addRoute(routes, "POST", "/workspace/:id/mcp", "client", async () => {
assertMcpAllowed(config);
- ensureWritable(config);
- requireClientScope(ctx, "collaborator");
- const workspace = await resolveWorkspace(config, ctx.params.id);
- const body = await readJsonBody(ctx.request);
- const name = String(body.name ?? "");
- validateUserMcpName(name);
- const configPayload = body.config as Record<string, unknown> | undefined;
- if (!configPayload) {
- throw new ApiError(400, "invalid_payload", "MCP config is required");
- }
- await requireApproval(ctx, {
- workspaceId: workspace.id,
- action: "mcp.add",
- summary: `Add MCP ${name}`,
- paths: [omnirushConfigPath(workspace.path)],
- });
- const result = await addMcp(config, workspace.id, name, configPayload);
- // Hot-add into the running engine so connect/auth works immediately,
- // without waiting for an engine instance rebuild.
- await syncRuntimeMcpToOpencodeEngine(
- config,
- workspace,
- [name],
- undefined,
- engineMcpServerState,
- ).catch(() => undefined);
- await recordAudit(workspace.path, {
- id: shortId(),
- workspaceId: workspace.id,
- actor: ctx.actor ?? { type: "remote" },
- action: "mcp.add",
- target: omnirushConfigPath(workspace.path),
- summary: `Added MCP ${name}`,
- timestamp: Date.now(),
- });
- emitReloadEvent(ctx.reloadEvents, workspace, "mcp", {
- type: "mcp",
- name,
- action: result.action,
- });
- const items = await listMcp(config, workspace.id, workspace.path);
- return jsonResponse({ items });
});
addRoute(routes, "DELETE", "/workspace/:id/mcp/:name", "client", async (ctx) => {
- assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -4888,7 +4683,6 @@ function createRoutes(
// Toggle `enabled` on a workspace MCP. Strict body validation — `Boolean(body.enabled)`
// would silently disable on `{}` or coerce `"false"` to true.
addRoute(routes, "POST", "/workspace/:id/mcp/:name/enabled", "client", async (ctx) => {
- assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -4898,6 +4692,7 @@ function createRoutes(
throw new ApiError(400, "invalid_payload", "enabled must be a boolean");
}
const enabled = body.enabled;
+ if (enabled) assertMcpAllowed(config);
const action = enabled ? "mcp.enable" : "mcp.disable";
const summary = `${enabled ? "Enable" : "Disable"} MCP ${name}`;
await requireApproval(ctx, {
@@ -4938,7 +4733,6 @@ function createRoutes(
});
addRoute(routes, "DELETE", "/workspace/:id/mcp/:name/auth", "client", async (ctx) => {
- assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -5976,16 +5770,17 @@ async function syncRuntimeMcpToOpencodeEngine(
serverState?: EngineMcpServerState | null,
): Promise<EngineMcpSyncResult> {
if (!mcpAllowed(config)) {
- // Existing runtime rows are retained for auditability, but must not remain
- // live in an engine under the deny policy.
- const runtimeConfig = await readEffectiveRuntimeOpencodeConfig(config, workspace.id).catch(() => undefined);
- const names = Object.keys(runtimeConfig ? runtimeMcpMap(runtimeConfig) : {})
- .filter((name) => !onlyNames || onlyNames.includes(name));
const state = activeEngineMcpServerState(config, serverState);
- for (const name of names) {
+ const recordedNames = state
+ ? [...(state.registrationByWorkspace.get(workspace.id)?.keys() ?? [])]
+ : [];
+ const liveNames = await readEngineMcpNames(config, workspace).catch(() => []);
+ const names = [...new Set([...recordedNames, ...liveNames])]
+ .filter((name) => !onlyNames || onlyNames.includes(name));
+ await Promise.all(names.map(async (name) => {
if (state) deleteEngineMcpRegistration(config, state, workspace, name);
await disconnectMcpFromOpencodeEngine(config, workspace, name).catch(() => undefined);
- }
+ }));
return { status: "skipped", syncedNames: [], failures: [] };
}
const activeState = activeEngineMcpServerState(config, serverState);
@@ -7165,6 +6960,34 @@ async function disconnectMcpFromOpencodeEngine(
}
}
+async function readEngineMcpNames(
+ config: ServerConfig,
+ workspace: WorkspaceInfo,
+): Promise<string[]> {
+ const connection = resolveWorkspaceOpencodeConnection(config, workspace);
+ const baseUrl = connection.baseUrl?.trim() ?? "";
+ if (!baseUrl) return [];
+ const url = new URL(baseUrl);
+ url.pathname = "/mcp";
+ url.search = "";
+ const directory = resolveOpencodeDirectory(workspace);
+ if (directory) url.searchParams.set("directory", directory);
+ const headers: Record<string, string> = {};
+ if (connection.authHeader) headers.Authorization = connection.authHeader;
+ const response = await loopbackFetch(url, { headers, signal: AbortSignal.timeout(10_000) });
+ if (!response.ok) return [];
+ const payload: unknown = await response.json().catch(() => null);
+ const values = isRecord(payload) && Array.isArray(payload.data)
+ ? payload.data
+ : isRecord(payload)
+ ? Object.entries(payload).map(([name, status]) => ({ name, status }))
+ : [];
+ return values.flatMap((entry) => {
+ if (!isRecord(entry) || typeof entry.name !== "string" || !entry.name.trim()) return [];
+ return [entry.name];
+ });
+}
+
async function requireApproval(
ctx: RequestContext,
input: Omit<ApprovalRequest, "id" | "createdAt" | "actor">,
diff --git a/apps/server/src/types.ts b/apps/server/src/types.ts
index 6b045d46..5e90dfd6 100644
--- a/apps/server/src/types.ts
+++ b/apps/server/src/types.ts
@@ -14,8 +14,6 @@ export type ProviderPlacement = "in-sandbox" | "host-machine" | "client-machine"
export type LogFormat = "pretty" | "json";
-export type McpPolicyMode = "disabled";
-
export interface WorkspaceConfig {
id?: string;
path: string;
@@ -151,8 +149,6 @@ export interface ServerConfig {
hostTokenSource: "cli" | "env" | "file" | "generated";
logFormat: LogFormat;
logRequests: boolean;
- /** Server-owned MCP execution policy. */
- mcpPolicy?: McpPolicyMode;
/** In-memory secure key custody supplied by an embedding host such as OmniRush.ai Desktop. */
localManagedMcpVaultKey?: LocalManagedMcpVaultKeyProvider;
/** Desktop-owned account credentials. They remain in the embedding process and are never serialized. */