Skip to content

A desktop coding agent with free access to frontier models.

TypeScript
27.6 KB
Raw Blame
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 { describeIgnored, evaluateMcp, MCP_ENV_ONLY_MARK, MCP_REASONS, mcpServerEnvironment, normalizePolicy, readPolicyFile } from "./mcp-allow.mjs";
import {
  decideMcpEntry,
  mcpEngineEnv,
  mcpFilterMissing,
  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 });
  delete (globalThis as Record<symbol, unknown>)[MCP_ENV_ONLY_MARK];
  for (const key of ["OMNIRUSH_MCP_POLICY_FILE", "OMNIRUSH_MCP_REPORT_DIR", "OMNIRUSH_MCP_WORKSPACE_DIR", "OMNIRUSH_BOX_HOME", "OMNIRUSH_MCP_FILTER", "PATH"]) {
    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("the engine never takes plugins or commands from a project's config, unless the app itself says so", () => {
    const state = temp("mcp-state-");
    expect(mcpEngineEnv(state, {}).OMNIRUSH_PROJECT_CODE).toBe("0");
    // The engine starts no MCP server unless the plugin marked its config (a missing plugin fails closed).
    expect(mcpEngineEnv(state, {}).OMNIRUSH_MCP_FILTER).toBe("required");
    expect(mcpEngineEnv(state, { OMNIRUSH_PROJECT_CODE: "true" }).OMNIRUSH_PROJECT_CODE).toBe("0");
    expect(mcpEngineEnv(state, { OMNIRUSH_PROJECT_CODE: "1" }).OMNIRUSH_PROJECT_CODE).toBe("1");
  });

  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);
    // Not the engine's process: no filter mode and no env-only mark unless a test sets them.
    delete process.env.OMNIRUSH_MCP_FILTER;
    process.env.OMNIRUSH_BOX_HOME = path.join(state, "box-home");
    // The runners resolve to absolute paths on PATH, outside the project.
    const bin = temp("mcp-bin-");
    for (const name of ["npx", "uvx"]) writeFileSync(path.join(bin, process.platform === "win32" ? `${name}.cmd` : name), "", { mode: 0o755 });
    process.env.PATH = bin;
    return { state, root, bin };
  }

  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, bin } = 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"]);
    const runner = (name: string) => path.join(bin, process.platform === "win32" ? `${name}.cmd` : name);
    const npx = [runner("npx"), "--prefix", path.join(process.env.OMNIRUSH_MCP_REPORT_DIR!, "..", "npx-prefix"), "-y"];
    expect(mcp.filesystem!.command).toEqual([...npx, "@modelcontextprotocol/[email protected]", "."]);
    expect(mcp.time!.command).toEqual([runner("uvx"), "--no-config", "[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, enabled: true },
      { id: "filesystem", package: "@modelcontextprotocol/server-filesystem", version: "2026.8.31", runtime: "npm", sandbox: false, enabled: true },
    ]);
  });

  test("a server the user turned off is listed, marked enabled: false", async () => {
    const { state, root } = setup();
    rememberMcpPolicy(state, { mcp: policyFixture });
    writeWorkspaceMcp(state, root, { files: { ...FILESYSTEM, enabled: false } });
    const hooks = await omnirushMcpPolicy({ directory: root });
    const output = { mcp: {} } as Record<string, unknown>;
    await hooks.config({}, output);
    const report = workspaceMcpReport(state, root);
    expect(report?.decisions[0]?.enabled).toBe(false);
    expect(mcpServersInUse(report)).toEqual([{ id: "filesystem", package: "@modelcontextprotocol/server-filesystem", version: "2026.8.31", runtime: "npm", sandbox: false, enabled: false }]);
  });

  test("no npx outside the project: the server is blocked, never started from the project", async () => {
    const { state, root } = setup();
    rememberMcpPolicy(state, { mcp: policyFixture });
    const empty = temp("mcp-nobin-");
    // A runner planted in the project is never used.
    writeFileSync(path.join(root, "npx"), "", { mode: 0o755 });
    process.env.PATH = `${root}${path.delimiter}${empty}`;
    const hooks = await omnirushMcpPolicy({ directory: root });
    const output = { mcp: { filesystem: FILESYSTEM } } as Record<string, unknown>;
    await hooks.config({}, output);
    expect(output.mcp).toEqual({});
    expect(workspaceMcpReport(state, root)?.decisions[0]).toMatchObject({ name: "filesystem", status: "blocked", code: "runner_missing" });
  });

  test("the report lists what the engine left out of the project's config", async () => {
    const { state, root } = setup();
    const hooks = await omnirushMcpPolicy({ directory: root });
    const ignored = [{ kind: "plugin", name: "file:///repo/.opencode/plugins/evil.ts", source: "/repo/.opencode/plugins" }, { kind: "lsp", name: "custom", source: "/repo/opencode.json" }, { kind: "provider", name: "provider", source: "/repo/opencode.json" }];
    await hooks.config({}, { mcp: {}, omnirush_ignored: ignored });
    const report = workspaceMcpReport(state, root);
    expect(report?.ignored?.map((item) => item.kind)).toEqual(["plugin", "lsp", "provider"]);
    expect(describeIgnored(report?.ignored)).toContain("Not loaded from this project's config: plugins evil.ts; language servers custom; model provider settings.");
    // The desktop shows this line as it is (GET /workspace/:id/mcp ignoredNotice): no path that only fits the CLI.
    expect(describeIgnored(report?.ignored)).toContain("your own (user-level) settings");
  });

  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", "mkdir -p /tmp/omnirush-mcp-npx && exec npx --prefix /tmp/omnirush-mcp-npx -y @modelcontextprotocol/[email protected] ."]);
    // 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);
  });

  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");
  });

  test("an engine that requires the filter but does not start servers env-only starts no local server; remote ones still start", async () => {
    const { state, root } = setup();
    rememberMcpPolicy(state, { mcp: policyFixture });
    process.env.OMNIRUSH_MCP_FILTER = "required";
    delete (globalThis as Record<symbol, unknown>)[MCP_ENV_ONLY_MARK];
    const config = () => ({ mcp: {
      files: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "{file:../outside.txt}"] },
      figma: { type: "remote", url: "http://127.0.0.1:3845/mcp" },
    } }) as Record<string, unknown>;
    const older = config();
    await (await omnirushMcpPolicy({ directory: root })).config({}, older);
    expect(Object.keys(older.mcp as object)).toEqual(["figma"]);
    let report = workspaceMcpReport(state, root);
    expect(report?.decisions[0]).toMatchObject({ name: "files", status: "blocked", code: "engine_update", reason: "This MCP server needs a newer engine; update OmniRush to use it." });
    expect(report?.decisions[1]).toMatchObject({ name: "figma", status: "allowed" });
    expect(report).toMatchObject({ filter_required: true, env_only: false });
    // The add route says the same while the last engine run was an older one.
    expect(decideMcpEntry(state, root, "filesystem", FILESYSTEM)).toMatchObject({ status: "blocked", code: "engine_update", reason: MCP_REASONS.engine_update });

    (globalThis as Record<symbol, unknown>)[MCP_ENV_ONLY_MARK] = true;
    const newer = config();
    newer.mcp = { files: FILESYSTEM, figma: (newer.mcp as Record<string, unknown>).figma };
    await (await omnirushMcpPolicy({ directory: root })).config({}, newer);
    expect(Object.keys(newer.mcp as object).sort()).toEqual(["figma", "filesystem"]);
    report = workspaceMcpReport(state, root);
    expect(report?.decisions.map((d) => d.status)).toEqual(["allowed", "allowed"]);
    expect(decideMcpEntry(state, root, "filesystem", FILESYSTEM)).toMatchObject({ status: "allowed" });
  });

  test("the filter not required: local servers start whatever the engine", async () => {
    const { state, root } = setup();
    rememberMcpPolicy(state, { mcp: policyFixture });
    delete process.env.OMNIRUSH_MCP_FILTER;
    delete (globalThis as Record<symbol, unknown>)[MCP_ENV_ONLY_MARK];
    const output = { mcp: { files: FILESYSTEM, figma: { type: "remote", url: "http://127.0.0.1:3845/mcp" } } } as Record<string, unknown>;
    await (await omnirushMcpPolicy({ directory: root })).config({}, output);
    expect(Object.keys(output.mcp as object).sort()).toEqual(["figma", "filesystem"]);
    expect(workspaceMcpReport(state, root)).toMatchObject({ filter_required: false, env_only: false });
  });

  test("a missing or empty MCP plugin file is reported (the engine then starts no MCP server)", () => {
    const dir = mkdtempSync(path.join(tmpdir(), "mcp-filter-"));
    try {
      expect(mcpFilterMissing(path.join(dir, "omnirush-mcp-policy.js"))).toBe(true);
      writeFileSync(path.join(dir, "empty.js"), "");
      expect(mcpFilterMissing(path.join(dir, "empty.js"))).toBe(true);
      writeFileSync(path.join(dir, "ok.js"), "export default {}");
      expect(mcpFilterMissing(path.join(dir, "ok.js"))).toBe(false);
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });
});

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("a server keeps the desktop session, git, Volta and registry settings; git logins and absent names are never set", () => {
    const env: Record<string, string | undefined> = {
      DISPLAY: ":99", WAYLAND_DISPLAY: "wayland-0", XAUTHORITY: "/home/u/.Xauthority", DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", PLAYWRIGHT_BROWSERS_PATH: "/p",
      GIT_AUTHOR_NAME: "A", GIT_COMMITTER_EMAIL: "[email protected]", GIT_SSH_COMMAND: "ssh -i k", GIT_CONFIG_GLOBAL: "/g", GIT_SSL_CAINFO: "/ca", VOLTA_HOME: "/v",
      UV_INDEX: "u", UV_EXTRA_INDEX_URL: "u", UV_INSECURE_HOST: "h", CURL_CA_BUNDLE: "/ca", PIP_CERT: "/ca", NPM_CONFIG_USERCONFIG: "/n",
      GIT_ASKPASS: "/h", GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "http.extraHeader", GIT_CONFIG_VALUE_0: "Authorization: x", GIT_CONFIG_PARAMETERS: "x", GIT_HTTP_EXTRAHEADER: "x", GIT_CREDENTIAL_HELPER: "s", GIT_TOKEN: "x",
      UV_PUBLISH_TOKEN: "x", OMNIRUSH_ACCESS_TOKEN: "t", OPENCODE_SERVER_PASSWORD: "p", EMPTY_ONE: "", UNSET_ONE: undefined,
    };
    const out = mcpServerEnvironment(env, {}, [], "linux");
    expect(Object.keys(out).sort()).toEqual(["GIT_ASKPASS", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_VALUE_0", "GIT_CREDENTIAL_HELPER", "GIT_HTTP_EXTRAHEADER", "GIT_TOKEN", "OMNIRUSH_ACCESS_TOKEN", "OPENCODE_SERVER_PASSWORD", "UV_PUBLISH_TOKEN"]);
    expect(new Set(Object.values(out))).toEqual(new Set([""]));
  });

  test("a server keeps uv, pip and npm settings, never their logins", () => {
    const env = {
      UV_CACHE_DIR: "/home/u/.cache/uv", UV_PYTHON: "3.12", PIP_CACHE_DIR: "/p", npm_config_cache: "/n", NPM_CONFIG_PREFIX: "/np", GIT_AUTHOR_EMAIL: "a@b",
      UV_PUBLISH_TOKEN: "x", UV_INDEX_CORP_PASSWORD: "x", PIP_PASSWORD: "x", npm_config__authToken: "x", NPM_CONFIG__AUTH: "x",
    };
    expect(Object.keys(mcpServerEnvironment({ ...env, UV_KEYRING_PROVIDER: "subprocess", PIP_CLIENT_CERT_KEY: "x" }, {}, [], "linux")).sort()).toEqual(["NPM_CONFIG__AUTH", "PIP_CLIENT_CERT_KEY", "PIP_PASSWORD", "UV_INDEX_CORP_PASSWORD", "UV_KEYRING_PROVIDER", "UV_PUBLISH_TOKEN", "npm_config__authToken"]);
    const more = { "npm_config_//registry.npmjs.org/:_authToken": "x", "npm_config_//host/:_password": "x", npm_config_authorization: "x", npm_config_otp: "123456", GIT_HTTP_PASS: "x", GIT_SSH_PASSPHRASE: "x", UV_INDEX_X_PASS: "x",
      XDG_SESSION_TYPE: "wayland", GIT_AUTHOR_NAME: "A", LC_ALL: "C", npm_config_init_author_name: "A" };
    expect(Object.keys(mcpServerEnvironment(more, {}, [], "linux")).sort()).toEqual(["GIT_HTTP_PASS", "GIT_SSH_PASSPHRASE", "UV_INDEX_X_PASS", "npm_config_//host/:_password", "npm_config_//registry.npmjs.org/:_authToken", "npm_config_authorization", "npm_config_otp"]);
  });

  test("Windows: a server's own variable wins over the engine's whatever the case", () => {
    expect(mcpServerEnvironment({ memory_file_path: "C:\\other" }, { MEMORY_FILE_PATH: "C:\\work\\m" }, [], "win32")).toEqual({ MEMORY_FILE_PATH: "C:\\work\\m" });
  });

  test("env-only engine: a server gets the allowed values, nothing empty, and no app value even when set later", () => {
    const policy = normalizePolicy(policyFixture);
    const engineEnv: Record<string, string> = { PATH: "/usr/bin", HOME: "/home/u", DISPLAY: ":0", HTTPS_PROXY: "http://proxy:3128", OMNIRUSH_ACCESS_TOKEN: "acc-0123456789", OPENCODE_SERVER_PASSWORD: "pw-0123456789", AWS_SECRET_ACCESS_KEY: "aws-0123456789" };
    const base = (env: Record<string, string>) => Object.fromEntries(Object.entries(env).filter(([k]) => /^(?:PATH|HOME|TMPDIR|LANG|LC_\w+|XDG_\w+)$/i.test(k)));
    for (const envOnly of [false, true]) {
      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: engineEnv, envOnly });
      const environment = (mcp as Record<string, { environment?: Record<string, string> }>).filesystem!.environment ?? {};
      if (envOnly) expect(Object.values(environment)).not.toContain("");
      const later = { ...engineEnv, OMNIRUSH_LATE_TOKEN: "late-0123456789" };
      const spawned = envOnly ? { ...base(later), ...environment } : { ...later, ...environment };
      for (const secret of ["acc-0123456789", "pw-0123456789", "aws-0123456789", ...(envOnly ? ["late-0123456789"] : [])]) expect(Object.values(spawned)).not.toContain(secret);
      expect(spawned).toMatchObject({ PATH: "/usr/bin", HOME: "/home/u", DISPLAY: ":0", HTTPS_PROXY: "http://proxy:3128" });
    }
  });

  test("an entry holding one of the app's values (args, variables, folder) does not start", () => {
    const policy = normalizePolicy(policyFixture);
    const env = { PATH: "/usr/bin", OMNIRUSH_ACCESS_TOKEN: "acc-0123456789", OPENCODE_SERVER_PASSWORD: "pw-0123456789", OMNIRUSH_PERMISSION_MODE: "careful" };
    const ctx = { root: "/work/app", platform: "linux", npmPrefix: "/state/npx", resolveRunner: (runner: string) => runner, env };
    for (const entry of [
      { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "./acc-0123456789"] },
      { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."], environment: { X: "pw-0123456789" } },
      { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."], cwd: "pw-0123456789" },
    ]) {
      const { mcp, decisions } = evaluateMcp({ filesystem: entry }, policy, ctx);
      expect(mcp).toEqual({});
      expect(decisions[0]).toMatchObject({ status: "blocked", code: "protected_value" });
      expect(JSON.stringify(decisions)).not.toContain("0123456789");
    }
    expect(evaluateMcp({ filesystem: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "careful"] } }, policy, ctx).decisions[0]!.status).toBe("allowed");
  });

  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);
    const ctx = { root: "/work/app", platform: "linux", npmPrefix: "/state/npx", resolveRunner: (runner: string) => runner, env: { FIGMA_API_KEY: "x".repeat(24) } };
    const { mcp, decisions } = evaluateMcp({ figma: { type: "local", command: ["npx", "-y", "figma-developer-mcp"], environment: { FRAMELINK_TELEMETRY: "on", DO_NOT_TRACK: "0" } } }, policy, ctx);
    expect(decisions[0]).toMatchObject({ status: "allowed", id: "figma" });
    expect((mcp as Record<string, { environment?: Record<string, string> }>).figma?.environment).toEqual({ FRAMELINK_TELEMETRY: "off", DO_NOT_TRACK: "1" });
  });
});