A desktop coding agent with free access to frontier models.
TypeScript
feat: supported MCP servers
Samrat Talukdar4ca6188e2958
diff --git a/apps/server/package.json b/apps/server/package.jsonindex befc2af0..e99ed89a 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -12,7 +12,7 @@"test:coverage": "bun --conditions=development test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage","test:artifacts": "bun --conditions=development test src/artifact-files.e2e.test.ts src/workspace-init.test.ts src/server.normalizeWorkspaceRelativePath.test.ts","build:enterprise-mcp-client": "pnpm --filter @omnirush/enterprise-mcp-client build",- "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",+ "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && node scripts/copy-mcp-allow.mjs && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins","build:bin": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun build --compile src/cli.ts --outfile dist/bin/omnirush-server","build:bin:all": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun ./script/build.ts --outdir dist/bin --target bun-darwin-arm64 --target bun-darwin-x64 --target bun-linux-x64 --target bun-linux-arm64 --target bun-windows-x64 --target bun-windows-arm64","prepare:npm": "pnpm build:bin && node scripts/publish-npm.mjs --prepare-only",diff --git a/apps/server/scripts/copy-mcp-allow.mjs b/apps/server/scripts/copy-mcp-allow.mjsnew file mode 100644index 00000000..2a1873ec--- /dev/null+++ b/apps/server/scripts/copy-mcp-allow.mjs@@ -0,0 +1,12 @@+// tsc does not emit the plain-JS MCP allowlist module (src/mcp-allow/mcp-allow.mjs,+// shared with the OmniRush CLI as is): copy it beside the compiled server so+// dist/mcp-allow/state.js can import it.+import { copyFileSync, mkdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const outdir = resolve(process.argv[2] ?? join(root, "dist"), "mcp-allow");+mkdirSync(outdir, { recursive: true });+for (const name of ["mcp-allow.mjs", "mcp-allow.d.mts"]) copyFileSync(join(root, "src", "mcp-allow", name), join(outdir, name));+process.stdout.write(`${JSON.stringify({ copied: outdir })}\n`);diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.tsindex 03bec94c..d6443be7 100644--- a/apps/server/src/cli.ts+++ b/apps/server/src/cli.ts@@ -34,6 +34,8 @@ import { assertOpencodeConfigCompat } from "./opencode-config-compat.js";import { adoptOpencodeCredentials, startEngine2SessionImport } from "./engine2/import.js";import { startWorkerActivityHeartbeat } from "./worker-activity-heartbeat.js";import pkg from "../package.json" with { type: "json" };+import { mcpEngineEnv } from "./mcp-allow/state.js";+import { runtimeStorageDir } from "./runtime-db.js";const args = parseCliArgs(process.argv.slice(2));@@ -97,6 +99,8 @@ if (!config.opencodeBaseUrl && process.env.OMNIRUSH_MANAGE_OPENCODE === "1") {OMNIRUSH_POLICY_TOKEN: managedDesktopPolicy(config).evaluationToken,OPENCODE_CONFIG: runtimeConfigPath,...opencodeModelsEnv,+ // The MCP plugin's policy, report and app-added servers (mcp-allow/state.ts).+ ...mcpEngineEnv(runtimeStorageDir(config)),};const engineSpawnTemplate: EngineSpawnTemplate = {bin: process.env.OMNIRUSH_OPENCODE_BIN,diff --git a/apps/server/src/cloud-plugins.ts b/apps/server/src/cloud-plugins.tsindex 3337f8e3..7279bf59 100644--- a/apps/server/src/cloud-plugins.ts+++ b/apps/server/src/cloud-plugins.ts@@ -411,7 +411,7 @@ function mcpNoConfigWarning(title: string): string {}function mcpDisabledWarning(title: string): string {- return `MCP component "${title}" was skipped because MCP servers are disabled in OmniRush.ai.`;+ return `MCP component "${title}" was skipped: MCP servers from plugins are not added. Add supported servers in Settings > MCP.`;}function mcpInactiveWarning(title: string): string {diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.tsindex 71ce08fe..de7d99b8 100644--- a/apps/server/src/embedded.ts+++ b/apps/server/src/embedded.ts@@ -50,6 +50,8 @@ import { assertOpencodeConfigCompat } from "./opencode-config-compat.js";import { adoptOpencodeCredentials, startEngine2SessionImport } from "./engine2/import.js";import type { ServeResult } from "./serve-node.js";import type { CaptureFileUpload, LocalManagedMcpVaultKeyProvider, OmniRushGatewayCredentials, ServerConfig } from "./types.js";+import { mcpEngineEnv } from "./mcp-allow/state.js";+import { runtimeStorageDir } from "./runtime-db.js";export type EmbeddedServerOptions = CliArgs & {/** When true, spawn a managed OpenCode child process. */@@ -277,6 +279,8 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): PromiOMNIRUSH_POLICY_TOKEN: managedDesktopPolicy(config).evaluationToken,OPENCODE_CONFIG: runtimeConfigPath,...opencodeModelsEnv,+ // The MCP plugin's policy, report and app-added servers (mcp-allow/state.ts).+ ...mcpEngineEnv(runtimeStorageDir(config)),...pluginsNoDepsEnv(omnirushOwnPluginPaths()),// Agent assist: the plugin's switch file and notes folder, the language servers' heap cap....agentAssistEngineEnv(config, process.env, { diagnostics: agentAssistFlags(await readGlobalRuntimeOpencodeConfig(config)).diagnostics }),diff --git a/apps/server/src/engine-plugin-bridge.e2e.test.ts b/apps/server/src/engine-plugin-bridge.e2e.test.tsindex df5875da..77ba3cb0 100644--- a/apps/server/src/engine-plugin-bridge.e2e.test.ts+++ b/apps/server/src/engine-plugin-bridge.e2e.test.ts@@ -9,6 +9,9 @@ import {omnirushMcpPolicyPluginPath,omnirushTitleRecoveryPluginPath,} from "./omnirush-extensions-plugin-path.js";+import { readReport, writePolicyFile } from "./mcp-allow/mcp-allow.mjs";+import { writeWorkspaceMcp } from "./mcp-allow/state.js";+import policyFixture from "./mcp-allow/mcp-policy.fixture.json" with { type: "json" };/*** OmniRush plugins that patch the global fetch the engine sends model@@ -19,8 +22,10 @@ import {* 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;- * - MCP policy: a configured local MCP is removed before the supported- * engine exposes its inventory or sends provider tools.+ * - MCP policy: the server's list applies to every configured MCP (the+ * engine config, the user's and the project's files, the app-added+ * ones): servers off the list never reach the engine's inventory or the+ * provider's tools, and the plugin's report says why.** Skipped when the sidecar binary is not present (prepare:sidecar not run).*/@@ -132,6 +137,9 @@ rl.on("line", (line) => {mkdirSync(join(data, "xdg-config", "opencode"), { recursive: true });writeFileSync(join(data, "xdg-config", "opencode", "opencode.jsonc"), `// another tool\n${JSON.stringify({ mcp: { blender: userMcp(join(data, "blender-started")) } })}`);writeFileSync(join(work, "opencode.json"), JSON.stringify({ mcp: { supabase: userMcp(join(data, "supabase-started")) } }));+ // The server's list (the backend's default) and one server the app added for this project.+ writePolicyFile(join(data, "mcp", "policy.json"), policyFixture);+ writeWorkspaceMcp(data, work, { "files-outside": { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/etc"], enabled: true } });const configPath = join(data, "runtime-opencode-config.json");writeFileSync(configPath, JSON.stringify({model: "mock/mock-model",@@ -155,6 +163,9 @@ rl.on("line", (line) => {OPENCODE_DISABLE_MODELS_FETCH: "1",OMNIRUSH_SERVER_URL: base,OMNIRUSH_POLICY_TOKEN: "policy",+ OMNIRUSH_MCP_POLICY_FILE: join(data, "mcp", "policy.json"),+ OMNIRUSH_MCP_REPORT_DIR: join(data, "mcp", "reports"),+ OMNIRUSH_MCP_WORKSPACE_DIR: join(data, "mcp", "workspaces"),OMNIRUSH_SERVER_TOKEN: "server",HOME: join(data, "home"),OPENCODE_TEST_HOME: join(data, "home"),@@ -196,7 +207,7 @@ rl.on("line", (line) => {console.log("title requests: optional parameters", JSON.stringify(refused));}, 90_000);- test("a configured MCP never reaches the engine inventory or provider tools", async () => {+ test("MCP servers off the list never reach the engine inventory or provider tools; the report says why", async () => {seen.length = 0;const status = await waitFor(async () => {const response = await engineFetch("/mcp");@@ -206,6 +217,16 @@ rl.on("line", (line) => {expect(status.anyof).toBeUndefined();expect(status.blender).toBeUndefined();expect(status.supabase).toBeUndefined();+ expect(status["files-outside"]).toBeUndefined();+ expect(status.filesystem).toBeUndefined();++ const report = await waitFor(async () => readReport(join(data, "mcp", "reports"), work), "the MCP report");+ expect(report.enabled).toBe(true);+ const byName = Object.fromEntries(report.decisions.map((decision) => [decision.name, decision]));+ expect(byName.anyof).toMatchObject({ status: "blocked", code: "unknown_command" });+ expect(byName.supabase).toMatchObject({ status: "blocked", code: "unknown_command" });+ expect(byName.blender).toMatchObject({ status: "blocked", code: "unknown_command" });+ expect(byName["files-outside"]).toMatchObject({ status: "blocked", code: "outside_project" });await prompt({ providerID: "anth", modelID: "claude-mock" }, "Use the export tool.");await waitFor(async () => seen.find((entry) => entry.path === "/v1/messages"), "an Anthropic request");diff --git a/apps/server/src/mcp-allow/PARITY.sha256 b/apps/server/src/mcp-allow/PARITY.sha256new file mode 100644index 00000000..d8ba0364--- /dev/null+++ b/apps/server/src/mcp-allow/PARITY.sha256@@ -0,0 +1,4 @@+# The MCP allowlist module: the same files in omnirush-cli (src/mcp/) and omnirush-gui (apps/server/src/mcp-allow/).+# A change to one must be ported to the other and this list updated in both.+ed7f09f9d1c1e442ff6d6d044d63f0c3edc62312bf25239947dcd3f715390bdd mcp-allow.mjs+0f43a2d8a25b5ea2bec2172fe477c8b052f02af093a981fd3b04412f4ccfb98a mcp-allow.d.mtsdiff --git a/apps/server/src/mcp-allow/mcp-allow-parity.test.ts b/apps/server/src/mcp-allow/mcp-allow-parity.test.tsnew file mode 100644index 00000000..d77d4818--- /dev/null+++ b/apps/server/src/mcp-allow/mcp-allow-parity.test.ts@@ -0,0 +1,19 @@+// The MCP allowlist module is the same pair of files in omnirush-cli (src/mcp/)+// and here; PARITY.sha256 lists their hashes in both repositories, so a change+// in one shows up here until it is ported.+import { describe, expect, test } from "bun:test";+import { createHash } from "node:crypto";+import { readFileSync } from "node:fs";+import path from "node:path";++describe("CLI/desktop parity: MCP allowlist", () => {+ test("mcp-allow/PARITY.sha256 matches its files", () => {+ const rows = readFileSync(path.join(import.meta.dir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));+ expect(rows.map((row) => row.split(/\s+/)[1])).toEqual(["mcp-allow.mjs", "mcp-allow.d.mts"]);+ for (const row of rows) {+ const [hash, name] = row.split(/\s+/);+ const actual = createHash("sha256").update(readFileSync(path.join(import.meta.dir, name ?? ""))).digest("hex");+ expect(`${name} ${actual}`).toBe(`${name} ${hash}`);+ }+ });+});diff --git a/apps/server/src/mcp-allow/mcp-allow.d.mts b/apps/server/src/mcp-allow/mcp-allow.d.mtsnew file mode 100644index 00000000..e2cf4788--- /dev/null+++ b/apps/server/src/mcp-allow/mcp-allow.d.mts@@ -0,0 +1,108 @@+// Types of mcp-allow.mjs (the same pair of files in omnirush-cli src/mcp/ and+// omnirush-gui apps/server/src/mcp-allow/; PARITY.sha256).++export const MCP_POLICY_FILE_VERSION: 1;+export const MCP_REASONS: Record<McpDecisionCode, string>;++export type McpRuntime = "npm" | "pypi";+export type McpDecisionCode =+ | "allowed" | "disabled" | "remote" | "unknown_command" | "not_allowed" | "denied"+ | "version" | "outside_project" | "missing_flag" | "missing_arg" | "flag" | "duplicate" | "invalid";++export type McpRules = {+ path_args?: "positional";+ min_args?: number;+ default_args?: string[];+ path_flags?: string[];+ require_flags?: string[];+ add_flags?: string[];+ forbid_flags?: string[];+ path_env?: Record<string, string>;+ local_urls?: boolean;+ path_inputs?: string[];+};++export type McpAllowEntry = {+ id: string;+ runtime: McpRuntime;+ package: string;+ bins: string[];+ versions: string;+ pin: string | null;+ title: string;+ why: string | null;+ rules: McpRules;+};++export type McpPolicy = {+ enabled: boolean;+ allow: McpAllowEntry[];+ deny: Array<{ match: string; reason: string | null }>;+ message: string | null;+};++export type McpDecision = {+ name: string;+ status: "allowed" | "blocked";+ code: McpDecisionCode;+ reason?: string;+ id?: string;+ package?: string;+ runtime?: McpRuntime;+ title?: string;+ version?: string;+ sandbox?: boolean;+ renamed_to?: string;+ url_host?: string | null;+ notes?: string[];+};++export type McpBox = { shell: string; key: string; croot?: string | null };++export type McpReport = { v: 1; root: string; at: number; enabled: boolean; decisions: McpDecision[] };++export type McpLaunch = {+ runtime: McpRuntime;+ name: string;+ version: string | null;+ bin: string | null;+ specIndex: number;+ rest: string[];+ restIndex: number;+};++export function versionParts(value: unknown): number[] | null;+export function versionInRange(version: unknown, range: unknown): boolean;+export function validRange(range: unknown): boolean;+export function normalizePolicy(block: unknown): McpPolicy | null;+export function splitSpec(spec: string, runtime: McpRuntime): { name: string; version: string | null } | null;+export function parseLaunch(command: unknown): McpLaunch | null;+export function insideRoot(root: string, p: string, platform?: string): boolean;+export function shellQuote(word: string): string;+export function evaluateMcp(+ mcpMap: unknown,+ policy: McpPolicy | null,+ ctx?: { root?: string; platform?: string; box?: McpBox | null },+): { mcp: Record<string, Record<string, unknown>>; decisions: McpDecision[] };+export function toolPrefix(name: string): string;+export function toolRefusal(+ state: { localOnly?: string[]; pathInputs?: Array<{ id: string; keys: string[] }>; roots?: Array<{ root: string; platform: string }> },+ tool: unknown,+ args: unknown,+): string | null;+export function readPolicyFile(file: string | null | undefined): McpPolicy | null;+export function writePolicyFile(file: string, block: unknown, now?: number): string;+export function reportPath(dir: string, root: string): string;+export function readReport(dir: string, root: string): McpReport | null;+export function describeDecision(d: McpDecision): string;+export function createMcpPolicyHooks(options?: {+ directory?: string;+ policyFile?: string | null;+ reportDir?: string | null;+ box?: McpBox | null | ((root: string) => McpBox | null);+ platform?: string;+ now?: () => number;+}): {+ config: (input: unknown, output?: unknown) => Promise<void>;+ "tool.execute.before": (input: { tool?: unknown; args?: unknown }, output?: { args?: unknown }) => Promise<void>;+};diff --git a/apps/server/src/mcp-allow/mcp-allow.mjs b/apps/server/src/mcp-allow/mcp-allow.mjsnew file mode 100644index 00000000..41d64ec5--- /dev/null+++ b/apps/server/src/mcp-allow/mcp-allow.mjs@@ -0,0 +1,588 @@+// MCP servers in the managed engine: the server's list of the ones a session+// may use (GET /collect/capabilities `mcp`), applied to the engine's final+// configuration by the engine plugin (createMcpPolicyHooks).+//+// The same file ships in omnirush-cli (src/mcp/) and omnirush-gui+// (apps/server/src/mcp-allow/); PARITY.sha256 lists it in both. No imports+// beyond node: built-ins, so the desktop's plugin bundler and the CLI's+// plain node both load it as is.+//+// A server is allowed only when it is a LOCAL program the app can name:+// launched through npx/bunx/pnpm dlx/yarn dlx/npm exec (npm) or uvx/uv tool+// run (PyPI) with a package on the server's list, at a version in the+// entry's range (an unpinned launch runs the entry's `pin`), and with every+// folder or file it works on inside the project. Remote servers, servers the+// app cannot name (a script path, docker, a bare binary) and everything not on+// the list are left out of the engine; the report says which and why.+//+// Allowed servers are keyed by the entry's id (the engine names their tools+// `<id>_<tool>`), so the same server gets the same tool names whatever the+// user called it. With the project's sandbox on, they run in the sandbox.++import { createHash } from "node:crypto";+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import path from "node:path";++export const MCP_POLICY_FILE_VERSION = 1;++/** Messages people see, by decision code. */+export const MCP_REASONS = {+ disabled: "MCP servers are turned off for this account.",+ remote: "Remote MCP servers are not supported: their answers come from an outside service or account, so the session could not be repeated.",+ unknown_command: "The app cannot tell which MCP server this is. Start it with npx (npm packages) or uvx (Python packages) and the package name.",+ not_allowed: "This MCP server is not on the supported list. Supported servers work only on the project's own files.",+ denied: "This MCP server is not supported.",+ version: "This version of the MCP server is not supported.",+ outside_project: "This MCP server may only use files inside the project folder.",+ missing_flag: "This MCP server needs a setting that points at a file in the project.",+ missing_arg: "This MCP server needs the file it works on, inside the project, as its argument.",+ flag: "This MCP server setting is not supported: it reaches outside the project.",+ duplicate: "Another entry already starts this MCP server.",+ invalid: "This MCP server entry is not valid.",+};++const ID = /^[a-z0-9][a-z0-9-]{0,39}$/;+const NPM_RUNNERS = new Set(["npx", "bunx", "pnpx"]);+const DLX_RUNNERS = new Set(["pnpm", "yarn"]);+const PY_RUNNERS = new Set(["uvx"]);+// Flags of the runners that take a value (the next word).+const NPX_VALUE_FLAGS = new Set(["-p", "--package", "--registry", "--cache", "--userconfig", "-c", "--call", "--prefix", "-w", "--workspace"]);+const UVX_VALUE_FLAGS = new Set(["--from", "--with", "--with-requirements", "--python", "-p", "--index", "--index-url", "--extra-index-url", "--default-index", "--directory", "--project", "--cache-dir", "--config-file", "--with-editable"]);+const LOCAL_URL = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|[\w.-]+\.localhost)(:\d+)?(\/|$|\?|#)|^(about|data):/i;++function isRecord(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function strings(value, limit = 64) {+ return Array.isArray(value) ? value.filter((v) => typeof v === "string" && v.length > 0 && v.length < 300).slice(0, limit) : [];+}++function text(value, limit = 400) {+ return typeof value === "string" && value.trim() ? value.trim().slice(0, limit) : null;+}++// ------------------------------------------------------------------ versions++/** Numeric parts of a plain dotted version ("2026.8.31", "0.0.83"); null for anything else. */+export function versionParts(value) {+ const match = /^v?(\d+(?:\.\d+){0,3})$/.exec(String(value ?? "").trim());+ return match ? match[1].split(".").map(Number) : null;+}++function compare(a, b) {+ for (let i = 0; i < Math.max(a.length, b.length); i += 1) {+ const d = (a[i] ?? 0) - (b[i] ?? 0);+ if (d !== 0) return d < 0 ? -1 : 1;+ }+ return 0;+}++/**+ * Whether `version` is in `range`: "*" (or empty) is any version; otherwise+ * space-separated terms that all hold, each `>=x`, `>x`, `<=x`, `<x`, `=x`+ * or a bare `x`. Only plain dotted versions match a range other than "*".+ */+export function versionInRange(version, range) {+ const wanted = String(range ?? "*").trim();+ if (wanted === "" || wanted === "*") return true;+ const have = versionParts(version);+ if (!have) return false;+ return wanted.split(/\s+/).every((term) => {+ const m = /^(>=|<=|>|<|=)?(.+)$/.exec(term);+ const want = m ? versionParts(m[2]) : null;+ if (!want) return false;+ const c = compare(have, want);+ switch (m[1] ?? "=") {+ case ">=": return c >= 0;+ case ">": return c > 0;+ case "<=": return c <= 0;+ case "<": return c < 0;+ default: return c === 0;+ }+ });+}++/** Whether `range` is one versionInRange understands. */+export function validRange(range) {+ const wanted = String(range ?? "*").trim();+ if (wanted === "" || wanted === "*") return true;+ return wanted.split(/\s+/).every((term) => {+ const m = /^(>=|<=|>|<|=)?(.+)$/.exec(term);+ return Boolean(m && versionParts(m[2]));+ });+}++// -------------------------------------------------------------------- policy++function normalizeRules(value) {+ const rules = isRecord(value) ? value : {};+ const out = {};+ if (rules.path_args === "positional") out.path_args = "positional";+ if (Number.isInteger(rules.min_args) && rules.min_args > 0 && rules.min_args < 9) out.min_args = rules.min_args;+ const defaults = strings(rules.default_args, 8);+ if (defaults.length) out.default_args = defaults;+ for (const key of ["path_flags", "require_flags", "add_flags", "forbid_flags"]) {+ const list = strings(rules[key], 32).filter((f) => f.startsWith("-"));+ if (list.length) out[key] = list;+ }+ if (isRecord(rules.path_env)) {+ const env = Object.fromEntries(Object.entries(rules.path_env)+ .filter(([k, v]) => /^[A-Z_][A-Z0-9_]{0,63}$/.test(k) && typeof v === "string" && v.length < 200 && !path.isAbsolute(v) && !v.split(/[\\/]/).includes(".."))+ .slice(0, 8));+ if (Object.keys(env).length) out.path_env = env;+ }+ if (rules.local_urls === true) out.local_urls = true;+ const inputs = strings(rules.path_inputs, 16).filter((k) => /^[A-Za-z_][\w]{0,63}$/.test(k));+ if (inputs.length) out.path_inputs = inputs;+ return out;+}++function normalizeEntry(value) {+ if (!isRecord(value)) return null;+ const id = text(value.id, 40)?.toLowerCase();+ const runtime = value.runtime === "npm" || value.runtime === "pypi" ? value.runtime : null;+ const pkg = text(value.package, 214);+ if (!id || !ID.test(id) || !runtime || !pkg || !/^(@[\w.-]+\/)?[\w.-]+$/.test(pkg)) return null;+ const pin = text(value.pin, 40);+ if (pin && !versionParts(pin)) return null;+ const versions = text(value.versions, 120) ?? "*";+ if (!validRange(versions)) return null;+ if (pin && !versionInRange(pin, versions)) return null;+ return {+ id,+ runtime,+ package: pkg,+ bins: strings(value.bins, 8),+ versions,+ pin,+ title: text(value.title, 80) ?? id,+ why: text(value.why, 400),+ rules: normalizeRules(value.rules),+ };+}++function normalizeDeny(value) {+ if (typeof value === "string") return text(value, 214) ? { match: value.trim().toLowerCase(), reason: null } : null;+ if (!isRecord(value)) return null;+ const match = text(value.match, 214)?.toLowerCase();+ return match ? { match, reason: text(value.reason, 400) } : null;+}++/**+ * The `mcp` block of a /collect/capabilities answer as the app uses it:+ * `{enabled, allow, deny, message}`; null when absent or unreadable (MCP off).+ */+export function normalizePolicy(block) {+ if (!isRecord(block)) return null;+ const allow = [];+ const seen = new Set();+ for (const raw of Array.isArray(block.allow) ? block.allow.slice(0, 64) : []) {+ const entry = normalizeEntry(raw);+ if (entry && !seen.has(entry.id)) { seen.add(entry.id); allow.push(entry); }+ }+ const deny = (Array.isArray(block.deny) ? block.deny.slice(0, 128) : []).map(normalizeDeny).filter(Boolean);+ return { enabled: block.enabled === true, allow, deny, message: text(block.message, 400) };+}++// -------------------------------------------------------------- the launches++function programName(word) {+ return String(word || "").split(/[\\/]/).pop().toLowerCase().replace(/\.(cmd|exe|bat|ps1)$/, "");+}++/** `@scope/[email protected]` / `[email protected]` / `name==1.2.3` -> {name, version}. */+export function splitSpec(spec, runtime) {+ const raw = String(spec || "");+ if (runtime === "pypi") {+ const eq = /^([A-Za-z0-9][\w.-]*)(?:\[[^\]]*\])?\s*(?:==|@)\s*([\w.+-]+)$/.exec(raw);+ if (eq) return { name: eq[1].toLowerCase(), version: eq[2] };+ const bare = /^([A-Za-z0-9][\w.-]*)(?:\[[^\]]*\])?$/.exec(raw);+ return bare ? { name: bare[1].toLowerCase(), version: null } : null;+ }+ const m = /^((?:@[\w.-]+\/)?[\w.-]+)(?:@(.+))?$/.exec(raw);+ if (!m) return null;+ return { name: m[1].toLowerCase(), version: m[2] && m[2] !== "latest" ? m[2] : null };+}++/**+ * What a local launch runs, or null when the app cannot name it:+ * `{runtime, name, version, bin, prefix, rest, specIndex, viaFrom}` where+ * `command[specIndex]` is the package spec (the one rewritten to pin) and+ * `rest` the server's own arguments.+ */+export function parseLaunch(command) {+ const argv = strings(command, 256);+ if (argv.length === 0 || argv.length !== (Array.isArray(command) ? command.length : -1)) return null;+ const prog = programName(argv[0]);+ let i = 1;+ let runtime = null;+ if (NPM_RUNNERS.has(prog)) runtime = "npm";+ else if (DLX_RUNNERS.has(prog) && argv[1] === "dlx") { runtime = "npm"; i = 2; }+ else if (prog === "npm" && (argv[1] === "exec" || argv[1] === "x")) { runtime = "npm"; i = 2; }+ else if (PY_RUNNERS.has(prog)) runtime = "pypi";+ else if (prog === "uv" && argv[1] === "tool" && argv[2] === "run") { runtime = "pypi"; i = 3; }+ if (!runtime) return null;+ const valueFlags = runtime === "npm" ? NPX_VALUE_FLAGS : UVX_VALUE_FLAGS;+ let from = null;+ let fromIndex = -1;+ for (; i < argv.length; i += 1) {+ const word = argv[i];+ if (word === "--") { i += 1; break; }+ if (!word.startsWith("-")) break;+ const [flag, inline] = word.includes("=") ? [word.slice(0, word.indexOf("=")), word.slice(word.indexOf("=") + 1)] : [word, null];+ const isFrom = runtime === "npm" ? flag === "-p" || flag === "--package" : flag === "--from";+ if (runtime === "npm" && (flag === "-c" || flag === "--call")) return null;+ if (runtime === "pypi" && (flag === "--with" || flag === "--with-requirements" || flag === "--with-editable" || flag.includes("index") || flag === "--directory" || flag === "--project")) return null;+ if (runtime === "npm" && (flag === "--registry" || flag === "--prefix" || flag === "-w" || flag === "--workspace")) return null;+ if (valueFlags.has(flag)) {+ if (inline === null) {+ if (isFrom) { if (from !== null) return null; from = argv[i + 1] ?? null; fromIndex = i + 1; }+ i += 1;+ } else if (isFrom) { if (from !== null) return null; from = inline; fromIndex = -2 - i; }+ }+ }+ if (i >= argv.length) return null;+ const first = argv[i];+ const spec = from ?? first;+ const parsed = splitSpec(spec, runtime);+ if (!parsed) return null;+ return {+ runtime,+ name: parsed.name,+ version: parsed.version,+ bin: from !== null ? programName(splitSpec(first, runtime)?.name ?? first) : null,+ specIndex: from !== null ? fromIndex : i,+ rest: argv.slice(i + 1),+ restIndex: i + 1,+ };+}++/** `command` with the package spec pinned to `version`. */+function pinned(command, launch, version) {+ const out = [...command];+ const spec = launch.runtime === "npm" ? `${launch.name}@${version}` : `${launch.name}==${version}`;+ if (launch.specIndex >= 0) {+ if (launch.runtime === "pypi" && launch.bin === null) out[launch.specIndex] = `${launch.name}@${version}`;+ else out[launch.specIndex] = spec;+ } else {+ const at = -2 - launch.specIndex;+ out[at] = `${out[at].slice(0, out[at].indexOf("="))}=${spec}`;+ }+ return out;+}++// ---------------------------------------------------------------------- paths++function samePlatformPath(p, platform) {+ return platform === "win32" ? p.toLowerCase() : p;+}++/** Whether `p` (relative: to `root`) is `root` or inside it. `~` paths are outside. */+export function insideRoot(root, p, platform = process.platform) {+ const value = String(p ?? "");+ if (!value || value.startsWith("~")) return false;+ const lib = platform === "win32" ? path.win32 : path.posix;+ const base = lib.resolve(root);+ const full = lib.resolve(base, value);+ const rel = lib.relative(samePlatformPath(base, platform), samePlatformPath(full, platform));+ return rel === "" || (!rel.startsWith("..") && !lib.isAbsolute(rel));+}++/** A path inside `root` as the sandbox sees it (`croot`); relative paths stay relative. */+function boxPath(p, root, box, platform) {+ if (!box || !box.croot || box.croot === root) return p;+ const lib = platform === "win32" ? path.win32 : path.posix;+ if (!lib.isAbsolute(p)) return p.split("\\").join("/");+ const rel = lib.relative(lib.resolve(root), lib.resolve(p)).split("\\").join("/");+ return rel ? `${box.croot.replace(/\/+$/, "")}/${rel}` : box.croot;+}++function flagValue(args, flag) {+ for (let i = 0; i < args.length; i += 1) {+ if (args[i] === flag) return { index: i + 1, value: args[i + 1] ?? null, inline: false };+ if (args[i].startsWith(`${flag}=`)) return { index: i, value: args[i].slice(flag.length + 1), inline: true };+ }+ return null;+}++// ------------------------------------------------------------------ the shell++/** POSIX single-quoting for the sandbox shell. */+export function shellQuote(word) {+ const s = String(word);+ return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;+}++// ------------------------------------------------------------------- evaluate++function denyReason(policy, ...keys) {+ for (const rule of policy.deny) {+ for (const key of keys) {+ if (!key) continue;+ const k = String(key).toLowerCase();+ if (k === rule.match || (rule.match.endsWith("*") && k.startsWith(rule.match.slice(0, -1)))) return rule.reason ?? MCP_REASONS.denied;+ }+ }+ return null;+}++function hostOf(url) {+ try { return new URL(String(url)).hostname.toLowerCase(); } catch { return null; }+}++function blocked(name, code, extra = {}) {+ return { name, status: "blocked", code, ...extra, reason: extra.reason ?? MCP_REASONS[code] ?? MCP_REASONS.invalid };+}++/**+ * Apply `policy` to the engine's `mcp` map. `ctx`: `{root, platform, box}`+ * where `box` is `{shell, key, croot}` when the project's sandbox is on.+ * Returns `{mcp, decisions}`: the map the engine gets (allowed servers only,+ * keyed by their ids) and one decision per configured entry.+ */+export function evaluateMcp(mcpMap, policy, ctx = {}) {+ const root = ctx.root || process.cwd();+ const platform = ctx.platform || process.platform;+ const box = ctx.box && typeof ctx.box.shell === "string" && typeof ctx.box.key === "string" ? ctx.box : null;+ const out = {};+ const decisions = [];+ const entries = isRecord(mcpMap) ? Object.entries(mcpMap) : [];+ for (const [name, raw] of entries) {+ if (!isRecord(raw)) { decisions.push(blocked(name, "invalid")); continue; }+ if (!policy || !policy.enabled) { decisions.push(blocked(name, "disabled", policy?.message ? { reason: policy.message } : {})); continue; }+ if (raw.type === "remote" || typeof raw.url === "string") {+ const reason = denyReason(policy, name, hostOf(raw.url));+ decisions.push(blocked(name, "remote", { url_host: hostOf(raw.url), ...(reason ? { reason: `${reason} ${MCP_REASONS.remote}` } : {}) }));+ continue;+ }+ if (raw.type !== undefined && raw.type !== "local") { decisions.push(blocked(name, "invalid")); continue; }+ const command = Array.isArray(raw.command) ? raw.command : null;+ const launch = command ? parseLaunch(command) : null;+ if (!launch) {+ const reason = denyReason(policy, name);+ decisions.push(blocked(name, reason ? "denied" : "unknown_command", reason ? { reason } : {}));+ continue;+ }+ const denied = denyReason(policy, launch.name);+ if (denied) { decisions.push(blocked(name, "denied", { reason: denied, package: launch.name })); continue; }+ const entry = policy.allow.find((e) => e.runtime === launch.runtime && e.package.toLowerCase() === launch.name+ && (launch.bin === null || e.bins.length === 0 || e.bins.includes(launch.bin)));+ if (!entry) { decisions.push(blocked(name, "not_allowed", { package: launch.name })); continue; }+ const base = { id: entry.id, package: entry.package, runtime: entry.runtime, title: entry.title };+ if (Object.hasOwn(out, entry.id)) { decisions.push(blocked(name, "duplicate", base)); continue; }+ let version = launch.version;+ const notes = [];+ if (version === null) {+ if (!entry.pin) { decisions.push(blocked(name, "version", { ...base, reason: `${MCP_REASONS.version} Name a version (for example ${launch.name}@1.2.3).` })); continue; }+ version = entry.pin;+ notes.push(`runs version ${version}`);+ } else if (!versionInRange(version, entry.versions)) {+ decisions.push(blocked(name, "version", { ...base, version, reason: `${MCP_REASONS.version} Supported: ${entry.versions}${entry.pin ? ` (leave the version out to run ${entry.pin})` : ""}.` }));+ continue;+ }+ let argv = launch.version === null ? pinned(command, launch, version) : [...command];+ const restAt = launch.restIndex;+ let rest = argv.slice(restAt);+ const rules = entry.rules;+ const environment = isRecord(raw.environment) ? Object.fromEntries(Object.entries(raw.environment).filter(([, v]) => typeof v === "string")) : {};+ let refusal = null;+ for (const flag of rules.forbid_flags ?? []) {+ if (flagValue(rest, flag)) { refusal = blocked(name, "flag", { ...base, version, reason: `${MCP_REASONS.flag} (${flag})` }); break; }+ }+ if (!refusal) for (const flag of rules.require_flags ?? []) {+ const found = flagValue(rest, flag);+ if (!found || !found.value) { refusal = blocked(name, "missing_flag", { ...base, version, reason: `${MCP_REASONS.missing_flag} (${flag} <file in the project>)` }); break; }+ }+ const cwd = typeof raw.cwd === "string" ? raw.cwd : null;+ if (!refusal && cwd && !insideRoot(root, cwd, platform)) refusal = blocked(name, "outside_project", { ...base, version, reason: `${MCP_REASONS.outside_project} (cwd ${cwd})` });+ const lib = platform === "win32" ? path.win32 : path.posix;+ const workRoot = cwd ? lib.resolve(root, cwd) : root;+ const inside = (p) => !String(p).startsWith("~") && insideRoot(root, lib.resolve(workRoot, String(p)), platform);+ if (!refusal && rules.path_args === "positional") {+ const positional = rest.map((a, k) => [a, k]).filter(([a]) => !a.startsWith("-"));+ if (positional.length === 0 && rules.default_args) {+ rest = [...rest, ...rules.default_args];+ notes.push(`opens ${rules.default_args.join(" ")}`);+ }+ for (const [a] of rest.map((a, k) => [a, k]).filter(([a]) => !a.startsWith("-"))) {+ if (!inside(a)) { refusal = blocked(name, "outside_project", { ...base, version, reason: `${MCP_REASONS.outside_project} (${a})` }); break; }+ }+ if (!refusal && rules.min_args && rest.filter((a) => !a.startsWith("-")).length < rules.min_args) {+ refusal = blocked(name, "missing_arg", { ...base, version });+ }+ if (!refusal) rest = rest.map((a) => (a.startsWith("-") ? a : boxPath(a, root, box, platform)));+ }+ if (!refusal) for (const flag of rules.path_flags ?? []) {+ const found = flagValue(rest, flag);+ if (!found || found.value === null) continue;+ if (!inside(found.value)) { refusal = blocked(name, "outside_project", { ...base, version, reason: `${MCP_REASONS.outside_project} (${flag} ${found.value})` }); break; }+ const mapped = boxPath(found.value, root, box, platform);+ rest = [...rest];+ if (found.inline) rest[found.index] = `${flag}=${mapped}`; else rest[found.index] = mapped;+ }+ if (!refusal) for (const [key, fallback] of Object.entries(rules.path_env ?? {})) {+ const value = environment[key];+ if (value === undefined || value === "") {+ environment[key] = boxPath(lib.join(lib.resolve(root), fallback), root, box, platform);+ notes.push(`keeps its data in ${fallback.split("\\").join("/")}`);+ } else if (!inside(value)) {+ refusal = blocked(name, "outside_project", { ...base, version, reason: `${MCP_REASONS.outside_project} (${key})` });+ break;+ } else {+ environment[key] = boxPath(value, root, box, platform);+ }+ }+ if (refusal) { decisions.push(refusal); continue; }+ for (const flag of rules.add_flags ?? []) {+ if (!flagValue(rest, flag)) { rest = [...rest, flag]; notes.push(`adds ${flag}`); }+ }+ argv = [...argv.slice(0, restAt), ...rest];+ const next = { ...raw, type: "local" };+ if (box) {+ const envWords = Object.entries(environment).map(([k, v]) => `${k}=${shellQuote(v)}`);+ next.command = [box.shell, "-c", `exec ${envWords.length ? `env ${envWords.join(" ")} ` : ""}${argv.map(shellQuote).join(" ")}`];+ next.environment = { OMNIRUSH_BOX_KEY: box.key };+ notes.push("runs in the sandbox");+ } else {+ next.command = argv;+ if (Object.keys(environment).length) next.environment = environment; else delete next.environment;+ }+ out[entry.id] = next;+ decisions.push({ name, status: "allowed", code: "allowed", ...base, version, sandbox: Boolean(box), ...(name !== entry.id ? { renamed_to: entry.id } : {}), notes });+ }+ return { mcp: out, decisions };+}++// ----------------------------------------------------------------- the tools++function urlsIn(args, depth = 0) {+ if (depth > 3) return [];+ if (typeof args === "string") return /^[a-z][a-z0-9+.-]*:/i.test(args) || /^[\w.-]+\.[a-z]{2,}(?:[:/]|$)/i.test(args) ? [args] : [];+ if (Array.isArray(args)) return args.flatMap((v) => urlsIn(v, depth + 1));+ if (!isRecord(args)) return [];+ return Object.entries(args).flatMap(([k, v]) => (/url|uri|href|page|address/i.test(k) ? urlsIn(v, depth + 1) : isRecord(v) || Array.isArray(v) ? urlsIn(v, depth + 1) : []));+}++/** The engine's id of a server's tools: `<sanitized name>_`. */+export function toolPrefix(name) {+ return `${String(name).replace(/[^a-zA-Z0-9_-]/g, "_")}_`;+}++/**+ * Why the engine must not run `tool` with `args`, or null: a `local_urls`+ * server opens pages on this machine only; a `path_inputs` server's tool+ * arguments of those names must be inside the project (`state.roots`: the+ * project folder, and where the sandbox sees it). (Entries left out never+ * reach the engine, so their tools do not exist.)+ */+export function toolRefusal(state, tool, args) {+ const id = String(tool || "");+ for (const entry of state.localOnly ?? []) {+ if (!id.startsWith(toolPrefix(entry))) continue;+ const away = urlsIn(args).find((u) => !LOCAL_URL.test(u.trim()));+ if (away) return `${entry} opens pages on this machine only (localhost) in this app, so the session can be repeated: ${away.slice(0, 200)}`;+ }+ for (const { id: entry, keys } of state.pathInputs ?? []) {+ if (!id.startsWith(toolPrefix(entry)) || !isRecord(args)) continue;+ for (const key of keys) {+ const value = args[key];+ if (value === undefined || value === null || value === "") continue;+ const roots = state.roots ?? [];+ const ok = typeof value === "string" && !value.startsWith("~")+ && roots.some((r) => insideRoot(r.root, (r.platform === "win32" ? path.win32 : path.posix).resolve(r.root, value), r.platform));+ if (!ok) return `${entry} may only use files inside the project folder in this app (${key}: ${String(value).slice(0, 200)}).`;+ }+ }+ return null;+}++// --------------------------------------------------------- the plugin's hooks++/** The policy the app wrote for the engine (`{v, policy, at}`); null: MCP off. */+export function readPolicyFile(file) {+ if (!file) return null;+ try {+ const value = JSON.parse(readFileSync(file, "utf8"));+ return value && value.v === MCP_POLICY_FILE_VERSION ? normalizePolicy(value.policy) : null;+ } catch {+ return null;+ }+}++/** Write the policy file the engine plugin reads (atomic). */+export function writePolicyFile(file, block, now = Date.now()) {+ mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;+ writeFileSync(tmp, JSON.stringify({ v: MCP_POLICY_FILE_VERSION, policy: isRecord(block) ? block : null, at: now }), { mode: 0o600 });+ renameSync(tmp, file);+ return file;+}++/** Where the plugin writes a project's report under `dir`. */+export function reportPath(dir, root) {+ return path.join(dir, `${createHash("sha256").update(path.resolve(root)).digest("hex").slice(0, 24)}.json`);+}++/** A project's last report (`{v, root, at, decisions}`), or null. */+export function readReport(dir, root) {+ try {+ const value = JSON.parse(readFileSync(reportPath(dir, root), "utf8"));+ return value && value.v === MCP_POLICY_FILE_VERSION && Array.isArray(value.decisions) ? value : null;+ } catch {+ return null;+ }+}++/** One line per decision, for a terminal or a notice. */+export function describeDecision(d) {+ if (d.status === "allowed") return `MCP ${d.id}${d.renamed_to && d.name !== d.id ? ` (${d.name})` : ""}: on${d.version ? `, ${d.package}@${d.version}` : ""}${d.notes?.length ? ` (${d.notes.join("; ")})` : ""}`;+ return `MCP ${d.name}: blocked. ${d.reason}`;+}++function configTarget(input, output) {+ if (isRecord(output) && (Object.hasOwn(output, "mcp") || !isRecord(input))) return output;+ return isRecord(input) ? input : isRecord(output) ? output : null;+}++/**+ * The engine plugin's hooks. `options`: `{directory, policyFile, reportDir,+ * box (null or a function of the root returning {shell, key, croot} or+ * null), platform, now}`. The `config` hook replaces `mcp` with the allowed+ * servers (none without a readable policy); `tool.execute.before` refuses+ * non-local pages for `local_urls` servers and paths outside the project+ * for `path_inputs` servers.+ */+export function createMcpPolicyHooks(options = {}) {+ const root = path.resolve(options.directory || process.cwd());+ const state = { localOnly: [], pathInputs: [], roots: [] };+ const apply = (input, output) => {+ const target = configTarget(input, output);+ if (!target) return;+ const policy = readPolicyFile(options.policyFile);+ const box = typeof options.box === "function" ? options.box(root) : options.box ?? null;+ const { mcp, decisions } = evaluateMcp(target.mcp, policy, { root, platform: options.platform, box });+ target.mcp = mcp;+ const on = policy ? policy.allow.filter((e) => Object.hasOwn(mcp, e.id)) : [];+ state.localOnly = on.filter((e) => e.rules.local_urls).map((e) => e.id);+ state.pathInputs = on.filter((e) => e.rules.path_inputs).map((e) => ({ id: e.id, keys: e.rules.path_inputs }));+ const platform = options.platform || process.platform;+ state.roots = [{ root, platform }, ...(box && box.croot && box.croot !== root ? [{ root: box.croot, platform: "linux" }] : [])];+ if (options.reportDir) {+ try {+ const file = reportPath(options.reportDir, root);+ mkdirSync(options.reportDir, { recursive: true });+ const tmp = `${file}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify({ v: MCP_POLICY_FILE_VERSION, root, at: (options.now ?? Date.now)(), enabled: Boolean(policy?.enabled), decisions }), { mode: 0o600 });+ renameSync(tmp, file);+ } catch { /* the report is for display only */ }+ }+ };+ return {+ config: async (input, output) => { apply(input, output); },+ "tool.execute.before": async (input, output) => {+ const why = toolRefusal(state, input?.tool, output?.args ?? input?.args);+ if (why) throw new Error(why);+ },+ };+}diff --git a/apps/server/src/mcp-allow/mcp-policy.fixture.json b/apps/server/src/mcp-allow/mcp-policy.fixture.jsonnew file mode 100644index 00000000..b555d969--- /dev/null+++ b/apps/server/src/mcp-allow/mcp-policy.fixture.json@@ -0,0 +1,20 @@+{+ "enabled": true,+ "allow": [+ {"id": "filesystem", "title": "Filesystem", "runtime": "npm", "package": "@modelcontextprotocol/server-filesystem", "versions": ">=2025.1.14", "pin": "2026.8.31", "rules": {"path_args": "positional", "default_args": ["."]}},+ {"id": "git", "title": "Git", "runtime": "pypi", "package": "mcp-server-git", "versions": ">=2025.1.0", "pin": "2026.8.18", "rules": {"path_flags": ["--repository", "-r"], "path_inputs": ["repo_path"]}},+ {"id": "sqlite", "title": "SQLite", "runtime": "npm", "package": "mcp-server-sqlite-npx", "versions": ">=0.8.0", "pin": "0.8.0", "rules": {"path_args": "positional", "min_args": 1}},+ {"id": "memory", "title": "Memory", "runtime": "npm", "package": "@modelcontextprotocol/server-memory", "versions": ">=2025.4.25", "pin": "2026.8.31", "rules": {"path_env": {"MEMORY_FILE_PATH": ".mcp-memory.jsonl"}}},+ {"id": "sequential-thinking", "title": "Sequential thinking", "runtime": "npm", "package": "@modelcontextprotocol/server-sequential-thinking", "versions": ">=2025.7.1", "pin": "2026.8.31"},+ {"id": "time", "title": "Time", "runtime": "pypi", "package": "mcp-server-time", "versions": ">=2025.1.0", "pin": "2026.8.18"},+ {"id": "everything", "title": "Everything (test server)", "runtime": "npm", "package": "@modelcontextprotocol/server-everything", "versions": ">=2025.7.1", "pin": "2026.8.31"},+ {"id": "playwright", "title": "Playwright (local pages)", "runtime": "npm", "package": "@playwright/mcp", "versions": ">=0.0.40", "pin": "0.0.83", "rules": {"add_flags": ["--isolated"], "forbid_flags": ["--cdp-endpoint", "--extension", "--user-data-dir", "--storage-state", "--remote-endpoint", "--proxy-server", "--allowed-hosts"], "local_urls": true}}+ ],+ "deny": [+ {"match": "@modelcontextprotocol/server-github", "reason": "The GitHub server works on your GitHub account."},+ {"match": "api.githubcopilot.com", "reason": "The GitHub server works on your GitHub account."},+ {"match": "@upstash/context7-mcp", "reason": "Context7 answers from an online service."},+ {"match": "mcp-server-fetch", "reason": "The fetch server reads the web; use the built-in web fetch."},+ {"match": "mcp-server-sqlite", "reason": "This SQLite server no longer starts with current libraries; use npx -y mcp-server-sqlite-npx <file in the project>."}+ ]+}diff --git a/apps/server/src/mcp-allow/state.test.ts b/apps/server/src/mcp-allow/state.test.tsnew file mode 100644index 00000000..25889dd6--- /dev/null+++ b/apps/server/src/mcp-allow/state.test.ts@@ -0,0 +1,154 @@+import { afterEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";++import omnirushMcpPolicy from "../opencode-plugins/omnirush-mcp-policy.js";+import { keyOf } from "../box/plugin-lib.js";+import { readPolicyFile } from "./mcp-allow.mjs";+import {+ decideMcpEntry,+ mcpEngineEnv,+ mcpPolicyEnabled,+ mcpServersInUse,+ readWorkspaceMcp,+ rememberMcpPolicy,+ workspaceMcpReport,+ writeWorkspaceMcp,+} from "./state.js";+import policyFixture from "./mcp-policy.fixture.json" with { type: "json" };++const dirs: string[] = [];+const saved = { ...process.env };+function temp(prefix: string): string {+ const dir = mkdtempSync(path.join(tmpdir(), prefix));+ dirs.push(dir);+ return dir;+}++afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+ for (const key of ["OMNIRUSH_MCP_POLICY_FILE", "OMNIRUSH_MCP_REPORT_DIR", "OMNIRUSH_MCP_WORKSPACE_DIR", "OMNIRUSH_BOX_HOME"]) {+ if (saved[key] === undefined) delete process.env[key];+ else process.env[key] = saved[key];+ }+});++const FILESYSTEM = { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."], enabled: true };++describe("the remembered MCP list", () => {+ test("is off until seen, follows each answer, and keeps the last one when no answer came", () => {+ const state = temp("mcp-state-");+ expect(mcpPolicyEnabled(state)).toBe(false);+ expect(rememberMcpPolicy(state, null)).toBe(false);+ expect(rememberMcpPolicy(state, { mcp: policyFixture })).toBe(true);+ expect(rememberMcpPolicy(state, { mcp: policyFixture })).toBe(false);+ expect(mcpPolicyEnabled(state)).toBe(true);+ expect(readPolicyFile(mcpEngineEnv(state).OMNIRUSH_MCP_POLICY_FILE)?.allow.map((entry) => entry.id)).toContain("filesystem");+ // A failed read says nothing: the last list stays.+ expect(rememberMcpPolicy(state, undefined)).toBe(false);+ expect(mcpPolicyEnabled(state)).toBe(true);+ // A backend that sends no block: MCP off.+ expect(rememberMcpPolicy(state, { schema_versions: [1, 2] } as { mcp?: unknown })).toBe(true);+ expect(mcpPolicyEnabled(state)).toBe(false);+ });++ test("decides one entry before it is saved", () => {+ const state = temp("mcp-state-");+ const root = temp("mcp-root-");+ expect(decideMcpEntry(state, root, "filesystem", FILESYSTEM)).toMatchObject({ status: "blocked", code: "disabled" });+ rememberMcpPolicy(state, { mcp: policyFixture });+ expect(decideMcpEntry(state, root, "filesystem", FILESYSTEM)).toMatchObject({ status: "allowed", id: "filesystem", version: "2026.8.31" });+ expect(decideMcpEntry(state, root, "gh", { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-github"] })).toMatchObject({ status: "blocked", code: "denied" });+ expect(decideMcpEntry(state, root, "notion", { type: "remote", url: "https://mcp.notion.com/mcp" })).toMatchObject({ status: "blocked", code: "remote" });+ });++ test("a project's app-added entries round-trip, and none removes the file", () => {+ const state = temp("mcp-state-");+ const root = temp("mcp-root-");+ expect(writeWorkspaceMcp(state, root, { filesystem: FILESYSTEM })).toBe(true);+ expect(writeWorkspaceMcp(state, root, { filesystem: FILESYSTEM })).toBe(false);+ expect(readWorkspaceMcp(mcpEngineEnv(state).OMNIRUSH_MCP_WORKSPACE_DIR, root)).toEqual({ filesystem: FILESYSTEM });+ expect(writeWorkspaceMcp(state, root, {})).toBe(true);+ expect(readWorkspaceMcp(mcpEngineEnv(state).OMNIRUSH_MCP_WORKSPACE_DIR, root)).toEqual({});+ });+});++describe("the engine plugin (omnirush-mcp-policy)", () => {+ function setup() {+ const state = temp("mcp-state-");+ const root = temp("mcp-root-");+ const env = mcpEngineEnv(state);+ Object.assign(process.env, env);+ process.env.OMNIRUSH_BOX_HOME = path.join(state, "box-home");+ return { state, root };+ }++ test("without a list: no MCP at all, and the session environment gets no field", async () => {+ const { state, root } = setup();+ const hooks = await omnirushMcpPolicy({ directory: root });+ const output = { mcp: { filesystem: FILESYSTEM } } as Record<string, unknown>;+ await hooks.config({}, output);+ expect(output.mcp).toEqual({});+ const report = workspaceMcpReport(state, root);+ expect(report?.enabled).toBe(false);+ expect(report?.decisions[0]).toMatchObject({ name: "filesystem", status: "blocked", code: "disabled" });+ expect(mcpServersInUse(report)).toBeNull();+ });++ test("with the list: config and app-added entries are filtered, renamed to their id and pinned", async () => {+ const { state, root } = setup();+ rememberMcpPolicy(state, { mcp: policyFixture });+ writeWorkspaceMcp(state, root, { files: FILESYSTEM, notion: { type: "remote", url: "https://mcp.notion.com/mcp" } });+ const hooks = await omnirushMcpPolicy({ directory: root });+ const output = { mcp: { time: { type: "local", command: ["uvx", "mcp-server-time"] }, script: { type: "local", command: ["node", "server.js"] } } } as Record<string, unknown>;+ await hooks.config({}, output);+ const mcp = output.mcp as Record<string, { command: string[] }>;+ expect(Object.keys(mcp).sort()).toEqual(["filesystem", "time"]);+ expect(mcp.filesystem!.command).toEqual(["npx", "-y", "@modelcontextprotocol/[email protected]", "."]);+ expect(mcp.time!.command).toEqual(["uvx", "[email protected]"]);+ const report = workspaceMcpReport(state, root);+ const byName = Object.fromEntries((report?.decisions ?? []).map((decision) => [decision.name, decision]));+ expect(byName.script).toMatchObject({ status: "blocked", code: "unknown_command" });+ expect(byName.notion).toMatchObject({ status: "blocked", code: "remote" });+ expect(byName.files).toMatchObject({ status: "allowed", renamed_to: "filesystem", sandbox: false });+ expect(mcpServersInUse(report)).toEqual([+ { id: "time", package: "mcp-server-time", version: "2026.8.18", runtime: "pypi", sandbox: false },+ { id: "filesystem", package: "@modelcontextprotocol/server-filesystem", version: "2026.8.31", runtime: "npm", sandbox: false },+ ]);+ });++ test("a project whose sandbox is on runs its servers through the box shell", async () => {+ const { state, root } = setup();+ rememberMcpPolicy(state, { mcp: policyFixture });+ const home = process.env.OMNIRUSH_BOX_HOME!;+ const key = keyOf(root);+ mkdirSync(path.join(home, "boxes"), { recursive: true });+ mkdirSync(path.join(home, "shell"), { recursive: true });+ writeFileSync(path.join(home, "desktop-projects.json"), JSON.stringify({ keys: [key] }));+ writeFileSync(path.join(home, "boxes", `${key}.json`), JSON.stringify({ state: "running", croot: "/work" }));+ writeFileSync(path.join(home, "shell", process.platform === "win32" ? "bash.exe" : "bash"), "");+ const hooks = await omnirushMcpPolicy({ directory: root });+ const output = { mcp: { filesystem: FILESYSTEM } } as Record<string, unknown>;+ await hooks.config({}, output);+ const entry = (output.mcp as Record<string, { command: string[]; environment: Record<string, string> }>).filesystem!;+ expect(entry.command[0]).toBe(path.join(home, "shell", process.platform === "win32" ? "bash.exe" : "bash"));+ expect(entry.command.slice(1)).toEqual(["-c", "exec npx -y @modelcontextprotocol/[email protected] ."]);+ expect(entry.environment).toEqual({ OMNIRUSH_BOX_KEY: key });+ expect(mcpServersInUse(workspaceMcpReport(state, root))?.[0]?.sandbox).toBe(true);+ });++ test("playwright refuses pages away from this machine", async () => {+ const { state, root } = setup();+ rememberMcpPolicy(state, { mcp: policyFixture });+ const hooks = await omnirushMcpPolicy({ directory: root });+ await hooks.config({}, { mcp: { playwright: { type: "local", command: ["npx", "@playwright/mcp"] } } });+ await expect(hooks["tool.execute.before"]({ tool: "playwright_browser_navigate" }, { args: { url: "https://example.com" } })).rejects.toThrow(/this machine only/);+ await hooks["tool.execute.before"]({ tool: "playwright_browser_navigate" }, { args: { url: "http://localhost:3000" } });+ // Other tools are untouched.+ await hooks["tool.execute.before"]({ tool: "bash" }, { args: { command: "curl https://example.com" } });+ const reports = mcpEngineEnv(state).OMNIRUSH_MCP_REPORT_DIR;+ expect(readFileSync(path.join(reports, readdirSync(reports)[0] ?? ""), "utf8")).toContain("playwright");+ });+});+diff --git a/apps/server/src/mcp-allow/state.ts b/apps/server/src/mcp-allow/state.tsnew file mode 100644index 00000000..8c58d8d4--- /dev/null+++ b/apps/server/src/mcp-allow/state.ts@@ -0,0 +1,170 @@+// The desktop's side of the MCP allowlist (mcp-allow.mjs is the shared part).+//+// <state>/mcp/policy.json the server's `mcp` block as last seen (GET /collect/capabilities)+// <state>/mcp/reports/ the engine plugin's report per project (allowed and blocked servers)+// <state>/mcp/workspaces/ the MCP entries a project added in the app (runtime config), per project+//+// The engine gets the three paths in its environment; its plugin+// (opencode-plugins/omnirush-mcp-policy.ts) reads them at each project's start.+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import path from "node:path";++import {+ evaluateMcp,+ readPolicyFile,+ readReport,+ reportPath,+ writePolicyFile,+ type McpDecision,+ type McpPolicy,+ type McpReport,+} from "./mcp-allow.mjs";++export const MCP_OFF_MESSAGE = "MCP servers are turned off for this account.";++export function mcpStateDir(stateDir: string): string {+ return path.join(stateDir, "mcp");+}++export function mcpPolicyFile(stateDir: string): string {+ return path.join(mcpStateDir(stateDir), "policy.json");+}++export function mcpReportDir(stateDir: string): string {+ return path.join(mcpStateDir(stateDir), "reports");+}++export function mcpWorkspaceDir(stateDir: string): string {+ return path.join(mcpStateDir(stateDir), "workspaces");+}++/** The engine's environment for its MCP plugin. */+export function mcpEngineEnv(stateDir: string): Record<string, string> {+ return {+ OMNIRUSH_MCP_POLICY_FILE: mcpPolicyFile(stateDir),+ OMNIRUSH_MCP_REPORT_DIR: mcpReportDir(stateDir),+ OMNIRUSH_MCP_WORKSPACE_DIR: mcpWorkspaceDir(stateDir),+ };+}++/** The policy as last seen; null: MCP off (never seen, or unreadable). */+export function currentMcpPolicy(stateDir: string): McpPolicy | null {+ return readPolicyFile(mcpPolicyFile(stateDir));+}++export function mcpPolicyEnabled(stateDir: string): boolean {+ return currentMcpPolicy(stateDir)?.enabled === true;+}++/** Why MCP is off, in the server's words when it gave some. */+export function mcpOffMessage(stateDir: string): string {+ return currentMcpPolicy(stateDir)?.message ?? MCP_OFF_MESSAGE;+}++function rawBlock(stateDir: string): string {+ try {+ const value = JSON.parse(readFileSync(mcpPolicyFile(stateDir), "utf8"));+ return JSON.stringify(value?.policy ?? null);+ } catch {+ return "missing";+ }+}++/**+ * Remembers the `mcp` block of a capabilities answer; whether it changed. No+ * answer (null) keeps the last one; an answer without the block is MCP off.+ */+export function rememberMcpPolicy(stateDir: string, capabilities: { mcp?: unknown } | null | undefined): boolean {+ if (!capabilities || typeof capabilities !== "object") return false;+ const block = capabilities.mcp && typeof capabilities.mcp === "object" && !Array.isArray(capabilities.mcp) ? capabilities.mcp : null;+ const before = rawBlock(stateDir);+ if (before === JSON.stringify(block)) return false;+ try {+ writePolicyFile(mcpPolicyFile(stateDir), block);+ } catch {+ return false;+ }+ return true;+}++/** Re-reads the capabilities every `everyMs` and remembers the block; `apply` runs on a change. Returns the stop. */+export function watchMcpPolicy({ stateDir, read, apply, everyMs }: { stateDir: string; read: () => Promise<{ mcp?: unknown } | null | undefined>; apply?: () => unknown; everyMs: number }): () => void {+ let busy = false;+ const timer = setInterval(() => {+ if (busy) return;+ busy = true;+ void read()+ .then((capabilities) => (rememberMcpPolicy(stateDir, capabilities) ? apply?.() : undefined))+ .catch(() => undefined)+ .finally(() => { busy = false; });+ }, everyMs);+ timer.unref?.();+ return () => clearInterval(timer);+}++/** The file with a project's app-added MCP entries (the plugin adds them to the project's config). */+export function workspaceMcpFile(stateDir: string, root: string): string {+ return reportPath(mcpWorkspaceDir(stateDir), root);+}++/** Write (or, with no entries, remove) a project's app-added MCP entries; whether the file changed. */+export function writeWorkspaceMcp(stateDir: string, root: string, entries: Record<string, unknown>): boolean {+ const file = workspaceMcpFile(stateDir, root);+ let before: string | null = null;+ try { before = readFileSync(file, "utf8"); } catch { /* none */ }+ if (Object.keys(entries).length === 0) {+ if (before === null) return false;+ rmSync(file, { force: true });+ return true;+ }+ const next = JSON.stringify({ v: 1, root: path.resolve(root), mcp: entries });+ if (before === next) return false;+ mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.${process.pid}.tmp`;+ writeFileSync(tmp, next, { mode: 0o600 });+ renameSync(tmp, file);+ return true;+}++/** A project's app-added MCP entries as the plugin reads them. */+export function readWorkspaceMcp(dir: string | null | undefined, root: string): Record<string, Record<string, unknown>> {+ if (!dir) return {};+ try {+ const value = JSON.parse(readFileSync(reportPath(dir, root), "utf8"));+ const mcp = value?.v === 1 && value.mcp && typeof value.mcp === "object" && !Array.isArray(value.mcp) ? value.mcp : {};+ return Object.fromEntries(Object.entries(mcp).filter((entry): entry is [string, Record<string, unknown>] => Boolean(entry[1]) && typeof entry[1] === "object" && !Array.isArray(entry[1])));+ } catch {+ return {};+ }+}++/** The plugin's last report for a project, or null. */+export function workspaceMcpReport(stateDir: string, root: string): McpReport | null {+ return readReport(mcpReportDir(stateDir), path.resolve(root));+}++/**+ * What the policy says about one entry before it is saved (the add route): the+ * decision for it alone, with no sandbox (paths are checked the same way).+ */+export function decideMcpEntry(stateDir: string, root: string, name: string, entry: Record<string, unknown>): McpDecision {+ const { decisions } = evaluateMcp({ [name]: entry }, currentMcpPolicy(stateDir), { root: path.resolve(root) });+ return decisions[0] ?? { name, status: "blocked", code: "invalid", reason: "This MCP server entry is not valid." };+}++export type McpServerUse = { id: string; package: string; version: string; runtime: string; sandbox: boolean };++/** The servers a session in this project uses (from the plugin's report); null when none is on. */+export function mcpServersInUse(report: McpReport | null): McpServerUse[] | null {+ if (!report || !report.enabled) return null;+ const used = report.decisions+ .filter((decision) => decision.status === "allowed" && decision.id && decision.package && decision.version && decision.runtime)+ .map((decision) => ({+ id: decision.id as string,+ package: decision.package as string,+ version: decision.version as string,+ runtime: decision.runtime as string,+ sandbox: decision.sandbox === true,+ }));+ return used.length ? used : null;+}diff --git a/apps/server/src/mcp-policy.test.ts b/apps/server/src/mcp-policy.test.tsindex 6365340b..a14c0ed1 100644--- a/apps/server/src/mcp-policy.test.ts+++ b/apps/server/src/mcp-policy.test.ts@@ -1,20 +1,65 @@-import { describe, expect, test } from "bun:test";+import { afterEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";import { ApiError } from "./errors.js";import {assertMcpAllowed,+ MCP_DISABLED_MESSAGE,mcpAllowed,+ mcpDisabledMessage,mcpPolicyForConfig,+ refuseAccountLinkedMcp,} from "./mcp-policy.js";+import { rememberMcpPolicy } from "./mcp-allow/state.js";+import type { ServerConfig } from "./types.js";-describe("MCP execution policy", () => {- test("fails closed for bare and legacy-shaped configurations", () => {- expect(mcpPolicyForConfig({})).toBe("disabled");- expect(mcpPolicyForConfig({ mcpPolicy: "enabled" })).toBe("disabled");- 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);+const dirs: string[] = [];+function configIn(): { config: ServerConfig; dir: string } {+ const dir = mkdtempSync(path.join(tmpdir(), "mcp-policy-"));+ dirs.push(dir);+ return { config: { configPath: path.join(dir, "server.json") } as ServerConfig, dir };+}++afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("MCP policy", () => {+ test("is off until the server's list was seen", () => {+ const { config } = configIn();+ expect(mcpPolicyForConfig(config)).toBe("disabled");+ expect(mcpAllowed(config)).toBe(false);+ expect(() => assertMcpAllowed(config)).toThrow(ApiError);+ expect(mcpDisabledMessage(config)).toBe(MCP_DISABLED_MESSAGE);+ expect(MCP_DISABLED_MESSAGE).toBe("MCP servers are turned off for this account.");+ });++ test("follows the remembered list", () => {+ const { config, dir } = configIn();+ expect(rememberMcpPolicy(dir, { mcp: { enabled: true, allow: [], deny: [] } })).toBe(true);+ expect(mcpPolicyForConfig(config)).toBe("allowlist");+ expect(mcpAllowed(config)).toBe(true);+ expect(() => assertMcpAllowed(config)).not.toThrow();+ // An answer without the block: off again.+ expect(rememberMcpPolicy(dir, {})).toBe(true);+ expect(mcpAllowed(config)).toBe(false);+ });++ test("the 403 carries the server's message", () => {+ const { config, dir } = configIn();+ rememberMcpPolicy(dir, { mcp: { enabled: false, message: "Paused for maintenance." } });+ try {+ assertMcpAllowed(config);+ throw new Error("expected a refusal");+ } catch (error) {+ expect(error).toBeInstanceOf(ApiError);+ expect((error as ApiError).status).toBe(403);+ expect((error as ApiError).message).toBe("Paused for maintenance.");+ }+ });++ test("account-linked MCP stays refused", () => {+ expect(() => refuseAccountLinkedMcp()).toThrow(ApiError);});});diff --git a/apps/server/src/mcp-policy.ts b/apps/server/src/mcp-policy.tsindex 3c7a634b..f2d7a32e 100644--- a/apps/server/src/mcp-policy.ts+++ b/apps/server/src/mcp-policy.ts@@ -1,19 +1,48 @@import { ApiError } from "./errors.js";+import { runtimeStorageDir } from "./runtime-db.js";+import { currentMcpPolicy, MCP_OFF_MESSAGE } from "./mcp-allow/state.js";+import type { ServerConfig } from "./types.js";-/** MCP is disabled for every OmniRush.ai server configuration. */-export type McpPolicyMode = "disabled";+/**+ * MCP servers follow the server's list (GET /collect/capabilities `mcp`, as+ * last seen; mcp-allow/): on when the list is on, else off. Only local+ * servers on the list reach the engine (its plugin filters them).+ */+export type McpPolicyMode = "allowlist" | "disabled";-export const MCP_DISABLED_MESSAGE =- "MCP servers are disabled in OmniRush.ai.";+export const MCP_DISABLED_MESSAGE = MCP_OFF_MESSAGE;-export function mcpPolicyForConfig(_config: unknown): McpPolicyMode {- return "disabled";+/** Account-linked MCP (Connect, managed OAuth connections, MCP apps): never on in this app. */+export const MCP_ACCOUNT_LINKED_MESSAGE =+ "Connected MCP services work on an outside account, so a session could not be repeated: they are not supported in OmniRush.ai. Supported local servers are listed in Settings > MCP.";++function stateDirOf(config: unknown): string | null {+ try {+ return config && typeof config === "object" ? runtimeStorageDir(config as ServerConfig) : null;+ } catch {+ return null;+ }+}++export function mcpPolicyForConfig(config: unknown): McpPolicyMode {+ return mcpAllowed(config) ? "allowlist" : "disabled";+}++export function mcpAllowed(config: unknown): boolean {+ const dir = stateDirOf(config);+ return dir ? currentMcpPolicy(dir)?.enabled === true : false;+}++export function mcpDisabledMessage(config: unknown): string {+ const dir = stateDirOf(config);+ return (dir ? currentMcpPolicy(dir)?.message : null) ?? MCP_DISABLED_MESSAGE;}-export function mcpAllowed(_config: unknown): false {- return false;+export function assertMcpAllowed(config: unknown): void {+ if (!mcpAllowed(config)) throw new ApiError(403, "mcp_disabled", mcpDisabledMessage(config));}-export function assertMcpAllowed(_config: unknown): never {- throw new ApiError(403, "mcp_disabled", MCP_DISABLED_MESSAGE);+/** Account-linked MCP flows stay off whatever the list says. */+export function refuseAccountLinkedMcp(): never {+ throw new ApiError(403, "mcp_account_linked", MCP_ACCOUNT_LINKED_MESSAGE);}diff --git a/apps/server/src/mcp.ts b/apps/server/src/mcp.tsindex 30411732..54a9106f 100644--- a/apps/server/src/mcp.ts+++ b/apps/server/src/mcp.ts@@ -6,7 +6,10 @@ 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, MCP_DISABLED_MESSAGE } from "./mcp-policy.js";+import { assertMcpAllowed, MCP_DISABLED_MESSAGE } from "./mcp-policy.js";+import { decideMcpEntry } from "./mcp-allow/state.js";+import { runtimeStorageDir } from "./runtime-db.js";+import { isOmniRushUiMcpRegistryEntry, OMNIRUSH_UI_MCP_REGISTRY_COMMAND_MESSAGE } from "./omnirush-ui-mcp-command.js";import {readRuntimeOpencodeConfig,runtimeMcpMap,@@ -476,8 +479,12 @@ function isMcpDisabledByTools(config: Record<string, unknown>, name: string): boreturn deniedToolIds([config], "", [`${sanitizedName}___omnirush_mcp_probe__`]).length > 0;}+/**+ * The project's configured MCP entries (its config files and the app's+ * runtime row), listed whether MCP is on or off: the MCP view shows each with+ * the engine plugin's decision (on, or blocked and why).+ */export async function listMcp(serverConfig: ServerConfig, workspaceId: string, workspaceRoot: string): Promise<McpItem[]> {- if (!mcpAllowed(serverConfig)) return [];return listMcpFromRuntimeSnapshot(workspaceRoot, await readRuntimeOpencodeConfig(serverConfig, workspaceId));}@@ -610,13 +617,17 @@ export async function configuredMcpNames(])].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_DISABLED_MESSAGE, { servers: names });+ throw new ApiError(403, "mcp_disabled", MCP_ENGINE_V2_MESSAGE, { servers: names });}/**@@ -702,10 +713,17 @@ export async function addMcp(workspaceId: string,name: string,config: Record<string, unknown>,+ workspaceRoot?: string,): Promise<{ action: "added" | "updated" }> {assertMcpAllowed(serverConfig);validateUserMcpName(name);validateMcpConfig(config);+ // Only a server the list allows is saved (its reason otherwise); the engine+ // plugin applies the same list again when the project starts.+ const decision = decideMcpEntry(runtimeStorageDir(serverConfig), workspaceRoot ?? process.cwd(), name, config);+ if (decision.status !== "allowed") {+ throw new ApiError(403, "mcp_not_supported", decision.reason ?? MCP_DISABLED_MESSAGE, { code: decision.code });+ }const runtimeConfig = await readRuntimeOpencodeConfig(serverConfig, workspaceId);const mcpMap = { ...runtimeMcpMap(runtimeConfig) };const existed = Object.prototype.hasOwnProperty.call(mcpMap, name);@@ -743,7 +761,22 @@ export async function setMcpEnabled(const runtimeConfig = await readRuntimeOpencodeConfig(serverConfig, workspaceId);const mcpMap = { ...runtimeMcpMap(runtimeConfig) };if (!Object.prototype.hasOwnProperty.call(mcpMap, name)) return false;- delete mcpMap[name];+ 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.+ 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 };await writeRuntimeOpencodeConfig(serverConfig, workspaceId, (currentConfig) => ({ ...currentConfig, mcp: mcpMap }));return true;}diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex fd1bd31c..2c70d031 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -1676,6 +1676,8 @@ export class OmniRushGatewayBroker {// The install log switch, passed on as the server said it (context/install-log.ts reads it)....(installLog ? { install_log: { enabled: installLog.enabled === true, sample_percent: typeof installLog.sample_percent === "number" ? installLog.sample_percent : 100 } } : {}),...(isRecord(payload.local_box) ? { local_box: localBoxCapability(payload.local_box) } : {}),+ // The MCP list, passed on as the server said it (mcp-allow/state.ts remembers it; absent is off).+ ...(isRecord(payload.mcp) ? { mcp: payload.mcp } : {}),// Automatic compaction (session-archive/auto-compact.ts reads it; absent is off)....(isRecord(payload.auto_compact) && typeof payload.auto_compact.enabled === "boolean" && typeof payload.auto_compact.after_turns === "number"? { auto_compact: { enabled: payload.auto_compact.enabled, after_turns: payload.auto_compact.after_turns, ...(typeof payload.auto_compact.min_context_tokens === "number" ? { min_context_tokens: payload.auto_compact.min_context_tokens } : {}) } }diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.tsindex cfa3a6dc..4f60eabd 100644--- a/apps/server/src/omnirush-runtime-config.test.ts+++ b/apps/server/src/omnirush-runtime-config.test.ts@@ -82,7 +82,7 @@ async function readConfigFile(config: ServerConfig): Promise<Record<string, unkn}describe("omnirush runtime config file", () => {- test("permanent MCP ban omits MCP and adds an engine permission fence", () => {+ test("leaves MCP to the policy plugin, loaded last, with no MCP permission rules", () => {const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({ mcp: { posthog: { type: "remote", url: "https://mcp.example" } } },undefined,@@ -91,8 +91,8 @@ describe("omnirush runtime config file", () => {undefined,undefined,);- expect(parsed.mcp).toEqual({});- expect(parsed.permission).toMatchObject({ "mcp.*": "deny" });+ expect(parsed.mcp).toBeUndefined();+ expect(JSON.stringify(parsed.permission)).not.toContain("mcp");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");@@ -117,16 +117,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" }, "mcp.*": "deny", webfetch: "deny", websearch: "deny" };+ const permission = { bash: { ...gitWorkflowPermissionRules(), "*": "deny", "curl *": "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(), "mcp.*": "deny" });+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}).permission).toEqual({ bash: gitWorkflowPermissionRules() });});test("full approval mode allows every permission category; the environment overrides the setting", () => {- const permission = { bash: { "*": "allow" }, read: { "*": "allow" }, edit: "allow", "mcp.*": "deny", webfetch: "allow", websearch: "allow", doom_loop: "allow", external_directory: "allow" };+ const permission = { bash: { "*": "allow" }, read: { "*": "allow" }, edit: "allow", webfetch: "allow", websearch: "allow", doom_loop: "allow", external_directory: "allow" };const full = buildOmniRushRuntimeConfigObjectFromSnapshot({ approvals: { mode: "full" }, permission: { external_directory: { "/Users/sam/Docs": "allow" } } },undefined,@@ -155,9 +155,9 @@ 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(), "mcp.*": "deny" });+ .toEqual({ bash: gitWorkflowPermissionRules() });expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, { OMNIRUSH_APPROVALS: "full" }).permission).toEqual(permission);- expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, {}).permission).toEqual({ bash: gitWorkflowPermissionRules(), "mcp.*": "deny" });+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, {}).permission).toEqual({ bash: gitWorkflowPermissionRules() });});test("omits global-row MCPs while writing omnirush defaults into the file", async () => {@@ -174,7 +174,7 @@ describe("omnirush runtime config file", () => {expect(path).toBe(omnirushRuntimeConfigFilePath(config));const parsed = await readConfigFile(config);- expect(parsed.mcp).toEqual({});+ expect(parsed.mcp).toBeUndefined();expect(parsed.default_agent).toBe("omnirush");expect(Array.isArray(parsed.plugin)).toBe(true);if (!Array.isArray(parsed.plugin)) throw new Error("Expected runtime plugins");@@ -334,7 +334,7 @@ describe("omnirush runtime config file", () => {"ui-bundled": bundled,},});- expect(built.mcp).toEqual({});+ expect(built.mcp).toBeUndefined();});test("omnirush prompt states identity, repo memory, artifacts, and Connect routing once, without the removed Memory Bank", async () => {@@ -593,7 +593,7 @@ describe("omnirush runtime config file", () => {// The refresh is fire-and-forget; poll briefly for the rewrite.await new Promise((resolve) => setTimeout(resolve, 50));const parsed = await readConfigFile(config);- expect(parsed.mcp).toEqual({});+ expect(parsed.mcp).toBeUndefined();});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.tsindex 4321e2a1..9b3ed74f 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -231,8 +231,10 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(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 = { "mcp.*": "deny" };- const { managedPolicy: _managedPolicy, approvals: _approvals, bestPractices: _bestPractices, agentAssist: _agentAssist, ...engineConfig } = runtimeConfig;+ // The global row's MCP entries are the account-linked Connect server, which+ // this app does not run; a project's own servers reach the engine through+ // its config files and the MCP plugin (opencode-plugins/omnirush-mcp-policy.ts).+ const { managedPolicy: _managedPolicy, approvals: _approvals, bestPractices: _bestPractices, agentAssist: _agentAssist, mcp: _mcp, ...engineConfig } = runtimeConfig;// Code diagnostics: the main languages' servers on, the rest off; the engine default (none) while off.const lsp = agentAssistFlags(runtimeConfig, env).diagnostics ? agentAssistLspConfig() : undefined;const enabled = bestPracticesEnabled(runtimeConfig);@@ -264,7 +266,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(...ownProviders,...(runtimeConfig.managedPolicy.allowZenModel !== false ? ["opencode"] : []),] } : onlyOwnProviders ? { enabled_providers: ownProviders } : {}),- permission: { ...engineConfig.permission, ...permissions, ...mcpPermission },+ permission: { ...engineConfig.permission, ...permissions },// omnirush.ai's own on-demand skills (the swarm procedure)....(skillPaths.length ? { skills: { paths: skillPaths } } : {}),default_agent: runtimeConfig.default_agent ?? "omnirush",@@ -280,7 +282,6 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(prompt: enabled ? `${OMNIRUSH_AGENT_PROMPT}\n\n${OMNIRUSH_BEST_PRACTICES.systemPrompt}` : OMNIRUSH_AGENT_PROMPT,permission: {...permissions,- ...mcpPermission,skill: {// OmniRush.ai supplies its own current skill routing and no longer// supports these engine or legacy workspace skills.@@ -313,15 +314,12 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(plugin: [...omnirushLeadingPluginPaths(),...runtimePluginList(runtimeConfig),- // This must be last: user/runtime plugins may not reintroduce MCP- // configuration or replace the deny rules.+ // This must be last: it applies the server's MCP list to the final+ // configuration, after every other plugin.omnirushMcpPolicyPluginPath(),],...(disabledProviders.length ? { disabled_providers: disabledProviders } : {}),...(lsp ? { lsp } : {}),- // 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.tsindex b4f5c995..4aafe59c 100644--- a/apps/server/src/omnirush-ui-mcp-guard.e2e.test.ts+++ b/apps/server/src/omnirush-ui-mcp-guard.e2e.test.ts@@ -15,10 +15,15 @@ import {} from "./runtime-opencode-config-store.js";import { registerTrustedOpencodeProcess, startServer, syncAllWorkspacesRuntimeMcpToEngine } from "./server.js";import type { ServerConfig } from "./types.js";+import { rememberMcpPolicy, workspaceMcpFile } from "./mcp-allow/state.js";+import { runtimeStorageDir } from "./runtime-db.js";+import policyFixture from "./mcp-allow/mcp-policy.fixture.json" with { type: "json" };-// Whatever reaches the stored config, a registry launch of omnirush-ui-mcp-// (desktop 1.0.x wrote `npx -y omnirush-ui-mcp`) must never be accepted by a-// write route or handed to the engine.+// MCP servers follow the server's list: off until it was seen; with it, only+// the supported local servers are stored, and nothing is pushed into a+// running engine (the engine's MCP plugin applies the list). A registry launch+// of omnirush-ui-mcp (desktop 1.0.x wrote `npx -y omnirush-ui-mcp`) is never+// accepted by a write route or handed to the engine.type EngineRequest = { method: string; pathname: string; body: unknown };@@ -121,9 +126,31 @@ async function seedRuntimeRow(config: ServerConfig, workspaceId: string, value:}}-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 () => {+function allowList(config: ServerConfig) {+ rememberMcpPolicy(runtimeStorageDir(config), { mcp: policyFixture });+}++describe("MCP allowlist at the HTTP and runtime boundaries", () => {+ test("off until the list was seen: adds are refused and the view says why", async () => {+ const { config, engine } = await fixture();+ const { call } = await start(config, engine.baseUrl);++ const response = await call("POST", "/workspace/ws_1/mcp", {+ name: "filesystem",+ config: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."], enabled: true },+ });+ expect(response.status).toBe(403);+ expect(await response.json()).toMatchObject({ code: "mcp_disabled", message: "MCP servers are turned off for this account." });+ expect((await readRuntimeOpencodeConfig(config, "ws_1")).mcp).toBeUndefined();++ const view = await (await call("GET", "/workspace/ws_1/mcp")).json() as { mcpPolicy: Record<string, unknown> };+ expect(view.mcpPolicy).toMatchObject({ enabled: false, message: "MCP servers are turned off for this account.", supported: [] });+ expect(engine.pushedNames()).toEqual([]);+ });++ test("with the list: a supported server is stored for the plugin, others are refused with the reason", async () => {const { config, engine } = await fixture();+ allowList(config);const { call } = await start(config, engine.baseUrl);for (const command of [@@ -136,21 +163,52 @@ describe("complete MCP ban at the HTTP and runtime boundaries", () => {config: { type: "local", command, enabled: true },});expect(response.status).toBe(403);- expect(await response.json()).toMatchObject({ code: "mcp_disabled" });+ expect(await response.json()).toMatchObject({ code: "mcp_not_supported" });}+ const remote = await call("POST", "/workspace/ws_1/mcp", {+ name: "notion",+ config: { type: "remote", url: "https://mcp.notion.com/mcp", enabled: true },+ });+ expect(remote.status).toBe(403);+ expect(await remote.json()).toMatchObject({ code: "mcp_not_supported", details: { code: "remote" } });+ const outside = await call("POST", "/workspace/ws_1/mcp", {+ name: "filesystem",+ config: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/etc"], enabled: true },+ });+ expect(outside.status).toBe(403);+ expect(await outside.json()).toMatchObject({ details: { code: "outside_project" } });expect((await readRuntimeOpencodeConfig(config, "ws_1")).mcp).toBeUndefined();++ const filesystem = { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."], enabled: true };+ const added = await call("POST", "/workspace/ws_1/mcp", { name: "filesystem", config: filesystem });+ expect(added.status).toBe(200);+ expect((await readRuntimeOpencodeConfig(config, "ws_1")).mcp).toEqual({ filesystem });+ const file = JSON.parse(await readFile(workspaceMcpFile(runtimeStorageDir(config), config.workspaces[0]!.path), "utf8")) as { mcp: Record<string, unknown> };+ expect(file.mcp).toEqual({ filesystem });+ // Nothing goes into the running engine: its MCP plugin applies the list when the project reloads.expect(engine.pushedNames()).toEqual([]);++ const view = await (await call("GET", "/workspace/ws_1/mcp")).json() as { items: Array<{ name: string }>; mcpPolicy: { enabled: boolean; supported: Array<{ id: string; command: string[] }> } };+ expect(view.mcpPolicy.enabled).toBe(true);+ expect(view.items.map((item) => item.name)).toEqual(["filesystem"]);+ expect(view.mcpPolicy.supported.find((preset) => preset.id === "filesystem")?.command).toEqual(["npx", "-y", "@modelcontextprotocol/server-filesystem", "."]);+ expect(view.mcpPolicy.supported.find((preset) => preset.id === "sqlite")?.command).toEqual(["npx", "-y", "mcp-server-sqlite-npx", "data.db"]);++ const removed = await call("DELETE", "/workspace/ws_1/mcp/filesystem");+ expect(removed.status).toBe(200);+ await expect(readFile(workspaceMcpFile(runtimeStorageDir(config), config.workspaces[0]!.path), "utf8")).rejects.toThrow();});test("PATCH /workspace/:id/config refuses MCP config before it is stored", async () => {const { config, engine } = await fixture();+ allowList(config);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(403);- expect(await response.json()).toMatchObject({ code: "mcp_disabled" });+ expect(await response.json()).toMatchObject({ code: "mcp_config_patch" });expect((await readRuntimeOpencodeConfig(config, "ws_1")).mcp).toBeUndefined();const provider = await call("PATCH", "/workspace/ws_1/config", {@@ -159,19 +217,50 @@ describe("complete MCP ban at the HTTP and runtime boundaries", () => {expect(provider.status).toBe(200);});- test("enabling a stored one over HTTP is refused and not pushed", async () => {+ test("enabling a stored registry launch is refused and not pushed", async () => {const { config, engine } = await fixture();await seedRuntimeRow(config, "ws_1", { mcp: { "omnirush-ui": { ...LEGACY, enabled: false } } });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(403);- expect(await response.json()).toMatchObject({ code: "mcp_disabled" });+ const off = await call("POST", "/workspace/ws_1/mcp/omnirush-ui/enabled", { enabled: true });+ expect(off.status).toBe(403);+ expect(await off.json()).toMatchObject({ code: "mcp_disabled" });++ allowList(config);+ const on = await call("POST", "/workspace/ws_1/mcp/omnirush-ui/enabled", { enabled: true });+ expect(on.status).toBe(400);+ expect(await on.json()).toMatchObject({ code: "unsafe_mcp_command" });+ expect(engine.pushedNames()).toEqual([]);+ });++ test("account-linked flows and runtime engine adds stay refused", async () => {+ const { config, engine } = await fixture();+ allowList(config);+ const { call } = await start(config, engine.baseUrl);++ for (const [method, path] of [+ ["POST", "/workspace/ws_1/mcp/managed"],+ ["GET", "/workspace/ws_1/mcp-apps/list"],+ ["GET", "/workspace/ws_1/mcp/omnirush-cloud/health"],+ ] as const) {+ const response = await call(method, path, method === "POST" ? {} : undefined);+ expect(response.status).toBe(403);+ expect(await response.json()).toMatchObject({ code: "mcp_account_linked" });+ }+ const add = await call("POST", "/workspace/ws_1/opencode/mcp", { name: "x", config: SAFE });+ expect(add.status).toBe(403);+ expect(await add.json()).toMatchObject({ code: "engine_mcp_managed" });+ const auth = await call("POST", "/workspace/ws_1/opencode/mcp/x/auth", {});+ expect(auth.status).toBe(403);+ expect(await auth.json()).toMatchObject({ code: "mcp_account_linked" });+ const list = await call("GET", "/workspace/ws_1/opencode/mcp");+ expect(list.status).toBe(200);expect(engine.pushedNames()).toEqual([]);});- test("legacy stored rows are hidden from runtime delivery and injected config", async () => {+ test("legacy stored rows are never pushed, and registry launches never reach the plugin's file", async () => {const { config, engine } = await fixture();+ allowList(config);await seedRuntimeRow(config, "ws_1", { mcp: { "omnirush-ui": LEGACY, "user-tool": SAFE } });await seedRuntimeRow(config, ENGINE_GLOBAL_RUNTIME_CONFIG_ID, {mcp: { "global-ui": { type: "local", command: ["sh", "-c", "npx -y omnirush-ui-mcp"] }, "global-tool": SAFE },@@ -180,14 +269,15 @@ describe("complete MCP ban at the HTTP and runtime boundaries", () => {await syncAllWorkspacesRuntimeMcpToEngine(config);expect(engine.pushedNames()).toEqual([]);+ const file = JSON.parse(await readFile(workspaceMcpFile(runtimeStorageDir(config), config.workspaces[0]!.path), "utf8")) as { mcp: Record<string, unknown> };+ // The plugin applies the list to "user-tool" (a bare script: blocked, with the reason in its report).+ expect(Object.keys(file.mcp)).toEqual(["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(injected.mcp).toEqual({});+ expect(injected.mcp).toBeUndefined();- // 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);});@@ -215,7 +305,7 @@ describe("complete MCP ban at the HTTP and runtime boundaries", () => {process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL = "1";const { call } = await start(config, engine.baseUrl);- // The engine's MCP policy plugin strips these entries; the prompt itself runs.+ // The engine's MCP plugin applies the list to these entries; the prompt itself runs.const response = await call("POST", "/workspace/ws_1/opencode/session/ses_1/prompt_async", {parts: [{ type: "text", text: "Fix the build" }],});diff --git a/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts b/apps/server/src/opencode-plugins/omnirush-mcp-policy.tsindex b9ee9afb..a340c45b 100644--- a/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts+++ b/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts@@ -1,89 +1,60 @@-type ConfigTarget = {- mcp?: unknown;- permission?: unknown;- permissions?: unknown;- tools?: unknown;-};--type ToolBeforeInput = {- tool?: unknown;-};+// Engine plugin: MCP servers follow the server's list (mcp-allow/mcp-allow.mjs,+// the same module as the CLI's). Loaded last, so no plugin before it can add+// servers after the list was applied.+//+// - config: the project's MCP entries (its config files, plus the ones added+// in the app: OMNIRUSH_MCP_WORKSPACE_DIR) are replaced by the allowed ones,+// keyed by their id, pinned, paths checked, and run in the project's sandbox+// when it is on. The report (OMNIRUSH_MCP_REPORT_DIR) says which and why.+// - tool.execute.before: servers limited to local pages refuse other pages.+//+// No policy file (OMNIRUSH_MCP_POLICY_FILE missing or unreadable): no MCP.+// The engine calls every function a plugin module exports: export only the plugin.+import { existsSync } from "node:fs";+import path from "node:path";++import { createMcpPolicyHooks, type McpBox } from "../mcp-allow/mcp-allow.mjs";+import { readWorkspaceMcp } from "../mcp-allow/state.js";+import { boxHome, desktopProjects, keyOf, record } from "../box/plugin-lib.js";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];+// The same choice of target as the shared hooks (both engine hook shapes).+function configTarget(input: unknown, output: unknown): Record<string, unknown> | null {+ if (isRecord(output) && (Object.hasOwn(output, "mcp") || !isRecord(input))) return output;+ return isRecord(input) ? input : isRecord(output) ? output : null;}-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),- ]);+/** The project's sandbox when the desktop has it on: its shell (boxsh), key and folder in the box. */+function boxFor(root: string): McpBox | null {+ const key = keyOf(root);+ if (!desktopProjects().keys.has(key)) return null;+ const rec = record(key);+ if (!rec || rec.state === "off") return null;+ const shell = path.join(boxHome(), "shell", process.platform === "win32" ? "bash.exe" : "bash");+ if (!existsSync(shell)) return null;+ return { shell, key, croot: typeof rec.croot === "string" ? rec.croot : null };}-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}___`);+export default async function omnirushMcpPolicy(input?: { directory?: string }) {+ const root = path.resolve(input?.directory || process.cwd());+ const hooks = createMcpPolicyHooks({+ directory: root,+ policyFile: process.env.OMNIRUSH_MCP_POLICY_FILE || null,+ reportDir: process.env.OMNIRUSH_MCP_REPORT_DIR || null,+ box: boxFor,});-}--/**- * 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 {- 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 this app.");+ config: async (configInput: unknown, output?: unknown) => {+ const target = configTarget(configInput, output);+ if (target) {+ const added = readWorkspaceMcp(process.env.OMNIRUSH_MCP_WORKSPACE_DIR, root);+ if (Object.keys(added).length) target.mcp = { ...(isRecord(target.mcp) ? target.mcp : {}), ...added };+ }+ await hooks.config(configInput, output);},+ "tool.execute.before": hooks["tool.execute.before"],};}diff --git a/apps/server/src/routes/cloud-mcp.ts b/apps/server/src/routes/cloud-mcp.tsindex 3be070f9..89179b77 100644--- a/apps/server/src/routes/cloud-mcp.ts+++ b/apps/server/src/routes/cloud-mcp.ts@@ -11,7 +11,7 @@ import {type CloudMcpLiveStatusObserver,} from "../cloud-mcp-health.js";import { ApiError } from "../errors.js";-import { assertMcpAllowed } from "../mcp-policy.js";+import { refuseAccountLinkedMcp } from "../mcp-policy.js";import type { ServerConfig, TokenScope, WorkspaceInfo } from "../types.js";import { addRoute, type RequestContext, type Route } from "./registry.js";@@ -96,14 +96,14 @@ export function registerCloudMcpRoutes(options: RegisterCloudMcpRoutesOptions):} = options;addRoute(routes, "GET", "/workspace/:id/mcp/omnirush-cloud/health", "client", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});addRoute(routes, "POST", "/workspace/:id/mcp/omnirush-cloud/engine-refresh", "client", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});addRoute(routes, "POST", "/workspace/:id/mcp/omnirush-cloud/reconcile", "client", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});}diff --git a/apps/server/src/runtime-opencode-config-store.test.ts b/apps/server/src/runtime-opencode-config-store.test.tsindex 9eee33d1..7c7d7a72 100644--- a/apps/server/src/runtime-opencode-config-store.test.ts+++ b/apps/server/src/runtime-opencode-config-store.test.ts@@ -122,16 +122,24 @@ describe("runtime OpenCode config store", () => {...current,mcp: { posthog: { type: "remote", url: "https://mcp.posthog.com/mcp", enabled: false } },}));- expect(third.changed).toBe(false);- expect(third.config).toEqual(first.config);- expect(writes).toBe(1);+ // A project's MCP entries are kept (the engine plugin applies the server's list).+ expect(third.changed).toBe(true);+ expect(third.config.mcp).toEqual({ posthog: { type: "remote", url: "https://mcp.posthog.com/mcp", enabled: false } });+ expect(writes).toBe(2);++ const global = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({+ ...current,+ mcp: { "omnirush-cloud": { type: "remote", url: "https://cloud.example/mcp" } },+ }));+ // The global row's MCP is the account-linked Connect server: never stored.+ expect(global.config.mcp).toBeUndefined();} finally {unsubscribe();}});});- test("drops MCP writes without rewriting workspace files", async () => {+ test("keeps a project's MCP writes in the runtime DB 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';@@ -145,10 +153,12 @@ describe("runtime OpenCode config store", () => {expect(await readFile(opencodePath, "utf8")).toBe(opencode);await expectMissing(join(root, ".opencode", "omnirush.json"));expect(result.changed).toBe(true);- expect((await readRuntimeOpencodeConfig(config, WORKSPACE_ID)).mcp).toBeUndefined();+ expect((await readRuntimeOpencodeConfig(config, WORKSPACE_ID)).mcp).toEqual({+ runtime: { type: "remote", url: "https://runtime.example/mcp", enabled: true },+ });const items = await listMcp(config, WORKSPACE_ID, root);- expect(items).toEqual([]);+ expect(items.map((item) => item.name).sort()).toEqual(["project", "runtime"]);});});@@ -175,7 +185,7 @@ describe("runtime OpenCode config store", () => {mcp?: Record<string, Record<string, unknown>>;};expect(runtimeConfig.plugin).toContain("runtime-plugin");- // Per-workspace MCPs reach the engine via the dynamic push, not the file.+ // Per-workspace MCPs reach the engine through its MCP plugin, not the file.expect(runtimeConfig.mcp?.runtime).toBeUndefined();});});diff --git a/apps/server/src/runtime-opencode-config-store.ts b/apps/server/src/runtime-opencode-config-store.tsindex 3bc8c07b..0e490fca 100644--- a/apps/server/src/runtime-opencode-config-store.ts+++ b/apps/server/src/runtime-opencode-config-store.ts@@ -587,11 +587,11 @@ function updateRuntimeConfig(const result = pending.catch(() => undefined).then(async () => {const row = await runtimeOpencodeConfigStore.getRow(config, workspaceId);const current = row?.value ?? {};- // 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))),- );+ // A project's MCP entries are kept (the engine's MCP plugin applies the+ // server's list to them). The global row's are the account-linked Connect+ // server, which this app does not run: never persisted there.+ const checked = refuseRegistryOmniRushUiMcp(current, normalizeRuntimeOpencodeConfig(updater(current)));+ const next = isEngineGlobalRuntimeConfigId(workspaceId) ? withoutMcpRuntimeConfig(checked) : checked;const configJson = runtimeOpencodeConfigStore.serialize(next);if (row?.valueJson === configJson) return { config: next, changed: false };await runtimeOpencodeConfigStore.setSerialized(config, workspaceId, configJson, Date.now());diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 83b01850..4c9c9201 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -145,7 +145,6 @@ import {markOmniRushCloudMcpStale,migrateOmniRushCloudMcpRuntimeConfig,OMNIRUSH_CLOUD_MCP_NAME,- reconcilePersistedOmniRushCloudMcp,removeOmniRushCloudMcpDesiredConfig,type CloudMcpHealth,} from "./cloud-mcp-health.js";@@ -184,7 +183,10 @@ import { rememberServerDefault, watchServerDefault } from "./box/launch.js";import { rememberWebSearchSwitch, watchWebSearchSwitch } from "./web-search.js";import { normalizeBackend } from "./box/backends/index.js";import { buildOmniRushRuntimeConfigObject, omnirushGatewayConfigured, omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";-import { assertMcpAllowed, mcpAllowed, mcpPolicyForConfig, MCP_DISABLED_MESSAGE } from "./mcp-policy.js";+import { assertMcpAllowed, mcpAllowed, mcpDisabledMessage, mcpPolicyForConfig, refuseAccountLinkedMcp } from "./mcp-policy.js";+import { currentMcpPolicy, rememberMcpPolicy, watchMcpPolicy, workspaceMcpReport, writeWorkspaceMcp } from "./mcp-allow/state.js";+import { isOmniRushUiMcpRegistryEntry } from "./omnirush-ui-mcp-command.js";+import type { McpAllowEntry } from "./mcp-allow/mcp-allow.mjs";import { omnirushModelWantsReasoningSummary, readOmniRushModelCatalog } from "./omnirush-model-catalog.js";import {SUBAGENT_MODEL_FALLBACK_TRACE,@@ -1256,10 +1258,15 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {const boxes = boxServiceFor(config, (level, message, attributes) => logger.log(level, message, attributes));let stopBoxDefaultWatch: () => void = () => {};let stopWebSearchWatch: () => void = () => {};+ let stopMcpPolicyWatch: () => void = () => {};if (gatewayBroker.enabled) {// Read before the first plan and the engine's first config (at most 1.5 s, else the last answer is// used until it comes): a switch flipped or rolled back on the server applies at this start.- const read = gatewayBroker.sessionUploadCapabilities().then((capabilities) => rememberServerDefault(runtimeStorageDir(config), capabilities)).catch(() => false);+ // The MCP list (mcp-allow/state.ts) is remembered from the same answer: the engine's MCP plugin reads it when a project starts.+ const read = gatewayBroker.sessionUploadCapabilities().then((capabilities) => {+ rememberMcpPolicy(runtimeStorageDir(config), capabilities);+ return rememberServerDefault(runtimeStorageDir(config), capabilities);+ }).catch(() => false);// The model's own web search (web-search.ts), from the same answer. Strict: a failed read keeps// the last answer, while an answer without the block (an older server) turns it off.const readWebSearch = gatewayBroker.sessionUploadCapabilities({ strict: true }).then((capabilities) => rememberWebSearchSwitch(runtimeStorageDir(config), capabilities)).catch(() => false);@@ -1274,6 +1281,11 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {});// Read again while the app stays open (from the capabilities cache: at most one request per its// TTL), so a switch flipped on the server reaches an app started before it without a restart.+ stopMcpPolicyWatch = watchMcpPolicy({+ stateDir: runtimeStorageDir(config),+ read: () => gatewayBroker.sessionUploadCapabilities(),+ everyMs: BOX_DEFAULT_REFRESH_MS,+ });stopBoxDefaultWatch = watchServerDefault({stateDir: runtimeStorageDir(config),read: () => gatewayBroker.sessionUploadCapabilities(),@@ -1645,6 +1657,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {} catch (error) {stopBoxDefaultWatch();stopWebSearchWatch();+ stopMcpPolicyWatch();bestPracticesReloads.stop();// First, and synchronously: archive part uploads in flight are aborted now, not after the other shutdown steps.const captureStopped = capture.stop();@@ -1735,7 +1748,8 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {// Before them, each chat in a box gets its last checkpoint (bounded; only when chats ran in a// box this run, and the account answers it is still stored within a second).stopBoxDefaultWatch();- stopWebSearchWatch();+ stopWebSearchWatch();+ stopMcpPolicyWatch();const archiveFinals = accountStillStored();if (boxes.hasChats() && await Promise.race([archiveFinals.catch(() => false), new Promise<false>((resolvePromise) => setTimeout(() => resolvePromise(false), 1_000).unref?.())])) {await boxes.finals({ budgetMs: 10_000 }).catch(() => []);@@ -1807,11 +1821,10 @@ export async function proxyOpencodeV2Request(input: {if (/^\/api\/config(?:\/|$)/.test(decodedPath)) {throw new ApiError(403, "engine_config_private", "Engine configuration is private");}- if (/^(?:\/api)?\/mcp(?:\/|$)/.test(decodedPath)) {- assertMcpAllowed(input.config);- if (method !== "GET" && method !== "HEAD") {- throw new ApiError(403, "engine_mcp_managed", "Manage connections through OmniRush.ai");- }+ // 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).+ if (/^(?:\/api)?\/mcp(?:\/|$)/.test(decodedPath) && method !== "GET" && method !== "HEAD") {+ throw new ApiError(403, "engine_mcp_managed", "Manage connections through OmniRush.ai");}const sessionMatch = routePath.match(/^\/api\/session\/([^/]+)(?:\/|$)/);const sessionId = sessionMatch?.[1] ? decodeEngineRouteParam(sessionMatch[1]) : null;@@ -2251,9 +2264,7 @@ export async function proxyOpencodeRequest(input: {if (method !== "GET" && method !== "HEAD") {ensureWritable(input.config);}- if (/^(?:\/api)?\/mcp(?:\/|$)/.test(normalizeOpencodeProxyPath(proxyPath))) {- assertMcpAllowed(input.config);- }+ assertEngineMcpRouteAllowed(input.config, method, normalizeOpencodeProxyPath(proxyPath));if (workspace && workspace.workspaceType !== "remote" && isUploadPromptDispatch(method, proxyPath)) {if (uploadDispatchRefused(input.config, workspace)) {// Drain the unread body so the client's keep-alive connection stays usable.@@ -3093,7 +3104,7 @@ function buildCapabilities(config: ServerConfig): Capabilities {providerSync: true,skills: { read: true, write: writeEnabled, source: "omnirush" },plugins: { read: true, write: writeEnabled },- mcp: { read: mcpAllowed(config), write: writeEnabled && mcpAllowed(config) },+ mcp: { read: true, write: writeEnabled && mcpAllowed(config) },commands: { read: true, write: writeEnabled },config: { read: true, write: writeEnabled },engine: { rollover: enginePoolForConfig(config) !== null },@@ -4603,8 +4614,10 @@ function createRoutes(if (opencode) {const configPath = omnirushConfigPath(workspace.path);const nextOpencode = ensurePlainObject(opencode);+ // MCP servers are added one at a time through POST /workspace/:id/mcp,+ // which checks each against the server's list.if (Object.prototype.hasOwnProperty.call(nextOpencode, "mcp")) {- assertMcpAllowed(config);+ throw new ApiError(403, "mcp_config_patch", "Add MCP servers in Settings > MCP: each is checked against the supported list.");}const { permission, provider, ...topLevelUpdates } = nextOpencode;const logicalUpdates: Record<string, unknown> = { ...topLevelUpdates };@@ -4996,28 +5009,34 @@ function createRoutes(return jsonResponse({ ok: true, name, path: result.path });});+ // The project's MCP servers with the engine plugin's decision for each (on,+ // or blocked and why), and the servers the list supports (one-click presets).addRoute(routes, "GET", "/workspace/:id/mcp", "client", async (ctx) => {- if (!mcpAllowed(config)) {- return jsonResponse({- items: [],- engineSync: null,- managedOAuthState: { available: false, recovery: false },- mcpPolicy: { mode: mcpPolicyForConfig(config), enabled: false, message: MCP_DISABLED_MESSAGE },- });- }const workspace = await resolveWorkspace(config, ctx.params.id);const items = await listMcp(config, workspace.id, workspace.path);- const managedState = await listLocalManagedMcpConnectionsSafe(config, workspace.id);- const managed = new Map(managedState.connections.map((connection) => [connection.name, connection]));+ const stateDir = runtimeStorageDir(config);+ const policy = currentMcpPolicy(stateDir);+ const report = workspace.workspaceType === "remote" ? null : workspaceMcpReport(stateDir, resolveOpencodeDirectory(workspace) || workspace.path);+ const decisions = report?.decisions ?? [];+ const enabled = policy?.enabled === true;return jsonResponse({- items: items.map((item) => ({ ...item, managedOAuth: managed.get(item.name) ?? null })),- engineSync: engineMcpSyncStateInState(config, engineMcpServerState, workspace),- managedOAuthState: { available: managedState.available, recovery: managedState.recovery },+ items: items.map((item) => ({ ...item, managedOAuth: null, decision: decisions.find((decision) => decision.name === item.name) ?? null })),+ engineSync: null,+ managedOAuthState: { available: false, recovery: false },+ mcpPolicy: {+ 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,+ },});});addRoute(routes, "GET", "/mcp-apps/sandbox.html", "none", async (ctx) => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();return new Response(MCP_APP_SANDBOX_PROXY_HTML, {headers: {"Content-Type": "text/html; charset=utf-8",@@ -5029,20 +5048,20 @@ function createRoutes(});});addRoute(routes, "GET", "/mcp-apps/sandbox.js", "none", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();return new Response(MCP_APP_SANDBOX_PROXY_SCRIPT, {headers: { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" },});});addRoute(routes, "GET", "/mcp-apps/sandbox.css", "none", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();return new Response(MCP_APP_SANDBOX_PROXY_CSS, {headers: { "Content-Type": "text/css; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" },});});addRoute(routes, "GET", "/workspace/:id/mcp-apps/list", "client", async (ctx) => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();requireClientScope(ctx, "viewer");const workspace = await resolveWorkspace(config, ctx.params.id);try {@@ -5058,38 +5077,76 @@ function createRoutes(});addRoute(routes, "POST", "/workspace/:id/mcp-apps/resolve", "client", async (ctx) => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});addRoute(routes, "POST", "/workspace/:id/mcp-apps/call", "client", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});addRoute(routes, "POST", "/workspace/:id/mcp/managed", "client", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});addRoute(routes, "GET", "/workspace/:id/mcp/:name/managed", "client", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});addRoute(routes, "POST", "/workspace/:id/mcp/:name/managed/connect", "client", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});addRoute(routes, "GET", "/mcp/oauth/callback", "none", async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();});const managedGatewayHandler = async () => {- assertMcpAllowed(config);+ refuseAccountLinkedMcp();};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 () => {+ // Adds a local MCP server the list allows (addMcp refuses others with the+ // reason). It reaches the engine through the MCP plugin when the project's+ // engine instance reloads (the reload event below).+ addRoute(routes, "POST", "/workspace/:id/mcp", "client", async (ctx) => {assertMcpAllowed(config);+ ensureWritable(config);+ requireClientScope(ctx, "collaborator");+ const workspace = await resolveWorkspace(config, ctx.params.id);+ if (workspace.workspaceType === "remote") throw new ApiError(400, "mcp_remote_workspace", "MCP servers can be added to local projects only.");+ const body = await readJsonBody(ctx.request);+ const name = String(body.name ?? "");+ validateUserMcpName(name);+ const configPayload = body.config as Record<string, unknown> | undefined;+ if (!configPayload || typeof configPayload !== "object" || Array.isArray(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, resolveOpencodeDirectory(workspace) || workspace.path);+ 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) => {@@ -5129,6 +5186,7 @@ function createRoutes(deleteEngineMcpRegistration(config, engineMcpServerState, affectedWorkspace, removedName);await disconnectMcpFromOpencodeEngine(config, affectedWorkspace, removedName).catch(() => undefined);}+ await syncRuntimeMcpToOpencodeEngine(config, affectedWorkspace, undefined, undefined, engineMcpServerState).catch(() => undefined);}));emitReloadEvent(ctx.reloadEvents, workspace, "mcp", {type: "mcp",@@ -6160,17 +6218,8 @@ function enqueueWorkspaceMcpRefreshSync(request: WorkspaceMcpRefreshRequest): Prasync function runWorkspaceMcpRefreshSync(input: WorkspaceMcpRefreshRequest): Promise<void> {const { config, workspace, trigger } = input;- if (!mcpAllowed(config)) {- // The policy is also applied at engine config/proxy level; skip cloud- // reconciliation so a background timer cannot recreate a live MCP entry.- await syncRuntimeMcpToOpencodeEngine(config, workspace, undefined, undefined, input.serverState ?? null).catch(() => undefined);- return;- }- const directory = resolveOpencodeDirectory(workspace);- // Re-register runtime-DB MCPs: a rebuilt instance reads disk configs- // (including the server-managed runtime config file for the primary- // workspace), but other workspaces' runtime MCPs only reach the engine- // through this dynamic push.+ // The project's app-added MCP entries go to the file the engine's MCP plugin+ // reads. The account-linked Connect server is never reconciled (not run here).try {await syncRuntimeMcpToOpencodeEngine(config,@@ -6182,28 +6231,6 @@ async function runWorkspaceMcpRefreshSync(input: WorkspaceMcpRefreshRequest): Pr} catch (error) {logRuntimeMcpSyncError({ config, workspace, trigger, error });}- try {- const health = await reconcilePersistedOmniRushCloudMcp({- config,- workspace,- directory,- serverMetadata: { serverVersion: SERVER_VERSION, expectedOpencodeVersion: OPENCODE_VERSION },- createWorkspaceOpencodeClient,- refreshRegistrationFromLiveStatus: refreshEngineMcpRegistrationFromLiveStatus,- registerRuntimeMcp: (routeConfig, routeWorkspace, onlyNames, options) =>- syncRuntimeMcpToOpencodeEngine(- routeConfig,- routeWorkspace,- onlyNames,- options,- input.serverState ?? null,- ),- trigger,- });- logPersistedCloudMcpReconcileResult({ config, workspace, trigger, health });- } catch (error) {- logPersistedCloudMcpReconcileError({ config, workspace, trigger, error });- }// The reconcile above may write the ENGINE_GLOBAL runtime row; refresh the// engine-visible file synchronously so the next provider-sync pass compares// against post-reload state instead of racing the async fresh-keeper and@@ -6229,142 +6256,76 @@ async function syncRuntimeMcpToOpencodeEngine(options?: { throwOnFailure?: boolean; deferred?: boolean },serverState?: EngineMcpServerState | null,): Promise<EngineMcpSyncResult> {- if (!mcpAllowed(config)) {- const state = activeEngineMcpServerState(config, serverState);- 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);- const coordinationState = activeEngineMcpServerState(config);- if (!coordinationState) {- return runRuntimeMcpSyncToOpencodeEngine(config, workspace, onlyNames, options, serverState);- }- if (activeState) {- reconcileEngineMcpWorkspaceIdentity(- activeState,- workspace.id,- engineMcpConnectionIdentity(config, workspace),- );- if (!options?.deferred) cancelDeferredEngineMcpSync(activeState, workspace.id);- }- return withEngineMcpRegistrationLock(coordinationState, workspace.id, () =>- runRuntimeMcpSyncToOpencodeEngine(config, workspace, onlyNames, options, serverState)- );+ // Nothing is pushed into a running engine: every MCP server goes through the+ // engine's MCP plugin (the server's list), which reads the project's+ // app-added entries from this file when the project's instance starts.+ await writeWorkspaceMcpFile(config, workspace);+ const state = activeEngineMcpServerState(config, serverState);+ const recordedNames = (state ? [...(state.registrationByWorkspace.get(workspace.id)?.keys() ?? [])] : [])+ .filter((name) => !onlyNames || onlyNames.includes(name));+ // Registrations an earlier push made (never by this version) are taken down.+ await Promise.all(recordedNames.map(async (name) => {+ if (state) deleteEngineMcpRegistration(config, state, workspace, name);+ await disconnectMcpFromOpencodeEngine(config, workspace, name).catch(() => undefined);+ }));+ return { status: "skipped", syncedNames: [], failures: [] };}-async function runRuntimeMcpSyncToOpencodeEngine(- config: ServerConfig,- workspace: WorkspaceInfo,- onlyNames?: string[],- options?: { throwOnFailure?: boolean; deferred?: boolean },- serverState?: EngineMcpServerState | null,-): Promise<EngineMcpSyncResult> {- const activeState = activeEngineMcpServerState(config, serverState);- const connection = resolveWorkspaceOpencodeConnection(config, workspace);- const baseUrl = connection.baseUrl?.trim() ?? "";- const connectionIdentity = engineMcpConnectionIdentity(config, workspace);- const registrationIdentity = engineMcpRegistrationIdentity(config, workspace);- if (activeState) reconcileEngineMcpWorkspaceIdentity(activeState, workspace.id, connectionIdentity);- if (activeState && !options?.deferred) cancelDeferredEngineMcpSync(activeState, workspace.id);- if (!baseUrl || !connectionIdentity) {- return { status: "skipped", syncedNames: [], failures: [] };- }-- const runtimeConfig = await readEffectiveRuntimeOpencodeConfig(config, workspace.id);- const entries = Object.entries(runtimeMcpMap(runtimeConfig)).filter(- ([name]) => !name.startsWith(CONNECT_MCP_SERVER_NAME_PREFIX)- && (!onlyNames || onlyNames.includes(name)),- );- if (entries.length === 0) {- if (!onlyNames) {- recordEngineMcpSyncResult(- config,- activeState ?? null,- workspace,- connectionIdentity,- registrationIdentity,- {- entries: [],- failures: [],- replace: true,- },- );- }- return { status: "skipped", syncedNames: [], failures: [] };+/** The project's app-added MCP entries (runtime row) for the engine's MCP plugin. */+async function writeWorkspaceMcpFile(config: ServerConfig, workspace: WorkspaceInfo): Promise<void> {+ if (workspace.workspaceType === "remote") return;+ const runtimeConfig = await readRuntimeOpencodeConfig(config, workspace.id).catch(() => ({}) as RuntimeOpencodeConfig);+ const entries = Object.fromEntries(Object.entries(runtimeMcpMap(runtimeConfig))+ .filter(([name, entry]) => !name.startsWith(CONNECT_MCP_SERVER_NAME_PREFIX) && name !== OMNIRUSH_CLOUD_MCP_NAME && !isOmniRushUiMcpRegistryEntry(entry)));+ try {+ writeWorkspaceMcp(runtimeStorageDir(config), resolveOpencodeDirectory(workspace) || workspace.path, entries);+ } catch (error) {+ createServerLogger(config).log("warn", "Could not write the project's MCP servers for the engine.", {+ "workspace.id": workspace.id,+ error: error instanceof Error ? error.message : String(error),+ });}+}- 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> = { "Content-Type": "application/json" };- if (connection.authHeader) headers.Authorization = connection.authHeader;-- // Keep going past per-entry failures: one dead or invalid MCP must not- // block re-registration of every entry after it (e.g. omnirush-ui) on- // each engine reload.- const failures: EngineMcpSyncFailure[] = [];- const registrations: EngineMcpRegistrationResult[] = [];- for (const [name, mcpConfig] of entries) {- const registration = await withEngineDirectoryFence(config, workspace, () =>- registerRuntimeMcpEntry(config, workspace, url, headers, name, mcpConfig)- );- registrations.push(registration);- if (registration.failure) failures.push(registration.failure);+/**+ * The engine's own MCP routes through the proxy: reading the list and+ * connecting or disconnecting a configured server are fine; adding a server+ * at runtime (it would skip the list) or its OAuth flow are not.+ */+function assertEngineMcpRouteAllowed(config: ServerConfig, method: string, routePath: string): void {+ const match = /^(?:\/api)?\/mcp(?:\/(.*))?$/.exec(routePath.split("?")[0] ?? "");+ if (!match) return;+ if (method === "GET" || method === "HEAD") return;+ const rest = match[1] ?? "";+ if (/^[^/]+\/(?:connect|disconnect)\/?$/.test(rest)) {+ assertMcpAllowed(config);+ return;}+ if (/^[^/]+\/auth(?:\/|$)/.test(rest)) refuseAccountLinkedMcp();+ throw new ApiError(403, "engine_mcp_managed", "Add MCP servers in Settings > MCP: only the supported servers run.");+}- recordEngineMcpSyncResult(- config,- activeState ?? null,- workspace,- connectionIdentity,- registrationIdentity,- {- entries,- registrations,- failures,- // A full sync covered every runtime entry, so its result replaces any- // previously recorded failures (e.g. for since-removed MCPs).- replace: !onlyNames,- },- );-- if (failures.length > 0) {- if (activeState && (!options?.deferred || failures.some((failure) => failure.deferredForActivity)) && hasRetryableMcpSyncFailure(failures)) {- scheduleDeferredEngineMcpSync({- config,- state: activeState,- workspace,- connectionIdentity,- onlyNames,- });- }- const names = failures.map((failure) => failure.name).join(", ");- createServerLogger(config).log("warn", `Engine MCP sync failed for workspace ${workspace.id}: ${names}`, {- "workspace.id": workspace.id,- "mcp.failed": names,- });- if (options?.throwOnFailure !== false) {- throw new ApiError(502, "opencode_mcp_sync_failed", `Failed to register MCPs with the engine: ${names}`, {- failures,- });- }+/** A supported server as a one-click preset: what it is, and the command it adds. */+function mcpPreset(entry: McpAllowEntry): { id: string; title: string; why: string | null; runtime: string; package: string; version: string | null; versions: string; command: string[]; localPagesOnly: boolean } {+ // The file a database server needs is a placeholder in the project: data.db.+ const placeholder = /sqlite|db/i.test(`${entry.id} ${entry.package}`) ? "data.db" : ".";+ const args: string[] = [...(entry.rules.default_args ?? [])];+ for (const flag of entry.rules.require_flags ?? []) {+ if (args.includes(flag)) continue;+ args.push(flag, placeholder);}-+ while (args.filter((arg) => !arg.startsWith("-")).length < (entry.rules.min_args ?? 0)) args.push(placeholder);+ const command = entry.runtime === "npm" ? ["npx", "-y", entry.package, ...args] : ["uvx", entry.package, ...args];return {- status: failures.length > 0 ? "failed" : "ok",- syncedNames: entries.map(([name]) => name),- failures,+ id: entry.id,+ title: entry.title,+ why: entry.why,+ runtime: entry.runtime,+ package: entry.package,+ version: entry.pin,+ versions: entry.versions,+ command,+ localPagesOnly: entry.rules.local_urls === true,};}diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.tsindex 415ab7d0..718dbe04 100644--- a/apps/server/src/session-uploader.ts+++ b/apps/server/src/session-uploader.ts@@ -41,6 +41,7 @@ import { maskWindowsProfiles } from "./context/privacy.js";import bundledBestPractices from "./bundled-best-practices.json" with { type: "json" };import serverPackage from "../package.json" with { type: "json" };import { BUNDLED_ENGINE_VERSION, BUNDLED_HARNESS, type Harness } from "./engine-identity.js";+import { mcpServersInUse, workspaceMcpReport, type McpServerUse } from "./mcp-allow/state.js";const execFileAsync = promisify(execFile);@@ -306,6 +307,8 @@ export type UploadEnvironment = {host_os_version?: string;/** The box the chat's commands ran in (box/box.ts label()); absent when they ran on this machine. */sandbox?: BoxLabel;+ /** The MCP servers the project's engine ran (mcp-allow/state.ts); absent when none. */+ mcp_servers?: McpServerUse[];};/** A box chat's toolchain without this machine's `system` and `shell` blocks. */@@ -870,6 +873,8 @@ export type TraceCapabilities = {auto_compact?: { enabled: boolean; after_turns: number; min_context_tokens?: number };/** The model's own web search (web-search.ts): the block as the server sent it; absent is off. */web_search?: Record<string, unknown>;+ /** The MCP list (mcp-allow/state.ts remembers it): absent is off. */+ mcp?: Record<string, unknown>;};@@ -5092,7 +5097,9 @@ export class SessionUploader {// blocks are this machine's; the box's are its image (sandbox.image). CLI: the same.const toolchain = probed && box ? withoutHostBlocks(probed) : probed;const importedFrom = engine2ImportedFrom(sessionId);- return { ...environment, ...boxEnvironment(environment, box?.label ?? null), ...(toolchain ? { toolchain } : {}), ...(box ? { sandbox: box.label } : {}), ...(importedFrom ? { imported_from: importedFrom } : {}) };+ // Only a project with at least one MCP server on gets the field; every other session uploads as before.+ const mcpServers = this.stateDir ? mcpServersInUse(workspaceMcpReport(this.stateDir, root)) : null;+ return { ...environment, ...boxEnvironment(environment, box?.label ?? null), ...(toolchain ? { toolchain } : {}), ...(box ? { sandbox: box.label } : {}), ...(importedFrom ? { imported_from: importedFrom } : {}), ...(mcpServers ? { mcp_servers: mcpServers } : {}) };}/**