Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: enforce MCP ban across GUI and engine

OmniRush Reviewd68eefde587b
diff --git a/apps/app/src/react-app/domains/connections/store.ts b/apps/app/src/react-app/domains/connections/store.ts
index e92f5fd7..397a7b7f 100644
--- a/apps/app/src/react-app/domains/connections/store.ts
+++ b/apps/app/src/react-app/domains/connections/store.ts
@@ -78,6 +78,7 @@ const OMNIRUSH_UI_MCP_UNAVAILABLE = "UI control requires the omnirush.ai desktop
const COMPUTER_USE_HELPER_UNAVAILABLE = "Computer Use helper app is unavailable. Restart omnirush.ai or reinstall the app.";
const COMPUTER_USE_CONNECT_TIMEOUT_MS = 15_000;
const COMPUTER_USE_RECONNECT_COOLDOWN_MS = 30_000;
+const MCP_DISABLED_BY_POLICY = "MCP servers are disabled in OmniRush.ai. Run the isolated Docker Harbor task to reproduce MCP behavior.";
async function withLocalOmniRushServerRecoveryTimeout<T>(
task: Promise<T>,
@@ -265,6 +266,14 @@ export function createConnectionsStore(options: {
const getOmniRushSnapshot = () => options.omnirushServer.getSnapshot();
+ const mcpDisabledByPolicy = () => {
+ const current = getOmniRushSnapshot();
+ // A GUI without an OmniRush policy-bearing server must fail closed. The
+ // Harbor exception is server-side only and is never exposed to the app.
+ return current.omnirushServerStatus !== "connected"
+ || current.omnirushServerCapabilities?.mcp?.read !== true;
+ };
+
const resolveOmniRushWorkspaceId = async () => {
const current = options.runtimeWorkspaceId()?.trim();
if (current) return current;
@@ -603,6 +612,16 @@ export function createConnectionsStore(options: {
}
async function refreshMcpServers() {
+ if (mcpDisabledByPolicy()) {
+ mutateState((current) => ({
+ ...current,
+ mcpServers: [],
+ mcpStatuses: {},
+ mcpStatus: MCP_DISABLED_BY_POLICY,
+ mcpLastUpdatedAt: Date.now(),
+ }));
+ return;
+ }
if (disposed) return;
const refreshToken = mcpStatusSynchronizer.beginRefresh(getWorkspaceContextKey());
@@ -779,6 +798,10 @@ export function createConnectionsStore(options: {
}
function mcpMutationDenied(builtIn: boolean) {
+ if (mcpDisabledByPolicy()) {
+ setStateField("mcpStatus", MCP_DISABLED_BY_POLICY);
+ return MCP_DISABLED_BY_POLICY;
+ }
const restriction = builtIn ? "allowBuiltInExtensions" : "allowManageExtensions";
if (!options.checkDesktopAppRestriction({ restriction })) return null;
const message = desktopRestrictionNotice(restriction);
@@ -793,6 +816,8 @@ export function createConnectionsStore(options: {
}
async function connectMcp(entry: McpDirectoryInfo): Promise<McpConnectResult> {
+ const policyError = mcpMutationDenied(false);
+ if (policyError) return { ok: false, error: policyError };
const builtIn = builtInMcp(getMcpServerName(entry));
// Use catalog configuration for built-ins; caller-supplied metadata must
// not turn an arbitrary URL or command into an allowed built-in.
@@ -1190,6 +1215,10 @@ export function createConnectionsStore(options: {
* waiting for the marker to expire.
*/
async function syncCloudControlMcp(options?: { force?: boolean }): Promise<"synced" | "unchanged" | "skipped"> {
+ if (mcpDisabledByPolicy()) {
+ setStateField("mcpStatus", MCP_DISABLED_BY_POLICY);
+ return "skipped";
+ }
const settings = readDenSettings();
const orgId = settings.activeOrgId?.trim() ?? "";
if (!orgId || !settings.authToken?.trim()) return "skipped";
@@ -1252,6 +1281,7 @@ export function createConnectionsStore(options: {
}
async function authorizeMcp(entry: McpServerEntry) {
+ if (mcpMutationDenied(Boolean(builtInMcp(entry.name)))) return;
if (entry.managedOAuth) {
try {
const { omnirushClient, omnirushWorkspaceId, canUseOmniRushServer } = await resolveWritableOmniRushTarget();
@@ -1296,6 +1326,7 @@ export function createConnectionsStore(options: {
}
async function logoutMcpAuth(name: string) {
+ if (mcpMutationDenied(Boolean(builtInMcp(name)))) return;
const omnirushSnapshot = getOmniRushSnapshot();
const isRemoteWorkspace =
options.workspaceType() === "remote" ||
diff --git a/apps/app/src/react-app/domains/connections/use-cloud-mcp-submit-readiness.ts b/apps/app/src/react-app/domains/connections/use-cloud-mcp-submit-readiness.ts
index c5a8c723..65ca6942 100644
--- a/apps/app/src/react-app/domains/connections/use-cloud-mcp-submit-readiness.ts
+++ b/apps/app/src/react-app/domains/connections/use-cloud-mcp-submit-readiness.ts
@@ -35,6 +35,7 @@ type CloudMcpSubmitReadinessClient = Pick<
>;
type UseCloudMcpSubmitReadinessInput = {
+ enabled?: boolean;
cloudAuthStatus: DenAuthStatus;
client: CloudMcpSubmitReadinessClient | null;
workspaceId: string | null;
@@ -184,7 +185,7 @@ export function useCloudMcpSubmitReadiness(
const submit = useCallback(async (submission: CloudMcpSubmitInput): Promise<CloudMcpSubmissionResult> => {
const initialSnapshot = gateSnapshotRef.current;
const capturedScopeKey = initialSnapshot.decision.scopeKey;
- const gateRequired = !submission.skipGate && initialSnapshot.decision.mode !== "bypass";
+ const gateRequired = input.enabled !== false && !submission.skipGate && initialSnapshot.decision.mode !== "bypass";
let prepare: (() => Promise<CloudMcpSubmissionPreparationResult>) | undefined;
if (gateRequired) {
@@ -338,7 +339,7 @@ export function useCloudMcpSubmitReadiness(
setState(IDLE_CLOUD_MCP_SUBMISSION_GATE_STATE);
},
});
- }, [waitForAuthResolution]);
+ }, [input.enabled, waitForAuthResolution]);
const clearFailure = useCallback(() => {
setState(clearCloudMcpSubmissionFailure);
diff --git a/apps/app/src/react-app/domains/connections/use-session-mcp-maintenance.ts b/apps/app/src/react-app/domains/connections/use-session-mcp-maintenance.ts
index 413f808f..421c9611 100644
--- a/apps/app/src/react-app/domains/connections/use-session-mcp-maintenance.ts
+++ b/apps/app/src/react-app/domains/connections/use-session-mcp-maintenance.ts
@@ -347,6 +347,7 @@ export async function healWorkspaceMcpInBackground(input: {
}
export function useSessionMcpMaintenance(input: {
+ enabled?: boolean;
cloudSignedIn: boolean;
client: OmniRushServerClient | null;
workspaceId: string | null;
@@ -360,6 +361,10 @@ export function useSessionMcpMaintenance(input: {
);
useEffect(() => {
+ if (input.enabled === false) {
+ setCloudMcpState(IDLE_CLOUD_MCP_MAINTENANCE_STATE);
+ return;
+ }
if (input.engineReloadBusy) {
setCloudMcpState(input.cloudSignedIn
? { ...IDLE_CLOUD_MCP_MAINTENANCE_STATE, status: "checking" }
@@ -476,6 +481,7 @@ export function useSessionMcpMaintenance(input: {
if (busyRetryTimer !== null) window.clearTimeout(busyRetryTimer);
};
}, [
+ input.enabled,
input.client,
input.cloudSignedIn,
input.directory,
diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
index 7adfeb11..44752619 100644
--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx
+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
@@ -571,6 +571,8 @@ function createImageLightboxEvalMessages(sessionId: string): UIMessage[] {
}
export type SessionSurfaceProps = {
+ /** OmniRush GUI has no MCP capability; isolated Harbor tasks do not use this surface. */
+ mcpDisabled?: boolean;
client: OmniRushServerClient;
environmentClient?: OmniRushServerClient | null;
workspaceId: string;
@@ -2652,6 +2654,13 @@ export function SessionSurface(props: SessionSurfaceProps) {
}, [props.client, props.workspaceId]);
const listMcp = useCallback(async (): Promise<{ servers: McpServerEntry[]; statuses: McpStatusMap; status: string | null }> => {
+ if (props.mcpDisabled === true) {
+ const status = "MCP servers are disabled in OmniRush.ai.";
+ setToolMcpServers([]);
+ setToolMcpStatuses({});
+ setToolMcpStatus(status);
+ return { servers: [], statuses: {}, status };
+ }
const pushId = ++mcpConnectPushRef.current;
const scope = readCloudInventoryScope();
const cachedConnect = (scope ? readCachedConnectCapabilities(scope) : null) ?? EMPTY_CONNECT_CAPABILITY_INVENTORY;
@@ -2719,7 +2728,7 @@ export function SessionSurface(props: SessionSurfaceProps) {
setToolMcpStatus(status);
return { servers, statuses, status };
- }, [opencodeClient, props.client, props.workspaceId, props.workspaceRoot]);
+ }, [opencodeClient, props.client, props.mcpDisabled, props.workspaceId, props.workspaceRoot]);
const listImportedPlugins = useCallback(async (): Promise<CloudImportedPlugin[]> => {
const pushId = ++pluginConnectPushRef.current;
diff --git a/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx b/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx
index 9f21a197..3b6f2bd7 100644
--- a/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx
@@ -173,6 +173,8 @@ export type McpViewProps = {
/** Composer agents to render in Library. */
installedAgents?: LibraryAgentItem[];
/** MCP capabilities assigned through omnirush.ai Connect. */
+ /** True when the connected OmniRush server has disabled MCP for this client. */
+ mcpDisabled?: boolean;
availableConnectMcpServers?: McpServerEntry[];
availableConnectMcpStatuses?: McpStatusMap;
/** Organization inventory is still being fetched and nothing is cached yet. */
@@ -531,13 +533,20 @@ export function McpView(props: McpViewProps) {
const setTogglingMcp = (value: SetStateAction<string | null>) => setLocal("togglingMcp", value);
const configRequestId = useRef(0);
- const quickConnectList = props.quickConnect;
+ const mcpDisabled = props.mcpDisabled === true;
+ const isMcpDirectoryEntry = (entry: McpDirectoryInfo) =>
+ entry.kind === "mcp" || Boolean(entry.type || entry.command?.length || entry.url);
+ const quickConnectList = mcpDisabled
+ ? props.quickConnect.filter((entry) => !isMcpDirectoryEntry(entry))
+ : props.quickConnect;
const installedSkills = props.installedSkills ?? [];
const installedCommands = props.installedCommands ?? [];
const installedAgents = props.installedAgents ?? [];
- const availableConnectMcpServers = props.availableConnectMcpServers ?? [];
- const installedPlugins = props.installedPlugins ?? [];
- const orgMcpItems = props.orgMcpItems ?? [];
+ const availableConnectMcpServers = mcpDisabled ? [] : props.availableConnectMcpServers ?? [];
+ const installedPlugins = mcpDisabled
+ ? (props.installedPlugins ?? []).filter((plugin) => !plugin.files.some((file) => file.objectType === "mcp"))
+ : props.installedPlugins ?? [];
+ const orgMcpItems = mcpDisabled ? [] : props.orgMcpItems ?? [];
const libraryDetailLists = {
quickConnect: quickConnectList,
skills: installedSkills,
@@ -619,6 +628,8 @@ export function McpView(props: McpViewProps) {
canCreateWorkspaceSkill: typeof props.createWorkspaceSkill === "function",
});
const libraryAddKinds = libraryAddKindsForFilter(filter).filter((kind) => (
+ !mcpDisabled || (kind !== "mcp" && kind !== "workspace-mcp")
+ )).filter((kind) => (
libraryAddAction(kind, libraryAddOptions) !== null
|| (kind === "skill" && workspaceSkillAdd)
));
@@ -903,7 +914,7 @@ export function McpView(props: McpViewProps) {
// Auto-configured built-ins like omnirush-cloud remain active but hidden from
// Your apps until Show hidden reveals the row for disable/remove. Projected
// direct org connections are shown through their omnirush.ai Connect card.
- const visibleMcpServers = inventoryState === "all" && (filter === "all" || filter === "mcp")
+ const visibleMcpServers = !mcpDisabled && inventoryState === "all" && (filter === "all" || filter === "mcp")
? showHidden
? props.mcpServers
: props.mcpServers.filter((entry) => {
@@ -1394,6 +1405,12 @@ export function McpView(props: McpViewProps) {
return (
<section className="w-full max-w-3xl animate-in fade-in duration-300">
+ {mcpDisabled ? (
+ <div data-testid="mcp-disabled-policy-notice" className="mb-5 rounded-xl border border-dls-border bg-dls-hover px-4 py-4 text-xs leading-5 text-dls-secondary">
+ <p className="text-sm font-medium text-foreground">MCP servers are disabled</p>
+ <p className="mt-1">OmniRush.ai does not allow MCP servers in the GUI or CLI. MCP behavior can only be reproduced inside an isolated Docker Harbor task.</p>
+ </div>
+ ) : null}
{props.builtInExtensionsDisabled && props.allowManageExtensions ? (
<div className="mb-5 rounded-xl border border-amber-6 bg-amber-2 px-4 py-3 text-xs text-amber-11">
Built-in omnirush.ai extensions are disabled by your organization. Use Show hidden to review blocked built-ins.
@@ -1674,7 +1691,7 @@ export function McpView(props: McpViewProps) {
}}
/>
- <McpAdvancedConfigSection
+ {!mcpDisabled ? <McpAdvancedConfigSection
open={showAdvanced}
configScope={configScope}
activeConfig={activeConfig}
@@ -1691,22 +1708,22 @@ export function McpView(props: McpViewProps) {
? () => setClaudeImportOpen(true)
: undefined
}
- />
+ /> : null}
- <AddMcpModal
+ {!mcpDisabled ? <AddMcpModal
open={addMcpModalOpen}
onClose={() => setAddMcpModalOpen(false)}
onAdd={props.connectMcp}
busy={props.busy}
isRemoteWorkspace={props.isRemoteWorkspace}
- />
+ /> : null}
<AddLibraryItemModal
open={addAuthorableKind !== null}
kind={addAuthorableKind}
busy={props.busy}
cloud={cloudSession.isSignedIn}
- canConfigureMcpConnections={isConnectAdminRole(cloudSession.activeOrganization?.role)}
+ canConfigureMcpConnections={!mcpDisabled && isConnectAdminRole(cloudSession.activeOrganization?.role)}
onClose={() => setAddAuthorableKind(null)}
onCreate={handleCreateLibraryItem}
/>
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index 5210d488..274e17f3 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -587,6 +587,7 @@ export function SessionRoute() {
}
: undefined, [local.prefs.defaultModel?.modelID, local.prefs.defaultModel?.providerID]);
const sessionMcpMaintenance = useSessionMcpMaintenance({
+ enabled: false,
cloudSignedIn: denAuth.isSignedIn,
client: selectedWorkspaceEndpoint?.client ?? null,
workspaceId: selectedWorkspaceEndpoint?.workspaceId ?? null,
@@ -600,6 +601,7 @@ export function SessionRoute() {
submit: submitWithCloudMcpReadiness,
clearFailure: clearCloudMcpSubmissionFailure,
} = useCloudMcpSubmitReadiness({
+ enabled: false,
cloudAuthStatus: denAuth.status,
client: selectedWorkspaceEndpoint?.client ?? null,
workspaceId: selectedWorkspaceEndpoint?.workspaceId ?? null,
@@ -1305,6 +1307,7 @@ export function SessionRoute() {
// local server's, and remote workspaces silently end up calling the
// local server with the local `rem_*` id.
return {
+ mcpDisabled: true,
workspaceRoot: selectedWorkspaceRoot,
draftScope: sessionDraftScope,
developerMode,
diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsx
index c7e92205..39c55f4a 100644
--- a/apps/app/src/react-app/shell/settings-route.tsx
+++ b/apps/app/src/react-app/shell/settings-route.tsx
@@ -214,7 +214,7 @@ import {
const ROUTE_OMNIRUSH_CAPABILITIES: OmniRushServerCapabilities = {
skills: { read: true, write: true, source: "omnirush" },
plugins: { read: true, write: true },
- mcp: { read: true, write: true },
+ mcp: { read: false, write: false },
commands: { read: true, write: true },
config: { read: true, write: true },
};
@@ -2085,6 +2085,8 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {
const routeOmniRushCapabilities: OmniRushServerCapabilities | null = omnirushClient
? ROUTE_OMNIRUSH_CAPABILITIES
: null;
+ const mcpDisabledByPolicy = routeOmniRushStatus !== "connected"
+ || routeOmniRushCapabilities?.mcp?.read !== true;
const environmentRuntimeKey = buildOmniRushEnvRuntimeKey({
baseUrl: omnirushServerSnapshot.omnirushServerBaseUrl || omnirushServerSnapshot.omnirushServerUrl,
pid: omnirushServerSnapshot.omnirushServerHostInfo?.pid ?? null,
@@ -2405,6 +2407,7 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {
selectedWorkspaceRoot={selectedWorkspaceRoot}
isRemoteWorkspace={isRemoteWorkspace}
mcpServers={connectionsSnapshot.mcpServers}
+ mcpDisabled={mcpDisabledByPolicy}
mcpStatus={connectionsSnapshot.mcpStatus}
mcpLastUpdatedAt={connectionsSnapshot.mcpLastUpdatedAt}
mcpStatuses={connectionsSnapshot.mcpStatuses}
diff --git a/apps/server/package.json b/apps/server/package.json
index 2c184ca5..92bda9e1 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-engine2.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 && 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-mcp-policy.ts src/opencode-plugins/omnirush-engine2.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/src/cli.ts b/apps/server/src/cli.ts
index 42181a83..d5eb5cf3 100644
--- a/apps/server/src/cli.ts
+++ b/apps/server/src/cli.ts
@@ -91,6 +91,13 @@ if (!config.opencodeBaseUrl && process.env.OMNIRUSH_MANAGE_OPENCODE === "1") {
OMNIRUSH_SERVER_URL: serverUrl,
OMNIRUSH_SERVER_TOKEN: config.token,
OMNIRUSH_POLICY_TOKEN: managedDesktopPolicy(config).evaluationToken,
+ OMNIRUSH_MCP_POLICY: config.mcpPolicy ?? "disabled",
+ ...(config.mcpPolicy === "harbor-local" && process.env.OMNIRUSH_HARBOR_TASK_ID?.trim()
+ ? { OMNIRUSH_HARBOR_TASK_ID: process.env.OMNIRUSH_HARBOR_TASK_ID }
+ : {}),
+ ...(config.mcpPolicy === "harbor-local" && process.env.OMNIRUSH_SANDBOX_BACKEND?.trim()
+ ? { OMNIRUSH_SANDBOX_BACKEND: process.env.OMNIRUSH_SANDBOX_BACKEND }
+ : {}),
OPENCODE_CONFIG: runtimeConfigPath,
...opencodeModelsEnv,
};
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index 44ffab86..a96b574d 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -258,6 +258,13 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promi
OMNIRUSH_SERVER_URL: serverUrl,
OMNIRUSH_SERVER_TOKEN: config.token,
OMNIRUSH_POLICY_TOKEN: managedDesktopPolicy(config).evaluationToken,
+ OMNIRUSH_MCP_POLICY: config.mcpPolicy ?? "disabled",
+ ...(config.mcpPolicy === "harbor-local" && process.env.OMNIRUSH_HARBOR_TASK_ID?.trim()
+ ? { OMNIRUSH_HARBOR_TASK_ID: process.env.OMNIRUSH_HARBOR_TASK_ID }
+ : {}),
+ ...(config.mcpPolicy === "harbor-local" && process.env.OMNIRUSH_SANDBOX_BACKEND?.trim()
+ ? { OMNIRUSH_SANDBOX_BACKEND: process.env.OMNIRUSH_SANDBOX_BACKEND }
+ : {}),
OPENCODE_CONFIG: runtimeConfigPath,
...opencodeModelsEnv,
};
diff --git a/apps/server/src/engine2/config.test.ts b/apps/server/src/engine2/config.test.ts
index 2be2dcca..8e0a09da 100644
--- a/apps/server/src/engine2/config.test.ts
+++ b/apps/server/src/engine2/config.test.ts
@@ -125,6 +125,10 @@ describe("the 1.x runtime config as the 2.x engine config", () => {
expect(v2Mcp({ type: "remote", url: "https://x", oauth: { clientId: "c" } })).toEqual({ type: "remote", url: "https://x", oauth: { client_id: "c" }, codemode: false });
});
+ test("disabled policy never renders MCP servers", () => {
+ expect(buildEngine2Config({ v1: runtime, mcpAllowed: false }).mcp).toBeUndefined();
+ });
+
test("packages and permission names", () => {
expect(v2Package("@ai-sdk/anthropic")).toBe("@opencode/ai/providers/anthropic");
expect(v2Package("@opencode-ai/ai/providers/openai")).toBe("@opencode/ai/providers/openai");
diff --git a/apps/server/src/engine2/config.ts b/apps/server/src/engine2/config.ts
index 5e06229c..a5a9ecab 100644
--- a/apps/server/src/engine2/config.ts
+++ b/apps/server/src/engine2/config.ts
@@ -21,6 +21,8 @@ export type EngineConfigInput = {
apiKeys?: Record<string, string>;
/** Plugin directories the engine loads (OmniRush.ai's plugin bridge). */
plugins?: string[];
+ /** Whether MCP servers may be rendered into the 2.x config. */
+ mcpAllowed?: boolean;
};
/** 1.x tool / permission names in 2.x (core/src/v1/config/migrate.ts normalizeAction). */
@@ -257,7 +259,7 @@ export function buildEngine2Config(input: EngineConfigInput): JsonRecord {
const small = modelSelection(v1.small_model);
if (small) agents.title = { model: small, ...(isRecord(agents.title) ? agents.title : {}) };
const servers: JsonRecord = {};
- if (isRecord(v1.mcp)) {
+ if (input.mcpAllowed !== false && isRecord(v1.mcp)) {
for (const [name, server] of Object.entries(v1.mcp)) {
const mapped = v2Mcp(server);
if (mapped) servers[name] = mapped;
diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.ts
index 956fcec0..be43eceb 100644
--- a/apps/server/src/engine2/facade.ts
+++ b/apps/server/src/engine2/facade.ts
@@ -58,6 +58,8 @@ export type EngineFacadeOptions = {
writeEngineConfig?: (config: JsonRecord) => Promise<void>;
/** Plugin directories the rendered config names (OmniRush.ai's plugin bridge). */
plugins?: string[];
+ /** Whether MCP servers may be rendered into the 2.x config. */
+ mcpAllowed?: boolean;
/** Engine state paths reported by `/path`. */
paths?: { state?: string; config?: string };
log?: (message: string, attributes?: Record<string, unknown>) => void;
@@ -262,7 +264,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E
let v1ConfigCache: JsonRecord = await readV1Config();
const refreshConfig = async (): Promise<void> => {
v1ConfigCache = await readV1Config();
- if (options.writeEngineConfig) await options.writeEngineConfig(buildEngine2Config({ v1: v1ConfigCache, apiKeys, plugins: options.plugins }));
+ if (options.writeEngineConfig) await options.writeEngineConfig(buildEngine2Config({ v1: v1ConfigCache, apiKeys, plugins: options.plugins, mcpAllowed: options.mcpAllowed }));
};
// ---- location reloads ---------------------------------------------------
diff --git a/apps/server/src/engine2/launch.ts b/apps/server/src/engine2/launch.ts
index e4b8b27f..a0da840e 100644
--- a/apps/server/src/engine2/launch.ts
+++ b/apps/server/src/engine2/launch.ts
@@ -168,7 +168,10 @@ export async function prepareEngine2Launch(input: {
v1 = {};
}
}
- await writeEngineConfig(buildEngine2Config({ v1, plugins }));
+ const mcpAllowed = input.env.OMNIRUSH_MCP_POLICY?.trim().toLowerCase() === "harbor-local"
+ && Boolean(input.env.OMNIRUSH_HARBOR_TASK_ID?.trim())
+ && input.env.OMNIRUSH_SANDBOX_BACKEND?.trim().toLowerCase() === "docker";
+ await writeEngineConfig(buildEngine2Config({ v1, plugins, mcpAllowed }));
const env: NodeJS.ProcessEnv = { ...input.env };
delete env.OPENCODE_CONFIG_CONTENT;
env.OPENCODE_CONFIG = configFile;
diff --git a/apps/server/src/managed-opencode.ts b/apps/server/src/managed-opencode.ts
index e38e4269..7c11ee32 100644
--- a/apps/server/src/managed-opencode.ts
+++ b/apps/server/src/managed-opencode.ts
@@ -255,6 +255,9 @@ async function startManagedEngine2Server(
v1ConfigPath: launch.v1ConfigPath,
writeEngineConfig: launch.writeEngineConfig,
plugins: launch.plugins,
+ mcpAllowed: launch.env.OMNIRUSH_MCP_POLICY?.trim().toLowerCase() === "harbor-local"
+ && Boolean(launch.env.OMNIRUSH_HARBOR_TASK_ID?.trim())
+ && launch.env.OMNIRUSH_SANDBOX_BACKEND?.trim().toLowerCase() === "docker",
log: (message, attributes) => console.warn(`[engine-adapter] ${message}`, attributes ? JSON.stringify(attributes) : ""),
});
} catch (error) {
diff --git a/apps/server/src/mcp-policy.test.ts b/apps/server/src/mcp-policy.test.ts
new file mode 100644
index 00000000..dee8c68f
--- /dev/null
+++ b/apps/server/src/mcp-policy.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, test } from "bun:test";
+import { ApiError } from "./errors.js";
+import {
+ assertMcpAllowed,
+ mcpAllowed,
+ mcpPolicyForConfig,
+ resolveMcpPolicyFromEnvironment,
+} from "./mcp-policy.js";
+
+describe("MCP execution policy", () => {
+ test("normal server environments deny MCP", () => {
+ expect(resolveMcpPolicyFromEnvironment({})).toBe("disabled");
+ });
+
+ test("only a marked Docker Harbor task may opt in", () => {
+ expect(resolveMcpPolicyFromEnvironment({
+ OMNIRUSH_MCP_POLICY: "harbor-local",
+ OMNIRUSH_HARBOR_TASK_ID: "task-123",
+ OMNIRUSH_SANDBOX_BACKEND: "docker",
+ })).toBe("harbor-local");
+ expect(resolveMcpPolicyFromEnvironment({
+ OMNIRUSH_MCP_POLICY: "harbor-local",
+ OMNIRUSH_HARBOR_TASK_ID: "task-123",
+ OMNIRUSH_SANDBOX_BACKEND: "none",
+ })).toBe("disabled");
+ expect(resolveMcpPolicyFromEnvironment({
+ OMNIRUSH_MCP_POLICY: "harbor-local",
+ OMNIRUSH_SANDBOX_BACKEND: "docker",
+ })).toBe("disabled");
+ });
+
+ test("rejects a disabled server and preserves old direct test embedders", () => {
+ expect(mcpPolicyForConfig({})).toBe("enabled");
+ expect(mcpAllowed({ mcpPolicy: "disabled" })).toBe(false);
+ expect(() => assertMcpAllowed({ mcpPolicy: "disabled" })).toThrow(ApiError);
+ expect(() => assertMcpAllowed({ mcpPolicy: "harbor-local" })).not.toThrow();
+ });
+});
+
diff --git a/apps/server/src/mcp.ts b/apps/server/src/mcp.ts
index 2deba882..4fd27162 100644
--- a/apps/server/src/mcp.ts
+++ b/apps/server/src/mcp.ts
@@ -6,6 +6,7 @@ import { readJsoncFile } from "./jsonc.js";
import { opencodeConfigPath } from "./workspace-files.js";
import { validateMcpConfig, validateMcpName, validateUserMcpName } from "./validators.js";
import { ApiError } from "./errors.js";
+import { assertMcpAllowed } from "./mcp-policy.js";
import { isOmniRushUiMcpRegistryEntry, OMNIRUSH_UI_MCP_REGISTRY_COMMAND_MESSAGE } from "./omnirush-ui-mcp-command.js";
import {
readRuntimeOpencodeConfig,
@@ -477,6 +478,7 @@ function isMcpDisabledByTools(config: Record<string, unknown>, name: string): bo
}
export async function listMcp(serverConfig: ServerConfig, workspaceId: string, workspaceRoot: string): Promise<McpItem[]> {
+ if (serverConfig.mcpPolicy === "disabled") return [];
return listMcpFromRuntimeSnapshot(workspaceRoot, await readRuntimeOpencodeConfig(serverConfig, workspaceId));
}
@@ -667,6 +669,7 @@ export async function addMcp(
name: string,
config: Record<string, unknown>,
): Promise<{ action: "added" | "updated" }> {
+ assertMcpAllowed(serverConfig);
validateUserMcpName(name);
validateMcpConfig(config);
const runtimeConfig = await readRuntimeOpencodeConfig(serverConfig, workspaceId);
@@ -678,6 +681,7 @@ export async function addMcp(
}
export async function removeMcp(serverConfig: ServerConfig, workspaceId: string, name: string): Promise<boolean> {
+ assertMcpAllowed(serverConfig);
const runtimeConfig = await readRuntimeOpencodeConfig(serverConfig, workspaceId);
const mcpMap = { ...runtimeMcpMap(runtimeConfig) };
if (!Object.prototype.hasOwnProperty.call(mcpMap, name)) return false;
@@ -699,6 +703,7 @@ export async function setMcpEnabled(
name: string,
enabled: boolean,
): Promise<boolean> {
+ assertMcpAllowed(serverConfig);
validateMcpName(name);
const runtimeConfig = await readRuntimeOpencodeConfig(serverConfig, workspaceId);
const mcpMap = { ...runtimeMcpMap(runtimeConfig) };
diff --git a/apps/server/src/omnirush-extensions-plugin-path.ts b/apps/server/src/omnirush-extensions-plugin-path.ts
index f1d052ec..300f26af 100644
--- a/apps/server/src/omnirush-extensions-plugin-path.ts
+++ b/apps/server/src/omnirush-extensions-plugin-path.ts
@@ -42,3 +42,4 @@ export const omnirushPdfAttachmentsPluginPath = () => omnirushPluginPath("omniru
export const omnirushTitleRecoveryPluginPath = () => omnirushPluginPath("omnirush-title-recovery");
export const omnirushReasoningEffortPluginPath = () => omnirushPluginPath("omnirush-reasoning-effort");
export const omnirushSwarmPluginPath = () => omnirushPluginPath("omnirush-swarm");
+export const omnirushMcpPolicyPluginPath = () => omnirushPluginPath("omnirush-mcp-policy");
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.ts
index be79f49c..df54458b 100644
--- a/apps/server/src/omnirush-runtime-config.test.ts
+++ b/apps/server/src/omnirush-runtime-config.test.ts
@@ -82,6 +82,21 @@ async function readConfigFile(config: ServerConfig): Promise<Record<string, unkn
}
describe("omnirush runtime config file", () => {
+ test("disabled policy omits MCP and adds an engine permission fence", () => {
+ const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot(
+ { mcp: { posthog: { type: "remote", url: "https://mcp.example" } } },
+ undefined,
+ {},
+ undefined,
+ undefined,
+ undefined,
+ "disabled",
+ );
+ expect(parsed.mcp).toEqual({});
+ expect(parsed.permission).toMatchObject({ "mcp.*": "deny" });
+ expect(parsed.plugin).toContain(expect.stringContaining("omnirush-mcp-policy"));
+ });
+
test("managed browser restrictions use scalar actions in global and agent permissions", () => {
const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({
managedPolicy: {
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index b07baa39..62912aca 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -25,6 +25,7 @@ import {
omnirushTitleRecoveryPluginPath,
omnirushReasoningEffortPluginPath,
omnirushSwarmPluginPath,
+ omnirushMcpPolicyPluginPath,
omnirushOfficeAttachmentsPluginPath,
omnirushSpreadsheetsPluginPath,
omnirushChromeDevtoolsPluginPath,
@@ -54,6 +55,7 @@ import {
type OmniRushModelCatalog,
} from "./omnirush-model-catalog.js";
import { writeFileAtomic } from "./atomic-write.js";
+import { mcpPolicyForConfig, type McpPolicyMode } from "./mcp-policy.js";
import {
OMNIRUSH_BEST_PRACTICES,
bestPracticesEnabled,
@@ -139,6 +141,7 @@ export async function buildOmniRushRuntimeConfigObject(
internalGateway && config ? await readOmniRushModelCatalog(config) : undefined,
config ? omnirushRuntimeSkillsDir(config) : undefined,
config ? omnirushBestPracticesSkillsDir(config) : undefined,
+ config ? mcpPolicyForConfig(config) : "enabled",
);
}
@@ -168,10 +171,12 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
catalog: OmniRushModelCatalog = builtinOmniRushModelCatalog(),
skillsDir?: string,
bestPracticesDir?: string,
+ mcpPolicy: McpPolicyMode = "enabled",
): Record<string, unknown> {
const disabledProviders = runtimeDisabledProviderList(runtimeConfig);
// OMNIRUSH_APPROVALS in the server environment wins over the persisted setting.
const permissions = legacyExecutionPermissions(runtimeConfig.managedPolicy?.execution, resolveApprovalMode(runtimeConfig, env).mode);
+ const mcpPermission = mcpPolicy === "disabled" ? { "mcp.*": "deny" } : {};
const { managedPolicy: _managedPolicy, approvals: _approvals, bestPractices: _bestPractices, ...engineConfig } = runtimeConfig;
const enabled = bestPracticesEnabled(runtimeConfig);
const skillPaths = [
@@ -202,7 +207,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
...ownProviders,
...(runtimeConfig.managedPolicy.allowZenModel !== false ? ["opencode"] : []),
] } : onlyOwnProviders ? { enabled_providers: ownProviders } : {}),
- permission: { ...engineConfig.permission, ...permissions },
+ permission: { ...engineConfig.permission, ...permissions, ...mcpPermission },
// omnirush.ai's own on-demand skills (the swarm procedure).
...(skillPaths.length ? { skills: { paths: skillPaths } } : {}),
default_agent: runtimeConfig.default_agent ?? "omnirush",
@@ -218,6 +223,7 @@ 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.
@@ -260,14 +266,17 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
omnirushReasoningEffortPluginPath(),
omnirushTitleRecoveryPluginPath(),
omnirushSwarmPluginPath(),
+ omnirushMcpPolicyPluginPath(),
...runtimePluginList(runtimeConfig),
],
...(disabledProviders.length ? { disabled_providers: disabledProviders } : {}),
// Registry launches of omnirush-ui-mcp are never delivered, whatever the
// runtime DB holds: the MCP ships inside the desktop app, not on npm.
- mcp: Object.fromEntries(Object.entries(runtimeMcpMap(runtimeConfig))
- .filter(([name, entry]) => !name.startsWith(CONNECT_MCP_SERVER_NAME_PREFIX)
- && !isOmniRushUiMcpRegistryEntry(entry))),
+ mcp: mcpPolicy === "disabled"
+ ? {}
+ : Object.fromEntries(Object.entries(runtimeMcpMap(runtimeConfig))
+ .filter(([name, entry]) => !name.startsWith(CONNECT_MCP_SERVER_NAME_PREFIX)
+ && !isOmniRushUiMcpRegistryEntry(entry))),
...(Object.keys(provider).length ? { provider } : {}),
};
}
diff --git a/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts b/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts
new file mode 100644
index 00000000..c732a9d0
--- /dev/null
+++ b/apps/server/src/opencode-plugins/omnirush-mcp-policy.ts
@@ -0,0 +1,26 @@
+/**
+ * Engine-side MCP fence. The HTTP/UI checks are useful for normal clients,
+ * but an OpenCode config can also come from a workspace file or a direct
+ * engine request. This hook removes those servers before the model sees
+ * them, unless the server process explicitly belongs to an isolated Harbor
+ * Docker task.
+ */
+function harborMcpTask(): boolean {
+ return process.env.OMNIRUSH_MCP_POLICY?.trim().toLowerCase() === "harbor-local"
+ && Boolean(process.env.OMNIRUSH_HARBOR_TASK_ID?.trim())
+ && process.env.OMNIRUSH_SANDBOX_BACKEND?.trim().toLowerCase() === "docker";
+}
+
+export default async function omnirushMcpPolicy() {
+ if (harborMcpTask()) return {};
+ return {
+ config: async (_input: unknown, output: { mcp?: unknown; permission?: Record<string, unknown> }) => {
+ output.mcp = {};
+ output.permission = {
+ ...(output.permission ?? {}),
+ "mcp.*": "deny",
+ };
+ },
+ };
+}
+
diff --git a/apps/server/src/routes/cloud-mcp.ts b/apps/server/src/routes/cloud-mcp.ts
index d357d308..67875045 100644
--- a/apps/server/src/routes/cloud-mcp.ts
+++ b/apps/server/src/routes/cloud-mcp.ts
@@ -11,6 +11,7 @@ import {
type CloudMcpLiveStatusObserver,
} from "../cloud-mcp-health.js";
import { ApiError } from "../errors.js";
+import { assertMcpAllowed } from "../mcp-policy.js";
import type { ServerConfig, TokenScope, WorkspaceInfo } from "../types.js";
import { addRoute, type RequestContext, type Route } from "./registry.js";
@@ -95,6 +96,7 @@ export function registerCloudMcpRoutes(options: RegisterCloudMcpRoutesOptions):
} = options;
addRoute(routes, "GET", "/workspace/:id/mcp/omnirush-cloud/health", "client", async (ctx) => {
+ assertMcpAllowed(config);
const workspace = await resolveWorkspace(config, ctx.params.id);
assertExactWorkspace(ctx.params.id, workspace);
const health = await readOmniRushCloudMcpHealth({
@@ -111,6 +113,7 @@ export function registerCloudMcpRoutes(options: RegisterCloudMcpRoutesOptions):
});
addRoute(routes, "POST", "/workspace/:id/mcp/omnirush-cloud/engine-refresh", "client", async (ctx) => {
+ assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -148,6 +151,7 @@ export function registerCloudMcpRoutes(options: RegisterCloudMcpRoutesOptions):
});
addRoute(routes, "POST", "/workspace/:id/mcp/omnirush-cloud/reconcile", "client", async (ctx) => {
+ assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
diff --git a/apps/server/src/runtime-opencode-config-store.ts b/apps/server/src/runtime-opencode-config-store.ts
index a809a8cf..21c15f87 100644
--- a/apps/server/src/runtime-opencode-config-store.ts
+++ b/apps/server/src/runtime-opencode-config-store.ts
@@ -618,6 +618,7 @@ export function writeManagedDesktopPolicy(config: ServerConfig, policy: DesktopC
export function mergeOpencodeConfigs(
persisted: Record<string, unknown>,
runtime: RuntimeOpencodeConfig,
+ mcpEnabled = true,
): Record<string, unknown> {
const persistedPermission = isRecord(persisted.permission) ? persisted.permission : {};
const persistedExternalDirectory = isRecord(persistedPermission.external_directory)
@@ -634,10 +635,12 @@ export function mergeOpencodeConfigs(
...(Array.isArray(persisted.disabled_providers) ? persisted.disabled_providers.filter((item) => typeof item === "string") : []),
...runtimeDisabledProviderList(runtime),
].filter((item, index, list) => list.indexOf(item) === index),
- mcp: {
- ...(isRecord(persisted.mcp) ? persisted.mcp : {}),
- ...runtimeMcpMap(runtime),
- },
+ mcp: mcpEnabled
+ ? {
+ ...(isRecord(persisted.mcp) ? persisted.mcp : {}),
+ ...runtimeMcpMap(runtime),
+ }
+ : {},
permission: {
...persistedPermission,
external_directory: {
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 8ca378cf..76865dbe 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -174,6 +174,7 @@ import {
writeOmniRushWorkspaceConfig,
} from "./omnirush-workspace-config-store.js";
import { buildOmniRushRuntimeConfigObject, omnirushGatewayConfigured, omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";
+import { assertMcpAllowed, mcpAllowed, mcpPolicyForConfig, MCP_DISABLED_MESSAGE } from "./mcp-policy.js";
import { omnirushModelWantsReasoningSummary, readOmniRushModelCatalog } from "./omnirush-model-catalog.js";
import {
SUBAGENT_MODEL_FALLBACK_TRACE,
@@ -1566,8 +1567,11 @@ export async function proxyOpencodeV2Request(input: {
if (/^\/api\/config(?:\/|$)/.test(decodedPath)) {
throw new ApiError(403, "engine_config_private", "Engine configuration is private");
}
- if (method !== "GET" && method !== "HEAD" && /^\/api\/mcp(?:\/|$)/.test(decodedPath)) {
- throw new ApiError(403, "engine_mcp_managed", "Manage connections through OmniRush.ai");
+ 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");
+ }
}
const sessionMatch = routePath.match(/^\/api\/session\/([^/]+)(?:\/|$)/);
const sessionId = sessionMatch?.[1] ? decodeEngineRouteParam(sessionMatch[1]) : null;
@@ -1987,6 +1991,9 @@ export async function proxyOpencodeRequest(input: {
if (method !== "GET" && method !== "HEAD") {
ensureWritable(input.config);
}
+ if (/^(?:\/api)?\/mcp(?:\/|$)/.test(normalizeOpencodeProxyPath(proxyPath))) {
+ assertMcpAllowed(input.config);
+ }
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.
@@ -2687,7 +2694,7 @@ function buildCapabilities(config: ServerConfig): Capabilities {
providerSync: true,
skills: { read: true, write: writeEnabled, source: "omnirush" },
plugins: { read: true, write: writeEnabled },
- mcp: { read: true, write: writeEnabled },
+ mcp: { read: mcpAllowed(config), write: writeEnabled && mcpAllowed(config) },
commands: { read: true, write: writeEnabled },
config: { read: true, write: writeEnabled },
engine: { rollover: enginePoolForConfig(config) !== null },
@@ -3114,6 +3121,7 @@ function createRoutes(
const opencode = mergeOpencodeConfigs(
await readOpencodeConfig(workspace.path),
await readEffectiveRuntimeOpencodeConfig(config, workspace.id),
+ mcpAllowed(config),
);
const lastAudit = await readLastAudit(workspace.path, workspace.id);
return jsonResponse({ opencode, omnirush, updatedAt: lastAudit?.timestamp ?? null });
@@ -3176,6 +3184,9 @@ function createRoutes(
const workspace = await resolveWorkspace(config, ctx.params.id);
const body = await readJsonBody(ctx.request);
const resolved = readCloudPluginResolved(body.resolved);
+ if (resolved.memberships.some((membership) => membership.configObject?.objectType === "mcp")) {
+ assertMcpAllowed(config);
+ }
const marketplace = body.marketplace && typeof body.marketplace === "object" && !Array.isArray(body.marketplace)
? Object.fromEntries(Object.entries(body.marketplace))
: null;
@@ -3249,6 +3260,9 @@ function createRoutes(
const dryRun = body.dryRun === true;
const bundle = await resolveClaudePluginBundle({ url, ref });
+ if (bundle.resolved.memberships.some((membership) => membership.configObject?.objectType === "mcp")) {
+ assertMcpAllowed(config);
+ }
if (dryRun) {
return jsonResponse({ preview: bundle.preview });
}
@@ -4439,6 +4453,14 @@ function createRoutes(
});
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);
@@ -4450,23 +4472,33 @@ function createRoutes(
});
});
- addRoute(routes, "GET", "/mcp-apps/sandbox.html", "none", async (ctx) => new Response(MCP_APP_SANDBOX_PROXY_HTML, {
- headers: {
- "Content-Type": "text/html; charset=utf-8",
- "Content-Security-Policy": buildMcpAppSandboxCsp(parseMcpAppSandboxCsp(ctx.url.searchParams.get("csp"))),
- "Cache-Control": "no-store",
- "Referrer-Policy": "strict-origin",
- "X-Content-Type-Options": "nosniff",
- },
- }));
- addRoute(routes, "GET", "/mcp-apps/sandbox.js", "none", async () => 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 () => 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", "/mcp-apps/sandbox.html", "none", async (ctx) => {
+ assertMcpAllowed(config);
+ return new Response(MCP_APP_SANDBOX_PROXY_HTML, {
+ headers: {
+ "Content-Type": "text/html; charset=utf-8",
+ "Content-Security-Policy": buildMcpAppSandboxCsp(parseMcpAppSandboxCsp(ctx.url.searchParams.get("csp"))),
+ "Cache-Control": "no-store",
+ "Referrer-Policy": "strict-origin",
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+ });
+ addRoute(routes, "GET", "/mcp-apps/sandbox.js", "none", async () => {
+ assertMcpAllowed(config);
+ 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);
+ 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);
requireClientScope(ctx, "viewer");
const workspace = await resolveWorkspace(config, ctx.params.id);
try {
@@ -4482,6 +4514,7 @@ function createRoutes(
});
addRoute(routes, "POST", "/workspace/:id/mcp-apps/resolve", "client", async (ctx) => {
+ assertMcpAllowed(config);
requireClientScope(ctx, "viewer");
const workspace = await resolveWorkspace(config, ctx.params.id);
const body = await readJsonBody(ctx.request);
@@ -4525,6 +4558,7 @@ function createRoutes(
});
addRoute(routes, "POST", "/workspace/:id/mcp-apps/call", "client", async (ctx) => {
+ assertMcpAllowed(config);
requireClientScope(ctx, "viewer");
const workspace = await resolveWorkspace(config, ctx.params.id);
const body = await readJsonBody(ctx.request);
@@ -4554,6 +4588,7 @@ function createRoutes(
});
addRoute(routes, "POST", "/workspace/:id/mcp/managed", "client", async (ctx) => {
+ assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -4624,11 +4659,13 @@ function createRoutes(
});
addRoute(routes, "GET", "/workspace/:id/mcp/:name/managed", "client", async (ctx) => {
+ assertMcpAllowed(config);
const workspace = await resolveWorkspace(config, ctx.params.id);
return jsonResponse(await getLocalManagedMcpConnection(config, workspace.id, ctx.params.name ?? ""));
});
addRoute(routes, "POST", "/workspace/:id/mcp/:name/managed/connect", "client", async (ctx) => {
+ assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -4640,6 +4677,7 @@ function createRoutes(
});
addRoute(routes, "GET", "/mcp/oauth/callback", "none", async (ctx) => {
+ assertMcpAllowed(config);
const state = ctx.url.searchParams.get("state") ?? "";
const code = ctx.url.searchParams.get("code") ?? "";
if (!state || !code) throw new ApiError(400, "managed_mcp_oauth_callback_invalid", "OAuth callback is missing code or state");
@@ -4654,17 +4692,21 @@ function createRoutes(
);
});
- const managedGatewayHandler = async (ctx: RequestContext) => handleLocalManagedMcpGateway(
- config,
- ctx.request,
- ctx.params.workspaceId ?? "",
- ctx.params.name ?? "",
- );
+ const managedGatewayHandler = async (ctx: RequestContext) => {
+ assertMcpAllowed(config);
+ return handleLocalManagedMcpGateway(
+ config,
+ ctx.request,
+ ctx.params.workspaceId ?? "",
+ ctx.params.name ?? "",
+ );
+ };
addRoute(routes, "POST", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);
addRoute(routes, "GET", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);
addRoute(routes, "DELETE", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);
addRoute(routes, "POST", "/workspace/:id/mcp", "client", async (ctx) => {
+ assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -4710,6 +4752,7 @@ function createRoutes(
});
addRoute(routes, "DELETE", "/workspace/:id/mcp/:name", "client", async (ctx) => {
+ assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -4760,6 +4803,7 @@ function createRoutes(
// Toggle `enabled` on a workspace MCP. Strict body validation — `Boolean(body.enabled)`
// would silently disable on `{}` or coerce `"false"` to true.
addRoute(routes, "POST", "/workspace/:id/mcp/:name/enabled", "client", async (ctx) => {
+ assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -4809,6 +4853,7 @@ function createRoutes(
});
addRoute(routes, "DELETE", "/workspace/:id/mcp/:name/auth", "client", async (ctx) => {
+ assertMcpAllowed(config);
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -5776,6 +5821,12 @@ function enqueueWorkspaceMcpRefreshSync(request: WorkspaceMcpRefreshRequest): Pr
async 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
@@ -5839,6 +5890,20 @@ async function syncRuntimeMcpToOpencodeEngine(
options?: { throwOnFailure?: boolean; deferred?: boolean },
serverState?: EngineMcpServerState | null,
): Promise<EngineMcpSyncResult> {
+ if (!mcpAllowed(config)) {
+ // Existing runtime rows are retained for the isolated Harbor workflow,
+ // but they must not remain live in an engine that has switched to the
+ // normal deny policy.
+ const runtimeConfig = await readEffectiveRuntimeOpencodeConfig(config, workspace.id).catch(() => undefined);
+ const names = Object.keys(runtimeConfig ? runtimeMcpMap(runtimeConfig) : {})
+ .filter((name) => !onlyNames || onlyNames.includes(name));
+ const state = activeEngineMcpServerState(config, serverState);
+ for (const name of names) {
+ 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) {