Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: MCP servers get no app tokens

ogsamrat9714af15a891
diff --git a/apps/server/src/mcp-allow/PARITY.sha256 b/apps/server/src/mcp-allow/PARITY.sha256
index ae38c365..e6a72dbe 100644
--- a/apps/server/src/mcp-allow/PARITY.sha256
+++ b/apps/server/src/mcp-allow/PARITY.sha256
@@ -1,4 +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.
-f647dccfe78833a8c988fdbfae0beb2018921d35b8c8d8215560c65821611ed6 mcp-allow.mjs
-72c6590d565a4d005ec069b3c0f1c47d2ec05084f84d7fb95e3199e9404afacd mcp-allow.d.mts
+11ed03b69f22891a9cd9397123cdc8946b318e8c1ddb7042d4eae8989b628515 mcp-allow.mjs
+3cd05cf4c762ef50667a2539f8fc8d8dffadc75ca9fd963cdb20cc32ea457dc3 mcp-allow.d.mts
diff --git a/apps/server/src/mcp-allow/mcp-allow.d.mts b/apps/server/src/mcp-allow/mcp-allow.d.mts
index 17bab47d..a2f45dfe 100644
--- a/apps/server/src/mcp-allow/mcp-allow.d.mts
+++ b/apps/server/src/mcp-allow/mcp-allow.d.mts
@@ -113,6 +113,10 @@ export function describeIgnored(items: McpIgnored[] | null | undefined): string
export function insideRoot(root: string, p: string, platform?: string): boolean;
export function insideRootReal(root: string, p: string, platform?: string): boolean;
export function shellQuote(word: string): string;
+/** The engine variables allowed through to a local MCP server (the rest are set empty for it). */
+export const MCP_ENV_ALLOW: readonly string[];
+/** The `environment` a local MCP server gets: `own`, every other engine variable empty except the basics and `keep`. */
+export function mcpServerEnvironment(engineEnv: Record<string, string | undefined> | undefined, own?: Record<string, string>, keep?: string[], platform?: string): Record<string, string>;
export function evaluateMcp(
mcpMap: unknown,
policy: McpPolicy | null,
diff --git a/apps/server/src/mcp-allow/mcp-allow.mjs b/apps/server/src/mcp-allow/mcp-allow.mjs
index bb9d082c..92590579 100644
--- a/apps/server/src/mcp-allow/mcp-allow.mjs
+++ b/apps/server/src/mcp-allow/mcp-allow.mjs
@@ -131,6 +131,51 @@ export function validRange(range) {
// -------------------------------------------------------------------- policy
+// The variables a local MCP server sees from the engine's own environment: what a program needs to
+// start on this computer, and the network's proxy, certificate and package registry settings. The
+// engine starts a server with its whole environment plus the entry's `environment`, so every other
+// variable it has (the app's tokens, the engine's password, the person's other keys) is set empty for
+// the server (mcpServerEnvironment). The server's own path_env / fixed_env and the key its rules name
+// (secret_env) are added on top.
+export const MCP_ENV_ALLOW = Object.freeze([
+ "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TMP", "TEMP", "LANG", "LANGUAGE", "TZ", "TERM", "COLORTERM",
+ "SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT", "USERPROFILE", "USERNAME", "USERDOMAIN", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA",
+ "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432", "COMMONPROGRAMFILES", "COMMONPROGRAMFILES(X86)", "HOMEDRIVE", "HOMEPATH",
+ "SYSTEMDRIVE", "ALLUSERSPROFILE", "PUBLIC", "COMPUTERNAME", "OS", "NUMBER_OF_PROCESSORS", "PROCESSOR_ARCHITECTURE", "__CF_USER_TEXT_ENCODING",
+ // Kept as they are, even when a proxy address carries its own login: the server's package
+ // manager needs the network's proxy, and the person set it for every program on this computer.
+ "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "ALL_PROXY",
+ "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE",
+ "NPM_CONFIG_REGISTRY", "NPM_CONFIG_CAFILE", "NPM_CONFIG_PROXY", "NPM_CONFIG_HTTPS_PROXY", "NPM_CONFIG_NOPROXY", "NPM_CONFIG_STRICT_SSL",
+ "UV_INDEX_URL", "UV_DEFAULT_INDEX", "UV_NATIVE_TLS", "PIP_INDEX_URL",
+]);
+const MCP_ENV_ALLOW_PREFIX = /^(?:LC_|XDG_)/i;
+// Never reaches a server, whatever its rules say.
+const MCP_ENV_NEVER = /^(?:OMNIRUSH_|OPENCODE_SERVER_|OPENCODE_PASSWORD$)/i;
+
+/**
+ * The `environment` a local MCP server gets from the app: `own` (its
+ * path_env / fixed_env values), every other variable of `engineEnv` set empty
+ * (the engine merges its own environment under it), except the allowed
+ * basics (MCP_ENV_ALLOW) and the keys in `keep` (the server's secret_env).
+ */
+export function mcpServerEnvironment(engineEnv, own = {}, keep = [], platform = process.platform) {
+ const norm = (k) => (platform === "win32" ? k.toUpperCase() : k);
+ const allowed = new Set(MCP_ENV_ALLOW.map((k) => k.toUpperCase()));
+ const kept = new Set(keep.filter((k) => !MCP_ENV_NEVER.test(k)).map(norm));
+ const out = {};
+ for (const key of Object.keys(engineEnv ?? {})) {
+ if (Object.hasOwn(own, key)) continue;
+ const upper = key.toUpperCase();
+ const basic = (allowed.has(upper) || MCP_ENV_ALLOW_PREFIX.test(key)) && !MCP_ENV_NEVER.test(key);
+ if (basic || kept.has(norm(key))) continue;
+ out[key] = "";
+ }
+ // A name the app keeps from every server is empty even when the server's own variables name it.
+ for (const [key, value] of Object.entries(own)) out[key] = MCP_ENV_NEVER.test(key) ? "" : value;
+ return out;
+}
+
// Variables a `fixed_env` rule may not set: they change which program runs or how it loads.
const FIXED_ENV_REFUSED = /^(?:PATH|PATHEXT|HOME|USERPROFILE|COMSPEC|SHELL|TMPDIR|TEMP|TMP|NODE_.*|NPM_.*|LD_.*|DYLD_.*|PYTHON.*|UV_.*|VIRTUAL_ENV|BUN_.*|DENO_.*|OMNIRUSH_.*|OPENCODE_.*|.*_PROXY|.*(?:KEY|TOKEN|SECRET|PASSWORD).*)$/i;
@@ -154,14 +199,14 @@ function normalizeRules(value) {
}
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(".."))
+ .filter(([k, v]) => !MCP_ENV_NEVER.test(k) && /^[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;
// Keys a server needs, read only from the person's own environment (never from a config file, which the
// project upload could carry); the first one present is passed on, none present: blocked.
- const secrets = strings(rules.secret_env, 4).filter((k) => /^[A-Z_][A-Z0-9_]{0,63}$/.test(k));
+ const secrets = strings(rules.secret_env, 4).filter((k) => /^[A-Z_][A-Z0-9_]{0,63}$/.test(k) && !MCP_ENV_NEVER.test(k));
if (secrets.length) out.secret_env = secrets;
// Variables the server always starts with, set to the list's literal values (a telemetry opt-out): never
// taken from a config file and never overridden by one. Names that change what runs (PATH, NODE_OPTIONS,
@@ -702,11 +747,16 @@ export function evaluateMcp(mcpMap, policy, ctx = {}) {
if (boxHere) {
const envWords = Object.entries(environment).map(([k, v]) => `${k}=${shellQuote(v)}`);
next.command = [box.shell, "-c", `${entry.runtime === "npm" ? `mkdir -p ${BOX_NPM_PREFIX} && ` : ""}exec ${envWords.length ? `env ${envWords.join(" ")} ` : ""}${argv.map(shellQuote).join(" ")}`];
- next.environment = { OMNIRUSH_BOX_KEY: box.key };
+ // The box shell needs its key; the engine's other variables are empty for it (mcpServerEnvironment).
+ // Its own settings (OMNIRUSH_BOX_HOME and the like: where the box lives, not a credential) stay too.
+ const boxVars = Object.fromEntries(Object.entries(userEnv).filter(([k, v]) => /^OMNIRUSH_BOX_/i.test(k) && typeof v === "string"));
+ next.environment = { ...mcpServerEnvironment(userEnv, {}, [], platform), ...boxVars, 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;
+ // The engine's tokens and the person's other keys never reach the server (mcpServerEnvironment).
+ next.environment = mcpServerEnvironment(userEnv, environment, secretNames, platform);
+ if (!Object.keys(next.environment).length) delete next.environment;
}
if (secretNames.length) notes.push(`uses ${secretNames[0]} from your environment`);
out[entry.id] = next;
diff --git a/apps/server/src/mcp-allow/state.test.ts b/apps/server/src/mcp-allow/state.test.ts
index 88294bcc..edc4bfa9 100644
--- a/apps/server/src/mcp-allow/state.test.ts
+++ b/apps/server/src/mcp-allow/state.test.ts
@@ -5,7 +5,7 @@ import path from "node:path";
import omnirushMcpPolicy from "../opencode-plugins/omnirush-mcp-policy.js";
import { keyOf } from "../box/plugin-lib.js";
-import { describeIgnored, evaluateMcp, normalizePolicy, readPolicyFile } from "./mcp-allow.mjs";
+import { describeIgnored, evaluateMcp, mcpServerEnvironment, normalizePolicy, readPolicyFile } from "./mcp-allow.mjs";
import {
decideMcpEntry,
mcpEngineEnv,
@@ -188,7 +188,9 @@ describe("the engine plugin (omnirush-mcp-policy)", () => {
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", "mkdir -p /tmp/omnirush-mcp-npx && exec npx --prefix /tmp/omnirush-mcp-npx -y @modelcontextprotocol/[email protected] ."]);
- expect(entry.environment).toEqual({ OMNIRUSH_BOX_KEY: key });
+ // Its box key, and every other engine variable empty for it (mcpServerEnvironment).
+ expect(entry.environment.OMNIRUSH_BOX_KEY).toBe(key);
+ expect(Object.entries(entry.environment).filter(([name, value]) => !name.startsWith("OMNIRUSH_BOX_") && value !== "" && !["PATH", "HOME"].includes(name.toUpperCase()))).toEqual([]);
expect(mcpServersInUse(workspaceMcpReport(state, root))?.[0]?.sandbox).toBe(true);
});
@@ -219,6 +221,70 @@ describe("the engine plugin (omnirush-mcp-policy)", () => {
});
});
+describe("MCP server environment", () => {
+ test("the app's tokens, the engine's password and other keys are empty for a server; the basics and its own key stay", () => {
+ const policy = normalizePolicy(policyFixture);
+ const engineEnv = {
+ PATH: "/usr/bin", HOME: "/home/u", LANG: "C.UTF-8", LC_ALL: "C", HTTPS_PROXY: "http://proxy:3128",
+ FIGMA_API_KEY: "f".repeat(24),
+ OMNIRUSH_ACCESS_TOKEN: "engine-token", OMNIRUSH_SERVER_TOKEN: "server-token", OMNIRUSH_POLICY_TOKEN: "policy-token",
+ OPENCODE_SERVER_PASSWORD: "pw", OPENCODE_SERVER_USERNAME: "u", AWS_SECRET_ACCESS_KEY: "aws", GITHUB_TOKEN: "gh", NODE_OPTIONS: "--require /tmp/x.js",
+ };
+ const ctx = { root: "/work/app", platform: "linux", npmPrefix: "/state/npx", resolveRunner: (runner: string) => runner, env: engineEnv };
+ const { mcp } = evaluateMcp({
+ figma: { type: "local", command: ["npx", "-y", "figma-developer-mcp"] },
+ filesystem: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."] },
+ }, policy, ctx);
+ const servers = mcp as Record<string, { environment?: Record<string, string> }>;
+ for (const id of ["figma", "filesystem"]) {
+ const environment = servers[id]!.environment!;
+ for (const secret of ["OMNIRUSH_ACCESS_TOKEN", "OMNIRUSH_SERVER_TOKEN", "OMNIRUSH_POLICY_TOKEN", "OPENCODE_SERVER_PASSWORD", "OPENCODE_SERVER_USERNAME", "AWS_SECRET_ACCESS_KEY", "GITHUB_TOKEN", "NODE_OPTIONS"]) {
+ expect([id, secret, environment[secret]]).toEqual([id, secret, ""]);
+ }
+ for (const basic of ["PATH", "HOME", "LANG", "LC_ALL", "HTTPS_PROXY"]) expect(environment).not.toHaveProperty(basic);
+ }
+ // The Figma server's own key stays (it reads it from the inherited environment); the filesystem server's is empty.
+ expect(servers.figma!.environment).not.toHaveProperty("FIGMA_API_KEY");
+ expect(servers.figma!.environment).toMatchObject({ FRAMELINK_TELEMETRY: "off", DO_NOT_TRACK: "1" });
+ expect(servers.filesystem!.environment!.FIGMA_API_KEY).toBe("");
+ });
+
+ test("a protected name stays empty even when a server's rules name it; the rules drop such names", () => {
+ expect(mcpServerEnvironment({ OMNIRUSH_ACCESS_TOKEN: "t", PATH: "/usr/bin" }, { OMNIRUSH_ACCESS_TOKEN: "/work/app/x", MEMORY_FILE_PATH: "/work/app/m" }, ["OPENCODE_SERVER_PASSWORD"], "linux"))
+ .toEqual({ OMNIRUSH_ACCESS_TOKEN: "", MEMORY_FILE_PATH: "/work/app/m" });
+ const block = JSON.parse(JSON.stringify(policyFixture)) as { allow: Array<{ rules?: Record<string, unknown> }> };
+ block.allow[0]!.rules = { ...(block.allow[0]!.rules ?? {}), path_env: { OMNIRUSH_ACCESS_TOKEN: "x", MEMORY_FILE_PATH: "m.jsonl" }, secret_env: ["OMNIRUSH_SERVER_TOKEN", "SOME_API_KEY"] };
+ const rules = normalizePolicy(block)!.allow[0]!.rules as { path_env?: Record<string, string>; secret_env?: string[] };
+ expect(rules.path_env).toEqual({ MEMORY_FILE_PATH: "m.jsonl" });
+ expect(rules.secret_env).toEqual(["SOME_API_KEY"]);
+ });
+
+ test("a sandboxed server's box shell keeps its own box settings, and its key", () => {
+ const policy = normalizePolicy(policyFixture);
+ const env = { OMNIRUSH_BOX_HOME: "/custom/box-home", OMNIRUSH_BOX_TIMING_LOG: "/tmp/t.log", OMNIRUSH_ACCESS_TOKEN: "t", PATH: "/usr/bin" };
+ const { mcp } = evaluateMcp({ filesystem: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."] } }, policy,
+ { root: "/work/app", platform: "linux", npmPrefix: "/state/npx", resolveRunner: (runner: string) => runner, env, box: { shell: "/custom/box-home/shell/bash", key: "k1", croot: "/workspace/app" } });
+ const environment = (mcp as Record<string, { environment?: Record<string, string> }>).filesystem!.environment!;
+ expect(environment).toMatchObject({ OMNIRUSH_BOX_HOME: "/custom/box-home", OMNIRUSH_BOX_TIMING_LOG: "/tmp/t.log", OMNIRUSH_BOX_KEY: "k1", OMNIRUSH_ACCESS_TOKEN: "" });
+ });
+
+ test("Windows: mixed-case names are matched whatever their case", () => {
+ expect(mcpServerEnvironment({ Path: "C:\\Windows", SystemRoot: "C:\\Windows", Omnirush_Access_Token: "t", opencode_server_password: "p", Aws_Secret: "a" }, {}, [], "win32"))
+ .toEqual({ Omnirush_Access_Token: "", opencode_server_password: "", Aws_Secret: "" });
+ });
+
+ test("Windows names match whatever their case; a server in the sandbox gets only its box key", () => {
+ const policy = normalizePolicy(policyFixture);
+ const env = { Path: "C:\\Windows", SystemRoot: "C:\\Windows", OMNIRUSH_ACCESS_TOKEN: "t" };
+ const win = evaluateMcp({ filesystem: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."] } }, policy,
+ { root: "C:\\work", platform: "win32", npmPrefix: "C:\\npx", resolveRunner: (runner: string) => runner, exists: () => true, env });
+ const environment = (win.mcp as Record<string, { environment?: Record<string, string> }>).filesystem?.environment ?? {};
+ expect(environment).not.toHaveProperty("Path");
+ expect(environment).not.toHaveProperty("SystemRoot");
+ expect(environment.OMNIRUSH_ACCESS_TOKEN).toBe("");
+ });
+});
+
describe("MCP fixed environment", () => {
test("the Figma key server always starts with its telemetry off, whatever the config says", () => {
const policy = normalizePolicy(policyFixture);