Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(mcp): override execution policy per database

二丫讲梵c48ebda19709
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 2b47a6a093..bcaeec06ac 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -90,6 +90,7 @@ import {
type UpdateDownloadSource,
type CustomThemeColors,
type CustomTheme,
+ type McpConnectionPolicy,
type ClickTableNavigationTarget,
type SqlCompletionTriggerMode,
SIDEBAR_INDENT_MIN,
@@ -1926,6 +1927,7 @@ function resetSettingsSearchState() {
settingsSearchActiveIndex.value = 0;
pendingSettingsSearchResult = null;
shortcutSearchQuery.value = "";
+ mcpPermissionPreviewSearchQuery.value = "";
clearSettingsSearchHighlight();
}
@@ -2219,7 +2221,16 @@ async function saveMcpPolicy(partial: {
allowDangerousSql?: boolean;
allowedConnectionIds?: string[] | null;
allowedToolNames?: string[] | null;
- connectionPolicies?: { connectionId: string; readOnly: boolean; allowDangerousSql: boolean; executionModeConfigured: boolean; databaseScope: "all" | "selected" | "none"; allowedDatabases: string[] }[];
+ connectionPolicies?: {
+ connectionId: string;
+ readOnly: boolean;
+ allowDangerousSql: boolean;
+ executionModeConfigured: boolean;
+ executionModePolicyVersion: number | null;
+ databaseScope: "all" | "selected" | "none";
+ allowedDatabases: string[];
+ databasePolicies: { databaseName: string; readOnly: boolean; allowDangerousSql: boolean }[];
+ }[];
queryTimeoutSecs?: number | null;
}) {
if (mcpPolicyControlsDisabled.value) return;
@@ -2327,16 +2338,87 @@ function mcpConnectionExecutionMode(connectionId: string): McpConnectionExecutio
return rule.allowDangerousSql ? "high_risk_write" : "safe_write";
}
+function mcpExecutionModeRank(mode: McpConnectionExecutionMode): number {
+ return mode === "read_only" ? 0 : mode === "safe_write" ? 1 : 2;
+}
+
+function migrateLegacyMcpConnectionPolicy(policy: McpConnectionPolicy) {
+ const connectionMode = mcpConnectionExecutionMode(policy.connectionId);
+ const legacyMode = connectionMode === "inherit" ? mcpExecutionMode.value : connectionMode;
+ const effectiveMode = mcpExecutionModeRank(legacyMode) < mcpExecutionModeRank(mcpExecutionMode.value) ? legacyMode : mcpExecutionMode.value;
+ const databasePolicies = policy.databasePolicies.map((databasePolicy) => {
+ const databaseMode: McpConnectionExecutionMode = databasePolicy.readOnly ? "read_only" : databasePolicy.allowDangerousSql ? "high_risk_write" : "safe_write";
+ const effectiveDatabaseMode = mcpExecutionModeRank(databaseMode) < mcpExecutionModeRank(effectiveMode) ? databaseMode : effectiveMode;
+ return {
+ ...databasePolicy,
+ readOnly: effectiveDatabaseMode === "read_only",
+ allowDangerousSql: effectiveDatabaseMode === "high_risk_write",
+ };
+ });
+ return {
+ readOnly: effectiveMode === "read_only",
+ allowDangerousSql: effectiveMode === "high_risk_write",
+ executionModeConfigured: true,
+ databasePolicies,
+ };
+}
+
+function mcpExecutionModeLabel(mode: McpConnectionExecutionMode): string {
+ return t(mode === "read_only" ? "settings.mcpExecutionModeReadOnly" : mode === "safe_write" ? "settings.mcpExecutionModeSafeWrite" : "settings.mcpExecutionModeHighRiskWrite");
+}
+
+function mcpEffectiveExecutionMode(connectionMode: McpConnectionExecutionMode | "inherit", databaseMode: McpConnectionExecutionMode | "inherit"): McpConnectionExecutionMode {
+ return databaseMode !== "inherit" ? databaseMode : connectionMode !== "inherit" ? connectionMode : mcpExecutionMode.value;
+}
+
+const mcpPermissionPreviewSearchQuery = ref("");
+const mcpPermissionPreviewRows = computed(() =>
+ mcpConnectionPolicyConnections.value.flatMap((connection) => {
+ const rule = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connection.id);
+ const connectionMode = mcpConnectionExecutionMode(connection.id);
+ if (rule?.databaseScope === "none") return [];
+ const databases = rule?.databaseScope === "selected" ? rule.allowedDatabases : [t("settings.mcpDatabaseScopeSummaryAll")];
+ return databases.map((database) => {
+ const databasePolicy = rule?.databasePolicies.find((item) => item.databaseName === database);
+ const databaseMode: McpConnectionExecutionMode | "inherit" = !databasePolicy ? "inherit" : databasePolicy.readOnly ? "read_only" : databasePolicy.allowDangerousSql ? "high_risk_write" : "safe_write";
+ return {
+ connection: connection.name,
+ database,
+ connectionMode,
+ databaseMode,
+ effectiveMode: mcpEffectiveExecutionMode(connectionMode, databaseMode),
+ };
+ });
+ }),
+);
+const filteredMcpPermissionPreviewRows = computed(() => {
+ const query = mcpPermissionPreviewSearchQuery.value.trim().toLocaleLowerCase();
+ if (!query) return mcpPermissionPreviewRows.value;
+ return mcpPermissionPreviewRows.value.filter((row) => [row.connection, row.database].some((value) => value.toLocaleLowerCase().includes(query)));
+});
+
function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConnectionExecutionMode | "inherit") {
const existing = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId);
const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId);
+ const migrated = existing && existing.executionModePolicyVersion !== 1 ? migrateLegacyMcpConnectionPolicy(existing) : null;
+ const selectedMode =
+ migrated && mode === "inherit"
+ ? migrated
+ : {
+ readOnly: mode === "read_only",
+ allowDangerousSql: mode === "high_risk_write",
+ executionModeConfigured: mode !== "inherit",
+ databasePolicies: migrated?.databasePolicies ?? existing?.databasePolicies ?? [],
+ };
const next = {
connectionId,
- readOnly: mode === "read_only",
- allowDangerousSql: mode === "high_risk_write",
- executionModeConfigured: mode !== "inherit",
+ readOnly: selectedMode.readOnly,
+ allowDangerousSql: selectedMode.allowDangerousSql,
+ executionModeConfigured: selectedMode.executionModeConfigured,
+ executionModePolicyVersion: 1,
databaseScope: existing?.databaseScope ?? ("all" as const),
allowedDatabases: existing?.allowedDatabases ?? [],
+ databasePolicies: selectedMode.databasePolicies,
};
if (next.executionModeConfigured || next.databaseScope !== "all") rules.push(next);
void saveMcpPolicy({ connectionPolicies: rules });
@@ -7893,6 +7975,7 @@ onUnmounted(() => {
:connections="mcpSelectableConnections"
:allowed-connection-ids="mcpAllowedConnectionIds"
:connection-policies="settingsStore.mcpGlobalPolicy.connectionPolicies"
+ :global-execution-mode="mcpExecutionMode"
:disabled="mcpPolicyControlsDisabled"
:busy="mcpPolicyLoading || mcpPolicySaving"
@update:connection-policies="onMcpConnectionPoliciesChange"
@@ -7943,6 +8026,44 @@ onUnmounted(() => {
</template>
<template #capabilities>
<div class="space-y-4">
+ <section class="space-y-2 rounded-md border bg-background p-3">
+ <div>
+ <p class="text-sm font-medium">{{ t("settings.mcpPermissionPreviewTitle") }}</p>
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpPermissionPreviewDescription") }}</p>
+ </div>
+ <template v-if="mcpPermissionPreviewRows.length">
+ <div class="relative">
+ <Search class="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
+ <Input v-model="mcpPermissionPreviewSearchQuery" autocomplete="off" :placeholder="t('settings.mcpPermissionPreviewSearchPlaceholder')" class="h-8 pl-9 text-xs" />
+ </div>
+ <div class="max-h-72 overflow-auto overscroll-contain rounded border">
+ <table class="w-full min-w-[42rem] border-separate border-spacing-0 text-xs">
+ <thead class="text-muted-foreground">
+ <tr>
+ <th scope="col" class="sticky top-0 z-10 bg-muted px-3 py-2 text-left font-medium shadow-[0_1px_0_hsl(var(--border))]">{{ t("settings.mcpPermissionPreviewConnection") }}</th>
+ <th scope="col" class="sticky top-0 z-10 bg-muted px-3 py-2 text-left font-medium shadow-[0_1px_0_hsl(var(--border))]">{{ t("settings.mcpPermissionPreviewDatabase") }}</th>
+ <th scope="col" class="sticky top-0 z-10 bg-muted px-3 py-2 text-left font-medium shadow-[0_1px_0_hsl(var(--border))]">{{ t("settings.mcpPermissionPreviewConnectionDefault") }}</th>
+ <th scope="col" class="sticky top-0 z-10 bg-muted px-3 py-2 text-left font-medium shadow-[0_1px_0_hsl(var(--border))]">{{ t("settings.mcpPermissionPreviewDatabaseOverride") }}</th>
+ <th scope="col" class="sticky top-0 z-10 bg-muted px-3 py-2 text-left font-medium shadow-[0_1px_0_hsl(var(--border))]">{{ t("settings.mcpPermissionPreviewEffective") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="row in filteredMcpPermissionPreviewRows" :key="`${row.connection}:${row.database}`" class="border-t">
+ <td class="px-3 py-2 font-medium">{{ row.connection }}</td>
+ <td class="px-3 py-2 font-mono">{{ row.database }}</td>
+ <td class="px-3 py-2">{{ row.connectionMode === "inherit" ? t("settings.mcpConnectionPolicyInherit") : mcpExecutionModeLabel(row.connectionMode) }}</td>
+ <td class="px-3 py-2">{{ row.databaseMode === "inherit" ? t("settings.mcpDatabasePolicyInherit") : mcpExecutionModeLabel(row.databaseMode) }}</td>
+ <td class="px-3 py-2 font-medium">{{ mcpExecutionModeLabel(row.effectiveMode) }}</td>
+ </tr>
+ <tr v-if="filteredMcpPermissionPreviewRows.length === 0">
+ <td colspan="5" class="px-3 py-8 text-center text-muted-foreground">{{ t("settings.mcpPermissionPreviewSearchNoResults") }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </template>
+ <p v-else class="text-xs text-muted-foreground">{{ t("settings.mcpPermissionPreviewEmpty") }}</p>
+ </section>
<section class="space-y-2">
<div>
<p class="text-sm font-medium">{{ t("settings.mcpToolPermissionsTitle") }}</p>
diff --git a/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue b/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue
index cf430eacc1..8fa5b4b175 100644
--- a/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue
+++ b/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue
@@ -10,6 +10,8 @@ import type { McpConnectionPolicy } from "@/stores/settingsStore";
import type { ConnectionConfig } from "@/types/database";
type DatabaseScope = McpConnectionPolicy["databaseScope"];
+type DatabaseExecutionMode = "inherit" | "read_only" | "safe_write" | "high_risk_write";
+type ExecutionMode = Exclude<DatabaseExecutionMode, "inherit">;
const { t } = useI18n();
@@ -20,6 +22,7 @@ const props = withDefaults(
connections: readonly ConnectionConfig[];
allowedConnectionIds: readonly string[] | null;
connectionPolicies: readonly McpConnectionPolicy[];
+ globalExecutionMode: ExecutionMode;
disabled?: boolean;
busy?: boolean;
}>(),
@@ -45,6 +48,7 @@ const selectedConnection = computed(() => scopedConnections.value.find((connecti
const selectedPolicy = computed(() => props.connectionPolicies.find((policy) => policy.connectionId === selectedConnectionId.value));
const selectedScope = computed<DatabaseScope>(() => selectedPolicy.value?.databaseScope ?? "all");
const selectedDatabases = computed(() => selectedPolicy.value?.allowedDatabases ?? []);
+const selectedDatabasePolicies = computed(() => selectedPolicy.value?.databasePolicies ?? []);
const displayedDatabases = computed(() => {
const query = search.value.trim().toLocaleLowerCase();
return (databasesByConnection.value[selectedConnectionId.value] ?? []).filter((database) => !query || database.toLocaleLowerCase().includes(query));
@@ -77,21 +81,29 @@ function policyFor(connectionId: string): McpConnectionPolicy {
readOnly: false,
allowDangerousSql: false,
executionModeConfigured: false,
+ executionModePolicyVersion: null,
databaseScope: "all",
allowedDatabases: [],
+ databasePolicies: [],
}
);
}
function updateSelectedPolicy(patch: Partial<McpConnectionPolicy>) {
if (props.disabled || !selectedConnectionId.value) return;
- const next = { ...policyFor(selectedConnectionId.value), ...patch };
+ const existing = policyFor(selectedConnectionId.value);
+ const migration = existing.executionModePolicyVersion === 1 ? {} : { ...promoteLegacyConnectionDefault(existing), executionModePolicyVersion: 1 as const };
+ const next = { ...existing, ...migration, ...patch };
const policies = props.connectionPolicies.filter((policy) => policy.connectionId !== selectedConnectionId.value);
emit("update:connectionPolicies", [...policies, next]);
}
function setScope(scope: DatabaseScope) {
- updateSelectedPolicy({ databaseScope: scope, allowedDatabases: scope === "selected" ? selectedDatabases.value : [] });
+ updateSelectedPolicy({
+ databaseScope: scope,
+ allowedDatabases: scope === "selected" ? selectedDatabases.value : [],
+ databasePolicies: scope === "selected" ? selectedDatabasePolicies.value.filter((policy) => selectedDatabases.value.includes(policy.databaseName)) : [],
+ });
}
function setConnectionPage(page: number) {
@@ -111,7 +123,77 @@ function selectConnection(connectionId: string) {
function toggleDatabase(database: string, checked: boolean) {
const databases = checked ? [...new Set([...selectedDatabases.value, database])] : selectedDatabases.value.filter((item) => item !== database);
- updateSelectedPolicy({ databaseScope: "selected", allowedDatabases: databases });
+ updateSelectedPolicy({
+ databaseScope: "selected",
+ allowedDatabases: databases,
+ databasePolicies: selectedDatabasePolicies.value.filter((policy) => databases.includes(policy.databaseName)),
+ });
+}
+
+function databaseExecutionMode(database: string): DatabaseExecutionMode {
+ const policy = selectedDatabasePolicies.value.find((item) => item.databaseName === database);
+ if (!policy) return "inherit";
+ if (policy.readOnly) return "read_only";
+ return policy.allowDangerousSql ? "high_risk_write" : "safe_write";
+}
+
+function connectionExecutionMode(): DatabaseExecutionMode {
+ const policy = selectedPolicy.value;
+ if (!policy || !policy.executionModeConfigured) return "inherit";
+ if (policy.readOnly) return "read_only";
+ return policy.allowDangerousSql ? "high_risk_write" : "safe_write";
+}
+
+function effectiveDatabaseExecutionMode(database: string): ExecutionMode {
+ const databaseMode = databaseExecutionMode(database);
+ if (databaseMode !== "inherit") return databaseMode;
+ const connectionMode = connectionExecutionMode();
+ return connectionMode === "inherit" ? props.globalExecutionMode : connectionMode;
+}
+
+function executionModeLabel(mode: ExecutionMode): string {
+ return t(mode === "read_only" ? "settings.mcpExecutionModeReadOnly" : mode === "safe_write" ? "settings.mcpExecutionModeSafeWrite" : "settings.mcpExecutionModeHighRiskWrite");
+}
+
+function executionModeRank(mode: DatabaseExecutionMode): number {
+ return mode === "read_only" ? 0 : mode === "safe_write" ? 1 : mode === "high_risk_write" ? 2 : 3;
+}
+
+function promoteLegacyConnectionDefault(policy: McpConnectionPolicy): Pick<McpConnectionPolicy, "readOnly" | "allowDangerousSql" | "executionModeConfigured" | "databasePolicies"> {
+ if (policy.executionModePolicyVersion === 1) {
+ return { readOnly: policy.readOnly, allowDangerousSql: policy.allowDangerousSql, executionModeConfigured: policy.executionModeConfigured, databasePolicies: policy.databasePolicies };
+ }
+ const legacyMode = connectionExecutionMode();
+ const effectiveMode = executionModeRank(legacyMode) < executionModeRank(props.globalExecutionMode) ? legacyMode : props.globalExecutionMode;
+ const databasePolicies = policy.databasePolicies.map((databasePolicy) => {
+ const databaseMode = databasePolicy.readOnly ? "read_only" : databasePolicy.allowDangerousSql ? "high_risk_write" : "safe_write";
+ const effectiveDatabaseMode = executionModeRank(databaseMode) < executionModeRank(effectiveMode) ? databaseMode : effectiveMode;
+ return {
+ ...databasePolicy,
+ readOnly: effectiveDatabaseMode === "read_only",
+ allowDangerousSql: effectiveDatabaseMode === "high_risk_write",
+ };
+ });
+ return {
+ readOnly: effectiveMode === "read_only",
+ allowDangerousSql: effectiveMode === "high_risk_write",
+ executionModeConfigured: true,
+ databasePolicies,
+ };
+}
+
+function setDatabaseExecutionMode(database: string, mode: DatabaseExecutionMode) {
+ const existing = policyFor(selectedConnectionId.value);
+ const migrated = promoteLegacyConnectionDefault(existing);
+ const policies = migrated.databasePolicies.filter((policy) => policy.databaseName !== database);
+ if (mode !== "inherit") {
+ policies.push({
+ databaseName: database,
+ readOnly: mode === "read_only",
+ allowDangerousSql: mode === "high_risk_write",
+ });
+ }
+ updateSelectedPolicy({ ...promoteLegacyConnectionDefault(existing), databasePolicies: policies, executionModePolicyVersion: 1 });
}
function addManualDatabase() {
@@ -185,12 +267,21 @@ watch(databasePageCount, () => setDatabasePage(databasePage.value));
</label>
</div>
<div class="space-y-1">
- <button v-for="connection in pagedScopedConnections" :key="connection.id" type="button" class="w-full rounded-md px-2 py-2 text-left transition-colors hover:bg-muted" :class="selectedConnectionId === connection.id ? 'bg-muted' : ''" @click="selectConnection(connection.id)">
- <div class="flex items-center justify-between gap-2">
+ <button
+ v-for="connection in pagedScopedConnections"
+ :key="connection.id"
+ type="button"
+ class="w-full cursor-pointer rounded-md px-2 py-2 text-left transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
+ :class="selectedConnectionId === connection.id ? 'bg-muted' : ''"
+ :aria-current="selectedConnectionId === connection.id ? 'true' : undefined"
+ @pointerdown="selectConnection(connection.id)"
+ @click="selectConnection(connection.id)"
+ >
+ <div class="pointer-events-none flex items-center justify-between gap-2">
<span class="min-w-0 truncate text-sm font-medium">{{ connection.name }}</span>
<Badge variant="outline" class="shrink-0 text-[10px] font-normal">{{ scopeSummary(connection) }}</Badge>
</div>
- <p class="mt-0.5 truncate font-mono text-[10px] text-muted-foreground">{{ connection.db_type }} · {{ connection.host || connection.database || connection.id }}</p>
+ <p class="pointer-events-none mt-0.5 truncate font-mono text-[10px] text-muted-foreground">{{ connection.db_type }} · {{ connection.host || connection.database || connection.id }}</p>
</button>
</div>
<div v-if="connectionPageCount > 1" class="mt-2 flex items-center justify-center gap-2 border-t pt-2 text-xs text-muted-foreground">
@@ -246,6 +337,16 @@ watch(databasePageCount, () => setDatabasePage(databasePage.value));
<label v-for="database in pagedDatabases" :key="database" class="flex cursor-pointer items-center gap-2 border-b px-3 py-2 text-xs last:border-b-0 hover:bg-muted/50">
<input type="checkbox" :checked="selectedDatabases.includes(database)" :disabled="disabled || busy" @change="toggleDatabase(database, ($event.target as HTMLInputElement).checked)" />
<span class="min-w-0 flex-1 truncate font-mono">{{ database }}</span>
+ <div v-if="selectedDatabases.includes(database)" class="flex shrink-0 items-center gap-1.5">
+ <span class="text-[11px] text-muted-foreground">{{ t("settings.mcpDatabasePolicySetting") }}</span>
+ <select :value="databaseExecutionMode(database)" :disabled="disabled || busy" class="h-7 max-w-32 rounded border bg-background px-1.5 text-[11px]" @click.stop @change="setDatabaseExecutionMode(database, ($event.target as HTMLSelectElement).value as DatabaseExecutionMode)">
+ <option value="inherit">{{ t("settings.mcpDatabasePolicyInherit") }}</option>
+ <option value="read_only">{{ t("settings.mcpConnectionPolicyReadOnly") }}</option>
+ <option value="safe_write">{{ t("settings.mcpConnectionPolicySafeWrite") }}</option>
+ <option value="high_risk_write">{{ t("settings.mcpConnectionPolicyHighRiskWrite") }}</option>
+ </select>
+ <Badge variant="secondary" class="text-[10px] font-normal">{{ t("settings.mcpDatabasePolicyEffective", { mode: executionModeLabel(effectiveDatabaseExecutionMode(database)) }) }}</Badge>
+ </div>
<Check v-if="selectedDatabases.includes(database)" class="h-3.5 w-3.5 text-green-600" />
</label>
<div v-if="databasePageCount > 1" class="flex items-center justify-center gap-2 border-t px-3 py-2 text-xs text-muted-foreground">
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index f02add5dc8..d33baa0b53 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -7022,8 +7022,8 @@ export default {
mcpWindsurfConfigPath: "Windsurf can use ~/.codeium/windsurf/mcp_config.json.",
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json globally, or opencode.json at the project level.",
mcpPiConfigPath: "First install the Pi MCP adapter plugin: pi install npm:pi-mcp-adapter. Then save to ~/.pi/agent/mcp.json (global) or .mcp.json (project), run /mcp to verify, and /reload to pick it up in Pi.",
- mcpExecutionMode: "MCP execution permission",
- mcpExecutionModeDescription: "Choose the permission level DBX enforces for every MCP client. Client-side read/write settings cannot change this level.",
+ mcpExecutionMode: "MCP global default permission",
+ mcpExecutionModeDescription: "Sets the default used when no connection or database permission is configured. Connection defaults and database settings can override it by scope.",
mcpExecutionModeReadOnly: "Read only",
mcpExecutionModeSafeWrite: "Data read/write",
mcpExecutionModeRecommended: "Recommended",
@@ -7059,10 +7059,10 @@ export default {
mcpAuthStepConnectionsDescription: "Decides which connections MCP can see",
mcpAuthStepDatabasesTitle: "Database scope",
mcpAuthStepDatabasesDescription: "Limit the databases each connection can access",
- mcpAuthStepOverridesTitle: "Connection exceptions",
- mcpAuthStepOverridesDescription: "Tighten execution permissions per connection",
+ mcpAuthStepOverridesTitle: "Connection defaults",
+ mcpAuthStepOverridesDescription: "Set the default execution permission for each connection",
mcpAuthStepCapabilitiesTitle: "Capabilities and execution",
- mcpAuthStepCapabilitiesDescription: "Choose MCP tools and the global operation level",
+ mcpAuthStepCapabilitiesDescription: "Choose MCP tools and the global default operation level",
mcpAuthStepRegionLabel: "Step {step}: {title}",
mcpAuthPreviousStep: "Previous",
mcpAuthNextStep: "Next",
@@ -7087,6 +7087,19 @@ export default {
mcpDatabaseScopeNoneTitle: "No access",
mcpDatabaseScopeNoneDescription: "Keep the rules but deny every database",
mcpDatabaseScopeSelectedSummary: "{count} databases allowed. Unchecked databases and cross-database requests are rejected by the MCP server.",
+ mcpDatabasePolicyInherit: "Inherit connection",
+ mcpDatabasePolicySetting: "Database priority setting",
+ mcpDatabasePolicyEffective: "Effective: {mode}",
+ mcpPermissionPreviewTitle: "Permission preview",
+ mcpPermissionPreviewDescription: "Permissions fall back by scope: database setting first, then connection default, then global default.",
+ mcpPermissionPreviewConnection: "Connection",
+ mcpPermissionPreviewDatabase: "Database",
+ mcpPermissionPreviewConnectionDefault: "Connection default",
+ mcpPermissionPreviewDatabaseOverride: "Database priority setting",
+ mcpPermissionPreviewEffective: "Effective",
+ mcpPermissionPreviewEmpty: "Allow at least one connection and configure its database scope first.",
+ mcpPermissionPreviewSearchPlaceholder: "Search connections or databases",
+ mcpPermissionPreviewSearchNoResults: "No matching connections or databases found.",
mcpDatabaseSearchPlaceholder: "Filter loaded databases",
mcpDatabaseManualPlaceholder: "Add a database name manually",
mcpDatabaseLoadFailed: "Failed to load databases: {error}. You can add the exact database names manually.",
@@ -7149,9 +7162,9 @@ export default {
mcpHttpErrorRemoteHostsAndOrigins: "Remote access requires both allowed hosts and allowed origins.",
mcpHttpErrorRemoteBinding: "Remote listening requires remote access plus Host and Origin allowlists.",
mcpHttpErrorPortInUse: "The port is already used by another application. DBX restarts its own MCP service when saving; close the other application using the port, or choose a different port.",
- mcpConnectionPolicyTitle: "Per-connection permission ceiling",
- mcpConnectionPolicyDescription: "Tighten permissions for each exposed connection; they cannot exceed the global MCP permissions.",
- mcpConnectionPolicyEmptyHint: "Allow at least one connection in step 1 before setting per-connection execution ceilings.",
+ mcpConnectionPolicyTitle: "Connection default permission",
+ mcpConnectionPolicyDescription: "Sets the default for every database in each exposed connection; database settings take priority over connection and global defaults.",
+ mcpConnectionPolicyEmptyHint: "Allow at least one connection in step 1 before setting connection default permissions.",
mcpConnectionPolicyInherit: "Inherit global",
mcpConnectionPolicyReadOnly: "Read only",
mcpConnectionPolicySafeWrite: "Allow safe writes",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 40e4615697..9cc802433e 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -6644,8 +6644,8 @@ export default withEnglishFallback({
mcpVsCodeConfigPath: "VS Code/Copilot puede usar .vscode/mcp.json en el espacio de trabajo o mcp.json en el perfil de usuario.",
mcpWindsurfConfigPath: "Windsurf puede usar ~/.codeium/windsurf/mcp_config.json.",
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json global, o opencode.json a nivel de proyecto.",
- mcpExecutionMode: "Permiso de ejecución MCP",
- mcpExecutionModeDescription: "Elige el nivel de permiso que DBX aplica a todos los clientes MCP. La configuración de lectura y escritura del cliente no puede cambiar este nivel.",
+ mcpExecutionMode: "Permiso predeterminado global de MCP",
+ mcpExecutionModeDescription: "Define el valor predeterminado cuando no hay permiso de conexión o base de datos. Los ajustes de conexión y base de datos pueden reemplazarlo por alcance.",
mcpExecutionModeReadOnly: "Solo lectura",
mcpExecutionModeSafeWrite: "Lectura y escritura de datos",
mcpExecutionModeRecommended: "Recomendado",
@@ -6681,10 +6681,10 @@ export default withEnglishFallback({
mcpAuthStepConnectionsDescription: "Define qué conexiones puede ver MCP",
mcpAuthStepDatabasesTitle: "Alcance de bases de datos",
mcpAuthStepDatabasesDescription: "Limita las bases de datos accesibles por conexión",
- mcpAuthStepOverridesTitle: "Excepciones de conexión",
- mcpAuthStepOverridesDescription: "Restringe aún más los permisos de ejecución por conexión",
+ mcpAuthStepOverridesTitle: "Valores predeterminados de conexión",
+ mcpAuthStepOverridesDescription: "Define el permiso de ejecución predeterminado de cada conexión",
mcpAuthStepCapabilitiesTitle: "Capacidades y ejecución",
- mcpAuthStepCapabilitiesDescription: "Elige las herramientas MCP y el nivel operativo global",
+ mcpAuthStepCapabilitiesDescription: "Elige las herramientas MCP y el nivel operativo global predeterminado",
mcpAuthStepRegionLabel: "Paso {step}: {title}",
mcpAuthPreviousStep: "Anterior",
mcpAuthNextStep: "Siguiente",
@@ -6709,6 +6709,19 @@ export default withEnglishFallback({
mcpDatabaseScopeNoneTitle: "Sin acceso",
mcpDatabaseScopeNoneDescription: "Conserva las reglas pero deniega todas las bases de datos",
mcpDatabaseScopeSelectedSummary: "{count} bases de datos permitidas. Las bases de datos no marcadas y las solicitudes entre bases de datos son rechazadas por el servidor MCP.",
+ mcpDatabasePolicyInherit: "Heredar conexión",
+ mcpDatabasePolicySetting: "Configuración prioritaria de base de datos",
+ mcpDatabasePolicyEffective: "Efectivo: {mode}",
+ mcpPermissionPreviewTitle: "Vista previa de permisos",
+ mcpPermissionPreviewDescription: "Los permisos se resuelven por alcance: base de datos, luego conexión y finalmente valor global.",
+ mcpPermissionPreviewConnection: "Conexión",
+ mcpPermissionPreviewDatabase: "Base de datos",
+ mcpPermissionPreviewConnectionDefault: "Predeterminado de conexión",
+ mcpPermissionPreviewDatabaseOverride: "Configuración prioritaria de base de datos",
+ mcpPermissionPreviewEffective: "Efectivo",
+ mcpPermissionPreviewEmpty: "Permite primero al menos una conexión y configura su alcance de bases de datos.",
+ mcpPermissionPreviewSearchPlaceholder: "Buscar conexiones o bases de datos",
+ mcpPermissionPreviewSearchNoResults: "No se encontraron conexiones ni bases de datos coincidentes.",
mcpDatabaseSearchPlaceholder: "Filtrar bases de datos cargadas",
mcpDatabaseManualPlaceholder: "Añadir nombre de base de datos manualmente",
mcpDatabaseLoadFailed: "Error al cargar bases de datos: {error}. Puedes añadir manualmente los nombres exactos.",
@@ -6771,9 +6784,9 @@ export default withEnglishFallback({
mcpHttpErrorRemoteHostsAndOrigins: "El acceso remoto requiere tanto Hosts permitidos como Origins permitidos.",
mcpHttpErrorRemoteBinding: "La escucha remota requiere el acceso remoto activado y las listas blancas de Host y Origin.",
mcpHttpErrorPortInUse: "El puerto ya está ocupado por otra aplicación. DBX reinicia su propio servicio MCP al guardar; cierra la otra aplicación que usa el puerto o elige otro puerto.",
- mcpConnectionPolicyTitle: "Límite de permisos por conexión",
- mcpConnectionPolicyDescription: "Restringe aún más los permisos de cada conexión expuesta; no pueden superar los permisos globales de MCP.",
- mcpConnectionPolicyEmptyHint: "Permite primero al menos una conexión en el paso 1 para configurar los límites de ejecución por conexión.",
+ mcpConnectionPolicyTitle: "Permiso predeterminado de conexión",
+ mcpConnectionPolicyDescription: "Define el permiso predeterminado de cada base de datos en una conexión expuesta; los ajustes por base tienen prioridad.",
+ mcpConnectionPolicyEmptyHint: "Permite primero al menos una conexión en el paso 1 para configurar permisos predeterminados de conexión.",
mcpConnectionPolicyInherit: "Heredar global",
mcpConnectionPolicyReadOnly: "Solo lectura",
mcpConnectionPolicySafeWrite: "Permitir escrituras seguras",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index d447cd0ab1..e29e3b5061 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -6644,8 +6644,8 @@ export default withEnglishFallback({
mcpVsCodeConfigPath: "VS Code/Copilot può usare .vscode/mcp.json nell'area di lavoro o mcp.json nel profilo utente.",
mcpWindsurfConfigPath: "Windsurf può usare ~/.codeium/windsurf/mcp_config.json.",
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json globalmente, o opencode.json a livello di progetto.",
- mcpExecutionMode: "Permesso di esecuzione MCP",
- mcpExecutionModeDescription: "Scegli il livello di autorizzazione applicato da DBX a tutti i client MCP. Le impostazioni di lettura e scrittura del client non possono modificare questo livello.",
+ mcpExecutionMode: "Permesso predefinito globale MCP",
+ mcpExecutionModeDescription: "Imposta il valore predefinito usato quando non è configurato un permesso di connessione o database. Le impostazioni più specifiche possono sostituirlo.",
mcpExecutionModeReadOnly: "Sola lettura",
mcpExecutionModeSafeWrite: "Lettura e scrittura dati",
mcpExecutionModeRecommended: "Consigliato",
@@ -6681,10 +6681,10 @@ export default withEnglishFallback({
mcpAuthStepConnectionsDescription: "Determina quali connessioni MCP può vedere",
mcpAuthStepDatabasesTitle: "Ambito database",
mcpAuthStepDatabasesDescription: "Limita i database accessibili per ogni connessione",
- mcpAuthStepOverridesTitle: "Eccezioni per connessione",
- mcpAuthStepOverridesDescription: "Restringe ulteriormente i permessi di esecuzione per connessione",
+ mcpAuthStepOverridesTitle: "Impostazioni predefinite della connessione",
+ mcpAuthStepOverridesDescription: "Imposta il permesso di esecuzione predefinito per ogni connessione",
mcpAuthStepCapabilitiesTitle: "Capacità ed esecuzione",
- mcpAuthStepCapabilitiesDescription: "Scegli gli strumenti MCP e il livello operativo globale",
+ mcpAuthStepCapabilitiesDescription: "Scegli gli strumenti MCP e il livello operativo globale predefinito",
mcpAuthStepRegionLabel: "Passaggio {step}: {title}",
mcpAuthPreviousStep: "Indietro",
mcpAuthNextStep: "Avanti",
@@ -6709,6 +6709,19 @@ export default withEnglishFallback({
mcpDatabaseScopeNoneTitle: "Nessun accesso",
mcpDatabaseScopeNoneDescription: "Mantiene le regole ma rifiuta tutti i database",
mcpDatabaseScopeSelectedSummary: "{count} database consentiti. I database non selezionati e le richieste tra database vengono rifiutati dal server MCP.",
+ mcpDatabasePolicyInherit: "Eredita dalla connessione",
+ mcpDatabasePolicySetting: "Impostazione prioritaria database",
+ mcpDatabasePolicyEffective: "Effettivo: {mode}",
+ mcpPermissionPreviewTitle: "Anteprima permessi",
+ mcpPermissionPreviewDescription: "I permessi seguono la priorità di ambito: database, poi connessione, infine valore globale.",
+ mcpPermissionPreviewConnection: "Connessione",
+ mcpPermissionPreviewDatabase: "Database",
+ mcpPermissionPreviewConnectionDefault: "Predefinito connessione",
+ mcpPermissionPreviewDatabaseOverride: "Impostazione prioritaria database",
+ mcpPermissionPreviewEffective: "Effettivo",
+ mcpPermissionPreviewEmpty: "Consenti prima almeno una connessione e configurane l'ambito database.",
+ mcpPermissionPreviewSearchPlaceholder: "Cerca connessioni o database",
+ mcpPermissionPreviewSearchNoResults: "Nessuna connessione o database corrispondente trovato.",
mcpDatabaseSearchPlaceholder: "Filtra i database caricati",
mcpDatabaseManualPlaceholder: "Aggiungi manualmente un nome di database",
mcpDatabaseLoadFailed: "Caricamento dei database non riuscito: {error}. Puoi aggiungere manualmente i nomi esatti.",
@@ -6771,9 +6784,9 @@ export default withEnglishFallback({
mcpHttpErrorRemoteHostsAndOrigins: "L'accesso remoto richiede sia Host sia Origin consentiti.",
mcpHttpErrorRemoteBinding: "L'ascolto remoto richiede l'accesso remoto attivo e gli elenchi consentiti di Host e Origin.",
mcpHttpErrorPortInUse: "La porta è già usata da un'altra applicazione. DBX riavvia il proprio servizio MCP al salvataggio; chiudi l'altra applicazione che usa la porta oppure scegli un'altra porta.",
- mcpConnectionPolicyTitle: "Limite di permessi per connessione",
- mcpConnectionPolicyDescription: "Restringe ulteriormente i permessi di ogni connessione esposta; non possono superare i permessi MCP globali.",
- mcpConnectionPolicyEmptyHint: "Consenti prima almeno una connessione nel passaggio 1 per impostare i limiti di esecuzione per connessione.",
+ mcpConnectionPolicyTitle: "Permesso predefinito della connessione",
+ mcpConnectionPolicyDescription: "Imposta il permesso predefinito per ogni database di una connessione esposta; le impostazioni per database hanno priorità.",
+ mcpConnectionPolicyEmptyHint: "Consenti prima almeno una connessione nel passaggio 1 per impostare i permessi predefiniti della connessione.",
mcpConnectionPolicyInherit: "Eredita globale",
mcpConnectionPolicyReadOnly: "Sola lettura",
mcpConnectionPolicySafeWrite: "Consenti scritture sicure",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 5065f858b1..ba50e075e2 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -6651,8 +6651,8 @@ export default withEnglishFallback({
mcpVsCodeConfigPath: "VS Code/Copilotはワークスペースの .vscode/mcp.json またはユーザープロファイルの mcp.json を使用できます。",
mcpWindsurfConfigPath: "Windsurfは ~/.codeium/windsurf/mcp_config.json を使用できます。",
mcpOpenCodeConfigPath: "グローバル ~/.config/opencode/opencode.json、プロジェクト opencode.json。",
- mcpExecutionMode: "MCP実行権限",
- mcpExecutionModeDescription: "DBXがすべてのMCPクライアントに適用する権限レベルを選択します。クライアント側の読み書き権限設定では、このレベルを変更できません。",
+ mcpExecutionMode: "MCP グローバル既定権限",
+ mcpExecutionModeDescription: "接続またはデータベースの権限が未設定の場合に使う既定値です。接続既定とデータベース設定はスコープに応じてこれを上書きできます。",
mcpExecutionModeReadOnly: "読み取り専用",
mcpExecutionModeSafeWrite: "データ読み書き",
mcpExecutionModeRecommended: "推奨",
@@ -6688,10 +6688,10 @@ export default withEnglishFallback({
mcpAuthStepConnectionsDescription: "MCP に公開する接続を決定します",
mcpAuthStepDatabasesTitle: "データベース範囲",
mcpAuthStepDatabasesDescription: "接続ごとにアクセス可能なデータベースを制限します",
- mcpAuthStepOverridesTitle: "接続の例外",
- mcpAuthStepOverridesDescription: "接続ごとに実行権限をさらに制限します",
+ mcpAuthStepOverridesTitle: "接続の既定権限",
+ mcpAuthStepOverridesDescription: "接続ごとの既定の実行権限を設定します",
mcpAuthStepCapabilitiesTitle: "機能と実行",
- mcpAuthStepCapabilitiesDescription: "MCP ツールとグローバル操作レベルを選択します",
+ mcpAuthStepCapabilitiesDescription: "MCP ツールとグローバル既定の操作レベルを選択します",
mcpAuthStepRegionLabel: "ステップ {step}:{title}",
mcpAuthPreviousStep: "前へ",
mcpAuthNextStep: "次へ",
@@ -6716,6 +6716,19 @@ export default withEnglishFallback({
mcpDatabaseScopeNoneTitle: "アクセス不許可",
mcpDatabaseScopeNoneDescription: "ルールは保持しすべてのデータベースを拒否",
mcpDatabaseScopeSelectedSummary: "{count} 個のデータベースを許可済みです。未チェックのデータベースとクロスデータベースのリクエストは MCP サーバーにより拒否されます。",
+ mcpDatabasePolicyInherit: "接続の既定を継承",
+ mcpDatabasePolicySetting: "データベース優先設定",
+ mcpDatabasePolicyEffective: "有効: {mode}",
+ mcpPermissionPreviewTitle: "権限プレビュー",
+ mcpPermissionPreviewDescription: "権限はスコープの優先順で決まります:データベース、接続既定、グローバル既定。",
+ mcpPermissionPreviewConnection: "接続",
+ mcpPermissionPreviewDatabase: "データベース",
+ mcpPermissionPreviewConnectionDefault: "接続の既定",
+ mcpPermissionPreviewDatabaseOverride: "データベース優先設定",
+ mcpPermissionPreviewEffective: "最終権限",
+ mcpPermissionPreviewEmpty: "先に少なくとも 1 つの接続を許可し、データベース範囲を設定してください。",
+ mcpPermissionPreviewSearchPlaceholder: "接続またはデータベースを検索",
+ mcpPermissionPreviewSearchNoResults: "一致する接続またはデータベースがありません。",
mcpDatabaseSearchPlaceholder: "読み込み済みデータベースを絞り込み",
mcpDatabaseManualPlaceholder: "データベース名を手動追加",
mcpDatabaseLoadFailed: "データベースの読み込みに失敗しました:{error}。正確なデータベース名を手動で追加できます。",
@@ -6778,9 +6791,9 @@ export default withEnglishFallback({
mcpHttpErrorRemoteHostsAndOrigins: "リモートアクセスには許可 Host と許可 Origin の両方が必要です。",
mcpHttpErrorRemoteBinding: "リモートリスニングにはリモートアクセスの有効化と Host・Origin のホワイトリストが必要です。",
mcpHttpErrorPortInUse: "このポートは他のアプリケーションで使用されています。DBX は保存時に自身の MCP サービスを再起動します。ポートを使用している他のアプリケーションを終了するか、別のポートを使用してください。",
- mcpConnectionPolicyTitle: "接続ごとの権限上限",
- mcpConnectionPolicyDescription: "公開した各接続に対して権限をさらに制限できます。グローバルの MCP 権限を超えることはできません。",
- mcpConnectionPolicyEmptyHint: "接続ごとの実行上限を設定するには、まずステップ 1 で少なくとも 1 つの接続を許可してください。",
+ mcpConnectionPolicyTitle: "接続の既定権限",
+ mcpConnectionPolicyDescription: "公開した各接続のデータベース既定権限を設定します。データベース設定は接続とグローバルの既定より優先されます。",
+ mcpConnectionPolicyEmptyHint: "接続の既定権限を設定するには、まずステップ 1 で少なくとも 1 つの接続を許可してください。",
mcpConnectionPolicyInherit: "グローバルを継承",
mcpConnectionPolicyReadOnly: "読み取り専用のみ",
mcpConnectionPolicySafeWrite: "安全な書き込みを許可",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 2dd7342e32..12b1be00de 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -6392,8 +6392,8 @@ export default withEnglishFallback({
mcpVsCodeConfigPath: "VS Code/Copilot은 작업 영역의 .vscode/mcp.json 또는 사용자 프로필의 mcp.json을 사용할 수 있습니다.",
mcpWindsurfConfigPath: "Windsurf는 ~/.codeium/windsurf/mcp_config.json을 사용할 수 있습니다.",
mcpOpenCodeConfigPath: "전역으로 ~/.config/opencode/opencode.json, 또는 프로젝트 수준의 opencode.json입니다.",
- mcpExecutionMode: "MCP 실행 권한",
- mcpExecutionModeDescription: "DBX가 모든 MCP 클라이언트에 적용하는 권한 수준을 선택하세요. 클라이언트 측 읽기/쓰기 설정으로 이 수준을 변경할 수 없습니다.",
+ mcpExecutionMode: "MCP 전역 기본 권한",
+ mcpExecutionModeDescription: "연결 또는 데이터베이스 권한이 없을 때 사용할 기본값입니다. 연결 기본값과 데이터베이스 설정은 범위에 따라 이를 재정의할 수 있습니다.",
mcpExecutionModeReadOnly: "읽기 전용",
mcpExecutionModeSafeWrite: "데이터 읽기/쓰기",
mcpExecutionModeRecommended: "권장",
@@ -6429,10 +6429,10 @@ export default withEnglishFallback({
mcpAuthStepConnectionsDescription: "MCP에 노출할 연결을 결정합니다",
mcpAuthStepDatabasesTitle: "데이터베이스 범위",
mcpAuthStepDatabasesDescription: "연결별로 접근 가능한 데이터베이스를 제한합니다",
- mcpAuthStepOverridesTitle: "연결 예외",
- mcpAuthStepOverridesDescription: "연결별로 실행 권한을 더 좁힙니다",
+ mcpAuthStepOverridesTitle: "연결 기본 권한",
+ mcpAuthStepOverridesDescription: "연결별 기본 실행 권한을 설정합니다",
mcpAuthStepCapabilitiesTitle: "기능 및 실행",
- mcpAuthStepCapabilitiesDescription: "MCP 도구와 전역 작업 수준을 선택합니다",
+ mcpAuthStepCapabilitiesDescription: "MCP 도구와 전역 기본 작업 수준을 선택합니다",
mcpAuthStepRegionLabel: "단계 {step}: {title}",
mcpAuthPreviousStep: "이전",
mcpAuthNextStep: "다음",
@@ -6457,6 +6457,19 @@ export default withEnglishFallback({
mcpDatabaseScopeNoneTitle: "접근 허용 안 함",
mcpDatabaseScopeNoneDescription: "규칙은 유지하되 모든 데이터베이스 거부",
mcpDatabaseScopeSelectedSummary: "{count}개 데이터베이스가 허용되었습니다. 선택하지 않은 데이터베이스와 크로스 데이터베이스 요청은 MCP 서버가 거부합니다.",
+ mcpDatabasePolicyInherit: "연결 기본값 상속",
+ mcpDatabasePolicySetting: "데이터베이스 우선 설정",
+ mcpDatabasePolicyEffective: "적용됨: {mode}",
+ mcpPermissionPreviewTitle: "권한 미리보기",
+ mcpPermissionPreviewDescription: "권한은 범위 우선순위로 결정됩니다: 데이터베이스, 연결 기본값, 전역 기본값.",
+ mcpPermissionPreviewConnection: "연결",
+ mcpPermissionPreviewDatabase: "데이터베이스",
+ mcpPermissionPreviewConnectionDefault: "연결 기본값",
+ mcpPermissionPreviewDatabaseOverride: "데이터베이스 우선 설정",
+ mcpPermissionPreviewEffective: "최종 적용",
+ mcpPermissionPreviewEmpty: "먼저 하나 이상의 연결을 허용하고 데이터베이스 범위를 설정하세요.",
+ mcpPermissionPreviewSearchPlaceholder: "연결 또는 데이터베이스 검색",
+ mcpPermissionPreviewSearchNoResults: "일치하는 연결 또는 데이터베이스가 없습니다.",
mcpDatabaseSearchPlaceholder: "불러온 데이터베이스 필터",
mcpDatabaseManualPlaceholder: "데이터베이스 이름 직접 추가",
mcpDatabaseLoadFailed: "데이터베이스 불러오기 실패: {error}. 정확한 데이터베이스 이름을 직접 추가할 수 있습니다.",
@@ -6519,9 +6532,9 @@ export default withEnglishFallback({
mcpHttpErrorRemoteHostsAndOrigins: "원격 접근에는 허용 Host와 허용 Origin을 모두 입력해야 합니다.",
mcpHttpErrorRemoteBinding: "원격 수신에는 원격 접근 활성화와 Host·Origin 화이트리스트가 필요합니다.",
mcpHttpErrorPortInUse: "이 포트는 다른 애플리케이션이 사용 중입니다. DBX는 저장 시 자체 MCP 서비스를 재시작합니다. 해당 포트를 사용하는 다른 애플리케이션을 종료하거나 다른 포트를 사용하세요.",
- mcpConnectionPolicyTitle: "연결별 권한 상한",
- mcpConnectionPolicyDescription: "노출된 각 연결에 대해 권한을 더 좁힐 수 있습니다. 전역 MCP 권한을 초과할 수 없습니다.",
- mcpConnectionPolicyEmptyHint: "연결별 실행 상한을 설정하려면 먼저 1단계에서 하나 이상의 연결을 허용하세요.",
+ mcpConnectionPolicyTitle: "연결 기본 권한",
+ mcpConnectionPolicyDescription: "노출된 각 연결의 데이터베이스 기본 권한을 설정합니다. 데이터베이스 설정이 연결 및 전역 기본값보다 우선합니다.",
+ mcpConnectionPolicyEmptyHint: "연결 기본 권한을 설정하려면 먼저 1단계에서 하나 이상의 연결을 허용하세요.",
mcpConnectionPolicyInherit: "전역 상속",
mcpConnectionPolicyReadOnly: "읽기 전용만",
mcpConnectionPolicySafeWrite: "안전한 쓰기 허용",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 9e666a05f7..3e85b8d00b 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -6646,8 +6646,8 @@ export default withEnglishFallback({
mcpVsCodeConfigPath: "O VS Code/Copilot pode usar .vscode/mcp.json no workspace ou mcp.json no perfil do usuário.",
mcpWindsurfConfigPath: "O Windsurf pode usar ~/.codeium/windsurf/mcp_config.json.",
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json globalmente, ou opencode.json no nível do projeto.",
- mcpExecutionMode: "Permissão de execução MCP",
- mcpExecutionModeDescription: "Escolha o nível de permissão que o DBX aplica a todos os clientes MCP. As configurações de leitura e gravação do cliente não podem alterar este nível.",
+ mcpExecutionMode: "Permissão padrão global do MCP",
+ mcpExecutionModeDescription: "Define o padrão usado quando não há permissão de conexão ou banco configurada. Configurações de conexão e banco podem substituí-lo por escopo.",
mcpExecutionModeReadOnly: "Somente leitura",
mcpExecutionModeSafeWrite: "Leitura e gravação de dados",
mcpExecutionModeRecommended: "Recomendado",
@@ -6683,10 +6683,10 @@ export default withEnglishFallback({
mcpAuthStepConnectionsDescription: "Define quais conexões o MCP pode ver",
mcpAuthStepDatabasesTitle: "Escopo de bancos de dados",
mcpAuthStepDatabasesDescription: "Limita os bancos acessíveis por conexão",
- mcpAuthStepOverridesTitle: "Exceções por conexão",
- mcpAuthStepOverridesDescription: "Restringe mais ainda as permissões de execução por conexão",
+ mcpAuthStepOverridesTitle: "Padrões de conexão",
+ mcpAuthStepOverridesDescription: "Define a permissão de execução padrão de cada conexão",
mcpAuthStepCapabilitiesTitle: "Capacidades e execução",
- mcpAuthStepCapabilitiesDescription: "Escolha as ferramentas do MCP e o nível de operação global",
+ mcpAuthStepCapabilitiesDescription: "Escolha as ferramentas do MCP e o nível de operação global padrão",
mcpAuthStepRegionLabel: "Etapa {step}: {title}",
mcpAuthPreviousStep: "Voltar",
mcpAuthNextStep: "Avançar",
@@ -6711,6 +6711,19 @@ export default withEnglishFallback({
mcpDatabaseScopeNoneTitle: "Sem acesso",
mcpDatabaseScopeNoneDescription: "Mantém as regras, mas recusa todos os bancos",
mcpDatabaseScopeSelectedSummary: "{count} bancos permitidos. Bancos não marcados e solicitações entre bancos são recusados pelo servidor MCP.",
+ mcpDatabasePolicyInherit: "Herdar conexão",
+ mcpDatabasePolicySetting: "Configuração prioritária do banco",
+ mcpDatabasePolicyEffective: "Efetivo: {mode}",
+ mcpPermissionPreviewTitle: "Prévia de permissões",
+ mcpPermissionPreviewDescription: "As permissões seguem a prioridade de escopo: banco, padrão da conexão e padrão global.",
+ mcpPermissionPreviewConnection: "Conexão",
+ mcpPermissionPreviewDatabase: "Banco de dados",
+ mcpPermissionPreviewConnectionDefault: "Padrão da conexão",
+ mcpPermissionPreviewDatabaseOverride: "Configuração prioritária do banco",
+ mcpPermissionPreviewEffective: "Efetiva",
+ mcpPermissionPreviewEmpty: "Permita primeiro ao menos uma conexão e configure seu escopo de bancos.",
+ mcpPermissionPreviewSearchPlaceholder: "Pesquisar conexões ou bancos de dados",
+ mcpPermissionPreviewSearchNoResults: "Nenhuma conexão ou banco de dados correspondente encontrado.",
mcpDatabaseSearchPlaceholder: "Filtrar bancos carregados",
mcpDatabaseManualPlaceholder: "Adicionar nome do banco manualmente",
mcpDatabaseLoadFailed: "Falha ao carregar bancos: {error}. Você pode adicionar manualmente os nomes exatos.",
@@ -6773,9 +6786,9 @@ export default withEnglishFallback({
mcpHttpErrorRemoteHostsAndOrigins: "O acesso remoto exige Hosts e Origins permitidos preenchidos.",
mcpHttpErrorRemoteBinding: "A escuta remota exige acesso remoto ativado e listas de permissão de Host e Origin.",
mcpHttpErrorPortInUse: "A porta já está em uso por outro aplicativo. O DBX reinicia o próprio serviço MCP ao salvar; feche o outro aplicativo que usa a porta ou escolha outra porta.",
- mcpConnectionPolicyTitle: "Limite de permissões por conexão",
- mcpConnectionPolicyDescription: "Restringe mais ainda as permissões de cada conexão exposta; elas não podem exceder as permissões globais do MCP.",
- mcpConnectionPolicyEmptyHint: "Permita primeiro pelo menos uma conexão na etapa 1 para configurar limites de execução por conexão.",
+ mcpConnectionPolicyTitle: "Permissão padrão da conexão",
+ mcpConnectionPolicyDescription: "Define a permissão padrão de cada banco em uma conexão exposta; configurações por banco têm prioridade.",
+ mcpConnectionPolicyEmptyHint: "Permita primeiro pelo menos uma conexão na etapa 1 para configurar permissões padrão da conexão.",
mcpConnectionPolicyInherit: "Herdar do global",
mcpConnectionPolicyReadOnly: "Somente leitura",
mcpConnectionPolicySafeWrite: "Permitir escritas seguras",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index b5b86651a9..01419edaa2 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -7006,8 +7006,8 @@ export default withEnglishFallback({
mcpWindsurfConfigPath: "Windsurf 可放在 ~/.codeium/windsurf/mcp_config.json。",
mcpOpenCodeConfigPath: "全局 ~/.config/opencode/opencode.json,项目级 opencode.json。",
mcpPiConfigPath: "先安装 Pi MCP 适配器插件:pi install npm:pi-mcp-adapter。然后保存到 ~/.pi/agent/mcp.json(全局)或 .mcp.json(项目),在 Pi 中运行 /mcp 确认、/reload 生效。",
- mcpExecutionMode: "MCP 执行权限",
- mcpExecutionModeDescription: "选择 DBX 对所有 MCP 客户端强制执行的权限级别。客户端的读写权限配置无法更改此级别。",
+ mcpExecutionMode: "MCP 全局默认权限",
+ mcpExecutionModeDescription: "设置未配置连接或单库权限时使用的默认级别。连接默认和单库设置可按范围覆盖此默认值。",
mcpExecutionModeReadOnly: "只读",
mcpExecutionModeSafeWrite: "数据读写",
mcpExecutionModeRecommended: "推荐",
@@ -7043,10 +7043,10 @@ export default withEnglishFallback({
mcpAuthStepConnectionsDescription: "决定哪些连接可被 MCP 看见",
mcpAuthStepDatabasesTitle: "数据库范围",
mcpAuthStepDatabasesDescription: "为每个连接限定可访问的库",
- mcpAuthStepOverridesTitle: "连接例外",
- mcpAuthStepOverridesDescription: "按连接进一步收紧执行权限",
+ mcpAuthStepOverridesTitle: "连接默认权限",
+ mcpAuthStepOverridesDescription: "为每个连接设置默认执行权限",
mcpAuthStepCapabilitiesTitle: "能力与执行",
- mcpAuthStepCapabilitiesDescription: "选择 MCP 工具和全局操作级别",
+ mcpAuthStepCapabilitiesDescription: "选择 MCP 工具和全局默认操作级别",
mcpAuthStepRegionLabel: "第 {step} 步:{title}",
mcpAuthPreviousStep: "上一步",
mcpAuthNextStep: "下一步",
@@ -7071,6 +7071,19 @@ export default withEnglishFallback({
mcpDatabaseScopeNoneTitle: "不允许访问",
mcpDatabaseScopeNoneDescription: "保留规则但拒绝所有库",
mcpDatabaseScopeSelectedSummary: "已允许 {count} 个数据库。未勾选数据库及跨库请求会被 MCP 服务端拒绝。",
+ mcpDatabasePolicyInherit: "继承连接默认",
+ mcpDatabasePolicySetting: "单库优先设置",
+ mcpDatabasePolicyEffective: "生效:{mode}",
+ mcpPermissionPreviewTitle: "权限预览",
+ mcpPermissionPreviewDescription: "权限按范围由小到大回退:单库设置优先,其次连接默认,最后全局默认。",
+ mcpPermissionPreviewConnection: "连接",
+ mcpPermissionPreviewDatabase: "数据库",
+ mcpPermissionPreviewConnectionDefault: "连接默认",
+ mcpPermissionPreviewDatabaseOverride: "单库优先设置",
+ mcpPermissionPreviewEffective: "最终生效",
+ mcpPermissionPreviewEmpty: "请先允许至少一个连接,并配置可访问的数据库范围。",
+ mcpPermissionPreviewSearchPlaceholder: "搜索连接或数据库",
+ mcpPermissionPreviewSearchNoResults: "未找到匹配的连接或数据库。",
mcpDatabaseSearchPlaceholder: "筛选已加载的数据库",
mcpDatabaseManualPlaceholder: "手工添加库名",
mcpDatabaseLoadFailed: "加载数据库失败:{error}。可手工添加准确的数据库名称。",
@@ -7133,9 +7146,9 @@ export default withEnglishFallback({
mcpHttpErrorRemoteHostsAndOrigins: "远程访问需要同时填写允许的 Host 和允许的 Origin。",
mcpHttpErrorRemoteBinding: "远程监听需要开启远程访问,并设置 Host 和 Origin 白名单。",
mcpHttpErrorPortInUse: "该端口已被其他应用占用。DBX 会在保存时自动重启自己的 MCP 服务;请关闭占用该端口的其他应用,或改用其他端口。",
- mcpConnectionPolicyTitle: "连接级权限上限",
- mcpConnectionPolicyDescription: "可针对每个已暴露连接进一步收紧权限;不能超过全局 MCP 权限。",
- mcpConnectionPolicyEmptyHint: "请先在第 1 步中允许至少一个连接,才能设置连接级执行上限。",
+ mcpConnectionPolicyTitle: "连接默认权限",
+ mcpConnectionPolicyDescription: "为每个已暴露连接设置数据库默认权限;单库设置优先于连接与全局默认。",
+ mcpConnectionPolicyEmptyHint: "请先在第 1 步中允许至少一个连接,才能设置连接默认权限。",
mcpConnectionPolicyInherit: "继承全局",
mcpConnectionPolicyReadOnly: "仅只读",
mcpConnectionPolicySafeWrite: "允许安全写入",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 54db4cabdd..6b8acecccb 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -5986,8 +5986,8 @@ export default withEnglishFallback({
mcpVsCodeConfigPath: "VS Code/Copilot 可放在工作區 .vscode/mcp.json 或使用者設定檔 mcp.json。",
mcpWindsurfConfigPath: "Windsurf 可放在 ~/.codeium/windsurf/mcp_config.json。",
mcpOpenCodeConfigPath: "全域 ~/.config/opencode/opencode.json,專案級 opencode.json。",
- mcpExecutionMode: "MCP 執行權限",
- mcpExecutionModeDescription: "選擇 DBX 對所有 MCP 用戶端強制執行的權限等級。用戶端的讀寫權限設定無法變更此等級。",
+ mcpExecutionMode: "MCP 全域預設權限",
+ mcpExecutionModeDescription: "設定未配置連線或單一資料庫權限時使用的預設等級。連線預設與單庫設定可依範圍覆蓋此預設值。",
mcpExecutionModeReadOnly: "唯讀",
mcpExecutionModeSafeWrite: "資料讀寫",
mcpExecutionModeRecommended: "推薦",
@@ -6023,10 +6023,10 @@ export default withEnglishFallback({
mcpAuthStepConnectionsDescription: "決定哪些連線可被 MCP 看見",
mcpAuthStepDatabasesTitle: "資料庫範圍",
mcpAuthStepDatabasesDescription: "為每個連線限定可存取的庫",
- mcpAuthStepOverridesTitle: "連線例外",
- mcpAuthStepOverridesDescription: "按連線進一步收緊執行權限",
+ mcpAuthStepOverridesTitle: "連線預設權限",
+ mcpAuthStepOverridesDescription: "為每個連線設定預設執行權限",
mcpAuthStepCapabilitiesTitle: "能力與執行",
- mcpAuthStepCapabilitiesDescription: "選擇 MCP 工具和全域操作層級",
+ mcpAuthStepCapabilitiesDescription: "選擇 MCP 工具和全域預設操作層級",
mcpAuthStepRegionLabel: "第 {step} 步:{title}",
mcpAuthPreviousStep: "上一步",
mcpAuthNextStep: "下一步",
@@ -6051,6 +6051,19 @@ export default withEnglishFallback({
mcpDatabaseScopeNoneTitle: "不允許存取",
mcpDatabaseScopeNoneDescription: "保留規則但拒絕所有庫",
mcpDatabaseScopeSelectedSummary: "已允許 {count} 個資料庫。未勾選資料庫及跨庫請求會被 MCP 服務端拒絕。",
+ mcpDatabasePolicyInherit: "繼承連線預設",
+ mcpDatabasePolicySetting: "單庫優先設定",
+ mcpDatabasePolicyEffective: "生效:{mode}",
+ mcpPermissionPreviewTitle: "權限預覽",
+ mcpPermissionPreviewDescription: "權限依範圍由小到大回退:單庫設定優先,其次連線預設,最後全域預設。",
+ mcpPermissionPreviewConnection: "連線",
+ mcpPermissionPreviewDatabase: "資料庫",
+ mcpPermissionPreviewConnectionDefault: "連線預設",
+ mcpPermissionPreviewDatabaseOverride: "單庫優先設定",
+ mcpPermissionPreviewEffective: "最終生效",
+ mcpPermissionPreviewEmpty: "請先允許至少一個連線,並設定可存取的資料庫範圍。",
+ mcpPermissionPreviewSearchPlaceholder: "搜尋連線或資料庫",
+ mcpPermissionPreviewSearchNoResults: "找不到相符的連線或資料庫。",
mcpDatabaseSearchPlaceholder: "篩選已載入的資料庫",
mcpDatabaseManualPlaceholder: "手動新增庫名",
mcpDatabaseLoadFailed: "載入資料庫失敗:{error}。可手動新增準確的資料庫名稱。",
@@ -6113,9 +6126,9 @@ export default withEnglishFallback({
mcpHttpErrorRemoteHostsAndOrigins: "遠端存取需要同時填寫允許的 Host 和允許的 Origin。",
mcpHttpErrorRemoteBinding: "遠端監聽需要開啟遠端存取,並設定 Host 和 Origin 白名單。",
mcpHttpErrorPortInUse: "該埠已被其他應用程式佔用。DBX 會在儲存時自動重新啟動自己的 MCP 服務;請關閉佔用該埠的其他應用程式,或改用其他埠。",
- mcpConnectionPolicyTitle: "連線級權限上限",
- mcpConnectionPolicyDescription: "可針對每個已暴露連線進一步收緊權限;不能超過全域 MCP 權限。",
- mcpConnectionPolicyEmptyHint: "請先在第 1 步中允許至少一個連線,才能設定連線級執行上限。",
+ mcpConnectionPolicyTitle: "連線預設權限",
+ mcpConnectionPolicyDescription: "為每個已暴露連線設定資料庫預設權限;單庫設定優先於連線與全域預設。",
+ mcpConnectionPolicyEmptyHint: "請先在第 1 步中允許至少一個連線,才能設定連線預設權限。",
mcpConnectionPolicyInherit: "繼承全域",
mcpConnectionPolicyReadOnly: "僅唯讀",
mcpConnectionPolicySafeWrite: "允許安全寫入",
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 92c8337b8c..880c2bc6b3 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -258,8 +258,16 @@ export interface McpConnectionPolicy {
readOnly: boolean;
allowDangerousSql: boolean;
executionModeConfigured: boolean;
+ executionModePolicyVersion: number | null;
databaseScope: "all" | "selected" | "none";
allowedDatabases: string[];
+ databasePolicies: McpDatabasePolicy[];
+}
+
+export interface McpDatabasePolicy {
+ databaseName: string;
+ readOnly: boolean;
+ allowDangerousSql: boolean;
}
export interface SavedSqlSyncEntry {
diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
index d0a6e6c52c..57ceddd4d3 100644
--- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
+++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
@@ -486,6 +486,51 @@ describe("normalizeMcpGlobalPolicy", () => {
expect(normalizeMcpGlobalPolicy({ allowedConnectionIds: [] }).allowedConnectionIds).toEqual([]);
});
+ it("keeps only selected-database execution policies and normalizes their names", () => {
+ const policy = normalizeMcpGlobalPolicy({
+ connectionPolicies: [
+ {
+ connectionId: " connection-1 ",
+ readOnly: false,
+ allowDangerousSql: true,
+ executionModeConfigured: true,
+ executionModePolicyVersion: 1,
+ databaseScope: "selected",
+ allowedDatabases: [" reporting ", "operations"],
+ databasePolicies: [
+ { databaseName: " reporting ", readOnly: true, allowDangerousSql: true },
+ { databaseName: "outside-scope", readOnly: true, allowDangerousSql: false },
+ ],
+ },
+ ],
+ });
+
+ expect(policy.connectionPolicies[0]).toMatchObject({
+ connectionId: "connection-1",
+ executionModePolicyVersion: 1,
+ allowedDatabases: ["reporting", "operations"],
+ databasePolicies: [{ databaseName: "reporting", readOnly: true, allowDangerousSql: false }],
+ });
+ });
+
+ it("leaves legacy connection rules unmarked until the user edits execution permissions", () => {
+ const policy = normalizeMcpGlobalPolicy({
+ connectionPolicies: [
+ {
+ connectionId: "legacy",
+ readOnly: false,
+ allowDangerousSql: true,
+ executionModeConfigured: true,
+ databaseScope: "all",
+ allowedDatabases: [],
+ databasePolicies: [],
+ } as any,
+ ],
+ });
+
+ expect(policy.connectionPolicies[0].executionModePolicyVersion).toBeNull();
+ });
+
it("round-trips queryTimeoutSecs null, undefined and positive numbers", () => {
expect(normalizeMcpGlobalPolicy({ queryTimeoutSecs: null }).queryTimeoutSecs).toBeNull();
expect(normalizeMcpGlobalPolicy({ queryTimeoutSecs: undefined } as any).queryTimeoutSecs).toBeNull();
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index aa94372203..f40d746b62 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -64,8 +64,16 @@ export interface McpConnectionPolicy {
readOnly: boolean;
allowDangerousSql: boolean;
executionModeConfigured: boolean;
+ executionModePolicyVersion: number | null;
databaseScope: "all" | "selected" | "none";
allowedDatabases: string[];
+ databasePolicies: McpDatabasePolicy[];
+}
+
+export interface McpDatabasePolicy {
+ databaseName: string;
+ readOnly: boolean;
+ allowDangerousSql: boolean;
}
export type DesktopIconTheme = "default" | "black";
@@ -116,13 +124,33 @@ export function normalizeMcpGlobalPolicy(policy: Partial<McpGlobalPolicy> | null
const connectionPolicies = Object.values(
(policy?.connectionPolicies ?? []).reduce<Record<string, McpConnectionPolicy>>((rules, rule) => {
if (!rule || typeof rule.connectionId !== "string" || !rule.connectionId.trim()) return rules;
+ const databaseScope = rule.databaseScope === "selected" || rule.databaseScope === "none" ? rule.databaseScope : "all";
+ const allowedDatabases = databaseScope === "selected" ? [...new Set((rule.allowedDatabases ?? []).filter((database): database is string => typeof database === "string" && database.trim().length > 0).map((database) => database.trim()))] : [];
+ const allowedDatabaseNames = new Set(allowedDatabases);
+ const databasePolicies = Object.values(
+ (databaseScope === "selected" ? (rule.databasePolicies ?? []) : []).reduce<Record<string, McpDatabasePolicy>>((policies, databasePolicy) => {
+ if (!databasePolicy || typeof databasePolicy.databaseName !== "string") return policies;
+ const databaseName = databasePolicy.databaseName.trim();
+ if (!databaseName || !allowedDatabaseNames.has(databaseName)) return policies;
+ const current = policies[databaseName];
+ const readOnly = current?.readOnly === true || databasePolicy.readOnly === true;
+ policies[databaseName] = {
+ databaseName,
+ readOnly,
+ allowDangerousSql: !readOnly && (current ? current.allowDangerousSql && databasePolicy.allowDangerousSql === true : databasePolicy.allowDangerousSql === true),
+ };
+ return policies;
+ }, {}),
+ );
rules[rule.connectionId.trim()] = {
connectionId: rule.connectionId.trim(),
readOnly: rule.readOnly === true,
allowDangerousSql: rule.readOnly !== true && rule.allowDangerousSql === true,
executionModeConfigured: rule.executionModeConfigured !== false,
- databaseScope: rule.databaseScope === "selected" || rule.databaseScope === "none" ? rule.databaseScope : "all",
- allowedDatabases: rule.databaseScope === "selected" ? [...new Set((rule.allowedDatabases ?? []).filter((database): database is string => typeof database === "string" && database.trim().length > 0).map((database) => database.trim()))] : [],
+ executionModePolicyVersion: rule.executionModePolicyVersion === 1 ? 1 : null,
+ databaseScope,
+ allowedDatabases,
+ databasePolicies,
};
return rules;
}, {}),
diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rs
index ce630ed308..ca3e4fecec 100644
--- a/crates/dbx-core/src/lib.rs
+++ b/crates/dbx-core/src/lib.rs
@@ -52,6 +52,7 @@ pub mod external;
pub mod hbase_ops;
pub mod history;
pub mod jdbc;
+pub mod mcp_policy;
pub mod models;
pub mod mongo_oidc;
pub mod mongo_ops;
diff --git a/crates/dbx-core/src/mcp_policy.rs b/crates/dbx-core/src/mcp_policy.rs
new file mode 100644
index 0000000000..9e96cd18eb
--- /dev/null
+++ b/crates/dbx-core/src/mcp_policy.rs
@@ -0,0 +1,208 @@
+use crate::models::connection::ConnectionConfig;
+use crate::production_safety::sql_references_disallowed_database;
+use crate::storage::McpGlobalPolicy;
+
+/// Version used by rules that opt into scoped override semantics.
+pub const MCP_EXECUTION_POLICY_VERSION: u8 = 1;
+
+/// Resolve an omitted or blank request database to the connection default.
+pub fn resolve_database(requested: &str, configured: Option<&str>) -> String {
+ let requested = requested.trim();
+ if requested.is_empty() {
+ configured.unwrap_or_default().trim().to_string()
+ } else {
+ requested.to_string()
+ }
+}
+
+/// Compute the effective execution mode while preserving legacy rule ceilings.
+/// Rules without the current version marker are never allowed to widen the
+/// global policy, including when they contain fields added by a newer client.
+pub fn effective_database_execution_policy(
+ policy: &McpGlobalPolicy,
+ connection_id: &str,
+ database: &str,
+) -> (bool, bool) {
+ let mut effective = (policy.read_only, policy.allow_dangerous_sql);
+ let Some(rule) = policy.connection_policies.iter().find(|rule| rule.connection_id == connection_id) else {
+ return effective;
+ };
+
+ if rule.execution_mode_policy_version == Some(MCP_EXECUTION_POLICY_VERSION) {
+ if rule.execution_mode_configured {
+ effective = (rule.read_only, !rule.read_only && rule.allow_dangerous_sql);
+ }
+ if let Some(database_policy) = rule.database_policies.iter().find(|rule| rule.database_name == database) {
+ effective = (database_policy.read_only, !database_policy.read_only && database_policy.allow_dangerous_sql);
+ }
+ } else {
+ // Legacy rules only carried a ceiling when the old UI had configured
+ // an execution mode; scope-only rules inherited the global mode
+ // untouched and must keep doing so instead of being narrowed by the
+ // implicit (false, false) ceiling.
+ if rule.execution_mode_configured {
+ effective = apply_ceiling(effective, (rule.read_only, rule.allow_dangerous_sql));
+ }
+ if let Some(database_policy) = rule.database_policies.iter().find(|rule| rule.database_name == database) {
+ effective = apply_ceiling(effective, (database_policy.read_only, database_policy.allow_dangerous_sql));
+ }
+ }
+ effective
+}
+
+fn apply_ceiling(current: (bool, bool), ceiling: (bool, bool)) -> (bool, bool) {
+ let read_only = current.0 || ceiling.0;
+ (read_only, !read_only && current.1 && ceiling.1)
+}
+
+/// Reject qualified SQL references when database-specific execution rules are
+/// present and individual referenced databases have not been evaluated.
+pub fn ensure_sql_database_execution_scope(
+ policy: &McpGlobalPolicy,
+ connection: &ConnectionConfig,
+ active_database: &str,
+ sql: &str,
+) -> Result<(), String> {
+ let Some(rule) = policy.connection_policies.iter().find(|rule| rule.connection_id == connection.id) else {
+ return Ok(());
+ };
+ if rule.database_policies.is_empty()
+ || !sql_references_disallowed_database(
+ sql,
+ &connection.db_type,
+ active_database,
+ &[active_database.to_string()],
+ )
+ {
+ return Ok(());
+ }
+ Err(
+ "DATABASE_EXECUTION_POLICY_OUT_OF_SCOPE: SQL cannot reference another database while database-specific MCP execution permissions are configured."
+ .to_string(),
+ )
+}
+
+/// Return databases targeted by MongoDB `$out` and `$merge` stages.
+pub fn mongo_pipeline_output_databases(pipeline_json: &str, active_database: &str) -> Result<Vec<String>, String> {
+ let stages = serde_json::from_str::<serde_json::Value>(pipeline_json)
+ .ok()
+ .and_then(|value| value.as_array().cloned())
+ .ok_or_else(|| "QUERY_ERROR: MongoDB aggregate pipeline must be a JSON array.".to_string())?;
+ let mut databases = Vec::new();
+ for stage in stages {
+ let Some(stage) = stage.as_object() else { continue };
+ for key in ["$out", "$merge"] {
+ let Some(target) = stage.get(key) else { continue };
+ let database = match target {
+ serde_json::Value::String(_) => active_database.to_string(),
+ serde_json::Value::Object(target) => target
+ .get("db")
+ .or_else(|| {
+ target.get("into").and_then(serde_json::Value::as_object).and_then(|into| into.get("db"))
+ })
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or(active_database)
+ .to_string(),
+ _ => return Err("QUERY_ERROR: MongoDB aggregate output target must be a string or object.".to_string()),
+ };
+ databases.push(database);
+ }
+ }
+ Ok(databases)
+}
+
+/// Reject cross-database MongoDB writes while database-specific rules exist.
+pub fn ensure_mongo_database_execution_scope(
+ policy: &McpGlobalPolicy,
+ connection_id: &str,
+ active_database: &str,
+ pipeline_json: &str,
+) -> Result<(), String> {
+ let has_database_policies = policy
+ .connection_policies
+ .iter()
+ .find(|rule| rule.connection_id == connection_id)
+ .is_some_and(|rule| !rule.database_policies.is_empty());
+ if !has_database_policies {
+ return Ok(());
+ }
+ if mongo_pipeline_output_databases(pipeline_json, active_database)?
+ .into_iter()
+ .any(|database| database != active_database)
+ {
+ return Err(
+ "DATABASE_EXECUTION_POLICY_OUT_OF_SCOPE: MongoDB aggregation cannot target another database while database-specific MCP execution permissions are configured."
+ .to_string(),
+ );
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{effective_database_execution_policy, resolve_database, MCP_EXECUTION_POLICY_VERSION};
+ use crate::storage::{McpConnectionPolicy, McpDatabasePolicy, McpGlobalPolicy};
+
+ fn policy(version: Option<u8>) -> McpGlobalPolicy {
+ McpGlobalPolicy {
+ read_only: true,
+ connection_policies: vec![McpConnectionPolicy {
+ connection_id: "conn".to_string(),
+ read_only: false,
+ allow_dangerous_sql: false,
+ execution_mode_configured: true,
+ execution_mode_policy_version: version,
+ database_scope: Default::default(),
+ allowed_databases: Vec::new(),
+ database_policies: vec![McpDatabasePolicy {
+ database_name: "db".to_string(),
+ read_only: false,
+ allow_dangerous_sql: true,
+ }],
+ }],
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn legacy_rules_cannot_widen_global_read_only() {
+ assert_eq!(effective_database_execution_policy(&policy(None), "conn", "db"), (true, false));
+ }
+
+ #[test]
+ fn current_rules_use_database_override() {
+ assert_eq!(
+ effective_database_execution_policy(&policy(Some(MCP_EXECUTION_POLICY_VERSION)), "conn", "db"),
+ (false, true)
+ );
+ }
+
+ #[test]
+ fn legacy_connection_ceiling_is_preserved_for_safe_write_rule() {
+ let mut policy = policy(None);
+ policy.read_only = false;
+ policy.allow_dangerous_sql = true;
+ policy.connection_policies[0].allow_dangerous_sql = false;
+ policy.connection_policies[0].database_policies.clear();
+ assert_eq!(effective_database_execution_policy(&policy, "conn", "db"), (false, false));
+ }
+
+ #[test]
+ fn legacy_scope_only_rules_inherit_global_mode() {
+ let mut policy = policy(None);
+ policy.read_only = false;
+ policy.allow_dangerous_sql = true;
+ policy.connection_policies[0].execution_mode_configured = false;
+ policy.connection_policies[0].database_policies.clear();
+ // Old-UI scope-only rules (configured=false, no mode saved) inherited
+ // the global mode verbatim; the implicit (false, false) values must
+ // not narrow allow_dangerous_sql on upgrade.
+ assert_eq!(effective_database_execution_policy(&policy, "conn", "db"), (false, true));
+ }
+
+ #[test]
+ fn blank_database_uses_connection_default() {
+ assert_eq!(resolve_database(" ", Some("sample")), "sample");
+ assert_eq!(resolve_database("analytics", Some("sample")), "analytics");
+ }
+}
diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rs
index 16e48b7fba..586de2da0d 100644
--- a/crates/dbx-core/src/storage.rs
+++ b/crates/dbx-core/src/storage.rs
@@ -238,9 +238,8 @@ pub struct McpGlobalPolicy {
/// allowlist and is enforced independently of connection permissions.
#[serde(default)]
pub allowed_tool_names: Option<Vec<String>>,
- /// Per-connection rules may only reduce the global execution ceiling.
- /// Keeping this in the global document preserves compatibility with the
- /// existing policy API while allowing each exposed connection to be safer.
+ /// Per-connection execution defaults and database overrides. Rules without
+ /// the current execution policy version remain legacy ceilings.
#[serde(default)]
pub connection_policies: Vec<McpConnectionPolicy>,
#[serde(default)]
@@ -259,17 +258,21 @@ pub struct McpConnectionPolicy {
/// permits writes.
#[serde(default)]
pub read_only: bool,
- /// Enables high-risk SQL only when the MCP-wide policy also enables it.
- /// The default is deliberately false, so adding a connection rule narrows
- /// a full-access global policy to safe writes unless chosen otherwise.
+ /// Enables high-risk SQL for this connection. Legacy rules require this
+ /// to remain within the global ceiling; versioned rules use it as the
+ /// connection default and still honor independent connection protections.
#[serde(default)]
pub allow_dangerous_sql: bool,
/// Whether the operation ceiling is explicitly overridden for this
- /// connection. Missing on older saved policies defaults to true so their
- /// existing safe-write/read-only behavior is preserved; database-only
- /// rules leave it false and inherit the global ceiling.
+ /// connection. Missing on older saved policies defaults to true for
+ /// deserialization compatibility; the version marker determines whether
+ /// those fields use legacy ceiling or current override semantics.
#[serde(default = "default_mcp_connection_execution_mode_configured")]
pub execution_mode_configured: bool,
+ /// Rules without this marker retain the legacy ceiling behavior. New UI
+ /// writes use version 1 for scoped override semantics.
+ #[serde(default)]
+ pub execution_mode_policy_version: Option<u8>,
/// Limits which databases below this connection can be reached by MCP.
/// The default preserves existing installations: all databases remain
/// available until a user explicitly narrows the scope.
@@ -279,6 +282,25 @@ pub struct McpConnectionPolicy {
/// An empty selected list intentionally denies every database.
#[serde(default)]
pub allowed_databases: Vec<String>,
+ /// Optional per-database execution settings. A missing entry inherits the
+ /// connection default, while a present entry takes priority over it.
+ #[serde(default)]
+ pub database_policies: Vec<McpDatabasePolicy>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpDatabasePolicy {
+ /// Exact database name matched after the connection scope has admitted it.
+ pub database_name: String,
+ /// When true, this database rejects writes regardless of the connection
+ /// and global defaults.
+ #[serde(default)]
+ pub read_only: bool,
+ /// Enables high-risk SQL for this database. Connection read-only,
+ /// production protection, scope, and database credentials remain hard limits.
+ #[serde(default)]
+ pub allow_dangerous_sql: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -412,6 +434,15 @@ impl McpGlobalPolicy {
}
current.execution_mode_configured = true;
}
+ current.execution_mode_policy_version =
+ match (current.execution_mode_policy_version, rule.execution_mode_policy_version) {
+ (Some(left), Some(right))
+ if left == crate::mcp_policy::MCP_EXECUTION_POLICY_VERSION && right == left =>
+ {
+ Some(left)
+ }
+ _ => None,
+ };
let (scope, databases) = intersect_mcp_database_scopes(
current.database_scope,
&current.allowed_databases,
@@ -420,14 +451,18 @@ impl McpGlobalPolicy {
);
current.database_scope = scope;
current.allowed_databases = databases;
+ current.database_policies =
+ merge_mcp_database_policies(&current.database_policies, &rule.database_policies);
})
.or_insert_with(|| McpConnectionPolicy {
connection_id: connection_id.to_string(),
read_only: rule.read_only,
allow_dangerous_sql: rule.allow_dangerous_sql,
execution_mode_configured: rule.execution_mode_configured,
+ execution_mode_policy_version: rule.execution_mode_policy_version,
database_scope: rule.database_scope,
allowed_databases: normalize_mcp_database_names(&rule.allowed_databases),
+ database_policies: normalize_mcp_database_policies(&rule.database_policies),
});
}
let mut connection_policies = policies.into_values().collect::<Vec<_>>();
@@ -439,6 +474,10 @@ impl McpGlobalPolicy {
rule.allowed_databases = normalize_mcp_database_names(&rule.allowed_databases);
if rule.database_scope != McpDatabaseScope::Selected {
rule.allowed_databases.clear();
+ rule.database_policies.clear();
+ } else {
+ rule.database_policies
+ .retain(|policy| rule.allowed_databases.binary_search(&policy.database_name).is_ok());
}
}
@@ -465,6 +504,44 @@ fn normalize_mcp_database_names(databases: &[String]) -> Vec<String> {
databases
}
+fn normalize_mcp_database_policies(policies: &[McpDatabasePolicy]) -> Vec<McpDatabasePolicy> {
+ let mut normalized = HashMap::<String, McpDatabasePolicy>::new();
+ for policy in policies {
+ let database_name = policy.database_name.trim();
+ if database_name.is_empty() {
+ continue;
+ }
+ normalized
+ .entry(database_name.to_string())
+ .and_modify(|current| {
+ // Duplicate entries represent independently supplied limits,
+ // so combine them as the strictest possible policy.
+ current.read_only |= policy.read_only;
+ current.allow_dangerous_sql &= policy.allow_dangerous_sql;
+ })
+ .or_insert_with(|| McpDatabasePolicy {
+ database_name: database_name.to_string(),
+ read_only: policy.read_only,
+ allow_dangerous_sql: !policy.read_only && policy.allow_dangerous_sql,
+ });
+ }
+ let mut normalized = normalized.into_values().collect::<Vec<_>>();
+ normalized.sort_by(|left, right| left.database_name.cmp(&right.database_name));
+ for policy in &mut normalized {
+ if policy.read_only {
+ policy.allow_dangerous_sql = false;
+ }
+ }
+ normalized
+}
+
+fn merge_mcp_database_policies(left: &[McpDatabasePolicy], right: &[McpDatabasePolicy]) -> Vec<McpDatabasePolicy> {
+ let mut policies = Vec::with_capacity(left.len() + right.len());
+ policies.extend_from_slice(left);
+ policies.extend_from_slice(right);
+ normalize_mcp_database_policies(&policies)
+}
+
fn intersect_mcp_database_scopes(
left_scope: McpDatabaseScope,
left_databases: &[String],
diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rs
index 47cd161c97..1edb1a6467 100644
--- a/crates/dbx-mcp/src/server.rs
+++ b/crates/dbx-mcp/src/server.rs
@@ -496,6 +496,7 @@ impl DbxMcpServer {
Ok(database) => database,
Err(error) => return error,
};
+ let policy = effective_policy_for_database(&resolved.policy, connection, &database);
if let Some(session) = &session {
if session.database != database {
return tool_error(
@@ -538,12 +539,17 @@ impl DbxMcpServer {
{
return error;
}
+ if let Err(error) =
+ ensure_sql_database_execution_scope(&resolved.policy, connection, &database, &request.sql)
+ {
+ return error;
+ }
}
- let permissions =
- match validate_sql_policy(connection, &resolved.policy, &database, &request.sql, allow_database_switch) {
- Ok(permissions) => permissions,
- Err(error) => return error,
- };
+ let permissions = match validate_sql_policy(connection, &policy, &database, &request.sql, allow_database_switch)
+ {
+ Ok(permissions) => permissions,
+ Err(error) => return error,
+ };
let mut arguments = json!({ "sql": request.sql, "limit": 100 });
if let Some(schema) = self.scope.schema.as_deref() {
arguments["schema"] = json!(schema);
@@ -652,14 +658,22 @@ impl DbxMcpServer {
if connection.db_type != DatabaseType::Redis {
return tool_error("INVALID_CONNECTION_TYPE", format!("Connection \"{}\" is not Redis.", connection.name));
}
+ let database = match self.resolve_redis_database(request.db, &resolved) {
+ Ok(database) => database,
+ Err(error) => return error,
+ };
let argv = match parse_command_argv(&request.command) {
Ok(argv) => argv,
Err(error) => return tool_error("REDIS_COMMAND_BLOCKED", error),
};
let safety = classify_command(&argv[0]);
- let permissions = mcp_permissions(connection, &resolved.policy);
- if safety != RedisCommandSafety::Allowed && resolved.policy.read_only {
- return tool_error("MCP_READ_ONLY", "DBX global MCP read-only mode is enabled. Redis command blocked.");
+ let policy = effective_policy_for_database(&resolved.policy, connection, &database.to_string());
+ let permissions = mcp_permissions(connection, &policy);
+ if safety != RedisCommandSafety::Allowed && policy.read_only {
+ return tool_error(
+ "MCP_READ_ONLY",
+ format!("MCP execution permission for Redis database {database} is read-only. Redis command blocked."),
+ );
}
if safety != RedisCommandSafety::Allowed && connection.read_only {
return tool_error(
@@ -682,10 +696,6 @@ impl DbxMcpServer {
"MCP Redis command execution is read-only in DBX MCP settings.",
);
}
- let database = match self.resolve_redis_database(request.db, &resolved) {
- Ok(database) => database,
- Err(error) => return error,
- };
// Production protection is stricter than the opt-in write flags by design.
if safety != RedisCommandSafety::Allowed && is_production_database(connection, &database.to_string()) {
return tool_error(
@@ -736,10 +746,15 @@ impl DbxMcpServer {
if request.topic.trim().is_empty() {
return tool_error("MESSAGE_TOPIC_REQUIRED", "Message topic must not be empty.");
}
- if resolved.policy.read_only {
+ let policy = effective_policy_for_database(
+ &resolved.policy,
+ connection,
+ connection.database.as_deref().unwrap_or(""),
+ );
+ if policy.read_only {
return tool_error(
"MCP_READ_ONLY",
- "DBX global MCP read-only mode is enabled. Message sending is blocked.",
+ "The effective MCP execution permission is read-only. Message sending is blocked.",
);
}
if connection.read_only {
@@ -1059,16 +1074,22 @@ impl DbxMcpServer {
Ok(database) => database,
Err(error) => return error,
};
+ let policy = effective_policy_for_database(&resolved.policy, connection, &database);
if connection.db_type != DatabaseType::MongoDb {
if let Err(error) = ensure_sql_database_scope(&resolved.database_scope, connection, &database, &request.sql)
{
return error;
}
+ if let Err(error) =
+ ensure_sql_database_execution_scope(&resolved.policy, connection, &database, &request.sql)
+ {
+ return error;
+ }
}
let permissions = if connection.db_type == DatabaseType::MongoDb {
- mcp_permissions(connection, &resolved.policy)
+ mcp_permissions(connection, &policy)
} else {
- match validate_sql_policy(connection, &resolved.policy, &database, &request.sql, false) {
+ match validate_sql_policy(connection, &policy, &database, &request.sql, false) {
Ok(permissions) => permissions,
Err(error) => return error,
}
@@ -1336,6 +1357,7 @@ fn backend_tool_error(default_code: &str, error: impl Into<String>) -> CallToolR
"MCP_READ_ONLY",
"CONNECTION_OUT_OF_SCOPE",
"DATABASE_OUT_OF_SCOPE",
+ "DATABASE_EXECUTION_POLICY_OUT_OF_SCOPE",
"INVALID_DATABASE_SCOPE",
"CONNECTION_READ_ONLY",
"PRODUCTION_DATABASE_READ_ONLY",
@@ -1388,7 +1410,6 @@ fn resolved_connection(
connection: dbx_core::models::connection::ConnectionConfig,
) -> ResolvedConnection {
let database_scope = database_scope_for_connection(&policy, &connection);
- let policy = effective_policy_for_connection(policy, &connection);
ResolvedConnection { connection, policy, database_scope }
}
@@ -1440,19 +1461,18 @@ fn format_database_names(databases: &[String]) -> String {
}
}
-/// A connection-level rule is a restrictive overlay, never an escalation. It
-/// therefore composes safely with the global policy, the connection's own
-/// read-only flag, and production-database protections checked elsewhere.
-fn effective_policy_for_connection(
- mut policy: McpGlobalPolicy,
+/// Execution modes are scoped defaults: a database rule overrides a configured
+/// connection default, which in turn overrides the global default. Connection
+/// read-only protection and production-database protections are enforced
+/// separately and cannot be bypassed by these defaults.
+fn effective_policy_for_database(
+ policy: &McpGlobalPolicy,
connection: &dbx_core::models::connection::ConnectionConfig,
+ database: &str,
) -> McpGlobalPolicy {
- if let Some(rule) = policy.connection_policies.iter().find(|rule| rule.connection_id == connection.id) {
- if rule.execution_mode_configured {
- policy.read_only |= rule.read_only;
- policy.allow_dangerous_sql &= !rule.read_only && rule.allow_dangerous_sql;
- }
- }
+ let mut policy = policy.clone();
+ (policy.read_only, policy.allow_dangerous_sql) =
+ dbx_core::mcp_policy::effective_database_execution_policy(&policy, &connection.id, database);
// This returned value is carried through the request only; retaining a
// complete policy document here could accidentally be reused for another
// connection by a future caller.
@@ -1460,6 +1480,21 @@ fn effective_policy_for_connection(
policy
}
+/// A database-level execution rule must not be bypassed by qualifying another
+/// allowed database in SQL. Until individual references are evaluated with
+/// their own policies, cross-database SQL is intentionally rejected whenever
+/// this connection has database-specific execution rules.
+#[allow(clippy::result_large_err)]
+fn ensure_sql_database_execution_scope(
+ policy: &McpGlobalPolicy,
+ connection: &dbx_core::models::connection::ConnectionConfig,
+ active_database: &str,
+ sql: &str,
+) -> Result<(), CallToolResult> {
+ dbx_core::mcp_policy::ensure_sql_database_execution_scope(policy, connection, active_database, sql)
+ .map_err(|error| tool_error("DATABASE_EXECUTION_POLICY_OUT_OF_SCOPE", error))
+}
+
fn mcp_permissions(
connection: &dbx_core::models::connection::ConnectionConfig,
policy: &McpGlobalPolicy,
@@ -1510,7 +1545,10 @@ fn validate_sql_policy(
// is permitted. Fail closed on either signal so read-only stays read-only.
let is_write = risk != SqlRisk::ReadOnly || is_write_sql_for_database(sql, connection.db_type);
if policy.read_only && is_write {
- return Err(tool_error("MCP_READ_ONLY", "DBX global MCP read-only mode is enabled. SQL write blocked."));
+ return Err(tool_error(
+ "MCP_READ_ONLY",
+ format!("MCP execution permission for database \"{database}\" is read-only. SQL write blocked."),
+ ));
}
if connection.read_only && is_write {
return Err(tool_error(
@@ -1552,11 +1590,21 @@ fn validate_mongo_command(
));
}
if let MongoCommand::Aggregate { pipeline, .. } = &command {
+ dbx_core::mcp_policy::ensure_mongo_database_execution_scope(policy, &connection.id, database, pipeline)
+ .map_err(|error| {
+ let (code, message) = error
+ .strip_prefix("QUERY_ERROR: ")
+ .map_or(("DATABASE_EXECUTION_POLICY_OUT_OF_SCOPE", error.as_str()), |message| {
+ ("QUERY_ERROR", message)
+ });
+ tool_error(code, message)
+ })?;
for target_database in mongo_aggregate_target_databases(pipeline, database)? {
ensure_database_in_scope(database_scope, &target_database)?;
}
}
- let permissions = mcp_permissions(connection, policy);
+ let effective_policy = effective_policy_for_database(policy, connection, database);
+ let permissions = mcp_permissions(connection, &effective_policy);
let production_database = match &command {
MongoCommand::Aggregate { pipeline, .. } => {
mongo_pipeline_targets_production_database(connection, database, pipeline)
@@ -1568,8 +1616,8 @@ fn validate_mongo_command(
{
return Err(match error {
MongoSafetyError::WritesDisabled => tool_error(
- if policy.read_only { "MCP_READ_ONLY" } else { "CONNECTION_READ_ONLY" },
- "MCP MongoDB execution is read-only in DBX MCP settings.",
+ if effective_policy.read_only { "MCP_READ_ONLY" } else { "CONNECTION_READ_ONLY" },
+ "MCP MongoDB execution is read-only for this database in DBX MCP settings.",
),
MongoSafetyError::EmptyFilter => tool_error(
"SQL_BLOCKED",
@@ -1589,36 +1637,8 @@ fn validate_mongo_command(
#[allow(clippy::result_large_err)]
fn mongo_aggregate_target_databases(pipeline: &str, active_database: &str) -> Result<Vec<String>, CallToolResult> {
- let stages = serde_json::from_str::<serde_json::Value>(pipeline)
- .ok()
- .and_then(|value| value.as_array().cloned())
- .ok_or_else(|| tool_error("QUERY_ERROR", "MongoDB aggregate pipeline must be a JSON array."))?;
- let mut databases = Vec::new();
- for stage in stages {
- let Some(stage) = stage.as_object() else { continue };
- for key in ["$out", "$merge"] {
- let Some(target) = stage.get(key) else { continue };
- let target_database = match target {
- serde_json::Value::String(_) => active_database.to_string(),
- serde_json::Value::Object(target) => target
- .get("db")
- .or_else(|| {
- target.get("into").and_then(serde_json::Value::as_object).and_then(|into| into.get("db"))
- })
- .and_then(serde_json::Value::as_str)
- .unwrap_or(active_database)
- .to_string(),
- _ => {
- return Err(tool_error(
- "QUERY_ERROR",
- "MongoDB aggregate output target must be a string or object.",
- ))
- }
- };
- databases.push(target_database);
- }
- }
- Ok(databases)
+ dbx_core::mcp_policy::mongo_pipeline_output_databases(pipeline, active_database)
+ .map_err(|error| tool_error("QUERY_ERROR", error.strip_prefix("QUERY_ERROR: ").unwrap_or(&error)))
}
fn non_empty_env(name: &str) -> Option<String> {
@@ -2249,6 +2269,52 @@ mod tests {
assert!(result_text(&error).contains("DATABASE_OUT_OF_SCOPE"));
}
+ #[test]
+ fn database_execution_policy_overrides_connection_and_global_defaults_and_blocks_cross_database_sql() {
+ let connection = connection("sql", "sql", "mysql", "operations");
+ let policy = McpGlobalPolicy {
+ connection_policies: vec![dbx_core::storage::McpConnectionPolicy {
+ connection_id: "sql".to_string(),
+ read_only: false,
+ allow_dangerous_sql: false,
+ execution_mode_configured: true,
+ execution_mode_policy_version: Some(dbx_core::mcp_policy::MCP_EXECUTION_POLICY_VERSION),
+ database_scope: McpDatabaseScope::Selected,
+ allowed_databases: vec!["operations".to_string(), "reporting".to_string()],
+ database_policies: vec![
+ dbx_core::storage::McpDatabasePolicy {
+ database_name: "operations".to_string(),
+ read_only: false,
+ allow_dangerous_sql: true,
+ },
+ dbx_core::storage::McpDatabasePolicy {
+ database_name: "reporting".to_string(),
+ read_only: true,
+ allow_dangerous_sql: false,
+ },
+ ],
+ }],
+ ..Default::default()
+ };
+
+ let operations = effective_policy_for_database(&policy, &connection, "operations");
+ assert!(!operations.read_only);
+ assert!(operations.allow_dangerous_sql);
+
+ let reporting = effective_policy_for_database(&policy, &connection, "reporting");
+ assert!(reporting.read_only);
+ assert!(!reporting.allow_dangerous_sql);
+
+ let error = ensure_sql_database_execution_scope(
+ &policy,
+ &connection,
+ "operations",
+ "UPDATE reporting.jobs SET done = 1",
+ )
+ .unwrap_err();
+ assert!(result_text(&error).contains("DATABASE_EXECUTION_POLICY_OUT_OF_SCOPE"));
+ }
+
#[tokio::test]
async fn selected_database_scope_can_be_discovered_without_a_connection_default_database() {
let connection = connection("sql", "sql", "mysql", "");
@@ -2262,7 +2328,9 @@ mod tests {
allow_dangerous_sql: false,
database_scope: McpDatabaseScope::Selected,
allowed_databases: vec!["aa".to_string(), "aaa".to_string(), "abc".to_string()],
+ database_policies: Vec::new(),
execution_mode_configured: false,
+ execution_mode_policy_version: None,
}],
..Default::default()
},
diff --git a/crates/dbx-web/src/routes/mcp_policy.rs b/crates/dbx-web/src/routes/mcp_policy.rs
index 56e6bfcb62..6b9431964e 100644
--- a/crates/dbx-web/src/routes/mcp_policy.rs
+++ b/crates/dbx-web/src/routes/mcp_policy.rs
@@ -2,7 +2,7 @@ use std::sync::Arc;
use axum::http::HeaderMap;
use dbx_core::models::connection::ConnectionConfig;
-use dbx_core::storage::McpGlobalPolicy;
+use dbx_core::storage::{McpDatabaseScope, McpGlobalPolicy};
use crate::error::AppError;
use crate::state::WebState;
@@ -240,6 +240,53 @@ fn ensure_allowed(policy: &McpGlobalPolicy, connection_id: &str) -> Result<(), A
Ok(())
}
+fn ensure_database_in_scope(policy: &McpGlobalPolicy, connection_id: &str, database: &str) -> Result<(), AppError> {
+ let Some(rule) = policy.connection_policies.iter().find(|rule| rule.connection_id == connection_id) else {
+ return Ok(());
+ };
+ match rule.database_scope {
+ McpDatabaseScope::All => Ok(()),
+ McpDatabaseScope::None => Err(AppError::from(format!(
+ "DATABASE_OUT_OF_SCOPE: database '{database}' is not allowed by DBX MCP settings for connection '{connection_id}'"
+ ))),
+ McpDatabaseScope::Selected if rule.allowed_databases.iter().any(|allowed| allowed == database) => Ok(()),
+ McpDatabaseScope::Selected => Err(AppError::from(format!(
+ "DATABASE_OUT_OF_SCOPE: database '{database}' is not allowed by DBX MCP settings for connection '{connection_id}'"
+ ))),
+ }
+}
+
+/// Execution modes are scoped defaults: a database setting overrides a
+/// configured connection default, which in turn overrides the global default.
+/// Connection read-only and production protections are checked separately.
+fn effective_database_execution_policy(policy: &McpGlobalPolicy, connection_id: &str, database: &str) -> (bool, bool) {
+ dbx_core::mcp_policy::effective_database_execution_policy(policy, connection_id, database)
+}
+
+fn ensure_sql_database_execution_scope(
+ policy: &McpGlobalPolicy,
+ connection: &ConnectionConfig,
+ active_database: &str,
+ sql: &str,
+) -> Result<(), AppError> {
+ dbx_core::mcp_policy::ensure_sql_database_execution_scope(policy, connection, active_database, sql)
+ .map_err(AppError::from)
+}
+
+fn mongo_pipeline_output_databases(pipeline_json: &str, active_database: &str) -> Result<Vec<String>, AppError> {
+ dbx_core::mcp_policy::mongo_pipeline_output_databases(pipeline_json, active_database).map_err(AppError::from)
+}
+
+fn ensure_mongo_database_execution_scope(
+ policy: &McpGlobalPolicy,
+ connection_id: &str,
+ active_database: &str,
+ pipeline_json: &str,
+) -> Result<(), AppError> {
+ dbx_core::mcp_policy::ensure_mongo_database_execution_scope(policy, connection_id, active_database, pipeline_json)
+ .map_err(AppError::from)
+}
+
fn connection_read_only_error(message: impl Into<String>) -> AppError {
AppError::from(format!("CONNECTION_READ_ONLY: {}", message.into()))
}
@@ -256,6 +303,19 @@ async fn load_connection(state: &Arc<WebState>, connection_id: &str) -> Result<C
.ok_or_else(|| AppError::from(format!("Connection with id '{connection_id}' not found")))
}
+pub async fn resolve_database(
+ state: &Arc<WebState>,
+ headers: &HeaderMap,
+ connection_id: &str,
+ database: &str,
+) -> Result<String, AppError> {
+ if !is_mcp_request(headers) {
+ return Ok(database.to_string());
+ }
+ let config = load_connection(state, connection_id).await?;
+ Ok(dbx_core::mcp_policy::resolve_database(database, config.database.as_deref()))
+}
+
pub async fn ensure_scope(state: &Arc<WebState>, headers: &HeaderMap, connection_id: &str) -> Result<(), AppError> {
if !is_mcp_request(headers) {
return Ok(());
@@ -289,17 +349,25 @@ pub async fn ensure_mongo_pipeline_target(
connection_id: &str,
database: &str,
pipeline_json: &str,
-) -> Result<(), AppError> {
+) -> Result<String, AppError> {
if !is_mcp_request(headers) {
- return Ok(());
+ return Ok(database.to_string());
}
+ let policy = load_policy(state).await?;
+ ensure_allowed(&policy, connection_id)?;
let config = load_connection(state, connection_id).await?;
- if dbx_core::production_safety::mongo_pipeline_targets_production_database(&config, database, pipeline_json) {
+ let database = dbx_core::mcp_policy::resolve_database(database, config.database.as_deref());
+ ensure_database_in_scope(&policy, connection_id, &database)?;
+ for target_database in mongo_pipeline_output_databases(pipeline_json, &database)? {
+ ensure_database_in_scope(&policy, connection_id, &target_database)?;
+ }
+ ensure_mongo_database_execution_scope(&policy, connection_id, &database, pipeline_json)?;
+ if dbx_core::production_safety::mongo_pipeline_targets_production_database(&config, &database, pipeline_json) {
return Err(AppError::from(
"PRODUCTION_DATABASE_READ_ONLY: MongoDB aggregate write targeting production scope is blocked.".to_string(),
));
}
- Ok(())
+ Ok(database)
}
async fn ensure_write_with_risk(
@@ -315,22 +383,27 @@ async fn ensure_write_with_risk(
}
let policy = load_policy(state).await?;
ensure_allowed(&policy, connection_id)?;
- if policy.read_only {
- return Err(AppError::from(format!("MCP_READ_ONLY: DBX MCP read-only mode is enabled. {action} blocked.")));
+ let config = load_connection(state, connection_id).await?;
+ let database = dbx_core::mcp_policy::resolve_database(database, config.database.as_deref());
+ ensure_database_in_scope(&policy, connection_id, &database)?;
+ let (read_only, allow_dangerous_sql) = effective_database_execution_policy(&policy, connection_id, &database);
+ if read_only {
+ return Err(AppError::from(format!(
+ "MCP_READ_ONLY: MCP execution permission for database '{database}' is read-only. {action} blocked."
+ )));
}
- if dangerous && !policy.allow_dangerous_sql {
+ if dangerous && !allow_dangerous_sql {
return Err(AppError::from(format!(
"SQL_BLOCKED: High-risk operation '{action}' is disabled in DBX MCP settings."
)));
}
- let config = load_connection(state, connection_id).await?;
if config.read_only {
return Err(connection_read_only_error(format!(
"Connection '{}' has read-only protection enabled. {action} blocked.",
config.name
)));
}
- if dbx_core::production_safety::is_production_database(&config, database) {
+ if dbx_core::production_safety::is_production_database(&config, &database) {
return Err(AppError::from(format!(
"PRODUCTION_DATABASE_READ_ONLY: {action} blocked for production database '{database}'."
)));
@@ -345,40 +418,97 @@ pub async fn ensure_sql(
database: &str,
sql: &str,
allow_database_switch: bool,
-) -> Result<(), AppError> {
+) -> Result<String, AppError> {
if !is_mcp_request(headers) {
- return Ok(());
+ return Ok(database.to_string());
}
let policy = load_policy(state).await?;
ensure_allowed(&policy, connection_id)?;
let config = load_connection(state, connection_id).await?;
+ let database = dbx_core::mcp_policy::resolve_database(database, config.database.as_deref());
+ ensure_database_in_scope(&policy, connection_id, &database)?;
if !allow_database_switch && dbx_core::sql_risk::mcp_sql_has_forbidden_database_switch(sql, config.db_type) {
return Err(AppError::from(
"SQL_BLOCKED: MCP does not allow USE or persistent database switching.".to_string(),
));
}
let is_write = dbx_core::query_execution_sql::is_write_sql_for_database(sql, config.db_type);
- if policy.read_only && is_write {
- return Err(AppError::from("MCP_READ_ONLY: DBX MCP read-only mode is enabled. SQL write blocked.".to_string()));
+ ensure_sql_database_execution_scope(&policy, &config, &database, sql)?;
+ let (read_only, allow_dangerous_sql) = effective_database_execution_policy(&policy, connection_id, &database);
+ if read_only && is_write {
+ return Err(AppError::from(format!(
+ "MCP_READ_ONLY: MCP execution permission for database '{database}' is read-only. SQL write blocked."
+ )));
}
- if !policy.allow_dangerous_sql && dbx_core::sql_risk::is_dangerous_sql_for_database(sql, config.db_type) {
+ if !allow_dangerous_sql && dbx_core::sql_risk::is_dangerous_sql_for_database(sql, config.db_type) {
return Err(AppError::from("SQL_BLOCKED: High-risk SQL is disabled in DBX MCP settings.".to_string()));
}
if config.read_only {
dbx_core::query_execution_sql::check_read_only(sql, &config.name, config.db_type)
.map_err(connection_read_only_error)?;
}
- if is_write && dbx_core::production_safety::targets_production_database(&config, database, sql) {
+ if is_write && dbx_core::production_safety::targets_production_database(&config, &database, sql) {
return Err(AppError::from(
"PRODUCTION_DATABASE_READ_ONLY: SQL write targeting production scope is blocked.".to_string(),
));
}
- Ok(())
+ Ok(database)
}
#[cfg(test)]
mod tests {
- use super::{connection_read_only_error, mongo_filter_is_effectively_unbounded, mongo_pipeline_has_write_stage};
+ use super::{
+ connection_read_only_error, effective_database_execution_policy, ensure_mongo_database_execution_scope,
+ mongo_filter_is_effectively_unbounded, mongo_pipeline_has_write_stage,
+ };
+ use dbx_core::storage::{McpConnectionPolicy, McpDatabasePolicy, McpDatabaseScope, McpGlobalPolicy};
+
+ fn database_policy() -> McpGlobalPolicy {
+ McpGlobalPolicy {
+ read_only: true,
+ allow_dangerous_sql: false,
+ connection_policies: vec![McpConnectionPolicy {
+ connection_id: "conn-1".to_string(),
+ read_only: true,
+ allow_dangerous_sql: false,
+ execution_mode_configured: true,
+ execution_mode_policy_version: Some(dbx_core::mcp_policy::MCP_EXECUTION_POLICY_VERSION),
+ database_scope: McpDatabaseScope::Selected,
+ allowed_databases: vec!["operations".to_string(), "reporting".to_string()],
+ database_policies: vec![McpDatabasePolicy {
+ database_name: "operations".to_string(),
+ read_only: false,
+ allow_dangerous_sql: true,
+ }],
+ }],
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn database_execution_policy_overrides_global_and_connection_defaults() {
+ let policy = database_policy();
+
+ assert_eq!(effective_database_execution_policy(&policy, "conn-1", "operations"), (false, true));
+ assert_eq!(effective_database_execution_policy(&policy, "conn-1", "reporting"), (true, false));
+ }
+
+ #[test]
+ fn database_execution_policy_blocks_cross_database_mongo_aggregate_output() {
+ let policy = database_policy();
+
+ assert!(
+ ensure_mongo_database_execution_scope(&policy, "conn-1", "operations", r#"[{"$out":"archive"}]"#,).is_ok()
+ );
+ let error = ensure_mongo_database_execution_scope(
+ &policy,
+ "conn-1",
+ "operations",
+ r#"[{"$merge":{"into":{"db":"reporting","coll":"archive"}}}]"#,
+ )
+ .unwrap_err();
+ assert!(error.message.starts_with("DATABASE_EXECUTION_POLICY_OUT_OF_SCOPE:"), "{}", error.message);
+ }
#[test]
fn connection_read_only_errors_use_the_stable_mcp_code() {
diff --git a/crates/dbx-web/src/routes/mongo.rs b/crates/dbx-web/src/routes/mongo.rs
index 86875dbfc4..70e2b4c951 100644
--- a/crates/dbx-web/src/routes/mongo.rs
+++ b/crates/dbx-web/src/routes/mongo.rs
@@ -338,7 +338,8 @@ pub async fn list_collections(
Json(req): Json<MongoCollectionRequest>,
) -> Result<Json<Vec<dbx_core::document_ops::CollectionInfo>>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
- let result = dbx_core::mongo_ops::mongo_list_collections_core(&state.app, &req.connection_id, &req.database)
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ let result = dbx_core::mongo_ops::mongo_list_collections_core(&state.app, &req.connection_id, &database)
.await
.map_err(AppError::from)?;
Ok(Json(result))
@@ -360,10 +361,10 @@ pub async fn drop_database(
headers: HeaderMap,
Json(req): Json<MongoCollectionRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Drop database")
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Drop database").await?;
ensure_writable(&state.app, &req.connection_id, "Drop database").await?;
- dbx_core::mongo_ops::mongo_drop_database_core(&state.app, &req.connection_id, &req.database)
+ dbx_core::mongo_ops::mongo_drop_database_core(&state.app, &req.connection_id, &database)
.await
.map_err(AppError::from)?;
Ok(Json(serde_json::json!({ "ok": true })))
@@ -374,10 +375,11 @@ pub async fn drop_collection(
headers: HeaderMap,
Json(req): Json<MongoCollectionNameRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Drop collection")
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Drop collection")
.await?;
ensure_writable(&state.app, &req.connection_id, "Drop collection").await?;
- dbx_core::mongo_ops::mongo_drop_collection_core(&state.app, &req.connection_id, &req.database, &req.collection)
+ dbx_core::mongo_ops::mongo_drop_collection_core(&state.app, &req.connection_id, &database, &req.collection)
.await
.map_err(AppError::from)?;
Ok(Json(serde_json::json!({ "ok": true })))
@@ -388,13 +390,14 @@ pub async fn rename_collection(
headers: HeaderMap,
Json(req): Json<MongoRenameCollectionRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Rename collection")
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Rename collection")
.await?;
ensure_writable(&state.app, &req.connection_id, "Rename collection").await?;
dbx_core::mongo_ops::mongo_rename_collection_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.new_name,
)
@@ -408,13 +411,14 @@ pub async fn clone_collection(
headers: HeaderMap,
Json(req): Json<MongoCloneCollectionRequest>,
) -> Result<Json<dbx_core::db::mongo_driver::MongoCloneCollectionResult>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Clone collection")
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Clone collection")
.await?;
ensure_writable(&state.app, &req.connection_id, "Clone collection").await?;
let result = dbx_core::mongo_ops::mongo_clone_collection_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.source_collection,
&req.target_collection,
)
@@ -429,13 +433,14 @@ pub async fn find_documents(
Json(req): Json<MongoFindRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
dbx_core::document_ops::find_documents_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
req.skip.unwrap_or(0),
req.limit.unwrap_or(50),
@@ -457,6 +462,7 @@ pub async fn explain_find(
Json(req): Json<MongoFindExplainRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
let verbosity = req.verbosity.as_deref().unwrap_or("queryPlanner");
let result = run_cancellable(
&state,
@@ -464,7 +470,7 @@ pub async fn explain_find(
dbx_core::mongo_ops::mongo_explain_find_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
req.skip.unwrap_or(0),
req.limit.unwrap_or(100),
@@ -506,13 +512,14 @@ pub async fn count_documents(
Json(req): Json<MongoCountRequest>,
) -> Result<Json<u64>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
let result = run_cancellable(
&state,
req.execution_id,
dbx_core::mongo_ops::mongo_count_documents_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
req.filter.as_deref(),
req.mode.as_deref(),
@@ -528,10 +535,11 @@ pub async fn server_version(
Json(req): Json<MongoServerVersionRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
- dbx_core::mongo_ops::mongo_server_version_core(&state.app, &req.connection_id, &req.database),
+ dbx_core::mongo_ops::mongo_server_version_core(&state.app, &req.connection_id, &database),
)
.await?;
Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))
@@ -543,13 +551,14 @@ pub async fn collection_stats(
Json(req): Json<MongoCollectionStatsRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
dbx_core::mongo_ops::mongo_collection_stats_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
req.scale,
),
@@ -564,23 +573,23 @@ pub async fn aggregate_documents(
Json(req): Json<MongoAggregateRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
+ let database = super::mcp_policy::ensure_mongo_pipeline_target(
+ &state,
+ &headers,
+ &req.connection_id,
+ &req.database,
+ &req.pipeline_json,
+ )
+ .await?;
if super::mcp_policy::mongo_pipeline_has_write_stage(&req.pipeline_json) {
super::mcp_policy::ensure_dangerous_write(
&state,
&headers,
&req.connection_id,
- &req.database,
+ &database,
"MongoDB aggregate write",
)
.await?;
- super::mcp_policy::ensure_mongo_pipeline_target(
- &state,
- &headers,
- &req.connection_id,
- &req.database,
- &req.pipeline_json,
- )
- .await?;
}
let result = run_cancellable(
&state,
@@ -588,7 +597,7 @@ pub async fn aggregate_documents(
dbx_core::mongo_ops::mongo_aggregate_documents_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.pipeline_json,
req.max_rows,
@@ -605,13 +614,14 @@ pub async fn distinct(
Json(req): Json<MongoDistinctRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
dbx_core::mongo_ops::mongo_distinct_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.field,
req.filter.as_deref(),
@@ -627,14 +637,11 @@ pub async fn list_index_specs(
Json(req): Json<MongoCollectionNameRequest>,
) -> Result<Json<Vec<dbx_core::db::mongo_driver::MongoIndexSpec>>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
- let result = dbx_core::mongo_ops::mongo_list_index_specs_core(
- &state.app,
- &req.connection_id,
- &req.database,
- &req.collection,
- )
- .await
- .map_err(AppError::from)?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ let result =
+ dbx_core::mongo_ops::mongo_list_index_specs_core(&state.app, &req.connection_id, &database, &req.collection)
+ .await
+ .map_err(AppError::from)?;
Ok(Json(result))
}
@@ -643,13 +650,13 @@ pub async fn create_index(
headers: HeaderMap,
Json(req): Json<MongoCreateIndexRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Create index")
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Create index").await?;
ensure_writable(&state.app, &req.connection_id, "Create index").await?;
let name = dbx_core::mongo_ops::mongo_create_index_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.keys_json,
req.options_json.as_deref(),
@@ -664,13 +671,13 @@ pub async fn create_user(
headers: HeaderMap,
Json(req): Json<MongoCreateUserRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Create user")
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Create user").await?;
ensure_writable(&state.app, &req.connection_id, "Create user").await?;
let affected_rows = dbx_core::mongo_ops::mongo_create_user_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.user_json,
req.write_concern_json.as_deref(),
)
@@ -684,19 +691,14 @@ pub async fn run_command(
headers: HeaderMap,
Json(req): Json<MongoRunCommandRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(
- &state,
- &headers,
- &req.connection_id,
- &req.database,
- "Run MongoDB command",
- )
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Run MongoDB command")
+ .await?;
ensure_writable(&state.app, &req.connection_id, "Run MongoDB command").await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
- dbx_core::mongo_ops::mongo_run_command_core(&state.app, &req.connection_id, &req.database, &req.command_json),
+ dbx_core::mongo_ops::mongo_run_command_core(&state.app, &req.connection_id, &database, &req.command_json),
)
.await?;
Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))
@@ -707,13 +709,13 @@ pub async fn drop_indexes(
headers: HeaderMap,
Json(req): Json<MongoDropIndexesRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Drop indexes")
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Drop indexes").await?;
ensure_writable(&state.app, &req.connection_id, "Drop indexes").await?;
let result = dbx_core::mongo_ops::mongo_drop_indexes_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
req.indexes_json.as_deref(),
req.single,
@@ -746,12 +748,13 @@ pub async fn insert_documents(
headers: HeaderMap,
Json(req): Json<MongoInsertDocumentsRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &req.database, "Insert").await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &database, "Insert").await?;
ensure_writable(&state.app, &req.connection_id, "Insert").await?;
let result = dbx_core::mongo_ops::mongo_insert_documents_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.docs_json,
)
@@ -784,17 +787,17 @@ pub async fn update_documents(
headers: HeaderMap,
Json(req): Json<MongoUpdateDocumentsRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
if super::mcp_policy::mongo_filter_is_effectively_unbounded(&req.filter_json) {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Update")
- .await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Update").await?;
} else {
- super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &req.database, "Update").await?;
+ super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &database, "Update").await?;
}
ensure_writable(&state.app, &req.connection_id, "Update").await?;
let result = dbx_core::mongo_ops::mongo_update_documents_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.filter_json,
&req.update_json,
@@ -811,13 +814,13 @@ pub async fn find_one_and_update(
headers: HeaderMap,
Json(req): Json<MongoFindOneAndUpdateRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- ensure_find_one_write_policy(&state, &headers, &req.connection_id, &req.database, &req.filter_json, "Update")
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ ensure_find_one_write_policy(&state, &headers, &req.connection_id, &database, &req.filter_json, "Update").await?;
ensure_writable(&state.app, &req.connection_id, "Update").await?;
let result = dbx_core::mongo_ops::mongo_find_one_and_update_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.filter_json,
&req.update_json,
@@ -833,13 +836,13 @@ pub async fn find_one_and_replace(
headers: HeaderMap,
Json(req): Json<MongoFindOneAndReplaceRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- ensure_find_one_write_policy(&state, &headers, &req.connection_id, &req.database, &req.filter_json, "Replace")
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ ensure_find_one_write_policy(&state, &headers, &req.connection_id, &database, &req.filter_json, "Replace").await?;
ensure_writable(&state.app, &req.connection_id, "Update").await?;
let result = dbx_core::mongo_ops::mongo_find_one_and_replace_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.filter_json,
&req.replacement_json,
@@ -855,13 +858,13 @@ pub async fn find_one_and_delete(
headers: HeaderMap,
Json(req): Json<MongoFindOneAndDeleteRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- ensure_find_one_write_policy(&state, &headers, &req.connection_id, &req.database, &req.filter_json, "Delete")
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ ensure_find_one_write_policy(&state, &headers, &req.connection_id, &database, &req.filter_json, "Delete").await?;
ensure_writable(&state.app, &req.connection_id, "Delete").await?;
let result = dbx_core::mongo_ops::mongo_find_one_and_delete_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.filter_json,
req.options_json.as_deref(),
@@ -894,17 +897,17 @@ pub async fn delete_documents(
headers: HeaderMap,
Json(req): Json<MongoDeleteDocumentsRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
if super::mcp_policy::mongo_filter_is_effectively_unbounded(&req.filter_json) {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Delete")
- .await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Delete").await?;
} else {
- super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &req.database, "Delete").await?;
+ super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &database, "Delete").await?;
}
ensure_writable(&state.app, &req.connection_id, "Delete").await?;
let result = dbx_core::mongo_ops::mongo_delete_documents_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.filter_json,
req.many,
diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rs
index 9f4d6b4029..81f23feaba 100644
--- a/crates/dbx-web/src/routes/query.rs
+++ b/crates/dbx-web/src/routes/query.rs
@@ -394,15 +394,22 @@ pub async fn execute_query(
Json(req): Json<ExecuteQueryRequest>,
) -> Result<Json<dbx_core::db::QueryResult>, AppError> {
let allow_database_switch = req.client_session_id.as_deref().is_some_and(|id| !id.trim().is_empty());
- super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql, allow_database_switch)
- .await?;
+ let database = super::mcp_policy::ensure_sql(
+ &state,
+ &headers,
+ &req.connection_id,
+ &req.database,
+ &req.sql,
+ allow_database_switch,
+ )
+ .await?;
let requested_execution_id = req.execution_id.filter(|id| !id.trim().is_empty());
let keep_timeout_reachable = requested_execution_id.is_some();
let execution_id = requested_execution_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let registered = state.app.running_queries.register_task(
execution_id.clone(),
- RunningTaskMetadata::query(req.connection_id.clone(), req.database.clone(), req.client_session_id.clone()),
+ RunningTaskMetadata::query(req.connection_id.clone(), database.clone(), req.client_session_id.clone()),
);
let cancel_token = registered.token();
@@ -411,7 +418,7 @@ pub async fn execute_query(
let result = dbx_core::query::execute_sql_statement_with_options_typed(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.sql,
req.schema.as_deref(),
Some(cancel_token),
@@ -447,13 +454,20 @@ pub async fn execute_conditional_update(
Json(req): Json<ExecuteQueryRequest>,
) -> Result<Json<dbx_core::db::QueryResult>, AppError> {
let allow_database_switch = req.client_session_id.as_deref().is_some_and(|id| !id.trim().is_empty());
- super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql, allow_database_switch)
- .await?;
+ let database = super::mcp_policy::ensure_sql(
+ &state,
+ &headers,
+ &req.connection_id,
+ &req.database,
+ &req.sql,
+ allow_database_switch,
+ )
+ .await?;
let execution_id = req.execution_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let registered = state.app.running_queries.register_task_for_terminal_confirmation(
execution_id.clone(),
- RunningTaskMetadata::query(req.connection_id.clone(), req.database.clone(), req.client_session_id.clone()),
+ RunningTaskMetadata::query(req.connection_id.clone(), database.clone(), req.client_session_id.clone()),
);
let cancel_token = registered.token();
let response_timeout = dbx_core::query::query_timeout_duration(req.timeout_secs);
@@ -464,7 +478,7 @@ pub async fn execute_conditional_update(
let result = dbx_core::query::execute_sql_statement_with_options_typed(
&app,
&req.connection_id,
- &req.database,
+ &database,
&req.sql,
req.schema.as_deref(),
Some(cancel_token),
@@ -524,15 +538,22 @@ pub async fn execute_multi(
Json(req): Json<ExecuteQueryRequest>,
) -> Result<Response, AppError> {
let allow_database_switch = req.client_session_id.as_deref().is_some_and(|id| !id.trim().is_empty());
- super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql, allow_database_switch)
- .await?;
+ let database = super::mcp_policy::ensure_sql(
+ &state,
+ &headers,
+ &req.connection_id,
+ &req.database,
+ &req.sql,
+ allow_database_switch,
+ )
+ .await?;
let requested_execution_id = req.execution_id.filter(|id| !id.trim().is_empty());
let keep_timeout_reachable = requested_execution_id.is_some();
let execution_id = requested_execution_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let registered = state.app.running_queries.register_task(
execution_id.clone(),
- RunningTaskMetadata::query(req.connection_id.clone(), req.database.clone(), req.client_session_id.clone()),
+ RunningTaskMetadata::query(req.connection_id.clone(), database.clone(), req.client_session_id.clone()),
);
let cancel_token = registered.token();
@@ -542,7 +563,7 @@ pub async fn execute_multi(
let result = dbx_core::query::execute_multi_core_with_options_for_client_typed(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.sql,
req.schema.as_deref(),
Some(cancel_token),
@@ -599,14 +620,15 @@ pub async fn execute_batch(
headers: HeaderMap,
Json(req): Json<ExecuteBatchRequest>,
) -> Result<Json<dbx_core::db::QueryResult>, AppError> {
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
for statement in &req.statements {
- super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, statement, false).await?;
+ super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &database, statement, false).await?;
}
tracing::debug!(connection_id = %req.connection_id, "execute_batch");
let result = dbx_core::query::execute_statements(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.statements,
req.schema.as_deref(),
req.timeout_secs,
diff --git a/crates/dbx-web/src/routes/vector.rs b/crates/dbx-web/src/routes/vector.rs
index dcad1cdec4..9a4c51e7ab 100644
--- a/crates/dbx-web/src/routes/vector.rs
+++ b/crates/dbx-web/src/routes/vector.rs
@@ -57,10 +57,10 @@ pub async fn drop_database(
headers: HeaderMap,
Json(req): Json<VectorDatabaseRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Drop database")
- .await?;
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Drop database").await?;
ensure_writable(&state, &req.connection_id, "Drop database").await?;
- dbx_core::schema::drop_vector_database_core(&state.app, &req.connection_id, &req.database)
+ dbx_core::schema::drop_vector_database_core(&state.app, &req.connection_id, &database)
.await
.map_err(AppError::from)?;
Ok(Json(serde_json::json!({ "ok": true })))
@@ -71,10 +71,11 @@ pub async fn drop_collection(
headers: HeaderMap,
Json(req): Json<VectorCollectionRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Drop collection")
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Drop collection")
.await?;
ensure_writable(&state, &req.connection_id, "Drop collection").await?;
- dbx_core::schema::drop_vector_collection_core(&state.app, &req.connection_id, &req.database, &req.collection)
+ dbx_core::schema::drop_vector_collection_core(&state.app, &req.connection_id, &database, &req.collection)
.await
.map_err(AppError::from)?;
Ok(Json(serde_json::json!({ "ok": true })))
@@ -85,13 +86,14 @@ pub async fn rename_collection(
headers: HeaderMap,
Json(req): Json<VectorRenameCollectionRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Rename collection")
+ let database = super::mcp_policy::resolve_database(&state, &headers, &req.connection_id, &req.database).await?;
+ super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &database, "Rename collection")
.await?;
ensure_writable(&state, &req.connection_id, "Rename collection").await?;
dbx_core::schema::rename_vector_collection_core(
&state.app,
&req.connection_id,
- &req.database,
+ &database,
&req.collection,
&req.new_name,
)
diff --git a/docs/content/docs/mcp.cn.mdx b/docs/content/docs/mcp.cn.mdx
index 8948e00daa..948fdbb001 100644
--- a/docs/content/docs/mcp.cn.mdx
+++ b/docs/content/docs/mcp.cn.mdx
@@ -210,7 +210,7 @@ DBX 在 **设置 → MCP** 中保存一份权威策略,并在每次请求时
`WHERE TRUE`、`WHERE 1 = 1`、`_id: {$exists: true}` 或不透明 MongoDB 过滤器仍按高风险处理。连接自身只读、生产库保护、数据库账号权限和 MCP 连接 allowlist 在任何模式下都是权限上限。
-对于已暴露给 MCP 的连接,**设置 → MCP** 还可以设置额外的连接级执行上限:继承全局、只读、安全写入或高风险写入。连接规则只能收窄权限。例如全局策略为高风险访问时,连接规则设为只读仍不能写入;任何连接规则也不能绕过 DBX 的生产库保护或连接自身保护。
+对于已暴露给 MCP 的连接,**设置 → MCP** 可以设置连接默认执行权限:继承全局、只读、安全写入或高风险写入。选择指定数据库后,还可为单个数据库设置执行权限。执行权限按范围由小到大回退:**单库设置 → 连接默认 → 全局默认**;例如全局和连接默认均为“数据读写”时,可为单个数据库设置“完全访问”。连接自身只读、生产库保护、数据库范围和数据库账号权限仍是独立的硬性限制,不能被单库设置绕过。
同一页面还可只暴露选定的 MCP 工具。这项限制在服务端的每一次调用中都会强制执行,不只是客户端的展示偏好;即使客户端缓存了旧工具列表,也会在服务端 allowlist 更新后被拒绝。
@@ -219,11 +219,13 @@ DBX 在 **设置 → MCP** 中保存一份权威策略,并在每次请求时
在 **设置 → MCP** 中建议按以下顺序定义最终权限范围:
1. 选择 MCP 可见的是**所有连接**(包括以后新增的连接),还是仅**指定连接**。
-2. 为每个已暴露连接选择**全部数据库**、**仅指定数据库**或**不允许访问**。指定数据库名按精确名称匹配;可先调用 `dbx_list_databases` 获取当前允许使用的名称。
-3. 对敏感连接按需设置连接级执行上限,使其低于全局权限模式。
-4. 仅选择客户端实际需要的 MCP 工具,再设置全局执行权限模式。
+2. 为每个已暴露连接选择**全部数据库**、**仅指定数据库**或**不允许访问**。指定数据库名按精确名称匹配;可先调用 `dbx_list_databases` 获取当前允许使用的名称,并为选中的数据库按需设置执行权限。
+3. 为每个连接设置默认执行权限。未配置单库覆盖、或选择全部数据库时,该默认值就是连接内数据库的执行权限。
+4. 仅选择客户端实际需要的 MCP 工具,再设置全局默认执行权限模式。
-每一层都是权限上限:已允许的工具也不能绕过隐藏连接、数据库范围、连接只读、生产库保护或数据库账号本身的权限。请求未被选中数据库时,服务会返回 `DATABASE_OUT_OF_SCOPE`。
+执行权限由最具体的设置决定,但已允许的工具仍不能绕过隐藏连接、数据库范围、连接只读、生产库保护或数据库账号本身的权限。请求未被选中数据库时,服务会返回 `DATABASE_OUT_OF_SCOPE`;配置单库执行权限时,跨库 SQL 和 MongoDB 聚合写入会被拒绝,避免绕过数据库级限制。
+
+升级时,未带执行策略版本的已保存连接规则继续使用旧的权限上限语义,不会放大全局权限。只有当前设置页面保存的规则会标记为范围覆盖语义;编辑旧规则时,系统会先固化其实际生效的权限上限,再启用新的覆盖行为。
新版 Server 不允许 `DBX_MCP_ALLOW_WRITES` 或 `DBX_MCP_ALLOW_DANGEROUS_SQL` 放宽 DBX 中央策略。为兼容升级,在中央策略首次保存前,旧配置中的 `DBX_MCP_ALLOW_WRITES=0`(或 `false`)仍会保持 MCP 只读;策略保存后仅以中央策略为准,并忽略旧权限变量。旧连接 scope 变量只能进一步收窄 DBX allowlist。
diff --git a/docs/content/docs/mcp.mdx b/docs/content/docs/mcp.mdx
index 00d02864e2..1a439c665e 100644
--- a/docs/content/docs/mcp.mdx
+++ b/docs/content/docs/mcp.mdx
@@ -210,7 +210,7 @@ DBX stores one authoritative MCP policy under **Settings → MCP** and reloads i
An ineffective condition such as `WHERE TRUE`, `WHERE 1 = 1`, `_id: {$exists: true}`, or an opaque MongoDB filter remains high risk. Connection-level read-only protection, production protection, database credentials, and the MCP connection allowlist remain upper bounds in every mode.
-For connections that are exposed to MCP, **Settings → MCP** can apply an additional per-connection ceiling: inherit the global mode, read only, safe write, or high-risk write. A connection rule only narrows access. For example, a global high-risk policy cannot make a connection writable when its connection rule is read only, and no connection rule can override DBX production or connection-level protection.
+For connections exposed to MCP, **Settings → MCP** can set a default execution permission: inherit the global mode, read only, safe write, or high-risk write. When selected databases are used, individual databases can receive their own execution permission. Execution permissions fall back from the most specific scope: **database setting → connection default → global default**. For example, a database can use full access while both the global and connection defaults use data read/write. Connection-level read-only protection, production protection, database scope, and database credentials remain independent hard limits that no database setting can bypass.
The same page can also expose only selected MCP tools. This is enforced at every call, rather than being only a client-side display preference; a client that retained an old tool list is denied once the server-side allowlist changes.
@@ -219,11 +219,13 @@ The same page can also expose only selected MCP tools. This is enforced at every
Use **Settings → MCP** to define the effective scope in this order:
1. Choose whether MCP can see **all connections** (including future connections) or only **specified connections**.
-2. For every exposed connection, choose **all databases**, **specified databases**, or **no access**. Specified database names are exact matches; use `dbx_list_databases` to discover the names that are currently allowed.
-3. Optionally set a per-connection execution ceiling to narrow the global permission mode for a sensitive connection.
-4. Select only the MCP tools that the client needs, then choose the global permission mode.
+2. For every exposed connection, choose **all databases**, **specified databases**, or **no access**. Specified database names are exact matches; use `dbx_list_databases` to discover the names that are currently allowed, then optionally set execution permissions for those databases.
+3. Set each connection's default execution permission. It applies to every database when all databases are exposed, and to selected databases that do not have an override.
+4. Select only the MCP tools that the client needs, then choose the global default execution permission.
-Every layer is an upper bound: an allowed tool still cannot bypass a hidden connection, a database scope, connection read-only status, production protection, or the database account's own privileges. Requests for a database outside the selected scope are rejected with `DATABASE_OUT_OF_SCOPE`.
+The most specific execution setting wins, but an allowed tool still cannot bypass a hidden connection, database scope, connection read-only status, production protection, or the database account's own privileges. Requests for a database outside the selected scope are rejected with `DATABASE_OUT_OF_SCOPE`. When database-specific execution permissions exist, cross-database SQL and MongoDB aggregation writes are rejected to prevent bypassing those limits.
+
+During upgrade, saved connection rules without an execution policy version keep the previous ceiling semantics and cannot widen the global permission. Only a rule saved by the current Settings UI is marked for scoped override semantics; editing an existing legacy rule first carries its effective ceiling forward before enabling the new behavior.
Updated servers do not let `DBX_MCP_ALLOW_WRITES` or `DBX_MCP_ALLOW_DANGEROUS_SQL` widen the DBX policy. For upgrade compatibility, `DBX_MCP_ALLOW_WRITES=0` (or `false`) still keeps MCP read-only until a central policy is saved for the first time. After that, the central policy is authoritative and the legacy permission variables are ignored. Legacy connection-scope variables can only narrow the DBX allowlist.
diff --git a/src-tauri/src/commands/mcp_bridge.rs b/src-tauri/src/commands/mcp_bridge.rs
index c4dd173da9..2a060aeb2a 100644
--- a/src-tauri/src/commands/mcp_bridge.rs
+++ b/src-tauri/src/commands/mcp_bridge.rs
@@ -294,12 +294,13 @@ fn find_config_by_name<'a>(
#[cfg(test)]
mod tests {
use super::{
- ensure_connection_in_mcp_scope, ensure_mcp_connection_sql_write_allowed, ensure_mcp_execute_and_show_supported,
+ effective_database_execution_policy, ensure_connection_in_mcp_scope, ensure_mcp_connection_sql_write_allowed,
+ ensure_mcp_execute_and_show_supported, ensure_mcp_mongo_pipeline_target_allowed_by_id,
ensure_mcp_sql_database_switch_allowed, mongo_filter_is_effectively_unbounded, mongo_pipeline_has_write_stage,
resolve_connection, resolve_mongo_database, resolve_mongo_target_values, write_port_file, AppState,
};
use dbx_core::models::connection::{ConnectionConfig, DatabaseType};
- use dbx_core::storage::{McpGlobalPolicy, Storage};
+ use dbx_core::storage::{McpConnectionPolicy, McpDatabasePolicy, McpDatabaseScope, McpGlobalPolicy, Storage};
use std::sync::Arc;
fn mysql_config(read_only: bool) -> ConnectionConfig {
@@ -446,6 +447,80 @@ mod tests {
assert!(ensure_connection_in_mcp_scope(&none, "conn-1").is_err());
}
+ #[test]
+ fn database_execution_policy_overrides_connection_and_global_defaults() {
+ let policy = McpGlobalPolicy {
+ read_only: false,
+ allow_dangerous_sql: false,
+ connection_policies: vec![McpConnectionPolicy {
+ connection_id: "conn-1".to_string(),
+ read_only: false,
+ allow_dangerous_sql: false,
+ execution_mode_configured: true,
+ execution_mode_policy_version: Some(dbx_core::mcp_policy::MCP_EXECUTION_POLICY_VERSION),
+ database_scope: McpDatabaseScope::Selected,
+ allowed_databases: vec!["aa".to_string(), "aaa".to_string()],
+ database_policies: vec![
+ McpDatabasePolicy { database_name: "aa".to_string(), read_only: false, allow_dangerous_sql: true },
+ McpDatabasePolicy { database_name: "aaa".to_string(), read_only: true, allow_dangerous_sql: false },
+ ],
+ }],
+ ..Default::default()
+ };
+
+ assert_eq!(effective_database_execution_policy(&policy, "conn-1", "aa"), (false, true));
+ assert_eq!(effective_database_execution_policy(&policy, "conn-1", "aaa"), (true, false));
+ assert_eq!(effective_database_execution_policy(&policy, "conn-1", "unconfigured"), (false, false));
+ }
+
+ #[tokio::test]
+ async fn database_execution_policy_blocks_cross_database_mongo_aggregate_output() {
+ let root = std::env::temp_dir().join(format!(
+ "dbx-mcp-bridge-database-policy-test-{}-{}",
+ std::process::id(),
+ uuid::Uuid::new_v4()
+ ));
+ std::fs::create_dir_all(&root).unwrap();
+ let storage = Storage::open(&root.join("storage.db")).await.unwrap();
+ let mut config = mysql_config(false);
+ config.id = "conn-1".to_string();
+ storage.save_connections(&[config]).await.unwrap();
+ storage
+ .save_mcp_global_policy(&McpGlobalPolicy {
+ connection_policies: vec![McpConnectionPolicy {
+ connection_id: "conn-1".to_string(),
+ read_only: false,
+ allow_dangerous_sql: true,
+ execution_mode_configured: true,
+ execution_mode_policy_version: Some(dbx_core::mcp_policy::MCP_EXECUTION_POLICY_VERSION),
+ database_scope: McpDatabaseScope::Selected,
+ allowed_databases: vec!["operations".to_string(), "reporting".to_string()],
+ database_policies: vec![McpDatabasePolicy {
+ database_name: "operations".to_string(),
+ read_only: false,
+ allow_dangerous_sql: true,
+ }],
+ }],
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ let state = Arc::new(AppState::new_with_plugin_dir(storage, root.join("plugins")));
+
+ let error = ensure_mcp_mongo_pipeline_target_allowed_by_id(
+ &state,
+ "conn-1",
+ "operations",
+ r#"[{"$merge":{"into":{"db":"reporting","coll":"archive"}}}]"#,
+ )
+ .await
+ .unwrap_err();
+ assert!(error.starts_with("DATABASE_EXECUTION_POLICY_OUT_OF_SCOPE:"), "{error}");
+
+ drop(state);
+ let _ = std::fs::remove_dir_all(root);
+ }
+
#[test]
fn mongo_aggregate_write_stages_are_detected_structurally() {
assert!(mongo_pipeline_has_write_stage(r#"[{"$match":{}},{"$out":"archive"}]"#));
@@ -586,15 +661,8 @@ fn ensure_database_in_mcp_scope(policy: &McpGlobalPolicy, connection_id: &str, d
}
}
-fn effective_connection_execution_policy(policy: &McpGlobalPolicy, connection_id: &str) -> (bool, bool) {
- let Some(rule) = policy
- .connection_policies
- .iter()
- .find(|rule| rule.connection_id == connection_id && rule.execution_mode_configured)
- else {
- return (policy.read_only, policy.allow_dangerous_sql);
- };
- (policy.read_only || rule.read_only, policy.allow_dangerous_sql && !rule.read_only && rule.allow_dangerous_sql)
+fn effective_database_execution_policy(policy: &McpGlobalPolicy, connection_id: &str, database: &str) -> (bool, bool) {
+ dbx_core::mcp_policy::effective_database_execution_policy(policy, connection_id, database)
}
async fn ensure_mcp_write_allowed(
@@ -616,9 +684,11 @@ async fn ensure_mcp_write_allowed_with_risk(
let policy = load_mcp_policy(state).await?;
ensure_connection_in_mcp_scope(&policy, &config.id)?;
ensure_database_in_mcp_scope(&policy, &config.id, database)?;
- let (read_only, allow_dangerous_sql) = effective_connection_execution_policy(&policy, &config.id);
+ let (read_only, allow_dangerous_sql) = effective_database_execution_policy(&policy, &config.id, database);
if read_only {
- return Err(format!("MCP_READ_ONLY: DBX MCP read-only mode is enabled. {action} blocked."));
+ return Err(format!(
+ "MCP_READ_ONLY: MCP execution permission for database '{database}' is read-only. {action} blocked."
+ ));
}
if dangerous && !allow_dangerous_sql {
return Err(format!("SQL_BLOCKED: High-risk operation '{action}' is disabled in DBX MCP settings."));
@@ -677,6 +747,7 @@ async fn ensure_mcp_mongo_pipeline_target_allowed_by_id(
) -> Result<(), String> {
let policy = load_mcp_policy(state).await?;
ensure_connection_in_mcp_scope(&policy, connection_id)?;
+ dbx_core::mcp_policy::ensure_mongo_database_execution_scope(&policy, connection_id, database, pipeline_json)?;
for target_database in mongo_pipeline_output_databases(pipeline_json, database)? {
ensure_database_in_mcp_scope(&policy, connection_id, &target_database)?;
}
@@ -694,31 +765,7 @@ async fn ensure_mcp_mongo_pipeline_target_allowed_by_id(
}
fn mongo_pipeline_output_databases(pipeline_json: &str, active_database: &str) -> Result<Vec<String>, String> {
- let stages = serde_json::from_str::<serde_json::Value>(pipeline_json)
- .ok()
- .and_then(|value| value.as_array().cloned())
- .ok_or_else(|| "QUERY_ERROR: MongoDB aggregate pipeline must be a JSON array.".to_string())?;
- let mut databases = Vec::new();
- for stage in stages {
- let Some(stage) = stage.as_object() else { continue };
- for key in ["$out", "$merge"] {
- let Some(target) = stage.get(key) else { continue };
- let database = match target {
- serde_json::Value::String(_) => active_database.to_string(),
- serde_json::Value::Object(target) => target
- .get("db")
- .or_else(|| {
- target.get("into").and_then(serde_json::Value::as_object).and_then(|into| into.get("db"))
- })
- .and_then(serde_json::Value::as_str)
- .unwrap_or(active_database)
- .to_string(),
- _ => return Err("QUERY_ERROR: MongoDB aggregate output target must be a string or object.".to_string()),
- };
- databases.push(database);
- }
- }
- Ok(databases)
+ dbx_core::mcp_policy::mongo_pipeline_output_databases(pipeline_json, active_database)
}
async fn ensure_mcp_write_allowed_by_id_with_risk(
@@ -1003,9 +1050,12 @@ async fn ensure_mcp_sql_allowed(
}
ensure_mcp_sql_database_switch_allowed(config.db_type, sql)?;
let is_write = dbx_core::query_execution_sql::is_write_sql_for_database(sql, config.db_type);
- let (read_only, allow_dangerous_sql) = effective_connection_execution_policy(&policy, &config.id);
+ dbx_core::mcp_policy::ensure_sql_database_execution_scope(&policy, config, database, sql)?;
+ let (read_only, allow_dangerous_sql) = effective_database_execution_policy(&policy, &config.id, database);
if read_only && is_write {
- return Err("MCP_READ_ONLY: DBX MCP read-only mode is enabled. SQL write blocked.".to_string());
+ return Err(format!(
+ "MCP_READ_ONLY: MCP execution permission for database '{database}' is read-only. SQL write blocked."
+ ));
}
if !allow_dangerous_sql && dbx_core::sql_risk::is_dangerous_sql_for_database(sql, config.db_type) {
return Err("SQL_BLOCKED: High-risk SQL is disabled in DBX MCP settings.".to_string());