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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(mcp): add resource group scopes with permission inheritance
二丫讲梵691ecd084bca
diff --git a/.github/workflows/notify.yml b/.github/workflows/notify.ymlindex 47e6d2359a..d8df7861f1 100644--- a/.github/workflows/notify.yml+++ b/.github/workflows/notify.yml@@ -195,7 +195,9 @@ jobs:PAYLOAD=$(jq -nc --arg msg "$MSG_CONTENT" \'{"umo": "default:GroupMessage:1087880322", "message": $msg}')- printf '%s' "$PAYLOAD" | ssh "root@${HOST}" "curl -fsS -X POST http://localhost:6185/api/v1/im/message \+ if ! printf '%s' "$PAYLOAD" | ssh "root@${HOST}" "curl -fsS -X POST http://localhost:6185/api/v1/im/message \-H 'Authorization: Bearer ${ASTRBOT_API_KEY}' \-H 'Content-Type: application/json' \- --data-binary @-"+ --data-binary @-"; then+ echo "::warning::QQ group notification failed; the event notification was sent to Feishu."+ fidiff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vueindex 1d818190c6..24264328ac 100644--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue@@ -10,8 +10,6 @@ import {Check,CheckCircle2,ChevronDown,- ChevronLeft,- ChevronRight,ChevronUp,CircleHelp,Cloud,@@ -96,6 +94,7 @@ import {type CustomThemeColors,type CustomTheme,type McpConnectionPolicy,+ type McpGroupPolicy,type ClickTableNavigationTarget,type SqlCompletionTriggerMode,SIDEBAR_INDENT_MIN,@@ -187,7 +186,7 @@ import { DEFAULT_SQL_SNIPPETS } from "@/lib/sql/sqlCompletion";import AiProviderLogo from "@/components/icons/AiProviderLogo.vue";import AppLogo from "@/components/icons/AppLogo.vue";import ChangelogPanel from "@/components/settings/ChangelogPanel.vue";-import McpConnectionScopePicker from "@/components/settings/McpConnectionScopePicker.vue";+import McpResourceScopePicker from "@/components/settings/McpResourceScopePicker.vue";import McpDatabaseScopePicker from "@/components/settings/McpDatabaseScopePicker.vue";import McpAuthorizationStepper from "@/components/settings/McpAuthorizationStepper.vue";import ScheduledDatabaseBackupSettings from "@/components/backup/ScheduledDatabaseBackupSettings.vue";@@ -213,6 +212,7 @@ import type { PromptTemplate } from "@/types/promptTemplate";import { GLOBAL_INSTRUCTIONS_MAX, PROMPT_TEMPLATE_CONTENT_MAX, PROMPT_TEMPLATE_NAME_MAX, promptTemplateCharacterCount } from "@/types/promptTemplate";import { METADATA_CACHE_HARD_MAX_MEMORY_MB, METADATA_CACHE_MIN_MEMORY_MB, normalizeMetadataCacheMemoryMb } from "@/lib/metadata/metadataRuntimeCache";import { databaseManifestEntry, manifestDatabaseTypes } from "@/lib/database/databaseDriverManifest";+import { buildConnectionGroupIdPathMap, connectionGroupDestinationRows, connectionIdsInGroups } from "@/lib/sidebar/sidebarLayout";const { t } = useI18n();const { toast } = useToast();@@ -2126,6 +2126,7 @@ async function exportDebugLogs() {type McpConfigTab = "claude" | "cursor" | "codebuddy" | "zcode" | "trae" | "vscode" | "windsurf" | "codex" | "deepseek-harness" | "opencode" | "pi" | "cherry-studio" | "qoder";type McpCopyKind = "install" | "uninstall" | "http-endpoint" | "http-token" | "http-config" | `${McpConfigTab}-config`;type McpTransportTab = "stdio" | "http";+type McpManagementTab = "access" | "permissions";const mcpStatus = ref<McpServerStatus | null>(null);const mcpStatusLoading = ref(false);@@ -2133,6 +2134,7 @@ const mcpStatusError = ref("");const mcpCopied = ref<"" | McpCopyKind>("");const mcpConfigTab = ref<McpConfigTab>("claude");const mcpTransportTab = ref<McpTransportTab>("stdio");+const mcpManagementTab = ref<McpManagementTab>("access");const mcpHttpSettings = ref<McpHttpServerSettings>({enabled: false,host: "127.0.0.1",@@ -2162,6 +2164,7 @@ const mcpInstallError = ref(false);const mcpExecutionMode = computed(() => mcpExecutionModeFromPolicy(settingsStore.mcpGlobalPolicy));const mcpExecutionModeOptions: McpExecutionMode[] = ["read_only", "safe_write", "high_risk_write"];const mcpAllowedConnectionIds = computed(() => settingsStore.mcpGlobalPolicy.allowedConnectionIds);+const mcpAllowedGroupIds = computed(() => settingsStore.mcpGlobalPolicy.allowedGroupIds);const mcpQueryTimeoutInput = ref<string>(settingsStore.mcpGlobalPolicy.queryTimeoutSecs === null ? "" : String(settingsStore.mcpGlobalPolicy.queryTimeoutSecs));watch(@@ -2188,6 +2191,13 @@ function onMcpQueryTimeoutInput() {void saveMcpPolicy({ queryTimeoutSecs: parsed });}const mcpSelectableConnections = computed(() => connectionStore.connections);+const mcpGroupRows = computed(() => connectionGroupDestinationRows(connectionStore.sidebarLayout));+const mcpConnectionGroupIdPaths = computed(() => buildConnectionGroupIdPathMap(connectionStore.sidebarLayout));+const mcpConnectionsInheritedFromGroups = computed(() => new Set(connectionIdsInGroups(connectionStore.sidebarLayout, mcpAllowedGroupIds.value)));+const mcpEffectiveAllowedConnectionIds = computed(() => {+ if (mcpAllowedConnectionIds.value === null) return null;+ return [...new Set([...mcpAllowedConnectionIds.value, ...mcpConnectionsInheritedFromGroups.value])];+});const mcpPolicyControlsDisabled = computed(() =>isMcpPolicyMutationBlocked({loading: mcpPolicyLoading.value,@@ -2237,6 +2247,7 @@ async function saveMcpPolicy(partial: {readOnly?: boolean;allowDangerousSql?: boolean;allowedConnectionIds?: string[] | null;+ allowedGroupIds?: string[];allowedToolNames?: string[] | null;connectionPolicies?: {connectionId: string;@@ -2248,6 +2259,7 @@ async function saveMcpPolicy(partial: {allowedDatabases: string[];databasePolicies: { databaseName: string; readOnly: boolean; allowDangerousSql: boolean }[];}[];+ groupPolicies?: McpGroupPolicy[];queryTimeoutSecs?: number | null;}) {if (mcpPolicyControlsDisabled.value) return;@@ -2289,8 +2301,8 @@ function onMcpExecutionModeKeydown(event: KeyboardEvent, mode: McpExecutionMode)onMcpExecutionModeChange(nextMode);}-function onMcpAllowedConnectionIdsChange(allowedConnectionIds: string[] | null) {- void saveMcpPolicy({ allowedConnectionIds });+function onMcpResourceScopeChange(scope: { allowedGroupIds: string[]; allowedConnectionIds: string[] | null }) {+ void saveMcpPolicy(scope);}type McpConnectionExecutionMode = "read_only" | "safe_write" | "high_risk_write";@@ -2328,28 +2340,9 @@ function onMcpToolAllowedChange(name: string, allowed: boolean) {}const mcpConnectionPolicyConnections = computed(() => {- const allowed = mcpAllowedConnectionIds.value;+ const allowed = mcpEffectiveAllowedConnectionIds.value;return allowed === null ? mcpSelectableConnections.value : mcpSelectableConnections.value.filter((connection) => allowed.includes(connection.id));});-const MCP_CONNECTION_POLICY_PAGE_SIZE_OPTIONS = [6, 10, 20] as const;-const mcpConnectionPolicyPageSize = ref<number>(MCP_CONNECTION_POLICY_PAGE_SIZE_OPTIONS[0]);-const mcpConnectionPolicyPage = ref(1);-const mcpConnectionPolicyPageCount = computed(() => Math.max(1, Math.ceil(mcpConnectionPolicyConnections.value.length / mcpConnectionPolicyPageSize.value)));-const pagedMcpConnectionPolicyConnections = computed(() => {- const start = (mcpConnectionPolicyPage.value - 1) * mcpConnectionPolicyPageSize.value;- return mcpConnectionPolicyConnections.value.slice(start, start + mcpConnectionPolicyPageSize.value);-});--function setMcpConnectionPolicyPage(page: number) {- mcpConnectionPolicyPage.value = Math.min(Math.max(1, page), mcpConnectionPolicyPageCount.value);-}--watch(mcpConnectionPolicyPageSize, () => {- mcpConnectionPolicyPage.value = 1;-});--watch(mcpConnectionPolicyPageCount, () => setMcpConnectionPolicyPage(mcpConnectionPolicyPage.value));-function mcpConnectionExecutionMode(connectionId: string): McpConnectionExecutionMode | "inherit" {const rule = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId);if (!rule || !rule.executionModeConfigured) return "inherit";@@ -2357,14 +2350,39 @@ function mcpConnectionExecutionMode(connectionId: string): McpConnectionExecutioreturn rule.allowDangerousSql ? "high_risk_write" : "safe_write";}+function mcpGroupExecutionMode(groupId: string): McpConnectionExecutionMode | "inherit" {+ const rule = settingsStore.mcpGlobalPolicy.groupPolicies.find((item) => item.groupId === groupId);+ if (!rule) return "inherit";+ if (rule.readOnly) return "read_only";+ return rule.allowDangerousSql ? "high_risk_write" : "safe_write";+}++function mcpInheritedGroupPolicy(connectionId: string): { mode: McpConnectionExecutionMode | "inherit"; source: string } {+ const path = mcpConnectionGroupIdPaths.value.get(connectionId) ?? [];+ for (let index = path.length - 1; index >= 0; index -= 1) {+ const mode = mcpGroupExecutionMode(path[index]);+ if (mode !== "inherit") {+ const group = mcpGroupRows.value.find((item) => item.id === path[index]);+ return { mode, source: group?.path.join(" / ") ?? path[index] };+ }+ }+ return { mode: "inherit", source: "" };+}++function mcpInheritedGroupExecutionMode(connectionId: string): McpConnectionExecutionMode | "inherit" {+ return mcpInheritedGroupPolicy(connectionId).mode;+}+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 groupMode = mcpInheritedGroupExecutionMode(policy.connectionId);+ const inheritedMode = groupMode === "inherit" ? mcpExecutionMode.value : groupMode;+ const legacyMode = connectionMode === "inherit" ? inheritedMode : connectionMode;+ const effectiveMode = mcpExecutionModeRank(legacyMode) < mcpExecutionModeRank(inheritedMode) ? legacyMode : inheritedMode;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;@@ -2386,8 +2404,15 @@ 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;+function mcpEffectiveExecutionMode(groupMode: McpConnectionExecutionMode | "inherit", connectionMode: McpConnectionExecutionMode | "inherit", databaseMode: McpConnectionExecutionMode | "inherit"): McpConnectionExecutionMode {+ return databaseMode !== "inherit" ? databaseMode : connectionMode !== "inherit" ? connectionMode : groupMode !== "inherit" ? groupMode : mcpExecutionMode.value;+}++function mcpPermissionSource(row: { databaseMode: McpConnectionExecutionMode | "inherit"; connectionMode: McpConnectionExecutionMode | "inherit"; groupMode: McpConnectionExecutionMode | "inherit"; groupSource: string }): string {+ if (row.databaseMode !== "inherit") return t("settings.mcpPermissionSourceDatabase");+ if (row.connectionMode !== "inherit") return t("settings.mcpPermissionSourceConnection");+ if (row.groupMode !== "inherit") return t("settings.mcpPermissionSourceGroup", { group: row.groupSource });+ return t("settings.mcpPermissionSourceGlobal");}const mcpPermissionPreviewSearchQuery = ref("");@@ -2395,17 +2420,22 @@ const mcpPermissionPreviewRows = computed(() =>mcpConnectionPolicyConnections.value.flatMap((connection) => {const rule = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connection.id);const connectionMode = mcpConnectionExecutionMode(connection.id);+ const groupPolicy = mcpInheritedGroupPolicy(connection.id);+ const groupMode = groupPolicy.mode;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 {+ connectionId: connection.id,connection: connection.name,database,+ groupMode,+ groupSource: groupPolicy.source,connectionMode,databaseMode,- effectiveMode: mcpEffectiveExecutionMode(connectionMode, databaseMode),+ effectiveMode: mcpEffectiveExecutionMode(groupMode, connectionMode, databaseMode),};});}),@@ -2413,10 +2443,24 @@ const mcpPermissionPreviewRows = computed(() =>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)));+ return mcpPermissionPreviewRows.value.filter((row) => [row.connection, row.database, row.groupSource].some((value) => value.toLocaleLowerCase().includes(query)));});+function onMcpGroupExecutionModeChange(groupId: string, mode: McpConnectionExecutionMode | "inherit") {+ if (mode === "high_risk_write" && !window.confirm(t("settings.mcpGroupPolicyHighRiskConfirm"))) return;+ const groupPolicies = settingsStore.mcpGlobalPolicy.groupPolicies.filter((item) => item.groupId !== groupId);+ if (mode !== "inherit") {+ groupPolicies.push({+ groupId,+ readOnly: mode === "read_only",+ allowDangerousSql: mode === "high_risk_write",+ });+ }+ void saveMcpPolicy({ groupPolicies });+}+function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConnectionExecutionMode | "inherit") {+ if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) return;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;@@ -2439,7 +2483,27 @@ function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConneallowedDatabases: existing?.allowedDatabases ?? [],databasePolicies: selectedMode.databasePolicies,};- if (next.executionModeConfigured || next.databaseScope !== "all") rules.push(next);+ if (next.executionModeConfigured || next.databaseScope !== "all" || next.databasePolicies.length > 0) rules.push(next);+ void saveMcpPolicy({ connectionPolicies: rules });+}++function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: string, mode: McpConnectionExecutionMode | "inherit") {+ if (mode === "high_risk_write" && !window.confirm(t("settings.mcpDatabasePolicyHighRiskConfirm"))) return;+ const existing = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId);+ if (!existing || existing.databaseScope !== "selected" || !existing.allowedDatabases.includes(databaseName)) return;+ const migrated = existing.executionModePolicyVersion === 1 ? null : migrateLegacyMcpConnectionPolicy(existing);+ const databasePolicies = (migrated?.databasePolicies ?? existing.databasePolicies).filter((policy) => policy.databaseName !== databaseName);+ if (mode !== "inherit") {+ databasePolicies.push({ databaseName, readOnly: mode === "read_only", allowDangerousSql: mode === "high_risk_write" });+ }+ const next = {+ ...existing,+ ...(migrated ?? {}),+ executionModePolicyVersion: 1,+ databasePolicies,+ };+ const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId);+ if (next.executionModeConfigured || next.databaseScope !== "all" || next.databasePolicies.length > 0) rules.push(next);void saveMcpPolicy({ connectionPolicies: rules });}@@ -7822,7 +7886,7 @@ LIMIT 100;</pre</section><section v-else-if="activeSettingsTab === 'mcp'" data-settings-search-id="mcp" :class="['flex flex-col gap-5 py-2', settingsSearchTargetClass('mcp')]">- <div class="rounded-md border bg-muted/20 p-4">+ <div class="rounded-lg border border-border/70 bg-card/70 p-4 shadow-[0_1px_2px_hsl(var(--foreground)/0.04)]"><div class="flex items-start justify-between gap-4"><div class="min-w-0 space-y-2"><div class="flex items-center gap-2">@@ -7833,7 +7897,12 @@ LIMIT 100;</pre</HelpTooltip></div></div>- <Badge v-if="!isWeb" variant="outline" class="shrink-0 rounded-md" :class="mcpStatusTone === 'ok' ? 'border-green-500/40 text-green-600 dark:text-green-400' : mcpStatusTone === 'warning' ? 'border-amber-500/40 text-amber-600 dark:text-amber-400' : 'text-muted-foreground'">+ <Badge+ v-if="!isWeb && mcpManagementTab === 'access' && mcpTransportTab === 'stdio'"+ variant="outline"+ class="shrink-0 rounded-md"+ :class="mcpStatusTone === 'ok' ? 'border-green-500/40 text-green-600 dark:text-green-400' : mcpStatusTone === 'warning' ? 'border-amber-500/40 text-amber-600 dark:text-amber-400' : 'text-muted-foreground'"+ ><Loader2 v-if="mcpStatusLoading" class="mr-1 h-3 w-3 animate-spin" /><CheckCircle2 v-else-if="mcpStatusTone === 'ok'" class="mr-1 h-3 w-3" /><AlertTriangle v-else-if="mcpStatusTone === 'warning'" class="mr-1 h-3 w-3" />@@ -7842,489 +7911,368 @@ LIMIT 100;</pre</div></div>- <Tabs v-model="mcpTransportTab" class="space-y-3">+ <Tabs v-model="mcpManagementTab" class="space-y-4"><TabsList class="grid h-9 w-full grid-cols-2">- <TabsTrigger value="stdio">{{ t("settings.mcpTransportLocalStdio") }}</TabsTrigger>- <TabsTrigger value="http">{{ t("settings.mcpTransportHttpService") }}</TabsTrigger>+ <TabsTrigger value="access">{{ t("settings.mcpManagementAccess") }}</TabsTrigger>+ <TabsTrigger value="permissions">{{ t("settings.mcpManagementPermissions") }}</TabsTrigger></TabsList>- </Tabs>-- <div v-if="isWeb && mcpTransportTab === 'http'" class="space-y-4">- <div class="rounded-md border bg-muted/20 p-4 space-y-2">- <div class="flex items-center justify-between gap-3">- <Label class="text-base">{{ t("settings.mcpHttpWebServiceTitle") }}</Label>- <Badge :variant="webMcpHttpStatus?.enabled ? 'default' : 'outline'">{{ webMcpHttpStatus?.enabled ? t("settings.mcpHttpStatusLabelEnabled") : t("settings.mcpHttpStatusLabelDisabled") }}</Badge>- </div>- <p class="text-xs text-muted-foreground">{{ t("settings.mcpHttpWebServiceDescription") }}</p>- <template v-if="webMcpHttpStatus">- <code class="block rounded border bg-background px-2 py-1.5 text-xs">{{ webMcpEndpoint }}</code>- <p class="text-[11px] text-muted-foreground">- {{- t("settings.mcpHttpWebTokenSourceAndHosts", {- tokenSource: webMcpHttpStatus.tokenSource || t("settings.mcpHttpNotConfigured"),- hosts: webMcpHttpStatus.allowedHosts.join(", ") || t("settings.mcpHttpNotConfigured"),- })- }}- </p>- <p v-if="webMcpHttpStatus.allowedOrigins.length" class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpWebAllowedOrigins", { origins: webMcpHttpStatus.allowedOrigins.join(", ") }) }}</p>- </template>- <Button type="button" variant="outline" size="sm" :disabled="mcpHttpLoading" @click="loadMcpHttpSettings">{{ t("settings.mcpHttpReloadStatus") }}</Button>- </div>- </div>-- <div v-if="!isWeb && mcpTransportTab === 'http'" class="space-y-4">- <div class="rounded-md border bg-muted/20 p-4">- <div class="flex items-start justify-between gap-4">- <div class="space-y-1">- <div class="flex items-center gap-2">- <Label class="text-base">{{ t("settings.mcpHttpServiceTitle") }}</Label>- <Badge :variant="mcpHttpStatus?.running ? 'default' : 'outline'">- {{ mcpHttpStatus?.running ? t("settings.mcpHttpStatusLabelRunning") : mcpHttpSettings.enabled ? t("settings.mcpHttpStatusLabelPending") : t("settings.mcpHttpStatusLabelDisabled") }}- </Badge>- </div>- <p class="text-xs leading-relaxed text-muted-foreground">{{ t("settings.mcpHttpServiceDescription") }}</p>- </div>- <Switch id="mcp-http-enabled" v-model="mcpHttpSettings.enabled" :disabled="mcpHttpLoading || mcpHttpSaving" />- </div>- </div>- <template v-if="mcpHttpSettings.enabled">- <section class="space-y-3 rounded-md border p-4">- <div>- <h4 class="text-sm font-medium">{{ t("settings.mcpHttpListenerTitle") }}</h4>- <p class="mt-1 text-xs text-muted-foreground">{{ t("settings.mcpHttpListenerHintPrefix") }}<code>127.0.0.1</code>{{ t("settings.mcpHttpListenerHintSuffix") }}</p>- </div>- <div class="grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(9rem,0.42fr)]">- <div class="space-y-1.5">- <Label for="mcp-http-host">{{ t("settings.mcpHttpHostLabel") }}</Label>- <Input id="mcp-http-host" v-model="mcpHttpSettings.host" :disabled="mcpHttpSaving" placeholder="127.0.0.1" />- </div>- <div class="space-y-1.5">- <Label for="mcp-http-port">{{ t("settings.mcpHttpPortLabel") }}</Label>- <Input id="mcp-http-port" v-model.number="mcpHttpSettings.port" :disabled="mcpHttpSaving" type="number" min="1" max="65535" />- </div>- <div class="space-y-1.5 sm:col-span-2">- <Label for="mcp-http-path">{{ t("settings.mcpHttpPathLabel") }}</Label>- <Input id="mcp-http-path" v-model="mcpHttpSettings.path" :disabled="mcpHttpSaving" placeholder="/mcp" />+ <TabsContent value="access" class="m-0 space-y-6">+ <div class="border-b border-border/60 pb-2 sm:ml-1">+ <div class="mb-2 flex items-center gap-2">+ <div class="min-w-0">+ <p class="text-sm font-semibold text-foreground">{{ t("settings.mcpTransportLabel") }}</p></div></div>- </section>-- <section class="space-y-3 rounded-md border p-4">- <div class="flex items-start justify-between gap-4">- <div>- <h4 class="text-sm font-medium">{{ t("settings.mcpHttpRemoteTitle") }}</h4>- <p class="mt-1 text-xs leading-relaxed text-muted-foreground">{{ t("settings.mcpHttpRemoteHintPrefix") }}<code>127.0.0.1</code>{{ t("settings.mcpHttpRemoteHintMiddle") }}<code>::1</code>{{ t("settings.mcpHttpRemoteHintSuffix") }}</p>- </div>- <Switch id="mcp-http-remote" v-model="mcpHttpSettings.allowRemote" :disabled="mcpHttpSaving" />- </div>- <div v-if="mcpHttpSettings.allowRemote" class="grid gap-3 sm:grid-cols-2">- <div class="space-y-1.5">- <Label for="mcp-http-hosts">{{ t("settings.mcpHttpAllowedHostsLabel") }}</Label>- <textarea id="mcp-http-hosts" v-model="mcpHttpAllowedHostsText" :disabled="mcpHttpSaving" class="min-h-20 w-full rounded-md border bg-background px-3 py-2 font-mono text-xs" placeholder="mcp.example.com 10.0.0.10" />- <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpHostsHint") }}</p>- </div>- <div class="space-y-1.5">- <Label for="mcp-http-origins">{{ t("settings.mcpHttpAllowedOriginsLabel") }}</Label>- <textarea id="mcp-http-origins" v-model="mcpHttpAllowedOriginsText" :disabled="mcpHttpSaving" class="min-h-20 w-full rounded-md border bg-background px-3 py-2 font-mono text-xs" placeholder="https://mcp.example.com" />- <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpOriginsHintPrefix") }}<code>https://</code>{{ t("settings.mcpHttpOriginsHintSuffix") }}</p>- </div>- </div>- <p v-else class="rounded bg-muted px-3 py-2 text-xs text-muted-foreground">{{ t("settings.mcpHttpRemoteDisabledHint") }}</p>- </section>-- <div v-if="mcpHttpDraftValidationError" class="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">- {{ mcpHttpDraftValidationError }}- </div>- <div v-if="mcpHttpError" class="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">- {{ mcpHttpError }}- </div>-- <div class="flex flex-col gap-3 rounded-md border bg-muted/20 p-3 sm:flex-row sm:items-center sm:justify-between">- <p class="text-xs text-muted-foreground">- {{ mcpHttpHasUnsavedChanges ? t("settings.mcpHttpUnsavedChangesHint") : t("settings.mcpHttpSaveHint") }}- </p>- <div class="flex shrink-0 justify-end gap-2">- <Button type="button" variant="outline" :disabled="mcpHttpLoading || mcpHttpSaving" @click="loadMcpHttpSettings">{{ t("settings.mcpHttpReload") }}</Button>- <Button type="button" :disabled="mcpHttpLoading || mcpHttpSaving || Boolean(mcpHttpDraftValidationError)" @click="saveMcpHttpSettings">- <Loader2 v-if="mcpHttpSaving" class="mr-2 h-4 w-4 animate-spin" />- {{ t("settings.mcpHttpSaveAndStart") }}- </Button>- </div>- </div>- </template>-- <div v-else class="flex flex-col gap-3 rounded-md border border-dashed px-4 py-3 text-xs text-muted-foreground sm:flex-row sm:items-center sm:justify-between">- <p>{{ t("settings.mcpHttpDisabledHint") }}</p>- <div class="flex shrink-0 justify-end gap-2">- <Button type="button" variant="outline" :disabled="mcpHttpLoading || mcpHttpSaving" @click="loadMcpHttpSettings">{{ t("settings.mcpHttpReload") }}</Button>- <Button type="button" :disabled="mcpHttpLoading || mcpHttpSaving" @click="saveMcpHttpSettings">- <Loader2 v-if="mcpHttpSaving" class="mr-2 h-4 w-4 animate-spin" />- {{ t("settings.mcpHttpSaveAndStop") }}- </Button>- </div>- </div>-- <div v-if="mcpHttpStatus?.lastError" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">- {{ mcpHttpStatus.lastError }}- </div>+ <Tabs v-model="mcpTransportTab" class="space-y-3">+ <TabsList variant="line" class="h-8 w-fit justify-start gap-1 border-b border-border/60 bg-transparent p-0">+ <TabsTrigger value="stdio" class="flex-none px-3">{{ t("settings.mcpTransportLocalStdio") }}</TabsTrigger>+ <TabsTrigger value="http" class="flex-none px-3">{{ t("settings.mcpTransportHttpService") }}</TabsTrigger>+ </TabsList>+ <TabsContent value="http" class="m-0 space-y-4">+ <div v-if="isWeb" class="space-y-4">+ <div class="rounded-md border bg-muted/20 p-4 space-y-2">+ <div class="flex items-center justify-between gap-3">+ <Label class="text-base">{{ t("settings.mcpHttpWebServiceTitle") }}</Label>+ <Badge :variant="webMcpHttpStatus?.enabled ? 'default' : 'outline'">{{ webMcpHttpStatus?.enabled ? t("settings.mcpHttpStatusLabelEnabled") : t("settings.mcpHttpStatusLabelDisabled") }}</Badge>+ </div>+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpHttpWebServiceDescription") }}</p>+ <template v-if="webMcpHttpStatus">+ <code class="block rounded border bg-background px-2 py-1.5 text-xs">{{ webMcpEndpoint }}</code>+ <p class="text-[11px] text-muted-foreground">+ {{+ t("settings.mcpHttpWebTokenSourceAndHosts", {+ tokenSource: webMcpHttpStatus.tokenSource || t("settings.mcpHttpNotConfigured"),+ hosts: webMcpHttpStatus.allowedHosts.join(", ") || t("settings.mcpHttpNotConfigured"),+ })+ }}+ </p>+ <p v-if="webMcpHttpStatus.allowedOrigins.length" class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpWebAllowedOrigins", { origins: webMcpHttpStatus.allowedOrigins.join(", ") }) }}</p>+ </template>+ <Button type="button" variant="outline" size="sm" :disabled="mcpHttpLoading" @click="loadMcpHttpSettings">{{ t("settings.mcpHttpReloadStatus") }}</Button>+ </div>+ </div>- <section v-if="mcpHttpStatus?.enabled" class="space-y-3 rounded-md border p-4">- <div class="flex flex-wrap items-center justify-between gap-2">- <div class="flex items-center gap-2 text-sm font-medium">- <span class="h-2 w-2 rounded-full" :class="mcpHttpStatus.running ? 'bg-green-500' : 'bg-amber-500'" />- {{ mcpHttpStatus.running ? t("settings.mcpHttpConnectionInfoTitle") : t("settings.mcpHttpServiceNotRunning") }}- </div>- <Badge variant="outline" class="font-normal">{{ mcpHttpStatus.running ? t("settings.mcpHttpRunningConfigBadge") : t("settings.mcpHttpLastStatusBadge") }}</Badge>- </div>- <p v-if="mcpHttpHasUnsavedChanges" class="rounded bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200">{{ t("settings.mcpHttpRunningDraftDiffersHint") }}</p>- <div v-if="mcpHttpStatus.endpoint" class="space-y-1">- <Label>{{ t("settings.mcpHttpEndpointLabel") }}</Label>- <div class="flex min-w-0 items-center gap-2">- <code class="min-w-0 flex-1 overflow-x-auto rounded border bg-background px-2 py-1.5 text-xs">{{ mcpHttpStatus.endpoint }}</code>- <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('http-endpoint', mcpHttpStatus.endpoint || '')">- <CheckCircle2 v-if="mcpCopied === 'http-endpoint'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>- </div>- </div>- <div v-if="mcpHttpStatus.accessToken" class="space-y-1">- <div class="flex items-center justify-between gap-3">- <Label>Bearer Token</Label>- <Button type="button" variant="outline" size="sm" :disabled="mcpHttpSaving" @click="rotateMcpHttpToken">{{ t("settings.mcpHttpRotateToken") }}</Button>- </div>- <div class="flex min-w-0 items-center gap-2">- <code class="min-w-0 flex-1 overflow-x-auto rounded border bg-background px-2 py-1.5 text-xs">{{ mcpHttpStatus.accessToken }}</code>- <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('http-token', mcpHttpStatus.accessToken || '')">- <CheckCircle2 v-if="mcpCopied === 'http-token'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>- </div>- <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpTokenHintPrefix") }}<code>Authorization: Bearer</code>{{ t("settings.mcpHttpTokenHintSuffix") }}</p>- </div>- <details v-if="mcpHttpClientConfig" class="rounded border bg-muted/20 p-3 text-xs">- <summary class="cursor-pointer font-medium">{{ t("settings.mcpHttpClientConfigTitle") }}</summary>- <div class="mt-3 space-y-2">- <div class="flex justify-end">- <Button type="button" variant="outline" size="sm" :title="t('common.copy')" @click="copyMcpText('http-config', mcpHttpClientConfig)">- <CheckCircle2 v-if="mcpCopied === 'http-config'" class="mr-1 h-3.5 w-3.5 text-green-500" />- <Copy v-else class="mr-1 h-3.5 w-3.5" />- {{ t("common.copy") }}- </Button>- </div>- <pre class="max-h-48 overflow-auto rounded border bg-background p-2 text-[11px] whitespace-pre-wrap">{{ mcpHttpClientConfig }}</pre>- <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpClientConfigHint") }}</p>- </div>- </details>- <details v-if="mcpHttpStatus.recentLogs.length" class="text-xs">- <summary class="cursor-pointer text-muted-foreground">{{ t("settings.mcpHttpLogsTitle") }}</summary>- <pre class="mt-2 max-h-40 overflow-auto rounded border bg-background p-2 text-[11px] whitespace-pre-wrap">{{ mcpHttpStatus.recentLogs.join("\n") }}</pre>- </details>- </section>- </div>+ <div v-if="!isWeb" class="space-y-4">+ <div class="rounded-md border bg-muted/20 p-4">+ <div class="flex items-start justify-between gap-4">+ <div class="space-y-1">+ <div class="flex items-center gap-2">+ <Label class="text-base">{{ t("settings.mcpHttpServiceTitle") }}</Label>+ <Badge :variant="mcpHttpStatus?.running ? 'default' : 'outline'">+ {{ mcpHttpStatus?.running ? t("settings.mcpHttpStatusLabelRunning") : mcpHttpSettings.enabled ? t("settings.mcpHttpStatusLabelPending") : t("settings.mcpHttpStatusLabelDisabled") }}+ </Badge>+ </div>+ <p class="text-xs leading-relaxed text-muted-foreground">{{ t("settings.mcpHttpServiceDescription") }}</p>+ </div>+ <Switch id="mcp-http-enabled" v-model="mcpHttpSettings.enabled" :disabled="mcpHttpLoading || mcpHttpSaving" />+ </div>+ </div>- <template v-if="mcpTransportTab === 'stdio'">- <div v-if="!isWeb" class="grid gap-3 sm:grid-cols-2">- <div class="rounded-md border p-3">- <div class="text-xs font-medium uppercase text-muted-foreground">- {{ t("settings.mcpCurrent") }}- </div>- <div class="mt-2 font-mono text-sm">- {{ mcpStatus?.current_version ? `v${mcpStatus.current_version}` : t("settings.mcpVersionMissing") }}- </div>- </div>- <div class="rounded-md border p-3">- <div class="text-xs font-medium uppercase text-muted-foreground">- {{ t("settings.mcpLatest") }}- </div>- <div class="mt-2 font-mono text-sm">- {{ mcpStatus?.latest_version ? `v${mcpStatus.latest_version}` : t("settings.mcpVersionUnknown") }}- </div>- </div>- <div class="rounded-md border p-3">- <div class="text-xs font-medium uppercase text-muted-foreground">Node.js</div>- <div class="mt-2 font-mono text-sm">- {{ mcpStatus?.node_version || t("settings.mcpVersionUnknown") }}- </div>- </div>- <div class="rounded-md border p-3">- <div class="text-xs font-medium uppercase text-muted-foreground">npm</div>- <div class="mt-2 font-mono text-sm">- {{ mcpStatus?.npm_available ? t("settings.mcpAvailable") : t("settings.mcpUnavailable") }}- </div>- </div>- </div>+ <template v-if="mcpHttpSettings.enabled">+ <section class="space-y-3 rounded-md border p-4">+ <div>+ <h4 class="text-sm font-medium">{{ t("settings.mcpHttpListenerTitle") }}</h4>+ <p class="mt-1 text-xs text-muted-foreground">{{ t("settings.mcpHttpListenerHintPrefix") }}<code>127.0.0.1</code>{{ t("settings.mcpHttpListenerHintSuffix") }}</p>+ </div>+ <div class="grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(9rem,0.42fr)]">+ <div class="space-y-1.5">+ <Label for="mcp-http-host">{{ t("settings.mcpHttpHostLabel") }}</Label>+ <Input id="mcp-http-host" v-model="mcpHttpSettings.host" :disabled="mcpHttpSaving" placeholder="127.0.0.1" />+ </div>+ <div class="space-y-1.5">+ <Label for="mcp-http-port">{{ t("settings.mcpHttpPortLabel") }}</Label>+ <Input id="mcp-http-port" v-model.number="mcpHttpSettings.port" :disabled="mcpHttpSaving" type="number" min="1" max="65535" />+ </div>+ <div class="space-y-1.5 sm:col-span-2">+ <Label for="mcp-http-path">{{ t("settings.mcpHttpPathLabel") }}</Label>+ <Input id="mcp-http-path" v-model="mcpHttpSettings.path" :disabled="mcpHttpSaving" placeholder="/mcp" />+ </div>+ </div>+ </section>++ <section class="space-y-3 rounded-md border p-4">+ <div class="flex items-start justify-between gap-4">+ <div>+ <h4 class="text-sm font-medium">{{ t("settings.mcpHttpRemoteTitle") }}</h4>+ <p class="mt-1 text-xs leading-relaxed text-muted-foreground">{{ t("settings.mcpHttpRemoteHintPrefix") }}<code>127.0.0.1</code>{{ t("settings.mcpHttpRemoteHintMiddle") }}<code>::1</code>{{ t("settings.mcpHttpRemoteHintSuffix") }}</p>+ </div>+ <Switch id="mcp-http-remote" v-model="mcpHttpSettings.allowRemote" :disabled="mcpHttpSaving" />+ </div>+ <div v-if="mcpHttpSettings.allowRemote" class="grid gap-3 sm:grid-cols-2">+ <div class="space-y-1.5">+ <Label for="mcp-http-hosts">{{ t("settings.mcpHttpAllowedHostsLabel") }}</Label>+ <textarea id="mcp-http-hosts" v-model="mcpHttpAllowedHostsText" :disabled="mcpHttpSaving" class="min-h-20 w-full rounded-md border bg-background px-3 py-2 font-mono text-xs" placeholder="mcp.example.com 10.0.0.10" />+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpHostsHint") }}</p>+ </div>+ <div class="space-y-1.5">+ <Label for="mcp-http-origins">{{ t("settings.mcpHttpAllowedOriginsLabel") }}</Label>+ <textarea id="mcp-http-origins" v-model="mcpHttpAllowedOriginsText" :disabled="mcpHttpSaving" class="min-h-20 w-full rounded-md border bg-background px-3 py-2 font-mono text-xs" placeholder="https://mcp.example.com" />+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpOriginsHintPrefix") }}<code>https://</code>{{ t("settings.mcpHttpOriginsHintSuffix") }}</p>+ </div>+ </div>+ <p v-else class="rounded bg-muted px-3 py-2 text-xs text-muted-foreground">{{ t("settings.mcpHttpRemoteDisabledHint") }}</p>+ </section>- <div v-if="mcpStatus?.bin_path" class="space-y-2">- <Label>{{ t("settings.mcpBinPath") }}</Label>- <div class="rounded-md border bg-muted/20 px-3 py-2 font-mono text-xs text-muted-foreground">- {{ mcpStatus.bin_path }}- </div>- </div>+ <div v-if="mcpHttpDraftValidationError" class="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">+ {{ mcpHttpDraftValidationError }}+ </div>+ <div v-if="mcpHttpError" class="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">+ {{ mcpHttpError }}+ </div>- <div v-if="!isWeb" class="space-y-2">- <Label>{{ mcpStatus?.installed ? t("settings.mcpUpdateCommand") : t("settings.mcpInstallCommand") }}</Label>- <div class="flex min-w-0 items-center gap-2">- <div class="min-w-0 flex-1 overflow-x-auto rounded-md border bg-background px-3 py-2 font-mono text-xs whitespace-nowrap">- {{ mcpCommand }}- </div>- <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('install', mcpCommand)">- <CheckCircle2 v-if="mcpCopied === 'install'" class="h-4 w-4 text-green-500" />- <Copy v-else class="h-4 w-4" />- </Button>- <Button type="button" variant="default" :disabled="mcpInstalling || mcpUninstalling || !mcpStatus?.npm_available || (mcpStatus?.installed && !mcpStatus?.update_available)" @click="installMcp">- <Loader2 v-if="mcpInstalling" class="mr-2 h-4 w-4 animate-spin" />- <CheckCircle2 v-if="!mcpInstalling && mcpStatus?.installed && !mcpStatus?.update_available" class="mr-2 h-4 w-4" />- {{ mcpInstalling ? t("settings.mcpInstalling") : !mcpStatus?.installed ? t("settings.mcpInstallButton") : mcpStatus?.update_available ? t("settings.mcpUpdateButton") : t("settings.mcpUpToDate") }}- </Button>- </div>- <div- v-if="mcpInstallMessage"- :class="['text-xs px-3 py-2 rounded-md border', mcpInstallError ? 'bg-red-50 text-red-700 border-red-200 dark:bg-red-950/30 dark:text-red-300 dark:border-red-800' : 'bg-green-50 text-green-700 border-green-200 dark:bg-green-950/30 dark:text-green-300 dark:border-green-800']"- >- {{ mcpInstallMessage }}- </div>- </div>+ <div class="flex flex-col gap-3 rounded-md border bg-muted/20 p-3 sm:flex-row sm:items-center sm:justify-between">+ <p class="text-xs text-muted-foreground">+ {{ mcpHttpHasUnsavedChanges ? t("settings.mcpHttpUnsavedChangesHint") : t("settings.mcpHttpSaveHint") }}+ </p>+ <div class="flex shrink-0 justify-end gap-2">+ <Button type="button" variant="outline" :disabled="mcpHttpLoading || mcpHttpSaving" @click="loadMcpHttpSettings">{{ t("settings.mcpHttpReload") }}</Button>+ <Button type="button" :disabled="mcpHttpLoading || mcpHttpSaving || Boolean(mcpHttpDraftValidationError)" @click="saveMcpHttpSettings">+ <Loader2 v-if="mcpHttpSaving" class="mr-2 h-4 w-4 animate-spin" />+ {{ t("settings.mcpHttpSaveAndStart") }}+ </Button>+ </div>+ </div>+ </template>++ <div v-else class="flex flex-col gap-3 rounded-md border border-dashed px-4 py-3 text-xs text-muted-foreground sm:flex-row sm:items-center sm:justify-between">+ <p>{{ t("settings.mcpHttpDisabledHint") }}</p>+ <div class="flex shrink-0 justify-end gap-2">+ <Button type="button" variant="outline" :disabled="mcpHttpLoading || mcpHttpSaving" @click="loadMcpHttpSettings">{{ t("settings.mcpHttpReload") }}</Button>+ <Button type="button" :disabled="mcpHttpLoading || mcpHttpSaving" @click="saveMcpHttpSettings">+ <Loader2 v-if="mcpHttpSaving" class="mr-2 h-4 w-4 animate-spin" />+ {{ t("settings.mcpHttpSaveAndStop") }}+ </Button>+ </div>+ </div>- <div v-if="!isWeb && mcpStatus?.installed" class="space-y-2">- <Label>{{ t("settings.mcpUninstallCommand") }}</Label>- <div class="flex min-w-0 items-center gap-2">- <div class="min-w-0 flex-1 overflow-x-auto rounded-md border bg-background px-3 py-2 font-mono text-xs whitespace-nowrap">- {{ mcpUninstallCommand }}- </div>- <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('uninstall', mcpUninstallCommand)">- <CheckCircle2 v-if="mcpCopied === 'uninstall'" class="h-4 w-4 text-green-500" />- <Copy v-else class="h-4 w-4" />- </Button>- <Button type="button" variant="outline" class="text-destructive hover:text-destructive" :disabled="mcpInstalling || mcpUninstalling || !mcpStatus.npm_available" @click="uninstallMcp">- <Loader2 v-if="mcpUninstalling" class="mr-2 h-4 w-4 animate-spin" />- <Trash2 v-else class="mr-2 h-4 w-4" />- {{ mcpUninstalling ? t("settings.mcpUninstalling") : t("settings.mcpUninstallButton") }}- </Button>- </div>- </div>+ <div v-if="mcpHttpStatus?.lastError" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">+ {{ mcpHttpStatus.lastError }}+ </div>- <McpAuthorizationStepper>- <template #connections>- <div class="space-y-3">- <p v-if="mcpPolicyLoadError" class="rounded-md border border-red-500/30 bg-red-500/5 px-3 py-2 text-xs text-red-600 dark:text-red-400">- {{- t("settings.mcpPolicyLoadFailed", {- error: mcpPolicyLoadError,- })- }}- </p>- <McpConnectionScopePicker :connections="mcpSelectableConnections" :allowed-connection-ids="mcpAllowedConnectionIds" :disabled="mcpPolicyControlsDisabled" :busy="mcpPolicyLoading || mcpPolicySaving" @update:allowed-connection-ids="onMcpAllowedConnectionIdsChange" />- </div>- </template>- <template #databases>- <McpDatabaseScopePicker- :connections="mcpSelectableConnections"- :allowed-connection-ids="mcpAllowedConnectionIds"- :connection-policies="settingsStore.mcpGlobalPolicy.connectionPolicies"- :global-execution-mode="mcpExecutionMode"- :disabled="mcpPolicyControlsDisabled"- :busy="mcpPolicyLoading || mcpPolicySaving"- @update:connection-policies="onMcpConnectionPoliciesChange"- />- </template>- <template #overrides>- <div v-if="mcpConnectionPolicyConnections.length" class="space-y-2">- <div class="flex flex-wrap items-start justify-between gap-2">- <div>- <p class="text-sm font-medium">{{ t("settings.mcpConnectionPolicyTitle") }}</p>- <p class="text-xs text-muted-foreground">{{ t("settings.mcpConnectionPolicyDescription") }}</p>+ <section v-if="mcpHttpStatus?.enabled" class="space-y-3 rounded-md border p-4">+ <div class="flex flex-wrap items-center justify-between gap-2">+ <div class="flex items-center gap-2 text-sm font-medium">+ <span class="h-2 w-2 rounded-full" :class="mcpHttpStatus.running ? 'bg-green-500' : 'bg-amber-500'" />+ {{ mcpHttpStatus.running ? t("settings.mcpHttpConnectionInfoTitle") : t("settings.mcpHttpServiceNotRunning") }}+ </div>+ <Badge variant="outline" class="font-normal">{{ mcpHttpStatus.running ? t("settings.mcpHttpRunningConfigBadge") : t("settings.mcpHttpLastStatusBadge") }}</Badge>+ </div>+ <p v-if="mcpHttpHasUnsavedChanges" class="rounded bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200">{{ t("settings.mcpHttpRunningDraftDiffersHint") }}</p>+ <div v-if="mcpHttpStatus.endpoint" class="space-y-1">+ <Label>{{ t("settings.mcpHttpEndpointLabel") }}</Label>+ <div class="flex min-w-0 items-center gap-2">+ <code class="min-w-0 flex-1 overflow-x-auto rounded border bg-background px-2 py-1.5 text-xs">{{ mcpHttpStatus.endpoint }}</code>+ <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('http-endpoint', mcpHttpStatus.endpoint || '')">+ <CheckCircle2 v-if="mcpCopied === 'http-endpoint'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>+ <div v-if="mcpHttpStatus.accessToken" class="space-y-1">+ <div class="flex items-center justify-between gap-3">+ <Label>Bearer Token</Label>+ <Button type="button" variant="outline" size="sm" :disabled="mcpHttpSaving" @click="rotateMcpHttpToken">{{ t("settings.mcpHttpRotateToken") }}</Button>+ </div>+ <div class="flex min-w-0 items-center gap-2">+ <code class="min-w-0 flex-1 overflow-x-auto rounded border bg-background px-2 py-1.5 text-xs">{{ mcpHttpStatus.accessToken }}</code>+ <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('http-token', mcpHttpStatus.accessToken || '')">+ <CheckCircle2 v-if="mcpCopied === 'http-token'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div>+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpTokenHintPrefix") }}<code>Authorization: Bearer</code>{{ t("settings.mcpHttpTokenHintSuffix") }}</p>+ </div>+ <details v-if="mcpHttpClientConfig" class="rounded border bg-muted/20 p-3 text-xs">+ <summary class="cursor-pointer font-medium">{{ t("settings.mcpHttpClientConfigTitle") }}</summary>+ <div class="mt-3 space-y-2">+ <div class="flex justify-end">+ <Button type="button" variant="outline" size="sm" :title="t('common.copy')" @click="copyMcpText('http-config', mcpHttpClientConfig)">+ <CheckCircle2 v-if="mcpCopied === 'http-config'" class="mr-1 h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="mr-1 h-3.5 w-3.5" />+ {{ t("common.copy") }}+ </Button>+ </div>+ <pre class="max-h-48 overflow-auto rounded border bg-background p-2 text-[11px] whitespace-pre-wrap">{{ mcpHttpClientConfig }}</pre>+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpHttpClientConfigHint") }}</p>+ </div>+ </details>+ <details v-if="mcpHttpStatus.recentLogs.length" class="text-xs">+ <summary class="cursor-pointer text-muted-foreground">{{ t("settings.mcpHttpLogsTitle") }}</summary>+ <pre class="mt-2 max-h-40 overflow-auto rounded border bg-background p-2 text-[11px] whitespace-pre-wrap">{{ mcpHttpStatus.recentLogs.join("\n") }}</pre>+ </details>+ </section></div>- <label class="flex h-8 items-center gap-1.5 rounded-md border bg-background px-2 text-xs text-muted-foreground">- {{ t("settings.mcpPerPage") }}- <select v-model.number="mcpConnectionPolicyPageSize" class="bg-transparent text-xs text-foreground outline-none" :disabled="mcpPolicyControlsDisabled">- <option v-for="size in MCP_CONNECTION_POLICY_PAGE_SIZE_OPTIONS" :key="size" :value="size">{{ size }}</option>- </select>- </label>- </div>- <div class="space-y-2">- <div v-for="connection in pagedMcpConnectionPolicyConnections" :key="connection.id" class="flex items-center justify-between gap-3 rounded-md border bg-background px-3 py-2">- <div class="min-w-0">- <p class="truncate text-sm font-medium">{{ connection.name }}</p>- <p class="truncate font-mono text-[11px] text-muted-foreground">{{ connection.db_type }} · {{ connection.host }}</p>+ </TabsContent>++ <TabsContent value="stdio" class="m-0 space-y-4">+ <div v-if="!isWeb" class="grid gap-3 sm:grid-cols-2">+ <div class="rounded-md border p-3">+ <div class="text-xs font-medium uppercase text-muted-foreground">+ {{ t("settings.mcpCurrent") }}+ </div>+ <div class="mt-2 font-mono text-sm">+ {{ mcpStatus?.current_version ? `v${mcpStatus.current_version}` : t("settings.mcpVersionMissing") }}+ </div></div>- <select- :value="mcpConnectionExecutionMode(connection.id)"- :disabled="mcpPolicyControlsDisabled"- class="h-8 shrink-0 rounded-md border bg-background px-2 text-xs"- @change="onMcpConnectionExecutionModeChange(connection.id, ($event.target as HTMLSelectElement).value as McpConnectionExecutionMode | 'inherit')"- >- <option value="inherit">{{ t("settings.mcpConnectionPolicyInherit") }}</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>- </div>- </div>- <div v-if="mcpConnectionPolicyPageCount > 1" class="flex items-center justify-center gap-2 border-t pt-2 text-xs text-muted-foreground">- <Button type="button" size="icon-sm" variant="ghost" :disabled="mcpConnectionPolicyPage === 1" :title="t('settings.mcpPreviousPage')" :aria-label="t('settings.mcpPreviousPage')" @click="setMcpConnectionPolicyPage(mcpConnectionPolicyPage - 1)"><ChevronLeft /></Button>- <span class="min-w-12 text-center tabular-nums">{{ mcpConnectionPolicyPage }} / {{ mcpConnectionPolicyPageCount }}</span>- <Button type="button" size="icon-sm" variant="ghost" :disabled="mcpConnectionPolicyPage === mcpConnectionPolicyPageCount" :title="t('settings.mcpNextPage')" :aria-label="t('settings.mcpNextPage')" @click="setMcpConnectionPolicyPage(mcpConnectionPolicyPage + 1)"- ><ChevronRight- /></Button>- </div>- </div>- <div v-else class="rounded-md border border-dashed px-3 py-8 text-center text-xs text-muted-foreground">{{ t("settings.mcpConnectionPolicyEmptyHint") }}</div>- </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 class="rounded-md border p-3">+ <div class="text-xs font-medium uppercase text-muted-foreground">+ {{ t("settings.mcpLatest") }}+ </div>+ <div class="mt-2 font-mono text-sm">+ {{ mcpStatus?.latest_version ? `v${mcpStatus.latest_version}` : t("settings.mcpVersionUnknown") }}+ </div></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 class="rounded-md border p-3">+ <div class="text-xs font-medium uppercase text-muted-foreground">Node.js</div>+ <div class="mt-2 font-mono text-sm">+ {{ mcpStatus?.node_version || t("settings.mcpVersionUnknown") }}+ </div>+ </div>+ <div class="rounded-md border p-3">+ <div class="text-xs font-medium uppercase text-muted-foreground">npm</div>+ <div class="mt-2 font-mono text-sm">+ {{ mcpStatus?.npm_available ? t("settings.mcpAvailable") : t("settings.mcpUnavailable") }}+ </div></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>- <p class="text-xs text-muted-foreground">{{ t("settings.mcpToolPermissionsDescription") }}</p>- </div>- <div class="grid gap-2 sm:grid-cols-2">- <label v-for="tool in mcpToolOptions" :key="tool.name" class="flex items-center gap-2 rounded border bg-background px-2.5 py-2 text-xs">- <input type="checkbox" :checked="mcpToolAllowed(tool.name)" :disabled="mcpPolicyControlsDisabled" @change="onMcpToolAllowedChange(tool.name, ($event.target as HTMLInputElement).checked)" />- <span>{{ t(tool.labelKey) }}</span>- </label></div>- </section>- <section class="space-y-3 border-t pt-4">- <div class="space-y-1">- <Label id="mcp-execution-mode-label">{{ t("settings.mcpExecutionMode") }}</Label>- <p class="text-xs text-muted-foreground">- {{ t("settings.mcpExecutionModeDescription") }}- </p>++ <div v-if="mcpStatus?.bin_path" class="space-y-2">+ <Label>{{ t("settings.mcpBinPath") }}</Label>+ <div class="rounded-md border bg-muted/20 px-3 py-2 font-mono text-xs text-muted-foreground">+ {{ mcpStatus.bin_path }}+ </div></div>- <div class="grid grid-cols-1 p-1 sm:grid-cols-3 gap-2.5" role="radiogroup" aria-labelledby="mcp-execution-mode-label">- <Button- :disabled="mcpPolicyControlsDisabled"- type="button"- role="radio"- data-mcp-execution-mode="read_only"- :aria-checked="mcpExecutionMode === 'read_only'"- :tabindex="mcpExecutionMode === 'read_only' ? 0 : -1"- variant="outline"- class="settings-choice-card h-auto justify-center border p-3"- :class="mcpExecutionMode === 'read_only' ? 'dbx-choice-selected' : ''"- @click="onMcpExecutionModeChange('read_only')"- @keydown="onMcpExecutionModeKeydown($event, 'read_only')"- >- <span>{{ t("settings.mcpExecutionModeReadOnly") }}</span>- </Button>- <Button- :disabled="mcpPolicyControlsDisabled"- type="button"- role="radio"- data-mcp-execution-mode="safe_write"- :aria-checked="mcpExecutionMode === 'safe_write'"- :tabindex="mcpExecutionMode === 'safe_write' ? 0 : -1"- variant="outline"- class="settings-choice-card h-auto justify-center border p-3"- :class="mcpExecutionMode === 'safe_write' ? 'dbx-choice-selected' : ''"- @click="onMcpExecutionModeChange('safe_write')"- @keydown="onMcpExecutionModeKeydown($event, 'safe_write')"- >- <span>{{ t("settings.mcpExecutionModeSafeWrite") }}</span>- <span class="text-[10px] font-normal text-green-600 dark:text-green-400">{{ t("settings.mcpExecutionModeRecommended") }}</span>- </Button>- <Button- :disabled="mcpPolicyControlsDisabled"- type="button"- role="radio"- data-mcp-execution-mode="high_risk_write"- :aria-checked="mcpExecutionMode === 'high_risk_write'"- :tabindex="mcpExecutionMode === 'high_risk_write' ? 0 : -1"- variant="outline"- class="settings-choice-card h-auto justify-center border p-3"- :class="mcpExecutionMode === 'high_risk_write' ? 'dbx-choice-selected' : ''"- @click="onMcpExecutionModeChange('high_risk_write')"- @keydown="onMcpExecutionModeKeydown($event, 'high_risk_write')"++ <div v-if="!isWeb" class="space-y-2">+ <Label>{{ mcpStatus?.installed ? t("settings.mcpUpdateCommand") : t("settings.mcpInstallCommand") }}</Label>+ <div class="flex min-w-0 items-center gap-2">+ <div class="min-w-0 flex-1 overflow-x-auto rounded-md border bg-background px-3 py-2 font-mono text-xs whitespace-nowrap">+ {{ mcpCommand }}+ </div>+ <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('install', mcpCommand)">+ <CheckCircle2 v-if="mcpCopied === 'install'" class="h-4 w-4 text-green-500" />+ <Copy v-else class="h-4 w-4" />+ </Button>+ <Button type="button" variant="default" :disabled="mcpInstalling || mcpUninstalling || !mcpStatus?.npm_available || (mcpStatus?.installed && !mcpStatus?.update_available)" @click="installMcp">+ <Loader2 v-if="mcpInstalling" class="mr-2 h-4 w-4 animate-spin" />+ <CheckCircle2 v-if="!mcpInstalling && mcpStatus?.installed && !mcpStatus?.update_available" class="mr-2 h-4 w-4" />+ {{ mcpInstalling ? t("settings.mcpInstalling") : !mcpStatus?.installed ? t("settings.mcpInstallButton") : mcpStatus?.update_available ? t("settings.mcpUpdateButton") : t("settings.mcpUpToDate") }}+ </Button>+ </div>+ <div+ v-if="mcpInstallMessage"+ :class="[+ 'text-xs px-3 py-2 rounded-md border',+ mcpInstallError ? 'bg-red-50 text-red-700 border-red-200 dark:bg-red-950/30 dark:text-red-300 dark:border-red-800' : 'bg-green-50 text-green-700 border-green-200 dark:bg-green-950/30 dark:text-green-300 dark:border-green-800',+ ]">- <span>{{ t("settings.mcpExecutionModeHighRiskWrite") }}</span>- </Button>- </div>- <!-- Keep every translation in one grid cell so mode changes cannot reflow the capability matrix. -->- <div data-mcp-execution-mode-description class="grid text-xs">- <p class="col-start-1 row-start-1 text-muted-foreground" :class="mcpExecutionMode === 'read_only' ? 'visible' : 'invisible'">- {{ t("settings.mcpExecutionModeReadOnlyDescription") }}- </p>- <p class="col-start-1 row-start-1 text-muted-foreground" :class="mcpExecutionMode === 'safe_write' ? 'visible' : 'invisible'">- {{ t("settings.mcpExecutionModeSafeWriteDescription") }}- </p>- <p class="col-start-1 row-start-1 flex items-start gap-1.5 text-amber-600 dark:text-amber-400" :class="mcpExecutionMode === 'high_risk_write' ? 'visible' : 'invisible'">- <AlertTriangle class="mt-0.5 h-3.5 w-3.5 shrink-0" />- <span>{{ t("settings.mcpExecutionModeHighRiskWriteDescription") }}</span>- </p>+ {{ mcpInstallMessage }}+ </div></div>- <div class="space-y-1.5">- <div class="space-y-0.5">- <Label id="mcp-query-timeout-label">{{ t("settings.mcpQueryTimeout") }}</Label>- <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpQueryTimeoutDescription") }}</p>++ <div v-if="!isWeb && mcpStatus?.installed" class="space-y-2">+ <Label>{{ t("settings.mcpUninstallCommand") }}</Label>+ <div class="flex min-w-0 items-center gap-2">+ <div class="min-w-0 flex-1 overflow-x-auto rounded-md border bg-background px-3 py-2 font-mono text-xs whitespace-nowrap">+ {{ mcpUninstallCommand }}+ </div>+ <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('uninstall', mcpUninstallCommand)">+ <CheckCircle2 v-if="mcpCopied === 'uninstall'" class="h-4 w-4 text-green-500" />+ <Copy v-else class="h-4 w-4" />+ </Button>+ <Button type="button" variant="outline" class="text-destructive hover:text-destructive" :disabled="mcpInstalling || mcpUninstalling || !mcpStatus.npm_available" @click="uninstallMcp">+ <Loader2 v-if="mcpUninstalling" class="mr-2 h-4 w-4 animate-spin" />+ <Trash2 v-else class="mr-2 h-4 w-4" />+ {{ mcpUninstalling ? t("settings.mcpUninstalling") : t("settings.mcpUninstallButton") }}+ </Button></div>- <Input id="mcp-query-timeout" v-model="mcpQueryTimeoutInput" type="number" min="0" step="1" inputmode="numeric" placeholder="0" :disabled="mcpPolicyControlsDisabled" @change="onMcpQueryTimeoutInput" /></div>- <details class="rounded-md border bg-background">- <summary class="cursor-pointer px-3 py-2.5 text-xs outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50">- <p class="text-xs font-medium">- {{ t("settings.mcpCapabilityTitle") }}- </p>- <p class="text-[11px] text-muted-foreground">- {{ t("settings.mcpCapabilityDescription") }}- </p>- </summary>- <div class="space-y-1.5 border-t p-3">- <div class="overflow-x-auto rounded-md border bg-background">- <table class="w-full min-w-[36rem] table-fixed text-xs">+ </TabsContent>+ </Tabs>+ </div>+ </TabsContent>++ <TabsContent value="permissions" class="m-0 space-y-4">+ <McpAuthorizationStepper>+ <template #connections>+ <div class="space-y-3">+ <p v-if="mcpPolicyLoadError" class="rounded-md border border-red-500/30 bg-red-500/5 px-3 py-2 text-xs text-red-600 dark:text-red-400">+ {{+ t("settings.mcpPolicyLoadFailed", {+ error: mcpPolicyLoadError,+ })+ }}+ </p>+ <McpResourceScopePicker+ :layout="connectionStore.sidebarLayout"+ :connections="mcpSelectableConnections"+ :allowed-group-ids="mcpAllowedGroupIds"+ :allowed-connection-ids="mcpAllowedConnectionIds"+ :group-policies="settingsStore.mcpGlobalPolicy.groupPolicies"+ :connection-policies="settingsStore.mcpGlobalPolicy.connectionPolicies"+ :disabled="mcpPolicyControlsDisabled"+ :busy="mcpPolicyLoading || mcpPolicySaving"+ @update:scope="onMcpResourceScopeChange"+ @set:group-policy="onMcpGroupExecutionModeChange"+ @set:connection-policy="onMcpConnectionExecutionModeChange"+ />+ </div>+ </template>+ <template #databases>+ <McpDatabaseScopePicker+ :connections="mcpSelectableConnections"+ :allowed-connection-ids="mcpEffectiveAllowedConnectionIds"+ :connection-policies="settingsStore.mcpGlobalPolicy.connectionPolicies"+ :disabled="mcpPolicyControlsDisabled"+ :busy="mcpPolicyLoading || mcpPolicySaving"+ @update:connection-policies="onMcpConnectionPoliciesChange"+ @set:database-policy="onMcpDatabaseExecutionModeChange"+ />+ </template>+ <template #overrides>+ <div class="space-y-4">+ <section class="space-y-3">+ <div class="space-y-1">+ <Label id="mcp-execution-mode-label">{{ t("settings.mcpExecutionMode") }}</Label>+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpExecutionModeDescription") }}</p>+ </div>+ <div class="grid grid-cols-1 gap-2 sm:grid-cols-3" role="radiogroup" aria-labelledby="mcp-execution-mode-label">+ <Button+ v-for="mode in mcpExecutionModeOptions"+ :key="mode"+ :disabled="mcpPolicyControlsDisabled"+ type="button"+ role="radio"+ :data-mcp-execution-mode="mode"+ :aria-checked="mcpExecutionMode === mode"+ :tabindex="mcpExecutionMode === mode ? 0 : -1"+ variant="outline"+ class="settings-choice-card h-10 justify-center"+ :class="mcpExecutionMode === mode ? 'dbx-choice-selected' : ''"+ @click="onMcpExecutionModeChange(mode)"+ @keydown="onMcpExecutionModeKeydown($event, mode)"+ >+ {{ mcpExecutionModeLabel(mode) }}+ </Button>+ </div>+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpPermissionGlobalDefaultHint") }}</p>+ <div class="space-y-2 border-t border-border/60 pt-3">+ <div>+ <p class="text-xs font-medium">{{ t("settings.mcpCapabilityTitle") }}</p>+ <p class="mt-1 text-[11px] text-muted-foreground">{{ t("settings.mcpCapabilityDescription") }}</p>+ </div>+ <div class="overflow-x-auto rounded border bg-background">+ <table class="w-full min-w-[34rem] table-fixed text-xs"><thead class="bg-muted/50 text-muted-foreground"><tr>- <th scope="col" class="w-[46%] px-3 py-2 text-left font-medium">- {{ t("settings.mcpCapabilityOperation") }}- </th>- <th v-for="column in MCP_EXECUTION_MODE_COLUMNS" :key="column.mode" scope="col" class="px-2 py-2 text-center font-medium">- {{ t(column.labelKey) }}- </th>+ <th scope="col" class="w-[46%] px-3 py-2 text-left font-medium">{{ t("settings.mcpCapabilityOperation") }}</th>+ <th v-for="column in MCP_EXECUTION_MODE_COLUMNS" :key="column.mode" scope="col" class="px-2 py-2 text-center font-medium">{{ t(column.labelKey) }}</th></tr></thead><tbody class="divide-y"><tr v-for="row in MCP_CAPABILITY_ROWS" :key="row.labelKey">- <th scope="row" class="px-3 py-2 text-left font-normal leading-relaxed">- {{ t(row.labelKey) }}- </th>+ <th scope="row" class="px-3 py-2 text-left font-normal leading-relaxed">{{ t(row.labelKey) }}</th><td v-for="column in MCP_EXECUTION_MODE_COLUMNS" :key="column.mode" class="px-2 py-2 text-center"><span class="inline-flex items-center justify-center" :class="row[column.mode] ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground/60'"><Check v-if="row[column.mode]" class="h-4 w-4" aria-hidden="true" />@@ -8336,236 +8284,301 @@ LIMIT 100;</pre</tbody></table></div>- <p class="text-[11px] leading-relaxed text-muted-foreground">- {{ t("settings.mcpCapabilityAlwaysEnforced") }}- </p>+ <p class="text-[11px] leading-relaxed text-muted-foreground">{{ t("settings.mcpCapabilityAlwaysEnforced") }}</p></div>- </details>- </section>- </div>- </template>- </McpAuthorizationStepper>-- <div class="space-y-2">- <Label>{{ t("settings.mcpConfig") }}</Label>- <Tabs v-model="mcpConfigTab" class="space-y-3">- <TabsList class="settings-mcp-config-tabs h-auto min-h-8 w-full min-w-0 max-w-full justify-start gap-1 overflow-x-auto overflow-y-hidden overscroll-x-contain group-data-horizontal/tabs:h-auto">- <TabsTrigger value="claude" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Claude Code</TabsTrigger>- <TabsTrigger value="cursor" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Cursor</TabsTrigger>- <TabsTrigger value="codebuddy" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">CodeBuddy Code</TabsTrigger>- <TabsTrigger value="zcode" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">ZCode</TabsTrigger>- <TabsTrigger value="trae" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">TRAE</TabsTrigger>- <TabsTrigger value="vscode" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">VS Code</TabsTrigger>- <TabsTrigger value="windsurf" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Windsurf</TabsTrigger>- <TabsTrigger value="codex" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Codex</TabsTrigger>- <TabsTrigger value="deepseek-harness" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">DeepSeek Harness</TabsTrigger>- <TabsTrigger value="opencode" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">OpenCode</TabsTrigger>- <TabsTrigger value="pi" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Pi</TabsTrigger>- <TabsTrigger value="cherry-studio" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Cherry Studio</TabsTrigger>- <TabsTrigger value="qoder" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Qoder</TabsTrigger>- </TabsList>-- <TabsContent value="claude" class="m-0">- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('claude-config', mcpJsonRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'claude-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ </section></div>- </TabsContent>-- <TabsContent value="cursor" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpCursorConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('cursor-config', mcpJsonRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'cursor-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>- </div>+ </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-[30rem] 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.mcpPermissionPreviewResource") }}</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>+ <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.mcpPermissionPreviewSource") }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="row in filteredMcpPermissionPreviewRows" :key="`${row.connectionId}:${row.database}`" class="border-t">+ <td class="px-3 py-2">+ <span class="font-medium">{{ row.connection }}</span+ ><span class="text-muted-foreground"> / </span><span class="font-mono">{{ row.database }}</span>+ </td>+ <td class="px-3 py-2 font-medium">{{ mcpExecutionModeLabel(row.effectiveMode) }}</td>+ <td class="px-3 py-2 text-muted-foreground">{{ mcpPermissionSource(row) }}</td>+ </tr>+ <tr v-if="filteredMcpPermissionPreviewRows.length === 0">+ <td colspan="3" 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>+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpToolPermissionsDescription") }}</p>+ </div>+ <div class="grid gap-2 sm:grid-cols-2">+ <label v-for="tool in mcpToolOptions" :key="tool.name" class="flex items-center gap-2 rounded border bg-background px-2.5 py-2 text-xs">+ <input type="checkbox" :checked="mcpToolAllowed(tool.name)" :disabled="mcpPolicyControlsDisabled" @change="onMcpToolAllowedChange(tool.name, ($event.target as HTMLInputElement).checked)" />+ <span>{{ t(tool.labelKey) }}</span>+ </label>+ </div>+ </section></div>- </TabsContent>-- <TabsContent value="codebuddy" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpCodeBuddyConfigPath") }}- </div>+ </template>+ </McpAuthorizationStepper>+ </TabsContent>+ <div v-if="mcpManagementTab === 'access'" class="space-y-5 border-t border-border/60 pt-5 sm:ml-1">+ <div class="space-y-3">+ <div>+ <p class="text-sm font-semibold text-foreground">{{ t("settings.mcpRuntimeSettings") }}</p>+ <p class="mt-1 text-xs text-muted-foreground">{{ t("settings.mcpQueryTimeoutDescription") }}</p>+ </div>+ <div class="grid items-center gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(12rem,18rem)]">+ <Label id="mcp-query-timeout-label">{{ t("settings.mcpQueryTimeout") }}</Label>+ <Input id="mcp-query-timeout" v-model="mcpQueryTimeoutInput" type="number" min="0" step="1" inputmode="numeric" placeholder="0" :disabled="mcpPolicyControlsDisabled" @change="onMcpQueryTimeoutInput" />+ </div>+ </div>+ <div v-if="mcpTransportTab === 'stdio'" class="space-y-3">+ <div>+ <Label>{{ t("settings.mcpConfig") }}</Label>+ <p class="mt-1 text-xs text-muted-foreground">{{ t("settings.mcpConfigOptionsHint") }}</p>+ </div>+ <Tabs v-model="mcpConfigTab" class="space-y-3">+ <TabsList class="settings-mcp-config-tabs h-auto min-h-8 w-full min-w-0 max-w-full justify-start gap-1 overflow-x-auto overflow-y-hidden overscroll-x-contain group-data-horizontal/tabs:h-auto">+ <TabsTrigger value="claude" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Claude Code</TabsTrigger>+ <TabsTrigger value="cursor" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Cursor</TabsTrigger>+ <TabsTrigger value="codebuddy" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">CodeBuddy Code</TabsTrigger>+ <TabsTrigger value="zcode" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">ZCode</TabsTrigger>+ <TabsTrigger value="trae" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">TRAE</TabsTrigger>+ <TabsTrigger value="vscode" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">VS Code</TabsTrigger>+ <TabsTrigger value="windsurf" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Windsurf</TabsTrigger>+ <TabsTrigger value="codex" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Codex</TabsTrigger>+ <TabsTrigger value="deepseek-harness" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">DeepSeek Harness</TabsTrigger>+ <TabsTrigger value="opencode" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">OpenCode</TabsTrigger>+ <TabsTrigger value="pi" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Pi</TabsTrigger>+ <TabsTrigger value="cherry-studio" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Cherry Studio</TabsTrigger>+ <TabsTrigger value="qoder" class="settings-mcp-config-tab h-7 flex-none shrink-0 px-2.5">Qoder</TabsTrigger>+ </TabsList>++ <TabsContent value="claude" class="m-0"><div class="relative rounded-md border bg-background p-3"><pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('codebuddy-config', mcpJsonRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'codebuddy-config'" class="h-3.5 w-3.5 text-green-500" />+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('claude-config', mcpJsonRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'claude-config'" class="h-3.5 w-3.5 text-green-500" /><Copy v-else class="h-3.5 w-3.5" /></Button></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="zcode" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpZCodeConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('zcode-config', mcpJsonRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'zcode-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ <TabsContent value="cursor" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpCursorConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('cursor-config', mcpJsonRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'cursor-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="trae" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpTraeConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpTraeRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('trae-config', mcpTraeRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'trae-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ <TabsContent value="codebuddy" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpCodeBuddyConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('codebuddy-config', mcpJsonRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'codebuddy-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="vscode" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpVsCodeConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpVsCodeRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('vscode-config', mcpVsCodeRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'vscode-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ <TabsContent value="zcode" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpZCodeConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('zcode-config', mcpJsonRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'zcode-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="windsurf" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpWindsurfConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('windsurf-config', mcpJsonRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'windsurf-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ <TabsContent value="trae" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpTraeConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpTraeRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('trae-config', mcpTraeRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'trae-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="codex" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpCodexConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpCodexRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('codex-config', mcpCodexRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'codex-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ <TabsContent value="vscode" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpVsCodeConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpVsCodeRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('vscode-config', mcpVsCodeRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'vscode-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="deepseek-harness" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpDeepSeekHarnessConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpDeepSeekHarnessRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('deepseek-harness-config', mcpDeepSeekHarnessRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'deepseek-harness-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ <TabsContent value="windsurf" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpWindsurfConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpJsonRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('windsurf-config', mcpJsonRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'windsurf-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="opencode" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpOpenCodeConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpOpenCodeRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('opencode-config', mcpOpenCodeRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'opencode-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ <TabsContent value="codex" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpCodexConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpCodexRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('codex-config', mcpCodexRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'codex-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="pi" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpPiConfigPath") }}- </div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpPiRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('pi-config', mcpPiRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'pi-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ <TabsContent value="deepseek-harness" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpDeepSeekHarnessConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpDeepSeekHarnessRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('deepseek-harness-config', mcpDeepSeekHarnessRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'deepseek-harness-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="cherry-studio" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpCherryStudioConfigPath") }}+ <TabsContent value="opencode" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpOpenCodeConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpOpenCodeRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('opencode-config', mcpOpenCodeRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'opencode-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpCherryStudioRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('cherry-studio-config', mcpCherryStudioRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'cherry-studio-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ </TabsContent>++ <TabsContent value="pi" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpPiConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpPiRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('pi-config', mcpPiRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'pi-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>+ </TabsContent>- <TabsContent value="qoder" class="m-0">- <div class="space-y-2">- <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">- {{ t("settings.mcpQoderConfigPath") }}+ <TabsContent value="cherry-studio" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpCherryStudioConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpCherryStudioRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('cherry-studio-config', mcpCherryStudioRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'cherry-studio-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- <div class="relative rounded-md border bg-background p-3">- <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpQoderRecommendedConfig }}</code></pre>- <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('qoder-config', mcpQoderRecommendedConfig)">- <CheckCircle2 v-if="mcpCopied === 'qoder-config'" class="h-3.5 w-3.5 text-green-500" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>+ </TabsContent>++ <TabsContent value="qoder" class="m-0">+ <div class="space-y-2">+ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("settings.mcpQoderConfigPath") }}+ </div>+ <div class="relative rounded-md border bg-background p-3">+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpQoderRecommendedConfig }}</code></pre>+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('qoder-config', mcpQoderRecommendedConfig)">+ <CheckCircle2 v-if="mcpCopied === 'qoder-config'" class="h-3.5 w-3.5 text-green-500" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ </div></div>- </div>- </TabsContent>- </Tabs>- </div>+ </TabsContent>+ </Tabs>+ </div>- <div v-if="mcpStatus?.error || mcpStatusError" class="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">- {{ mcpStatusError || mcpStatus?.error }}- </div>+ <div v-if="mcpTransportTab === 'stdio' && (mcpStatus?.error || mcpStatusError)" class="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">+ {{ mcpStatusError || mcpStatus?.error }}+ </div>- <div class="flex items-center gap-2 text-xs text-muted-foreground">- <Terminal class="h-3.5 w-3.5" />- <span>{{ t("settings.mcpDetectionTiming") }} {{ t("settings.mcpNpmBoundary") }}</span>+ <div v-if="mcpTransportTab === 'stdio'" class="flex items-center gap-2 text-xs text-muted-foreground">+ <Terminal class="h-3.5 w-3.5" />+ <span>{{ t("settings.mcpDetectionTiming") }} {{ t("settings.mcpNpmBoundary") }}</span>+ </div></div>- </template>+ </Tabs></section><section v-else-if="activeSettingsTab === 'security' && isWeb" data-settings-search-id="security" :class="['flex flex-col gap-5 py-2', settingsSearchTargetClass('security')]">diff --git a/apps/desktop/src/components/settings/McpAuthorizationStepper.vue b/apps/desktop/src/components/settings/McpAuthorizationStepper.vueindex 62589d7666..1a465c8ec6 100644--- a/apps/desktop/src/components/settings/McpAuthorizationStepper.vue+++ b/apps/desktop/src/components/settings/McpAuthorizationStepper.vue@@ -7,13 +7,13 @@ type StepId = "capabilities" | "connections" | "databases" | "overrides";const { t } = useI18n();const steps = computed<Array<{ id: StepId; title: string; description: string }>>(() => [+ { id: "overrides", title: t("settings.mcpAuthStepOverridesTitle"), description: t("settings.mcpAuthStepOverridesDescription") },{ id: "connections", title: t("settings.mcpAuthStepConnectionsTitle"), description: t("settings.mcpAuthStepConnectionsDescription") },{ id: "databases", title: t("settings.mcpAuthStepDatabasesTitle"), description: t("settings.mcpAuthStepDatabasesDescription") },- { id: "overrides", title: t("settings.mcpAuthStepOverridesTitle"), description: t("settings.mcpAuthStepOverridesDescription") },{ id: "capabilities", title: t("settings.mcpAuthStepCapabilitiesTitle"), description: t("settings.mcpAuthStepCapabilitiesDescription") },]);-const currentStep = ref<StepId>("connections");+const currentStep = ref<StepId>("overrides");const currentIndex = computed(() => steps.value.findIndex((step) => step.id === currentStep.value));function scrollableAncestor(target: EventTarget | null): HTMLElement | null {@@ -56,12 +56,12 @@ function nextStep(event: Event) {<p class="text-xs text-muted-foreground">{{ t("settings.mcpAuthDescription") }}</p></header>- <nav class="grid gap-1 rounded-md border bg-muted/50 p-1 sm:grid-cols-4" :aria-label="t('settings.mcpAuthStepsLabel')">+ <nav class="flex items-stretch gap-1 overflow-x-auto rounded-md border bg-muted/50 p-1 sm:grid sm:grid-cols-4" :aria-label="t('settings.mcpAuthStepsLabel')"><buttonv-for="(step, index) in steps":key="step.id"type="button"- class="group flex min-w-0 items-center gap-2 rounded px-2.5 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"+ class="group flex min-h-16 min-w-48 flex-none items-start gap-2 rounded px-2.5 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 sm:min-w-0":class="currentStep === step.id ? 'bg-background shadow-sm' : 'text-muted-foreground hover:bg-background/70'":aria-current="currentStep === step.id ? 'step' : undefined"@click="selectStep(step.id, $event)"@@ -71,16 +71,16 @@ function nextStep(event: Event) {:class="currentStep === step.id ? 'border-primary bg-primary text-primary-foreground' : index < currentIndex ? 'border-primary/40 bg-primary/10 text-primary' : 'bg-background text-muted-foreground'">{{ index + 1 }}</span>- <span class="min-w-0">- <span class="block truncate text-xs font-medium">{{ step.title }}</span>- <span class="hidden truncate text-[10px] text-muted-foreground lg:block">{{ step.description }}</span>+ <span class="min-w-0 flex-1">+ <span class="block whitespace-normal text-xs font-medium leading-5">{{ step.title }}</span>+ <span class="mt-0.5 block whitespace-normal text-[10px] leading-4 text-muted-foreground">{{ step.description }}</span></span></button></nav>- <div :class="currentStep === 'connections' ? 'block' : 'hidden'" :aria-hidden="currentStep !== 'connections'" role="region" :aria-label="t('settings.mcpAuthStepRegionLabel', { step: 1, title: t('settings.mcpAuthStepConnectionsTitle') })"><slot name="connections" /></div>- <div :class="currentStep === 'databases' ? 'block' : 'hidden'" :aria-hidden="currentStep !== 'databases'" role="region" :aria-label="t('settings.mcpAuthStepRegionLabel', { step: 2, title: t('settings.mcpAuthStepDatabasesTitle') })"><slot name="databases" /></div>- <div :class="currentStep === 'overrides' ? 'block' : 'hidden'" :aria-hidden="currentStep !== 'overrides'" role="region" :aria-label="t('settings.mcpAuthStepRegionLabel', { step: 3, title: t('settings.mcpAuthStepOverridesTitle') })"><slot name="overrides" /></div>+ <div :class="currentStep === 'overrides' ? 'block' : 'hidden'" :aria-hidden="currentStep !== 'overrides'" role="region" :aria-label="t('settings.mcpAuthStepRegionLabel', { step: 1, title: t('settings.mcpAuthStepOverridesTitle') })"><slot name="overrides" /></div>+ <div :class="currentStep === 'connections' ? 'block' : 'hidden'" :aria-hidden="currentStep !== 'connections'" role="region" :aria-label="t('settings.mcpAuthStepRegionLabel', { step: 2, title: t('settings.mcpAuthStepConnectionsTitle') })"><slot name="connections" /></div>+ <div :class="currentStep === 'databases' ? 'block' : 'hidden'" :aria-hidden="currentStep !== 'databases'" role="region" :aria-label="t('settings.mcpAuthStepRegionLabel', { step: 3, title: t('settings.mcpAuthStepDatabasesTitle') })"><slot name="databases" /></div><div :class="currentStep === 'capabilities' ? 'block' : 'hidden'" :aria-hidden="currentStep !== 'capabilities'" role="region" :aria-label="t('settings.mcpAuthStepRegionLabel', { step: 4, title: t('settings.mcpAuthStepCapabilitiesTitle') })"><slot name="capabilities" /></div><footer class="flex items-center justify-between gap-3 border-t pt-3">diff --git a/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue b/apps/desktop/src/components/settings/McpDatabaseScopePicker.vueindex 8fa5b4b175..6e9e560d14 100644--- a/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue+++ b/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue@@ -10,19 +10,17 @@ 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">;-+type ExecutionMode = "read_only" | "safe_write" | "high_risk_write";const { t } = useI18n();const PAGE_SIZE_OPTIONS = [6, 10, 20] as const;+const DATABASE_SCOPES: DatabaseScope[] = ["all", "selected", "none"];const props = withDefaults(defineProps<{connections: readonly ConnectionConfig[];allowedConnectionIds: readonly string[] | null;connectionPolicies: readonly McpConnectionPolicy[];- globalExecutionMode: ExecutionMode;disabled?: boolean;busy?: boolean;}>(),@@ -31,6 +29,7 @@ const props = withDefaults(const emit = defineEmits<{"update:connectionPolicies": [value: McpConnectionPolicy[]];+ "set:database-policy": [connectionId: string, databaseName: string, mode: ExecutionMode | "inherit"];}>();const selectedConnectionId = ref("");@@ -92,13 +91,13 @@ function policyFor(connectionId: string): McpConnectionPolicy {function updateSelectedPolicy(patch: Partial<McpConnectionPolicy>) {if (props.disabled || !selectedConnectionId.value) return;const existing = policyFor(selectedConnectionId.value);- const migration = existing.executionModePolicyVersion === 1 ? {} : { ...promoteLegacyConnectionDefault(existing), executionModePolicyVersion: 1 as const };- const next = { ...existing, ...migration, ...patch };+ const next = { ...existing, ...patch };const policies = props.connectionPolicies.filter((policy) => policy.connectionId !== selectedConnectionId.value);emit("update:connectionPolicies", [...policies, next]);}function setScope(scope: DatabaseScope) {+ if (scope !== "selected" && selectedDatabasePolicies.value.length > 0 && !window.confirm(t("settings.mcpDatabaseScopeClearsPermissionExceptions"))) return;updateSelectedPolicy({databaseScope: scope,allowedDatabases: scope === "selected" ? selectedDatabases.value : [],@@ -106,6 +105,17 @@ function setScope(scope: DatabaseScope) {});}+function onScopeKeydown(event: KeyboardEvent, scope: DatabaseScope) {+ if (props.disabled || props.busy || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) return;+ event.preventDefault();+ const currentIndex = DATABASE_SCOPES.indexOf(scope);+ const nextIndex = event.key === "Home" ? 0 : event.key === "End" ? DATABASE_SCOPES.length - 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? (currentIndex - 1 + DATABASE_SCOPES.length) % DATABASE_SCOPES.length : (currentIndex + 1) % DATABASE_SCOPES.length;+ const nextScope = DATABASE_SCOPES[nextIndex];+ const group = event.currentTarget instanceof HTMLElement ? event.currentTarget.closest<HTMLElement>('[role="radiogroup"]') : null;+ group?.querySelector<HTMLElement>(`[data-database-scope="${nextScope}"]`)?.focus();+ setScope(nextScope);+}+function setConnectionPage(page: number) {connectionPage.value = Math.min(Math.max(1, page), connectionPageCount.value);}@@ -122,6 +132,7 @@ function selectConnection(connectionId: string) {}function toggleDatabase(database: string, checked: boolean) {+ if (!checked && selectedDatabasePolicies.value.some((policy) => policy.databaseName === database) && !window.confirm(t("settings.mcpDatabaseScopeClearsPermissionExceptions"))) return;const databases = checked ? [...new Set([...selectedDatabases.value, database])] : selectedDatabases.value.filter((item) => item !== database);updateSelectedPolicy({databaseScope: "selected",@@ -130,72 +141,13 @@ function toggleDatabase(database: string, checked: boolean) {});}-function databaseExecutionMode(database: string): DatabaseExecutionMode {+function databasePolicyMode(database: string): ExecutionMode | "inherit" {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() {const database = manualDatabase.value.trim();if (!database) return;@@ -295,9 +247,9 @@ watch(databasePageCount, () => setDatabasePage(databasePage.value));<div class="flex flex-wrap items-start justify-between gap-2"><div><p class="text-sm font-medium">{{ selectedConnection.name }}</p>- <p class="text-xs text-muted-foreground">{{ t("settings.mcpDatabaseScopePermissionNote") }}</p>+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpDatabaseScopeDescription") }}</p></div>- <Button type="button" variant="outline" size="sm" :disabled="disabled || Boolean(loadingConnectionId)" @click="loadConnectionDatabases">+ <Button v-if="selectedScope !== 'all'" type="button" variant="outline" size="sm" :disabled="disabled || Boolean(loadingConnectionId)" @click="loadConnectionDatabases"><Loader2 v-if="loadingConnectionId === selectedConnection.id" class="mr-1.5 h-3.5 w-3.5 animate-spin" /><RefreshCw v-else class="mr-1.5 h-3.5 w-3.5" />{{ t("settings.mcpDatabaseLoadButton") }}@@ -305,19 +257,55 @@ watch(databasePageCount, () => setDatabasePage(databasePage.value));</div><div class="grid gap-2 sm:grid-cols-3" role="radiogroup" :aria-label="t('settings.mcpDatabaseScopeAriaLabel')">- <Button type="button" variant="outline" class="h-auto justify-start px-3 py-2 text-left" :class="selectedScope === 'all' ? 'dbx-choice-selected' : ''" :disabled="disabled || busy" @click="setScope('all')">+ <Button+ type="button"+ role="radio"+ data-database-scope="all"+ variant="outline"+ class="h-auto justify-start px-3 py-2 text-left"+ :class="selectedScope === 'all' ? 'dbx-choice-selected' : ''"+ :aria-checked="selectedScope === 'all'"+ :tabindex="selectedScope === 'all' ? 0 : -1"+ :disabled="disabled || busy"+ @click="setScope('all')"+ @keydown="onScopeKeydown($event, 'all')"+ ><span><span class="block text-sm">{{ t("settings.mcpDatabaseScopeAllTitle") }}</span><span class="block text-[11px] font-normal text-muted-foreground">{{ t("settings.mcpDatabaseScopeAllDescription") }}</span></span></Button>- <Button type="button" variant="outline" class="h-auto justify-start px-3 py-2 text-left" :class="selectedScope === 'selected' ? 'dbx-choice-selected' : ''" :disabled="disabled || busy" @click="setScope('selected')">+ <Button+ type="button"+ role="radio"+ data-database-scope="selected"+ variant="outline"+ class="h-auto justify-start px-3 py-2 text-left"+ :class="selectedScope === 'selected' ? 'dbx-choice-selected' : ''"+ :aria-checked="selectedScope === 'selected'"+ :tabindex="selectedScope === 'selected' ? 0 : -1"+ :disabled="disabled || busy"+ @click="setScope('selected')"+ @keydown="onScopeKeydown($event, 'selected')"+ ><span><span class="block text-sm">{{ t("settings.mcpDatabaseScopeSelectedTitle") }}</span><span class="block text-[11px] font-normal text-muted-foreground">{{ t("settings.mcpDatabaseScopeSelectedDescription") }}</span></span></Button>- <Button type="button" variant="outline" class="h-auto justify-start px-3 py-2 text-left" :class="selectedScope === 'none' ? 'dbx-choice-selected' : ''" :disabled="disabled || busy" @click="setScope('none')">+ <Button+ type="button"+ role="radio"+ data-database-scope="none"+ variant="outline"+ class="h-auto justify-start px-3 py-2 text-left"+ :class="selectedScope === 'none' ? 'dbx-choice-selected' : ''"+ :aria-checked="selectedScope === 'none'"+ :tabindex="selectedScope === 'none' ? 0 : -1"+ :disabled="disabled || busy"+ @click="setScope('none')"+ @keydown="onScopeKeydown($event, 'none')"+ ><span><span class="block text-sm">{{ t("settings.mcpDatabaseScopeNoneTitle") }}</span><span class="block text-[11px] font-normal text-muted-foreground">{{ t("settings.mcpDatabaseScopeNoneDescription") }}</span></span@@ -337,17 +325,20 @@ 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" />+ <select+ v-if="selectedDatabases.includes(database)"+ :value="databasePolicyMode(database)"+ class="h-7 shrink-0 rounded border bg-background px-1.5 text-[11px]"+ :disabled="disabled || busy"+ @click.stop+ @change="$emit('set:database-policy', selectedConnectionId, database, ($event.target as HTMLSelectElement).value as ExecutionMode | 'inherit')"+ >+ <option value="inherit">{{ t("settings.mcpConnectionPolicyInherit") }}</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></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"><Button type="button" size="icon-sm" variant="ghost" :disabled="databasePage === 1" :title="t('settings.mcpPreviousPage')" :aria-label="t('settings.mcpPreviousPage')" @click="setDatabasePage(databasePage - 1)"><ChevronLeft /></Button>diff --git a/apps/desktop/src/components/settings/McpResourceScopePicker.vue b/apps/desktop/src/components/settings/McpResourceScopePicker.vuenew file mode 100644index 0000000000..7a95723842--- /dev/null+++ b/apps/desktop/src/components/settings/McpResourceScopePicker.vue@@ -0,0 +1,354 @@+<script setup lang="ts">+import { computed, ref } from "vue";+import { ChevronDown, ChevronRight, Database, Folder, Search } from "@lucide/vue";+import { useI18n } from "vue-i18n";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import type { ConnectionConfig, SidebarLayout, SidebarOrderEntry } from "@/types/database";++type ScopeMode = "all" | "custom";+type ExecutionMode = "read_only" | "safe_write" | "high_risk_write";+type ResourceNode = GroupNode | ConnectionNode;++interface GroupNode {+ type: "group";+ id: string;+ name: string;+ pathNames: string[];+ pathIds: string[];+ depth: number;+ children: ResourceNode[];+}++interface ConnectionNode {+ type: "connection";+ id: string;+ connection: ConnectionConfig;+ pathIds: string[];+ depth: number;+}++const props = withDefaults(+ defineProps<{+ layout: SidebarLayout;+ connections: readonly ConnectionConfig[];+ allowedGroupIds: readonly string[];+ allowedConnectionIds: readonly string[] | null;+ groupPolicies?: readonly { groupId: string; readOnly: boolean; allowDangerousSql: boolean }[];+ connectionPolicies?: readonly { connectionId: string; readOnly: boolean; allowDangerousSql: boolean; executionModeConfigured?: boolean }[];+ disabled?: boolean;+ busy?: boolean;+ }>(),+ { disabled: false, busy: false },+);++const emit = defineEmits<{+ "update:scope": [value: { allowedGroupIds: string[]; allowedConnectionIds: string[] | null }];+ "set:group-policy": [groupId: string, mode: ExecutionMode | "inherit"];+ "set:connection-policy": [connectionId: string, mode: ExecutionMode | "inherit"];+}>();++const { t } = useI18n();+const search = ref("");+const expandedGroupIds = ref(new Set<string>());+const initializedExpansion = ref(false);++const scopeMode = computed<ScopeMode>(() => (props.allowedConnectionIds === null ? "all" : "custom"));+const connectionById = computed(() => new Map(props.connections.map((connection) => [connection.id, connection])));+const groupNameById = computed(() => new Map(props.layout.groups.map((group) => [group.id, group.name])));++function entryChildren(entry: Extract<SidebarOrderEntry, { type: "group" }>): SidebarOrderEntry[] {+ return entry.children ?? entry.connectionIds?.map((id) => ({ type: "connection" as const, id })) ?? [];+}++const resourceTree = computed<ResourceNode[]>(() => {+ const seenConnections = new Set<string>();+ const seenGroups = new Set<string>();+ const build = (entries: SidebarOrderEntry[], pathIds: string[], pathNames: string[], depth: number): ResourceNode[] =>+ entries.flatMap((entry): ResourceNode[] => {+ if (entry.type === "connection") {+ const connection = connectionById.value.get(entry.id);+ if (!connection || seenConnections.has(entry.id)) return [];+ seenConnections.add(entry.id);+ return [{ type: "connection", id: entry.id, connection, pathIds, depth }];+ }+ if (seenGroups.has(entry.id)) return [];+ const name = groupNameById.value.get(entry.id);+ if (!name) return [];+ seenGroups.add(entry.id);+ const nextPathIds = [...pathIds, entry.id];+ const nextPathNames = [...pathNames, name];+ return [{ type: "group", id: entry.id, name, pathIds: nextPathIds, pathNames: nextPathNames, depth, children: build(entryChildren(entry), nextPathIds, nextPathNames, depth + 1) }];+ });++ const nodes = build(props.layout.order, [], [], 0);+ for (const connection of props.connections) {+ if (!seenConnections.has(connection.id)) nodes.push({ type: "connection", id: connection.id, connection, pathIds: [], depth: 0 });+ }+ if (!initializedExpansion.value) {+ expandedGroupIds.value = new Set();+ initializedExpansion.value = true;+ }+ return nodes;+});++const selectedGroupIds = computed(() => new Set(props.allowedGroupIds));+const explicitConnectionIds = computed(() => new Set(props.allowedConnectionIds ?? []));++function selectedAncestor(node: ResourceNode): string | null {+ const ancestors = node.type === "group" ? node.pathIds.slice(0, -1) : node.pathIds;+ for (let index = ancestors.length - 1; index >= 0; index -= 1) {+ if (selectedGroupIds.value.has(ancestors[index])) return ancestors[index];+ }+ return null;+}++function groupLabel(groupId: string): string {+ const group = allGroups.value.get(groupId);+ return group?.pathNames.join(" / ") ?? groupId;+}++const allGroups = computed(() => {+ const result = new Map<string, GroupNode>();+ const visit = (nodes: ResourceNode[]) => {+ for (const node of nodes) {+ if (node.type !== "group") continue;+ result.set(node.id, node);+ visit(node.children);+ }+ };+ visit(resourceTree.value);+ return result;+});++function descendants(group: GroupNode): { groupIds: string[]; connectionIds: string[] } {+ const groupIds: string[] = [];+ const connectionIds: string[] = [];+ const visit = (nodes: ResourceNode[]) => {+ for (const node of nodes) {+ if (node.type === "connection") connectionIds.push(node.id);+ else {+ groupIds.push(node.id);+ visit(node.children);+ }+ }+ };+ visit(group.children);+ return { groupIds, connectionIds };+}++const effectiveConnectionIds = computed(() => {+ if (props.allowedConnectionIds === null) return new Set(props.connections.map((connection) => connection.id));+ const result = new Set(props.allowedConnectionIds);+ for (const groupId of props.allowedGroupIds) {+ const group = allGroups.value.get(groupId);+ if (!group) continue;+ for (const connectionId of descendants(group).connectionIds) result.add(connectionId);+ }+ return result;+});++const groupCoveredConnectionIds = computed(() => {+ const result = new Set<string>();+ for (const groupId of props.allowedGroupIds) {+ const group = allGroups.value.get(groupId);+ if (!group) continue;+ for (const connectionId of descendants(group).connectionIds) result.add(connectionId);+ }+ return result;+});++const directConnectionCount = computed(() => props.connections.filter((connection) => explicitConnectionIds.value.has(connection.id) && !groupCoveredConnectionIds.value.has(connection.id)).length);++const directGroupCount = computed(+ () =>+ props.allowedGroupIds.filter((groupId) => {+ const group = allGroups.value.get(groupId);+ return group && !selectedAncestor(group);+ }).length,+);++const summary = computed(() =>+ scopeMode.value === "all"+ ? t("settings.mcpResourceScopeAllSummary", { count: props.connections.length })+ : t("settings.mcpResourceScopeCustomSummary", {+ effective: props.connections.filter((connection) => effectiveConnectionIds.value.has(connection.id)).length,+ groups: directGroupCount.value,+ connections: directConnectionCount.value,+ }),+);++function searchableText(node: ResourceNode): string {+ if (node.type === "group") return node.pathNames.join(" ").toLocaleLowerCase();+ const connection = node.connection;+ return [connection.name, connection.db_type, connection.host, connection.port, connection.database, connection.id].filter(Boolean).join(" ").toLocaleLowerCase();+}++function subtreeMatches(node: ResourceNode, query: string): boolean {+ if (searchableText(node).includes(query)) return true;+ return node.type === "group" && node.children.some((child) => subtreeMatches(child, query));+}++const visibleRows = computed(() => {+ const rows: ResourceNode[] = [];+ const query = search.value.trim().toLocaleLowerCase();+ const visit = (nodes: ResourceNode[], includeAll = false) => {+ for (const node of nodes) {+ const ownMatch = !query || searchableText(node).includes(query);+ if (query && !includeAll && !subtreeMatches(node, query)) continue;+ rows.push(node);+ if (node.type === "group" && (query || expandedGroupIds.value.has(node.id))) visit(node.children, includeAll || ownMatch);+ }+ };+ visit(resourceTree.value);+ return rows;+});++function setScopeMode(mode: ScopeMode) {+ if (props.disabled || mode === scopeMode.value) return;+ if (mode === "all" && (props.allowedGroupIds.length > 0 || (props.allowedConnectionIds?.length ?? 0) > 0) && !window.confirm(t("settings.mcpResourceScopeAllConfirm"))) return;+ emit("update:scope", mode === "all" ? { allowedGroupIds: [], allowedConnectionIds: null } : { allowedGroupIds: [], allowedConnectionIds: [] });+}++function groupHasSelectedDescendant(group: GroupNode): boolean {+ const childIds = descendants(group);+ return childIds.groupIds.some((id) => selectedGroupIds.value.has(id)) || childIds.connectionIds.some((id) => explicitConnectionIds.value.has(id));+}++function toggleExpanded(groupId: string) {+ const next = new Set(expandedGroupIds.value);+ if (next.has(groupId)) next.delete(groupId);+ else next.add(groupId);+ expandedGroupIds.value = next;+}++function setGroupAllowed(group: GroupNode, allowed: boolean) {+ if (props.disabled || selectedAncestor(group)) return;+ const childIds = descendants(group);+ const nextGroups = props.allowedGroupIds.filter((id) => id !== group.id && (!allowed || !childIds.groupIds.includes(id)));+ const nextConnections = (props.allowedConnectionIds ?? []).filter((id) => !allowed || !childIds.connectionIds.includes(id));+ if (allowed) nextGroups.push(group.id);+ emit("update:scope", { allowedGroupIds: nextGroups, allowedConnectionIds: nextConnections });+}++function setConnectionAllowed(connectionId: string, allowed: boolean) {+ if (props.disabled) return;+ const next = new Set(props.allowedConnectionIds ?? []);+ if (allowed) next.add(connectionId);+ else next.delete(connectionId);+ emit("update:scope", { allowedGroupIds: [...props.allowedGroupIds], allowedConnectionIds: [...next] });+}++function policyMode(policy: { readOnly: boolean; allowDangerousSql: boolean; executionModeConfigured?: boolean } | undefined): ExecutionMode | "inherit" {+ if (!policy || policy.executionModeConfigured === false) return "inherit";+ if (policy.readOnly) return "read_only";+ return policy.allowDangerousSql ? "high_risk_write" : "safe_write";+}++function groupPolicyMode(groupId: string): ExecutionMode | "inherit" {+ return policyMode(props.groupPolicies?.find((policy) => policy.groupId === groupId));+}++function connectionPolicyMode(connectionId: string): ExecutionMode | "inherit" {+ return policyMode(props.connectionPolicies?.find((policy) => policy.connectionId === connectionId));+}+</script>++<template>+ <section class="overflow-hidden rounded-md border bg-background" :aria-busy="busy">+ <div class="flex flex-wrap items-start justify-between gap-3 p-3">+ <div class="min-w-0 space-y-1">+ <p class="text-sm font-medium">{{ t("settings.mcpResourceScopeTitle") }}</p>+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpResourceScopeDescription") }}</p>+ </div>+ <Badge variant="outline" class="max-w-full rounded-md font-normal">{{ summary }}</Badge>+ </div>++ <div class="grid grid-cols-2 gap-1 border-t bg-muted/40 p-1" role="radiogroup" :aria-label="t('settings.mcpResourceScopeTitle')">+ <Button type="button" role="radio" variant="ghost" class="h-9" :class="scopeMode === 'all' ? 'bg-background shadow-sm' : 'text-muted-foreground'" :aria-checked="scopeMode === 'all'" :disabled="disabled" @click="setScopeMode('all')">+ {{ t("settings.mcpScopeModeAll") }}+ </Button>+ <Button type="button" role="radio" variant="ghost" class="h-9" :class="scopeMode === 'custom' ? 'bg-background shadow-sm' : 'text-muted-foreground'" :aria-checked="scopeMode === 'custom'" :disabled="disabled" @click="setScopeMode('custom')">+ {{ t("settings.mcpResourceScopeModeCustom") }}+ </Button>+ </div>++ <template v-if="scopeMode === 'custom'">+ <div class="border-t p-2">+ <div class="relative">+ <Search class="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input v-model="search" class="h-8 pl-8 text-xs" :placeholder="t('settings.mcpResourceScopeSearch')" :disabled="disabled" />+ </div>+ </div>+ <div v-if="visibleRows.length" class="max-h-80 overflow-auto border-t py-1" role="tree" :aria-label="t('settings.mcpResourceScopeTreeLabel')">+ <div+ v-for="node in visibleRows"+ :key="`${node.type}:${node.id}`"+ role="treeitem"+ class="flex min-h-9 items-center gap-2 px-2 text-xs hover:bg-muted/50"+ :aria-level="node.depth + 1"+ :aria-expanded="node.type === 'group' ? (search.trim() ? true : expandedGroupIds.has(node.id)) : undefined"+ :style="{ paddingLeft: `${8 + node.depth * 18}px` }"+ >+ <button v-if="node.type === 'group'" type="button" class="flex size-6 shrink-0 items-center justify-center rounded hover:bg-muted" :aria-label="node.name" @click="toggleExpanded(node.id)">+ <ChevronDown v-if="search.trim() || expandedGroupIds.has(node.id)" class="size-3.5" />+ <ChevronRight v-else class="size-3.5" />+ </button>+ <span v-else class="size-6 shrink-0" />++ <input+ v-if="node.type === 'group'"+ type="checkbox"+ :checked="selectedGroupIds.has(node.id) || Boolean(selectedAncestor(node))"+ :indeterminate="!selectedGroupIds.has(node.id) && !selectedAncestor(node) && groupHasSelectedDescendant(node)"+ :disabled="disabled || Boolean(selectedAncestor(node))"+ :aria-checked="!selectedGroupIds.has(node.id) && !selectedAncestor(node) && groupHasSelectedDescendant(node) ? 'mixed' : selectedGroupIds.has(node.id) || Boolean(selectedAncestor(node))"+ :aria-label="node.pathNames.join(' / ')"+ @change="setGroupAllowed(node, ($event.target as HTMLInputElement).checked)"+ />+ <input v-else type="checkbox" :checked="explicitConnectionIds.has(node.id) || Boolean(selectedAncestor(node))" :disabled="disabled || Boolean(selectedAncestor(node))" :aria-label="node.connection.name" @change="setConnectionAllowed(node.id, ($event.target as HTMLInputElement).checked)" />++ <Folder v-if="node.type === 'group'" class="size-4 shrink-0 text-muted-foreground" />+ <Database v-else class="size-4 shrink-0 text-muted-foreground" />+ <div class="min-w-0 flex-1">+ <p class="truncate font-medium">{{ node.type === "group" ? node.name : node.connection.name }}</p>+ <p v-if="node.type === 'connection'" class="truncate font-mono text-[10px] text-muted-foreground">{{ node.connection.db_type }} · {{ node.connection.host || node.connection.database || node.id }}</p>+ </div>+ <select+ v-if="node.type === 'group' && selectedGroupIds.has(node.id)"+ :value="groupPolicyMode(node.id)"+ class="h-7 shrink-0 rounded border bg-background px-1.5 text-[11px]"+ :disabled="disabled || busy"+ @click.stop+ @change="emit('set:group-policy', node.id, ($event.target as HTMLSelectElement).value as ExecutionMode | 'inherit')"+ >+ <option value="inherit">{{ t("settings.mcpConnectionPolicyInherit") }}</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>+ <select+ v-if="node.type === 'connection' && (explicitConnectionIds.has(node.id) || Boolean(selectedAncestor(node)))"+ :value="connectionPolicyMode(node.id)"+ class="h-7 shrink-0 rounded border bg-background px-1.5 text-[11px]"+ :disabled="disabled || busy"+ @click.stop+ @change="emit('set:connection-policy', node.id, ($event.target as HTMLSelectElement).value as ExecutionMode | 'inherit')"+ >+ <option value="inherit">{{ selectedAncestor(node) ? t("settings.mcpGroupPolicyInherit") : t("settings.mcpConnectionPolicyInherit") }}</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 v-if="selectedAncestor(node)" variant="secondary" class="shrink-0 rounded font-normal">{{ t("settings.mcpResourceScopeInherited", { group: groupLabel(selectedAncestor(node)!) }) }}</Badge>+ <Badge v-else-if="node.type === 'group' && selectedGroupIds.has(node.id)" variant="outline" class="shrink-0 rounded font-normal">{{ t("settings.mcpResourceScopeDynamic") }}</Badge>+ <Badge v-else-if="node.type === 'group' && groupHasSelectedDescendant(node)" variant="secondary" class="shrink-0 rounded font-normal">{{ t("settings.mcpResourceScopePartial") }}</Badge>+ <Badge v-else-if="node.type === 'connection' && explicitConnectionIds.has(node.id)" variant="outline" class="shrink-0 rounded font-normal">{{ t("settings.mcpResourceScopeDirect") }}</Badge>+ </div>+ </div>+ <p v-else class="border-t px-3 py-8 text-center text-xs text-muted-foreground">{{ t("settings.mcpResourceScopeEmpty") }}</p>+ <p class="border-t px-3 py-2 text-[11px] text-muted-foreground">{{ t("settings.mcpResourceScopeHint") }}</p>+ </template>+ </section>+</template>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 81a334ac91..9ce35ec46a 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -7270,20 +7270,37 @@ export default {mcpRefresh: "Check again",mcpGuide: "MCP guide",mcpAuthTitle: "MCP authorization",- mcpAuthDescription: "Complete the authorization in order: choose connections first, then limit databases and connection exceptions, and finally set the available tools and the global execution level.",+ mcpAuthDescription: "Complete authorization in order: set the global default, choose groups and connections, limit databases, then review the final policy.",mcpAuthStepsLabel: "MCP authorization steps",- mcpAuthStepConnectionsTitle: "Connection scope",- mcpAuthStepConnectionsDescription: "Decides which connections MCP can see",+ mcpAuthStepConnectionsTitle: "Groups and connections",+ mcpAuthStepConnectionsDescription: "Choose what MCP can see and set connection permissions",mcpAuthStepDatabasesTitle: "Database scope",- mcpAuthStepDatabasesDescription: "Limit the databases each connection can access",- mcpAuthStepOverridesTitle: "Connection defaults",- mcpAuthStepOverridesDescription: "Set the default execution permission for each connection",- mcpAuthStepCapabilitiesTitle: "Capabilities and execution",- mcpAuthStepCapabilitiesDescription: "Choose MCP tools and the global default operation level",+ mcpAuthStepDatabasesDescription: "Limit each connection's databases and set database permissions",+ mcpAuthStepOverridesTitle: "Default permissions",+ mcpAuthStepOverridesDescription: "Set the global default for all later scopes",+ mcpAuthStepCapabilitiesTitle: "Summary and review",+ mcpAuthStepCapabilitiesDescription: "Review effective permissions, choose tools, and confirm",mcpAuthStepRegionLabel: "Step {step}: {title}",mcpAuthPreviousStep: "Previous",mcpAuthNextStep: "Next",mcpAuthStepProgress: "Step {current} of {total}",+ mcpResourceScopeTitle: "Connections visible to MCP",+ mcpResourceScopeDescription: "Select groups for dynamic coverage and individual connections for precise exceptions.",+ mcpResourceScopeModeCustom: "Custom scope",+ mcpResourceScopeAllSummary: "All {count} connections",+ mcpResourceScopeCustomSummary: "{effective} effective · {groups} group rules · {connections} direct rules",+ mcpResourceScopeSearch: "Search groups or connections",+ mcpResourceScopeTreeLabel: "MCP connection resource tree",+ mcpResourceScopeInherited: "From {group}",+ mcpResourceScopeDynamic: "Dynamic",+ mcpResourceScopeDirect: "Direct",+ mcpResourceScopePartial: "Partially allowed",+ mcpResourceScopeEmpty: "No matching groups or connections.",+ mcpResourceScopeHint: "A selected group includes its current and future descendant connections. Direct selections are independent exceptions.",+ mcpResourceScopeAllConfirm: "Switching to all connections removes the current custom group and connection rules. Continue?",+ mcpPermissionGlobalDefaultHint: "Group, connection, and database permissions override this default, but never expand connection visibility.",+ mcpDatabasePolicyHighRiskConfirm: "Allow high-risk writes for this database? Connection read-only and production protections still apply.",+ mcpDatabaseScopeClearsPermissionExceptions: "Changing this database scope will remove its database permission exceptions. Continue?",mcpPerPage: "Per page",mcpPreviousPage: "Previous page",mcpNextPage: "Next page",@@ -7295,7 +7312,7 @@ export default {mcpDatabaseScopeSummaryNone: "No database access",mcpDatabaseScopeSummarySelected: "{count} selected",mcpDatabaseScopePermissionNote: "The selected scope does not change the connection's existing database permissions in DBX.",- mcpDatabaseLoadButton: "Load from connection",+ mcpDatabaseLoadButton: "Load resource list",mcpDatabaseScopeAriaLabel: "Database access scope",mcpDatabaseScopeAllTitle: "All databases",mcpDatabaseScopeAllDescription: "Keep the current access scope",@@ -7308,19 +7325,40 @@ export default {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.",+ mcpPermissionPreviewDescription: "Permission precedence: database, connection, nearest group, ancestor group, then global default.",mcpPermissionPreviewConnection: "Connection",mcpPermissionPreviewDatabase: "Database",mcpPermissionPreviewConnectionDefault: "Connection default",+ mcpPermissionPreviewGroupDefault: "Group default",+ mcpGroupScopeTitle: "Connection groups",+ mcpGroupScopeDescription: "Selecting a group dynamically exposes all of its current and future descendant connections. Other connections can still be added explicitly.",+ mcpGroupScopeSelected: "{count} groups selected",+ mcpGroupScopeSearch: "Search group paths",+ mcpGroupScopeNoResults: "No matching groups found.",+ mcpGroupScopeEmpty: "There are no connection groups to configure.",+ mcpGroupPolicyTitle: "Group default permissions",+ mcpGroupPolicyDescription: "A child group overrides its parent; connection and database settings can override the group default.",+ mcpGroupPolicyInherit: "Inherit parent or global",+ mcpGroupPolicyHighRiskConfirm: "Allow high-risk writes for this group? Connection read-only and production protections still apply.",mcpPermissionPreviewDatabaseOverride: "Database priority setting",mcpPermissionPreviewEffective: "Effective",+ mcpPermissionPreviewResource: "Resource",+ mcpPermissionPreviewSource: "Source",+ mcpPermissionSourceDatabase: "Database exception",+ mcpPermissionSourceConnection: "Connection exception",+ mcpPermissionSourceGroup: "Group: {group}",+ mcpPermissionSourceGlobal: "Global default",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.",- mcpDatabaseEmptyHint: "Click 'Load from connection' to fetch the database list, or add allowed databases manually.",+ mcpDatabaseEmptyHint: "Click 'Load resource list' to fetch the database list, or add allowed databases manually.",+ mcpManagementAccess: "Access methods",+ mcpManagementPermissions: "Permission management",+ mcpTransportLabel: "Connection type",+ mcpRuntimeSettings: "Runtime settings",mcpTransportLocalStdio: "Local stdio",mcpTransportHttpService: "HTTP service",mcpHttpWebServiceTitle: "Web Streamable HTTP service",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex b3316a43d1..3c2ea013d5 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -6815,20 +6815,43 @@ export default withEnglishFallback({mcpRefresh: "Comprobar de nuevo",mcpGuide: "Guía MCP",mcpAuthTitle: "Autorización de MCP",- mcpAuthDescription: "Completa la autorización en orden: elige primero las conexiones, luego limita las bases de datos y las excepciones por conexión y, por último, define las herramientas disponibles y el nivel de ejecución global.",+ mcpAuthDescription: "Completa la autorización en orden: define el valor global, elige grupos y conexiones, limita las bases de datos y revisa la política final.",mcpAuthStepsLabel: "Pasos de autorización de MCP",- mcpAuthStepConnectionsTitle: "Alcance de conexiones",- mcpAuthStepConnectionsDescription: "Define qué conexiones puede ver MCP",+ mcpAuthStepConnectionsTitle: "Grupos y conexiones",+ mcpAuthStepConnectionsDescription: "Elige lo que MCP puede ver y configura los permisos",mcpAuthStepDatabasesTitle: "Alcance de bases de datos",- mcpAuthStepDatabasesDescription: "Limita las bases de datos accesibles 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 predeterminado",+ mcpAuthStepDatabasesDescription: "Limita las bases de datos y configura permisos por base",+ mcpAuthStepOverridesTitle: "Permisos predeterminados",+ mcpAuthStepOverridesDescription: "Define el permiso global para los ámbitos posteriores",+ mcpAuthStepCapabilitiesTitle: "Resumen y confirmación",+ mcpAuthStepCapabilitiesDescription: "Revisa los permisos efectivos, elige herramientas y confirma",mcpAuthStepRegionLabel: "Paso {step}: {title}",mcpAuthPreviousStep: "Anterior",mcpAuthNextStep: "Siguiente",mcpAuthStepProgress: "Paso {current} de {total}",+ mcpResourceScopeTitle: "Conexiones visibles para MCP",+ mcpResourceScopeDescription: "Selecciona grupos para una cobertura dinámica y conexiones individuales para excepciones precisas.",+ mcpResourceScopeModeCustom: "Ámbito personalizado",+ mcpResourceScopeAllSummary: "Las {count} conexiones",+ mcpResourceScopeCustomSummary: "{effective} efectivas · {groups} reglas de grupo · {connections} reglas directas",+ mcpResourceScopeSearch: "Buscar grupos o conexiones",+ mcpResourceScopeTreeLabel: "Árbol de recursos de conexiones MCP",+ mcpResourceScopeInherited: "De {group}",+ mcpResourceScopeDynamic: "Dinámico",+ mcpResourceScopeDirect: "Directo",+ mcpResourceScopePartial: "Permitido parcialmente",+ mcpResourceScopeEmpty: "No hay grupos ni conexiones coincidentes.",+ mcpResourceScopeHint: "Un grupo seleccionado incluye sus conexiones descendientes actuales y futuras. Las selecciones directas son excepciones independientes.",+ mcpResourceScopeAllConfirm: "Al cambiar a todas las conexiones se eliminan las reglas actuales de grupos y conexiones personalizadas. ¿Continuar?",+ mcpPermissionGlobalDefaultHint: "Los permisos de grupo, conexión y base de datos reemplazan este valor predeterminado, pero nunca amplían la visibilidad de las conexiones.",+ mcpDatabasePolicyHighRiskConfirm: "¿Permitir escrituras de alto riesgo para esta base de datos? Las protecciones de solo lectura y producción de la conexión siguen aplicándose.",+ mcpDatabaseScopeClearsPermissionExceptions: "Al cambiar este ámbito de base de datos se eliminarán sus excepciones de permisos. ¿Continuar?",+ mcpPermissionPreviewResource: "Recurso",+ mcpPermissionPreviewSource: "Origen",+ mcpPermissionSourceDatabase: "Excepción de base de datos",+ mcpPermissionSourceConnection: "Excepción de conexión",+ mcpPermissionSourceGroup: "Grupo: {group}",+ mcpPermissionSourceGlobal: "Predeterminado global",mcpPerPage: "Por página",mcpPreviousPage: "Página anterior",mcpNextPage: "Página siguiente",@@ -6840,7 +6863,7 @@ export default withEnglishFallback({mcpDatabaseScopeSummaryNone: "Sin acceso a bases de datos",mcpDatabaseScopeSummarySelected: "{count} seleccionadas",mcpDatabaseScopePermissionNote: "El alcance seleccionado no cambia los permisos de bases de datos que la conexión ya tiene en DBX.",- mcpDatabaseLoadButton: "Cargar desde la conexión",+ mcpDatabaseLoadButton: "Cargar lista de recursos",mcpDatabaseScopeAriaLabel: "Alcance de acceso a bases de datos",mcpDatabaseScopeAllTitle: "Todas las bases de datos",mcpDatabaseScopeAllDescription: "Mantiene el alcance de acceso actual",@@ -6853,10 +6876,21 @@ export default withEnglishFallback({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.",+ mcpPermissionPreviewDescription: "Prioridad: base de datos, conexión, grupo más cercano, grupo superior y valor global.",mcpPermissionPreviewConnection: "Conexión",mcpPermissionPreviewDatabase: "Base de datos",mcpPermissionPreviewConnectionDefault: "Predeterminado de conexión",+ mcpPermissionPreviewGroupDefault: "Predeterminado del grupo",+ mcpGroupScopeTitle: "Grupos de conexiones",+ mcpGroupScopeDescription: "Seleccionar un grupo expone dinámicamente todas sus conexiones descendientes actuales y futuras. También puede agregar otras conexiones de forma explícita.",+ mcpGroupScopeSelected: "{count} grupos seleccionados",+ mcpGroupScopeSearch: "Buscar rutas de grupos",+ mcpGroupScopeNoResults: "No se encontraron grupos coincidentes.",+ mcpGroupScopeEmpty: "No hay grupos de conexiones para configurar.",+ mcpGroupPolicyTitle: "Permisos predeterminados del grupo",+ mcpGroupPolicyDescription: "Un grupo hijo reemplaza al padre; la conexión y la base de datos pueden reemplazar al grupo.",+ mcpGroupPolicyInherit: "Heredar del padre o global",+ mcpGroupPolicyHighRiskConfirm: "¿Permitir escrituras de alto riesgo para este grupo? Las protecciones de solo lectura y producción siguen activas.",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.",@@ -6865,7 +6899,11 @@ export default withEnglishFallback({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.",- mcpDatabaseEmptyHint: "Haz clic en 'Cargar desde la conexión' para obtener la lista de bases de datos o añade manualmente las permitidas.",+ mcpDatabaseEmptyHint: "Haz clic en 'Cargar lista de recursos' para obtener la lista de bases de datos o añade manualmente las permitidas.",+ mcpManagementAccess: "Métodos de acceso",+ mcpManagementPermissions: "Gestión de permisos",+ mcpTransportLabel: "Tipo de conexión",+ mcpRuntimeSettings: "Ajustes de ejecución",mcpTransportLocalStdio: "stdio local",mcpTransportHttpService: "Servicio HTTP",mcpHttpWebServiceTitle: "Servicio Web Streamable HTTP",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 00a7389944..642e224be8 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -6815,20 +6815,43 @@ export default withEnglishFallback({mcpRefresh: "Verifica di nuovo",mcpGuide: "Guida MCP",mcpAuthTitle: "Autorizzazione MCP",- mcpAuthDescription: "Completa l'autorizzazione in ordine: scegli prima le connessioni, poi limita i database e le eccezioni per connessione e infine definisci gli strumenti disponibili e il livello di esecuzione globale.",+ mcpAuthDescription: "Completa l'autorizzazione in ordine: imposta il valore globale, scegli gruppi e connessioni, limita i database e rivedi la policy finale.",mcpAuthStepsLabel: "Passaggi di autorizzazione MCP",- mcpAuthStepConnectionsTitle: "Ambito connessioni",+ mcpAuthStepConnectionsTitle: "Gruppi e connessioni",mcpAuthStepConnectionsDescription: "Determina quali connessioni MCP può vedere",mcpAuthStepDatabasesTitle: "Ambito database",mcpAuthStepDatabasesDescription: "Limita i database accessibili per ogni 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 predefinito",+ mcpAuthStepOverridesTitle: "Permessi predefiniti",+ mcpAuthStepOverridesDescription: "Imposta il permesso globale per gli ambiti successivi",+ mcpAuthStepCapabilitiesTitle: "Riepilogo e conferma",+ mcpAuthStepCapabilitiesDescription: "Rivedi i permessi effettivi, scegli gli strumenti e conferma",mcpAuthStepRegionLabel: "Passaggio {step}: {title}",mcpAuthPreviousStep: "Indietro",mcpAuthNextStep: "Avanti",mcpAuthStepProgress: "Passaggio {current} di {total}",+ mcpResourceScopeTitle: "Connessioni visibili a MCP",+ mcpResourceScopeDescription: "Seleziona gruppi per una copertura dinamica e singole connessioni per eccezioni precise.",+ mcpResourceScopeModeCustom: "Ambito personalizzato",+ mcpResourceScopeAllSummary: "Tutte le {count} connessioni",+ mcpResourceScopeCustomSummary: "{effective} effettive · {groups} regole di gruppo · {connections} regole dirette",+ mcpResourceScopeSearch: "Cerca gruppi o connessioni",+ mcpResourceScopeTreeLabel: "Albero delle risorse di connessione MCP",+ mcpResourceScopeInherited: "Da {group}",+ mcpResourceScopeDynamic: "Dinamico",+ mcpResourceScopeDirect: "Diretto",+ mcpResourceScopePartial: "Consentito parzialmente",+ mcpResourceScopeEmpty: "Nessun gruppo o connessione corrispondente.",+ mcpResourceScopeHint: "Un gruppo selezionato include le connessioni discendenti attuali e future. Le selezioni dirette sono eccezioni indipendenti.",+ mcpResourceScopeAllConfirm: "Il passaggio a tutte le connessioni rimuove le regole correnti di gruppi e connessioni personalizzate. Continuare?",+ mcpPermissionGlobalDefaultHint: "I permessi di gruppo, connessione e database sostituiscono questo valore predefinito, ma non ampliano mai la visibilità delle connessioni.",+ mcpDatabasePolicyHighRiskConfirm: "Consentire scritture ad alto rischio per questo database? Le protezioni di sola lettura e produzione della connessione restano attive.",+ mcpDatabaseScopeClearsPermissionExceptions: "La modifica di questo ambito database rimuoverà le relative eccezioni di autorizzazione. Continuare?",+ mcpPermissionPreviewResource: "Risorsa",+ mcpPermissionPreviewSource: "Origine",+ mcpPermissionSourceDatabase: "Eccezione database",+ mcpPermissionSourceConnection: "Eccezione connessione",+ mcpPermissionSourceGroup: "Gruppo: {group}",+ mcpPermissionSourceGlobal: "Predefinito globale",mcpPerPage: "Per pagina",mcpPreviousPage: "Pagina precedente",mcpNextPage: "Pagina successiva",@@ -6840,7 +6863,7 @@ export default withEnglishFallback({mcpDatabaseScopeSummaryNone: "Nessun accesso ai database",mcpDatabaseScopeSummarySelected: "{count} selezionati",mcpDatabaseScopePermissionNote: "L'ambito selezionato non modifica le autorizzazioni database già esistenti della connessione in DBX.",- mcpDatabaseLoadButton: "Carica dalla connessione",+ mcpDatabaseLoadButton: "Carica elenco risorse",mcpDatabaseScopeAriaLabel: "Ambito di accesso ai database",mcpDatabaseScopeAllTitle: "Tutti i database",mcpDatabaseScopeAllDescription: "Mantiene l'ambito di accesso attuale",@@ -6853,10 +6876,21 @@ export default withEnglishFallback({mcpDatabasePolicySetting: "Impostazione prioritaria database",mcpDatabasePolicyEffective: "Effettivo: {mode}",mcpPermissionPreviewTitle: "Anteprima permessi",- mcpPermissionPreviewDescription: "I permessi seguono la priorità di ambito: database, poi connessione, infine valore globale.",+ mcpPermissionPreviewDescription: "Priorità: database, connessione, gruppo più vicino, gruppo superiore e valore globale.",mcpPermissionPreviewConnection: "Connessione",mcpPermissionPreviewDatabase: "Database",mcpPermissionPreviewConnectionDefault: "Predefinito connessione",+ mcpPermissionPreviewGroupDefault: "Predefinito gruppo",+ mcpGroupScopeTitle: "Gruppi di connessioni",+ mcpGroupScopeDescription: "La selezione di un gruppo espone dinamicamente tutte le connessioni discendenti presenti e future. È ancora possibile aggiungere altre connessioni.",+ mcpGroupScopeSelected: "{count} gruppi selezionati",+ mcpGroupScopeSearch: "Cerca percorsi gruppo",+ mcpGroupScopeNoResults: "Nessun gruppo corrispondente.",+ mcpGroupScopeEmpty: "Non ci sono gruppi di connessioni da configurare.",+ mcpGroupPolicyTitle: "Permessi predefiniti del gruppo",+ mcpGroupPolicyDescription: "Un gruppo figlio sostituisce il padre; connessione e database possono sostituire il gruppo.",+ mcpGroupPolicyInherit: "Eredita dal padre o globale",+ mcpGroupPolicyHighRiskConfirm: "Consentire scritture ad alto rischio per questo gruppo? Le protezioni di sola lettura e produzione restano attive.",mcpPermissionPreviewDatabaseOverride: "Impostazione prioritaria database",mcpPermissionPreviewEffective: "Effettivo",mcpPermissionPreviewEmpty: "Consenti prima almeno una connessione e configurane l'ambito database.",@@ -6865,7 +6899,11 @@ export default withEnglishFallback({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.",- mcpDatabaseEmptyHint: "Fai clic su 'Carica dalla connessione' per ottenere l'elenco dei database oppure aggiungi manualmente quelli consentiti.",+ mcpDatabaseEmptyHint: "Fai clic su 'Carica elenco risorse' per ottenere l'elenco dei database oppure aggiungi manualmente quelli consentiti.",+ mcpManagementAccess: "Modalità di accesso",+ mcpManagementPermissions: "Gestione autorizzazioni",+ mcpTransportLabel: "Tipo di connessione",+ mcpRuntimeSettings: "Impostazioni di esecuzione",mcpTransportLocalStdio: "stdio locale",mcpTransportHttpService: "Servizio HTTP",mcpHttpWebServiceTitle: "Servizio Web Streamable HTTP",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 59b8dbaee8..084bfc27d2 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -6822,20 +6822,43 @@ export default withEnglishFallback({mcpRefresh: "再確認",mcpGuide: "MCPガイド",mcpAuthTitle: "MCP 権限設定",- mcpAuthDescription: "順番に設定を進めてください:まず接続を選択し、次にデータベースと接続ごとの例外を制限し、最後に利用するツールとグローバル実行レベルを確定します。",+ mcpAuthDescription: "順番に設定します:グローバル既定値、グループと接続、データベース範囲を設定し、最後に最終ポリシーを確認します。",mcpAuthStepsLabel: "MCP 権限設定の手順",- mcpAuthStepConnectionsTitle: "接続範囲",+ mcpAuthStepConnectionsTitle: "グループと接続",mcpAuthStepConnectionsDescription: "MCP に公開する接続を決定します",mcpAuthStepDatabasesTitle: "データベース範囲",mcpAuthStepDatabasesDescription: "接続ごとにアクセス可能なデータベースを制限します",- mcpAuthStepOverridesTitle: "接続の既定権限",- mcpAuthStepOverridesDescription: "接続ごとの既定の実行権限を設定します",- mcpAuthStepCapabilitiesTitle: "機能と実行",- mcpAuthStepCapabilitiesDescription: "MCP ツールとグローバル既定の操作レベルを選択します",+ mcpAuthStepOverridesTitle: "既定の権限",+ mcpAuthStepOverridesDescription: "後続の範囲に適用するグローバル既定値を設定します",+ mcpAuthStepCapabilitiesTitle: "概要と確認",+ mcpAuthStepCapabilitiesDescription: "有効な権限を確認し、ツールを選択して確定します",mcpAuthStepRegionLabel: "ステップ {step}:{title}",mcpAuthPreviousStep: "前へ",mcpAuthNextStep: "次へ",mcpAuthStepProgress: "ステップ {current} / {total}",+ mcpResourceScopeTitle: "MCP から表示する接続",+ mcpResourceScopeDescription: "動的な範囲にはグループを、個別の例外には接続を選択します。",+ mcpResourceScopeModeCustom: "カスタム範囲",+ mcpResourceScopeAllSummary: "全 {count} 接続",+ mcpResourceScopeCustomSummary: "有効 {effective} 件 · グループルール {groups} 件 · 直接ルール {connections} 件",+ mcpResourceScopeSearch: "グループまたは接続を検索",+ mcpResourceScopeTreeLabel: "MCP 接続リソースツリー",+ mcpResourceScopeInherited: "{group} から",+ mcpResourceScopeDynamic: "動的",+ mcpResourceScopeDirect: "直接",+ mcpResourceScopePartial: "一部許可",+ mcpResourceScopeEmpty: "一致するグループまたは接続がありません。",+ mcpResourceScopeHint: "選択したグループには現在および今後の子孫接続が含まれます。直接選択は独立した例外です。",+ mcpResourceScopeAllConfirm: "すべての接続に切り替えると、現在のカスタムグループと接続ルールが削除されます。続行しますか?",+ mcpPermissionGlobalDefaultHint: "グループ、接続、データベースの権限はこの既定値を上書きしますが、接続の表示範囲を拡張することはありません。",+ mcpDatabasePolicyHighRiskConfirm: "このデータベースで高リスク書き込みを許可しますか?接続の読み取り専用および本番保護は引き続き適用されます。",+ mcpDatabaseScopeClearsPermissionExceptions: "このデータベース範囲を変更すると、データベース権限の例外が削除されます。続行しますか?",+ mcpPermissionPreviewResource: "リソース",+ mcpPermissionPreviewSource: "適用元",+ mcpPermissionSourceDatabase: "データベース例外",+ mcpPermissionSourceConnection: "接続例外",+ mcpPermissionSourceGroup: "グループ: {group}",+ mcpPermissionSourceGlobal: "グローバル既定値",mcpPerPage: "表示件数",mcpPreviousPage: "前のページ",mcpNextPage: "次のページ",@@ -6847,7 +6870,7 @@ export default withEnglishFallback({mcpDatabaseScopeSummaryNone: "データベースアクセスなし",mcpDatabaseScopeSummarySelected: "{count} 件を選択済み",mcpDatabaseScopePermissionNote: "範囲を選択しても、DBX 内のこの接続の既存のデータベース権限は変更されません。",- mcpDatabaseLoadButton: "接続から読み込む",+ mcpDatabaseLoadButton: "リソース一覧を読み込む",mcpDatabaseScopeAriaLabel: "データベースアクセス範囲",mcpDatabaseScopeAllTitle: "すべてのデータベース",mcpDatabaseScopeAllDescription: "現在のアクセス範囲を維持",@@ -6860,10 +6883,21 @@ export default withEnglishFallback({mcpDatabasePolicySetting: "データベース優先設定",mcpDatabasePolicyEffective: "有効: {mode}",mcpPermissionPreviewTitle: "権限プレビュー",- mcpPermissionPreviewDescription: "権限はスコープの優先順で決まります:データベース、接続既定、グローバル既定。",+ mcpPermissionPreviewDescription: "権限の優先順:データベース、接続、最も近いグループ、上位グループ、グローバル。",mcpPermissionPreviewConnection: "接続",mcpPermissionPreviewDatabase: "データベース",mcpPermissionPreviewConnectionDefault: "接続の既定",+ mcpPermissionPreviewGroupDefault: "グループの既定",+ mcpGroupScopeTitle: "接続グループ",+ mcpGroupScopeDescription: "グループを選択すると、現在および今後追加されるすべての子孫接続が動的に公開されます。他の接続も個別に追加できます。",+ mcpGroupScopeSelected: "{count} グループを選択",+ mcpGroupScopeSearch: "グループパスを検索",+ mcpGroupScopeNoResults: "一致するグループがありません。",+ mcpGroupScopeEmpty: "設定可能な接続グループがありません。",+ mcpGroupPolicyTitle: "グループの既定権限",+ mcpGroupPolicyDescription: "子グループは親を上書きし、接続とデータベースの設定はグループを上書きできます。",+ mcpGroupPolicyInherit: "親またはグローバルを継承",+ mcpGroupPolicyHighRiskConfirm: "このグループに高リスク書き込みを許可しますか?接続の読み取り専用と本番保護は引き続き有効です。",mcpPermissionPreviewDatabaseOverride: "データベース優先設定",mcpPermissionPreviewEffective: "最終権限",mcpPermissionPreviewEmpty: "先に少なくとも 1 つの接続を許可し、データベース範囲を設定してください。",@@ -6872,7 +6906,11 @@ export default withEnglishFallback({mcpDatabaseSearchPlaceholder: "読み込み済みデータベースを絞り込み",mcpDatabaseManualPlaceholder: "データベース名を手動追加",mcpDatabaseLoadFailed: "データベースの読み込みに失敗しました:{error}。正確なデータベース名を手動で追加できます。",- mcpDatabaseEmptyHint: "「接続から読み込む」をクリックしてデータベース一覧を取得するか、許可するデータベースを手動で追加してください。",+ mcpDatabaseEmptyHint: "「リソース一覧を読み込む」をクリックしてデータベース一覧を取得するか、許可するデータベースを手動で追加してください。",+ mcpManagementAccess: "接続方式",+ mcpManagementPermissions: "権限管理",+ mcpTransportLabel: "接続タイプ",+ mcpRuntimeSettings: "実行設定",mcpTransportLocalStdio: "ローカル stdio",mcpTransportHttpService: "HTTP サービス",mcpHttpWebServiceTitle: "Web Streamable HTTP サービス",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 168f276e52..a8e49578ec 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -6568,20 +6568,43 @@ export default withEnglishFallback({mcpRefresh: "다시 확인",mcpGuide: "MCP 가이드",mcpAuthTitle: "MCP 권한 설정",- mcpAuthDescription: "순서대로 권한을 설정하세요: 먼저 연결을 선택하고, 데이터베이스와 연결 예외를 제한한 뒤, 마지막으로 사용할 도구와 전역 실행 수준을 확정합니다.",+ mcpAuthDescription: "순서대로 권한을 설정하세요: 전역 기본값을 정하고 그룹과 연결, 데이터베이스 범위를 설정한 뒤 최종 정책을 확인합니다.",mcpAuthStepsLabel: "MCP 권한 설정 단계",- mcpAuthStepConnectionsTitle: "연결 범위",+ mcpAuthStepConnectionsTitle: "그룹 및 연결",mcpAuthStepConnectionsDescription: "MCP에 노출할 연결을 결정합니다",mcpAuthStepDatabasesTitle: "데이터베이스 범위",mcpAuthStepDatabasesDescription: "연결별로 접근 가능한 데이터베이스를 제한합니다",- mcpAuthStepOverridesTitle: "연결 기본 권한",- mcpAuthStepOverridesDescription: "연결별 기본 실행 권한을 설정합니다",- mcpAuthStepCapabilitiesTitle: "기능 및 실행",- mcpAuthStepCapabilitiesDescription: "MCP 도구와 전역 기본 작업 수준을 선택합니다",+ mcpAuthStepOverridesTitle: "기본 권한",+ mcpAuthStepOverridesDescription: "이후 범위에 적용할 전역 기본 권한을 설정합니다",+ mcpAuthStepCapabilitiesTitle: "요약 및 확인",+ mcpAuthStepCapabilitiesDescription: "최종 권한을 검토하고 도구를 선택한 뒤 확인합니다",mcpAuthStepRegionLabel: "단계 {step}: {title}",mcpAuthPreviousStep: "이전",mcpAuthNextStep: "다음",mcpAuthStepProgress: "{total}단계 중 {current}단계",+ mcpResourceScopeTitle: "MCP에 표시되는 연결",+ mcpResourceScopeDescription: "동적 범위에는 그룹을 선택하고 정확한 예외에는 개별 연결을 선택하세요.",+ mcpResourceScopeModeCustom: "사용자 지정 범위",+ mcpResourceScopeAllSummary: "모든 {count}개 연결",+ mcpResourceScopeCustomSummary: "유효 {effective}개 · 그룹 규칙 {groups}개 · 직접 규칙 {connections}개",+ mcpResourceScopeSearch: "그룹 또는 연결 검색",+ mcpResourceScopeTreeLabel: "MCP 연결 리소스 트리",+ mcpResourceScopeInherited: "{group}에서 상속",+ mcpResourceScopeDynamic: "동적",+ mcpResourceScopeDirect: "직접",+ mcpResourceScopePartial: "부분 허용",+ mcpResourceScopeEmpty: "일치하는 그룹 또는 연결이 없습니다.",+ mcpResourceScopeHint: "선택한 그룹에는 현재와 미래의 모든 하위 연결이 포함됩니다. 직접 선택은 독립적인 예외입니다.",+ mcpResourceScopeAllConfirm: "모든 연결로 전환하면 현재 사용자 지정 그룹 및 연결 규칙이 제거됩니다. 계속하시겠습니까?",+ mcpPermissionGlobalDefaultHint: "그룹, 연결 및 데이터베이스 권한은 이 기본값을 재정의하지만 연결 표시 범위를 확장하지는 않습니다.",+ mcpDatabasePolicyHighRiskConfirm: "이 데이터베이스에 고위험 쓰기를 허용하시겠습니까? 연결 읽기 전용 및 운영 환경 보호는 계속 적용됩니다.",+ mcpDatabaseScopeClearsPermissionExceptions: "이 데이터베이스 범위를 변경하면 데이터베이스 권한 예외가 제거됩니다. 계속하시겠습니까?",+ mcpPermissionPreviewResource: "리소스",+ mcpPermissionPreviewSource: "적용 출처",+ mcpPermissionSourceDatabase: "데이터베이스 예외",+ mcpPermissionSourceConnection: "연결 예외",+ mcpPermissionSourceGroup: "그룹: {group}",+ mcpPermissionSourceGlobal: "전역 기본값",mcpPerPage: "페이지당",mcpPreviousPage: "이전 페이지",mcpNextPage: "다음 페이지",@@ -6593,7 +6616,7 @@ export default withEnglishFallback({mcpDatabaseScopeSummaryNone: "데이터베이스 접근 없음",mcpDatabaseScopeSummarySelected: "{count}개 선택됨",mcpDatabaseScopePermissionNote: "범위를 선택해도 DBX에서 이 연결의 기존 데이터베이스 권한은 변경되지 않습니다.",- mcpDatabaseLoadButton: "연결에서 불러오기",+ mcpDatabaseLoadButton: "리소스 목록 불러오기",mcpDatabaseScopeAriaLabel: "데이터베이스 접근 범위",mcpDatabaseScopeAllTitle: "모든 데이터베이스",mcpDatabaseScopeAllDescription: "현재 접근 범위 유지",@@ -6606,10 +6629,21 @@ export default withEnglishFallback({mcpDatabasePolicySetting: "데이터베이스 우선 설정",mcpDatabasePolicyEffective: "적용됨: {mode}",mcpPermissionPreviewTitle: "권한 미리보기",- mcpPermissionPreviewDescription: "권한은 범위 우선순위로 결정됩니다: 데이터베이스, 연결 기본값, 전역 기본값.",+ mcpPermissionPreviewDescription: "권한 우선순위: 데이터베이스, 연결, 가장 가까운 그룹, 상위 그룹, 전역 기본값.",mcpPermissionPreviewConnection: "연결",mcpPermissionPreviewDatabase: "데이터베이스",mcpPermissionPreviewConnectionDefault: "연결 기본값",+ mcpPermissionPreviewGroupDefault: "그룹 기본값",+ mcpGroupScopeTitle: "연결 그룹",+ mcpGroupScopeDescription: "그룹을 선택하면 현재 및 향후의 모든 하위 연결이 동적으로 노출됩니다. 다른 연결도 개별적으로 추가할 수 있습니다.",+ mcpGroupScopeSelected: "{count}개 그룹 선택됨",+ mcpGroupScopeSearch: "그룹 경로 검색",+ mcpGroupScopeNoResults: "일치하는 그룹이 없습니다.",+ mcpGroupScopeEmpty: "구성할 연결 그룹이 없습니다.",+ mcpGroupPolicyTitle: "그룹 기본 권한",+ mcpGroupPolicyDescription: "하위 그룹은 상위 그룹을 재정의하며 연결 및 데이터베이스 설정은 그룹 기본값을 재정의할 수 있습니다.",+ mcpGroupPolicyInherit: "상위 또는 전역 상속",+ mcpGroupPolicyHighRiskConfirm: "이 그룹에 고위험 쓰기를 허용하시겠습니까? 연결 읽기 전용 및 프로덕션 보호는 계속 적용됩니다.",mcpPermissionPreviewDatabaseOverride: "데이터베이스 우선 설정",mcpPermissionPreviewEffective: "최종 적용",mcpPermissionPreviewEmpty: "먼저 하나 이상의 연결을 허용하고 데이터베이스 범위를 설정하세요.",@@ -6618,7 +6652,11 @@ export default withEnglishFallback({mcpDatabaseSearchPlaceholder: "불러온 데이터베이스 필터",mcpDatabaseManualPlaceholder: "데이터베이스 이름 직접 추가",mcpDatabaseLoadFailed: "데이터베이스 불러오기 실패: {error}. 정확한 데이터베이스 이름을 직접 추가할 수 있습니다.",- mcpDatabaseEmptyHint: "'연결에서 불러오기'를 클릭해 데이터베이스 목록을 가져오거나, 허용할 데이터베이스를 직접 추가하세요.",+ mcpDatabaseEmptyHint: "'리소스 목록 불러오기'를 클릭해 데이터베이스 목록을 가져오거나, 허용할 데이터베이스를 직접 추가하세요.",+ mcpManagementAccess: "접속 방식",+ mcpManagementPermissions: "권한 관리",+ mcpTransportLabel: "연결 유형",+ mcpRuntimeSettings: "실행 설정",mcpTransportLocalStdio: "로컬 stdio",mcpTransportHttpService: "HTTP 서비스",mcpHttpWebServiceTitle: "Web Streamable HTTP 서비스",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex c761619969..295c7dfa9a 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -6817,20 +6817,43 @@ export default withEnglishFallback({mcpRefresh: "Verificar novamente",mcpGuide: "Guia do MCP",mcpAuthTitle: "Autorização do MCP",- mcpAuthDescription: "Conclua a autorização em ordem: escolha as conexões primeiro, depois limite os bancos de dados e as exceções por conexão e, por fim, defina as ferramentas disponíveis e o nível de execução global.",+ mcpAuthDescription: "Conclua a autorização em ordem: defina o padrão global, escolha grupos e conexões, limite os bancos e revise a política final.",mcpAuthStepsLabel: "Etapas de autorização do MCP",- mcpAuthStepConnectionsTitle: "Escopo de conexões",+ mcpAuthStepConnectionsTitle: "Grupos e conexões",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: "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 padrão",+ mcpAuthStepOverridesTitle: "Permissões padrão",+ mcpAuthStepOverridesDescription: "Defina a permissão global para os escopos seguintes",+ mcpAuthStepCapabilitiesTitle: "Resumo e confirmação",+ mcpAuthStepCapabilitiesDescription: "Revise as permissões efetivas, escolha as ferramentas e confirme",mcpAuthStepRegionLabel: "Etapa {step}: {title}",mcpAuthPreviousStep: "Voltar",mcpAuthNextStep: "Avançar",mcpAuthStepProgress: "Etapa {current} de {total}",+ mcpResourceScopeTitle: "Conexões visíveis ao MCP",+ mcpResourceScopeDescription: "Selecione grupos para cobertura dinâmica e conexões individuais para exceções precisas.",+ mcpResourceScopeModeCustom: "Escopo personalizado",+ mcpResourceScopeAllSummary: "Todas as {count} conexões",+ mcpResourceScopeCustomSummary: "{effective} efetivas · {groups} regras de grupo · {connections} regras diretas",+ mcpResourceScopeSearch: "Pesquisar grupos ou conexões",+ mcpResourceScopeTreeLabel: "Árvore de recursos de conexões MCP",+ mcpResourceScopeInherited: "De {group}",+ mcpResourceScopeDynamic: "Dinâmico",+ mcpResourceScopeDirect: "Direto",+ mcpResourceScopePartial: "Parcialmente permitido",+ mcpResourceScopeEmpty: "Nenhum grupo ou conexão correspondente.",+ mcpResourceScopeHint: "Um grupo selecionado inclui suas conexões descendentes atuais e futuras. Seleções diretas são exceções independentes.",+ mcpResourceScopeAllConfirm: "Mudar para todas as conexões remove as regras atuais de grupos e conexões personalizadas. Continuar?",+ mcpPermissionGlobalDefaultHint: "As permissões de grupo, conexão e banco de dados substituem este padrão, mas nunca ampliam a visibilidade das conexões.",+ mcpDatabasePolicyHighRiskConfirm: "Permitir gravações de alto risco para este banco de dados? As proteções de somente leitura e de produção da conexão continuam aplicadas.",+ mcpDatabaseScopeClearsPermissionExceptions: "Alterar este escopo de banco de dados removerá suas exceções de permissão. Continuar?",+ mcpPermissionPreviewResource: "Recurso",+ mcpPermissionPreviewSource: "Origem",+ mcpPermissionSourceDatabase: "Exceção de banco de dados",+ mcpPermissionSourceConnection: "Exceção de conexão",+ mcpPermissionSourceGroup: "Grupo: {group}",+ mcpPermissionSourceGlobal: "Padrão global",mcpPerPage: "Por página",mcpPreviousPage: "Página anterior",mcpNextPage: "Próxima página",@@ -6842,7 +6865,7 @@ export default withEnglishFallback({mcpDatabaseScopeSummaryNone: "Sem acesso a bancos",mcpDatabaseScopeSummarySelected: "{count} selecionados",mcpDatabaseScopePermissionNote: "O escopo selecionado não altera as permissões de bancos que a conexão já tem no DBX.",- mcpDatabaseLoadButton: "Carregar da conexão",+ mcpDatabaseLoadButton: "Carregar lista de recursos",mcpDatabaseScopeAriaLabel: "Escopo de acesso aos bancos",mcpDatabaseScopeAllTitle: "Todos os bancos de dados",mcpDatabaseScopeAllDescription: "Mantém o escopo de acesso atual",@@ -6855,10 +6878,21 @@ export default withEnglishFallback({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.",+ mcpPermissionPreviewDescription: "Prioridade: banco, conexão, grupo mais próximo, grupo superior e padrão global.",mcpPermissionPreviewConnection: "Conexão",mcpPermissionPreviewDatabase: "Banco de dados",mcpPermissionPreviewConnectionDefault: "Padrão da conexão",+ mcpPermissionPreviewGroupDefault: "Padrão do grupo",+ mcpGroupScopeTitle: "Grupos de conexões",+ mcpGroupScopeDescription: "Selecionar um grupo expõe dinamicamente todas as conexões descendentes atuais e futuras. Outras conexões ainda podem ser adicionadas explicitamente.",+ mcpGroupScopeSelected: "{count} grupos selecionados",+ mcpGroupScopeSearch: "Buscar caminhos de grupos",+ mcpGroupScopeNoResults: "Nenhum grupo correspondente.",+ mcpGroupScopeEmpty: "Não há grupos de conexões para configurar.",+ mcpGroupPolicyTitle: "Permissões padrão do grupo",+ mcpGroupPolicyDescription: "Um grupo filho substitui o pai; conexão e banco de dados podem substituir o grupo.",+ mcpGroupPolicyInherit: "Herdar do pai ou global",+ mcpGroupPolicyHighRiskConfirm: "Permitir gravações de alto risco para este grupo? As proteções de somente leitura e produção continuam ativas.",mcpPermissionPreviewDatabaseOverride: "Configuração prioritária do banco",mcpPermissionPreviewEffective: "Efetiva",mcpPermissionPreviewEmpty: "Permita primeiro ao menos uma conexão e configure seu escopo de bancos.",@@ -6867,7 +6901,11 @@ export default withEnglishFallback({mcpDatabaseSearchPlaceholder: "Filtrar bancos carregados",mcpDatabaseManualPlaceholder: "Adicionar nome do banco manualmente",mcpDatabaseLoadFailed: "Falha ao carregar bancos: {error}. Você pode adicionar manualmente os nomes exatos.",- mcpDatabaseEmptyHint: "Clique em 'Carregar da conexão' para obter a lista de bancos ou adicione manualmente os permitidos.",+ mcpDatabaseEmptyHint: "Clique em 'Carregar lista de recursos' para obter a lista de bancos ou adicione manualmente os permitidos.",+ mcpManagementAccess: "Formas de acesso",+ mcpManagementPermissions: "Gerenciamento de permissões",+ mcpTransportLabel: "Tipo de conexão",+ mcpRuntimeSettings: "Configurações de execução",mcpTransportLocalStdio: "stdio local",mcpTransportHttpService: "Serviço HTTP",mcpHttpWebServiceTitle: "Serviço Web Streamable HTTP",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex a3866cc572..80c34c0091 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -7184,20 +7184,37 @@ export default withEnglishFallback({mcpRefresh: "Yeniden denetle",mcpGuide: "MCP kılavuzu",mcpAuthTitle: "MCP yetkilendirmesi",- mcpAuthDescription: "Yetkilendirmeyi sırayla tamamlayın: önce bağlantıları seçin, sonra veritabanlarını ve bağlantı istisnalarını sınırlayın, en son kullanılabilir araçları ve genel yürütme düzeyini belirleyin.",+ mcpAuthDescription: "Yetkilendirmeyi sırayla tamamlayın: genel varsayılanı belirleyin, grup ve bağlantıları seçin, veritabanlarını sınırlayın ve son politikayı inceleyin.",mcpAuthStepsLabel: "MCP yetkilendirme adımları",- mcpAuthStepConnectionsTitle: "Bağlantı kapsamı",+ mcpAuthStepConnectionsTitle: "Gruplar ve bağlantılar",mcpAuthStepConnectionsDescription: "MCP'nin hangi bağlantıları görebileceğini belirler",mcpAuthStepDatabasesTitle: "Veritabanı kapsamı",mcpAuthStepDatabasesDescription: "Her bağlantının erişebileceği veritabanlarını sınırlayın",- mcpAuthStepOverridesTitle: "Bağlantı varsayılanları",- mcpAuthStepOverridesDescription: "Her bağlantı için varsayılan yürütme yetkisini belirleyin",- mcpAuthStepCapabilitiesTitle: "Yetenekler ve yürütme",- mcpAuthStepCapabilitiesDescription: "MCP araçlarını ve genel varsayılan işlem düzeyini seçin",+ mcpAuthStepOverridesTitle: "Varsayılan izinler",+ mcpAuthStepOverridesDescription: "Sonraki kapsamlar için genel varsayılan izni belirleyin",+ mcpAuthStepCapabilitiesTitle: "Özet ve onay",+ mcpAuthStepCapabilitiesDescription: "Etkin izinleri inceleyin, araçları seçin ve onaylayın",mcpAuthStepRegionLabel: "Adım {step}: {title}",mcpAuthPreviousStep: "Geri",mcpAuthNextStep: "İleri",mcpAuthStepProgress: "{total} adımdan {current}. adım",+ mcpResourceScopeTitle: "MCP'ye görünür bağlantılar",+ mcpResourceScopeDescription: "Dinamik kapsam için grupları, hassas istisnalar için tek tek bağlantıları seçin.",+ mcpResourceScopeModeCustom: "Özel kapsam",+ mcpResourceScopeAllSummary: "Tüm {count} bağlantı",+ mcpResourceScopeCustomSummary: "{effective} etkin · {groups} grup kuralı · {connections} doğrudan kural",+ mcpResourceScopeSearch: "Grup veya bağlantı ara",+ mcpResourceScopeTreeLabel: "MCP bağlantı kaynak ağacı",+ mcpResourceScopeInherited: "{group} grubundan",+ mcpResourceScopeDynamic: "Dinamik",+ mcpResourceScopeDirect: "Doğrudan",+ mcpResourceScopePartial: "Kısmen izinli",+ mcpResourceScopeEmpty: "Eşleşen grup veya bağlantı yok.",+ mcpResourceScopeHint: "Seçilen bir grup, mevcut ve gelecekteki alt bağlantılarını kapsar. Doğrudan seçimler bağımsız istisnalardır.",+ mcpResourceScopeAllConfirm: "Tüm bağlantılara geçmek, mevcut özel grup ve bağlantı kurallarını kaldırır. Devam edilsin mi?",+ mcpPermissionGlobalDefaultHint: "Grup, bağlantı ve veritabanı izinleri bu varsayılanı geçersiz kılar; ancak bağlantı görünürlüğünü asla genişletmez.",+ mcpDatabasePolicyHighRiskConfirm: "Bu veritabanı için yüksek riskli yazmalara izin verilsin mi? Bağlantı salt okunur ve üretim korumaları yine geçerlidir.",+ mcpDatabaseScopeClearsPermissionExceptions: "Bu veritabanı kapsamını değiştirmek, veritabanı izin istisnalarını kaldırır. Devam edilsin mi?",mcpPerPage: "Sayfa başına",mcpPreviousPage: "Önceki sayfa",mcpNextPage: "Sonraki sayfa",@@ -7209,7 +7226,7 @@ export default withEnglishFallback({mcpDatabaseScopeSummaryNone: "Veritabanı erişimi yok",mcpDatabaseScopeSummarySelected: "{count} seçildi",mcpDatabaseScopePermissionNote: "Seçili kapsam, bağlantının DBX'teki mevcut veritabanı yetkilerini değiştirmez.",- mcpDatabaseLoadButton: "Bağlantıdan yükle",+ mcpDatabaseLoadButton: "Kaynak listesini yükle",mcpDatabaseScopeAriaLabel: "Veritabanı erişim kapsamı",mcpDatabaseScopeAllTitle: "Tüm veritabanları",mcpDatabaseScopeAllDescription: "Geçerli erişim kapsamını koru",@@ -7222,19 +7239,40 @@ export default withEnglishFallback({mcpDatabasePolicySetting: "Veritabanı önceliği ayarı",mcpDatabasePolicyEffective: "Geçerli: {mode}",mcpPermissionPreviewTitle: "Yetki önizlemesi",- mcpPermissionPreviewDescription: "Yetkiler kapsama göre geri dönüş yapar: önce veritabanı ayarı, sonra bağlantı varsayılanı, sonra genel varsayılan.",+ mcpPermissionPreviewDescription: "Öncelik: veritabanı, bağlantı, en yakın grup, üst grup ve genel varsayılan.",mcpPermissionPreviewConnection: "Bağlantı",mcpPermissionPreviewDatabase: "Veritabanı",mcpPermissionPreviewConnectionDefault: "Bağlantı varsayılanı",+ mcpPermissionPreviewGroupDefault: "Grup varsayılanı",+ mcpGroupScopeTitle: "Bağlantı grupları",+ mcpGroupScopeDescription: "Bir grup seçildiğinde mevcut ve gelecekteki tüm alt bağlantılar dinamik olarak açılır. Diğer bağlantılar ayrıca eklenebilir.",+ mcpGroupScopeSelected: "{count} grup seçildi",+ mcpGroupScopeSearch: "Grup yollarını ara",+ mcpGroupScopeNoResults: "Eşleşen grup bulunamadı.",+ mcpGroupScopeEmpty: "Yapılandırılacak bağlantı grubu yok.",+ mcpGroupPolicyTitle: "Grup varsayılan izinleri",+ mcpGroupPolicyDescription: "Alt grup üst grubu geçersiz kılar; bağlantı ve veritabanı ayarları grup varsayılanını geçersiz kılabilir.",+ mcpGroupPolicyInherit: "Üst veya genelden devral",+ mcpGroupPolicyHighRiskConfirm: "Bu grup için yüksek riskli yazmalara izin verilsin mi? Salt okunur ve üretim korumaları geçerli kalır.",mcpPermissionPreviewDatabaseOverride: "Veritabanı önceliği ayarı",mcpPermissionPreviewEffective: "Geçerli",+ mcpPermissionPreviewResource: "Kaynak",+ mcpPermissionPreviewSource: "İzin kaynağı",+ mcpPermissionSourceDatabase: "Veritabanı istisnası",+ mcpPermissionSourceConnection: "Bağlantı istisnası",+ mcpPermissionSourceGroup: "Grup: {group}",+ mcpPermissionSourceGlobal: "Genel varsayılan",mcpPermissionPreviewEmpty: "Önce en az bir bağlantıya izin verin ve veritabanı kapsamını yapılandırın.",mcpPermissionPreviewSearchPlaceholder: "Bağlantı veya veritabanı ara",mcpPermissionPreviewSearchNoResults: "Eşleşen bağlantı ya da veritabanı bulunamadı.",mcpDatabaseSearchPlaceholder: "Yüklenen veritabanlarını filtrele",mcpDatabaseManualPlaceholder: "Elle bir veritabanı adı ekle",mcpDatabaseLoadFailed: "Veritabanları yüklenemedi: {error}. Veritabanı adlarını tam olarak elle ekleyebilirsiniz.",- mcpDatabaseEmptyHint: "Veritabanı listesini almak için 'Bağlantıdan yükle'ye tıklayın ya da izin verilen veritabanlarını elle ekleyin.",+ mcpDatabaseEmptyHint: "Veritabanı listesini almak için 'Kaynak listesini yükle'ye tıklayın ya da izin verilen veritabanlarını elle ekleyin.",+ mcpManagementAccess: "Erişim yöntemleri",+ mcpManagementPermissions: "İzin yönetimi",+ mcpTransportLabel: "Bağlantı türü",+ mcpRuntimeSettings: "Çalışma zamanı ayarları",mcpTransportLocalStdio: "Yerel stdio",mcpTransportHttpService: "HTTP servisi",mcpHttpWebServiceTitle: "Web Streamable HTTP servisi",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 7b1802ef26..2a5c4f6988 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -7255,20 +7255,37 @@ export default withEnglishFallback({mcpRefresh: "重新检查",mcpGuide: "MCP 指南",mcpAuthTitle: "MCP 授权设置",- mcpAuthDescription: "按顺序完成授权:先选择连接,再限定数据库和连接例外,最后确定可用工具与全局执行级别。",+ mcpAuthDescription: "按顺序完成授权:先设置全局默认权限,再选择分组与连接、限定数据库,最后确认最终策略。",mcpAuthStepsLabel: "MCP 授权步骤",- mcpAuthStepConnectionsTitle: "连接范围",- mcpAuthStepConnectionsDescription: "决定哪些连接可被 MCP 看见",+ mcpAuthStepConnectionsTitle: "分组与连接",+ mcpAuthStepConnectionsDescription: "决定哪些分组和连接可被 MCP 看见,并设置连接权限",mcpAuthStepDatabasesTitle: "数据库范围",- mcpAuthStepDatabasesDescription: "为每个连接限定可访问的库",- mcpAuthStepOverridesTitle: "连接默认权限",- mcpAuthStepOverridesDescription: "为每个连接设置默认执行权限",- mcpAuthStepCapabilitiesTitle: "能力与执行",- mcpAuthStepCapabilitiesDescription: "选择 MCP 工具和全局默认操作级别",+ mcpAuthStepDatabasesDescription: "为每个连接限定可访问的库,并设置单库权限",+ mcpAuthStepOverridesTitle: "默认权限",+ mcpAuthStepOverridesDescription: "设置全局默认权限,后续范围可按需覆盖",+ mcpAuthStepCapabilitiesTitle: "汇总与确认",+ mcpAuthStepCapabilitiesDescription: "查看最终生效权限、选择 MCP 工具并确认策略",mcpAuthStepRegionLabel: "第 {step} 步:{title}",mcpAuthPreviousStep: "上一步",mcpAuthNextStep: "下一步",mcpAuthStepProgress: "第 {current} 步,共 {total} 步",+ mcpResourceScopeTitle: "MCP 可见的连接",+ mcpResourceScopeDescription: "选择分组可动态覆盖其下连接,也可单独选择连接作为精确例外。",+ mcpResourceScopeModeCustom: "自定义范围",+ mcpResourceScopeAllSummary: "全部 {count} 个连接",+ mcpResourceScopeCustomSummary: "最终 {effective} 个连接 · {groups} 条分组规则 · {connections} 条单连接规则",+ mcpResourceScopeSearch: "搜索分组或连接",+ mcpResourceScopeTreeLabel: "MCP 连接资源树",+ mcpResourceScopeInherited: "来自 {group}",+ mcpResourceScopeDynamic: "动态包含",+ mcpResourceScopeDirect: "单独授权",+ mcpResourceScopePartial: "部分授权",+ mcpResourceScopeEmpty: "没有匹配的分组或连接。",+ mcpResourceScopeHint: "选中分组会包含当前及未来新增的所有下级连接;单连接授权是独立例外。",+ mcpResourceScopeAllConfirm: "切换到全部连接会清除当前的自定义分组和单连接规则,是否继续?",+ mcpPermissionGlobalDefaultHint: "分组、连接和数据库权限会覆盖此默认值,但不会扩大连接可见范围。",+ mcpDatabasePolicyHighRiskConfirm: "确认允许此数据库执行高风险写操作吗?连接只读与生产库保护仍会生效。",+ mcpDatabaseScopeClearsPermissionExceptions: "切换数据库范围会删除当前连接已有的单库权限例外,是否继续?",mcpPerPage: "每页",mcpPreviousPage: "上一页",mcpNextPage: "下一页",@@ -7280,7 +7297,7 @@ export default withEnglishFallback({mcpDatabaseScopeSummaryNone: "无库访问",mcpDatabaseScopeSummarySelected: "已选 {count} 个库",mcpDatabaseScopePermissionNote: "选择范围不会改变此连接在 DBX 中原有的数据库权限。",- mcpDatabaseLoadButton: "从连接加载",+ mcpDatabaseLoadButton: "加载资源列表",mcpDatabaseScopeAriaLabel: "数据库访问范围",mcpDatabaseScopeAllTitle: "全部数据库",mcpDatabaseScopeAllDescription: "保持现有访问范围",@@ -7293,19 +7310,40 @@ export default withEnglishFallback({mcpDatabasePolicySetting: "单库优先设置",mcpDatabasePolicyEffective: "生效:{mode}",mcpPermissionPreviewTitle: "权限预览",- mcpPermissionPreviewDescription: "权限按范围由小到大回退:单库设置优先,其次连接默认,最后全局默认。",+ mcpPermissionPreviewDescription: "权限优先级:单库设置、连接默认、最近的分组默认、上级分组默认、全局默认。",mcpPermissionPreviewConnection: "连接",mcpPermissionPreviewDatabase: "数据库",mcpPermissionPreviewConnectionDefault: "连接默认",+ mcpPermissionPreviewGroupDefault: "分组默认",+ mcpGroupScopeTitle: "连接分组",+ mcpGroupScopeDescription: "选择分组后,将动态开放其中当前及未来新增的所有下级连接;仍可单独添加其他连接。",+ mcpGroupScopeSelected: "已选 {count} 个分组",+ mcpGroupScopeSearch: "搜索分组路径",+ mcpGroupScopeNoResults: "未找到匹配的分组。",+ mcpGroupScopeEmpty: "当前没有可配置的连接分组。",+ mcpGroupPolicyTitle: "分组默认权限",+ mcpGroupPolicyDescription: "子分组覆盖父分组;连接和数据库设置可继续覆盖分组默认值。",+ mcpGroupPolicyInherit: "继承上级或全局",+ mcpGroupPolicyHighRiskConfirm: "确认允许此分组执行高风险写操作吗?连接只读与生产库保护仍会生效。",mcpPermissionPreviewDatabaseOverride: "单库优先设置",mcpPermissionPreviewEffective: "最终生效",+ mcpPermissionPreviewResource: "资源",+ mcpPermissionPreviewSource: "权限来源",+ mcpPermissionSourceDatabase: "数据库例外",+ mcpPermissionSourceConnection: "连接例外",+ mcpPermissionSourceGroup: "分组:{group}",+ mcpPermissionSourceGlobal: "全局默认",mcpPermissionPreviewEmpty: "请先允许至少一个连接,并配置可访问的数据库范围。",mcpPermissionPreviewSearchPlaceholder: "搜索连接或数据库",mcpPermissionPreviewSearchNoResults: "未找到匹配的连接或数据库。",mcpDatabaseSearchPlaceholder: "筛选已加载的数据库",mcpDatabaseManualPlaceholder: "手工添加库名",mcpDatabaseLoadFailed: "加载数据库失败:{error}。可手工添加准确的数据库名称。",- mcpDatabaseEmptyHint: "点击“从连接加载”获取数据库列表,或手工添加允许的数据库。",+ mcpDatabaseEmptyHint: "点击“加载资源列表”获取数据库列表,或手工添加允许的数据库。",+ mcpManagementAccess: "接入方式",+ mcpManagementPermissions: "权限管理",+ mcpTransportLabel: "接入类型",+ mcpRuntimeSettings: "运行参数",mcpTransportLocalStdio: "本地 stdio",mcpTransportHttpService: "HTTP 服务",mcpHttpWebServiceTitle: "Web Streamable HTTP 服务",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 423ab7b30a..8cb8f16f1e 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -6150,20 +6150,43 @@ export default withEnglishFallback({mcpRefresh: "重新檢查",mcpGuide: "MCP 指南",mcpAuthTitle: "MCP 授權設定",- mcpAuthDescription: "按順序完成授權:先選擇連線,再限定資料庫和連線例外,最後確定可用工具與全域執行層級。",+ mcpAuthDescription: "按順序完成授權:先設定全域預設權限,再選擇群組與連線、限定資料庫,最後確認最終策略。",mcpAuthStepsLabel: "MCP 授權步驟",- mcpAuthStepConnectionsTitle: "連線範圍",+ mcpAuthStepConnectionsTitle: "群組與連線",mcpAuthStepConnectionsDescription: "決定哪些連線可被 MCP 看見",mcpAuthStepDatabasesTitle: "資料庫範圍",mcpAuthStepDatabasesDescription: "為每個連線限定可存取的庫",- mcpAuthStepOverridesTitle: "連線預設權限",- mcpAuthStepOverridesDescription: "為每個連線設定預設執行權限",- mcpAuthStepCapabilitiesTitle: "能力與執行",- mcpAuthStepCapabilitiesDescription: "選擇 MCP 工具和全域預設操作層級",+ mcpAuthStepOverridesTitle: "預設權限",+ mcpAuthStepOverridesDescription: "設定套用至後續範圍的全域預設權限",+ mcpAuthStepCapabilitiesTitle: "摘要與確認",+ mcpAuthStepCapabilitiesDescription: "檢視最終權限、選擇工具並確認策略",mcpAuthStepRegionLabel: "第 {step} 步:{title}",mcpAuthPreviousStep: "上一步",mcpAuthNextStep: "下一步",mcpAuthStepProgress: "第 {current} 步,共 {total} 步",+ mcpResourceScopeTitle: "MCP 可見的連線",+ mcpResourceScopeDescription: "選擇群組可動態涵蓋其下連線,也可單獨選擇連線作為精確例外。",+ mcpResourceScopeModeCustom: "自訂範圍",+ mcpResourceScopeAllSummary: "全部 {count} 個連線",+ mcpResourceScopeCustomSummary: "最終 {effective} 個連線 · {groups} 條群組規則 · {connections} 條單連線規則",+ mcpResourceScopeSearch: "搜尋群組或連線",+ mcpResourceScopeTreeLabel: "MCP 連線資源樹",+ mcpResourceScopeInherited: "來自 {group}",+ mcpResourceScopeDynamic: "動態包含",+ mcpResourceScopeDirect: "單獨授權",+ mcpResourceScopePartial: "部分授權",+ mcpResourceScopeEmpty: "沒有符合的群組或連線。",+ mcpResourceScopeHint: "選取群組會包含目前及未來新增的所有下層連線;單連線授權是獨立例外。",+ mcpResourceScopeAllConfirm: "切換到全部連線會清除目前的自訂群組和單連線規則,是否繼續?",+ mcpPermissionGlobalDefaultHint: "群組、連線和資料庫權限會覆寫此預設值,但不會擴大連線可見範圍。",+ mcpDatabasePolicyHighRiskConfirm: "確認允許此資料庫執行高風險寫入操作嗎?連線唯讀與正式環境保護仍會生效。",+ mcpDatabaseScopeClearsPermissionExceptions: "切換資料庫範圍會移除目前的資料庫權限例外,是否繼續?",+ mcpPermissionPreviewResource: "資源",+ mcpPermissionPreviewSource: "權限來源",+ mcpPermissionSourceDatabase: "資料庫例外",+ mcpPermissionSourceConnection: "連線例外",+ mcpPermissionSourceGroup: "群組:{group}",+ mcpPermissionSourceGlobal: "全域預設",mcpPerPage: "每頁",mcpPreviousPage: "上一頁",mcpNextPage: "下一頁",@@ -6175,7 +6198,7 @@ export default withEnglishFallback({mcpDatabaseScopeSummaryNone: "無庫存取",mcpDatabaseScopeSummarySelected: "已選 {count} 個庫",mcpDatabaseScopePermissionNote: "選擇範圍不會改變此連線在 DBX 中原有的資料庫權限。",- mcpDatabaseLoadButton: "從連線載入",+ mcpDatabaseLoadButton: "載入資源清單",mcpDatabaseScopeAriaLabel: "資料庫存取範圍",mcpDatabaseScopeAllTitle: "全部資料庫",mcpDatabaseScopeAllDescription: "保持現有存取範圍",@@ -6188,10 +6211,21 @@ export default withEnglishFallback({mcpDatabasePolicySetting: "單庫優先設定",mcpDatabasePolicyEffective: "生效:{mode}",mcpPermissionPreviewTitle: "權限預覽",- mcpPermissionPreviewDescription: "權限依範圍由小到大回退:單庫設定優先,其次連線預設,最後全域預設。",+ mcpPermissionPreviewDescription: "權限優先順序:單庫設定、連線預設、最近的群組預設、上層群組預設、全域預設。",mcpPermissionPreviewConnection: "連線",mcpPermissionPreviewDatabase: "資料庫",mcpPermissionPreviewConnectionDefault: "連線預設",+ mcpPermissionPreviewGroupDefault: "群組預設",+ mcpGroupScopeTitle: "連線群組",+ mcpGroupScopeDescription: "選取群組後,會動態開放其中目前及未來新增的所有下層連線;仍可個別新增其他連線。",+ mcpGroupScopeSelected: "已選 {count} 個群組",+ mcpGroupScopeSearch: "搜尋群組路徑",+ mcpGroupScopeNoResults: "找不到相符的群組。",+ mcpGroupScopeEmpty: "目前沒有可設定的連線群組。",+ mcpGroupPolicyTitle: "群組預設權限",+ mcpGroupPolicyDescription: "子群組會覆寫父群組;連線與資料庫設定可繼續覆寫群組預設值。",+ mcpGroupPolicyInherit: "繼承上層或全域",+ mcpGroupPolicyHighRiskConfirm: "確定允許此群組執行高風險寫入嗎?連線唯讀與正式資料庫保護仍會生效。",mcpPermissionPreviewDatabaseOverride: "單庫優先設定",mcpPermissionPreviewEffective: "最終生效",mcpPermissionPreviewEmpty: "請先允許至少一個連線,並設定可存取的資料庫範圍。",@@ -6200,7 +6234,11 @@ export default withEnglishFallback({mcpDatabaseSearchPlaceholder: "篩選已載入的資料庫",mcpDatabaseManualPlaceholder: "手動新增庫名",mcpDatabaseLoadFailed: "載入資料庫失敗:{error}。可手動新增準確的資料庫名稱。",- mcpDatabaseEmptyHint: "點擊「從連線載入」取得資料庫清單,或手動新增允許的資料庫。",+ mcpDatabaseEmptyHint: "點擊「載入資源清單」取得資料庫清單,或手動新增允許的資料庫。",+ mcpManagementAccess: "接入方式",+ mcpManagementPermissions: "權限管理",+ mcpTransportLabel: "接入類型",+ mcpRuntimeSettings: "執行參數",mcpTransportLocalStdio: "本機 stdio",mcpTransportHttpService: "HTTP 服務",mcpHttpWebServiceTitle: "Web Streamable HTTP 服務",diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.tsindex 207c5c3f15..acd244d9ac 100644--- a/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts+++ b/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts@@ -81,7 +81,7 @@ describe("MCP policy settings state", () => {it("guards the mutation entry point and wires the shared disabled state to policy controls", () => {expect(settingsDialogSource).toContain("if (mcpPolicyControlsDisabled.value) return;");expect(settingsDialogSource).toContain(':disabled="mcpPolicyControlsDisabled"');- expect(settingsDialogSource).toContain('@update:allowed-connection-ids="onMcpAllowedConnectionIdsChange"');+ expect(settingsDialogSource).toContain('@update:scope="onMcpResourceScopeChange"');const loadingStart = settingsDialogSource.indexOf("mcpPolicyLoading.value = true;");const policyLoad = settingsDialogSource.indexOf("await settingsStore.initMcpGlobalPolicy(true);");@@ -91,23 +91,22 @@ describe("MCP policy settings state", () => {expect(loadingEnd).toBeGreaterThan(policyLoad);});- it("keeps translated mode descriptions in one responsive layout track", () => {- const descriptionStart = settingsDialogSource.indexOf("data-mcp-execution-mode-description");- const descriptionEnd = settingsDialogSource.indexOf("settings.mcpCapabilityTitle", descriptionStart);- const descriptionSource = settingsDialogSource.slice(descriptionStart, descriptionEnd);-- expect(descriptionStart).toBeGreaterThan(-1);- expect(descriptionEnd).toBeGreaterThan(descriptionStart);- expect(descriptionSource).toContain('class="grid text-xs"');- expect(descriptionSource.match(/col-start-1 row-start-1/g)).toHaveLength(3);- expect(descriptionSource.match(/\? 'visible' : 'invisible'/g)).toHaveLength(3);+ it("renders one static mode hint in place of stacked per-mode description tracks", () => {+ expect(settingsDialogSource).not.toContain("data-mcp-execution-mode-description");+ const groupStart = settingsDialogSource.indexOf('role="radiogroup" aria-labelledby="mcp-execution-mode-label"');+ const hintIndex = settingsDialogSource.indexOf("settings.mcpPermissionGlobalDefaultHint");+ expect(groupStart).toBeGreaterThan(-1);+ expect(hintIndex).toBeGreaterThan(groupStart);});it("keeps execution mode cards accessible as a keyboard radio group", () => {expect(settingsDialogSource).toContain('role="radiogroup" aria-labelledby="mcp-execution-mode-label"');- expect(settingsDialogSource.match(/role="radio"/g)).toHaveLength(3);- expect(settingsDialogSource).toContain(":aria-checked=\"mcpExecutionMode === 'safe_write'\"");- expect(settingsDialogSource).toContain("onMcpExecutionModeKeydown($event, 'safe_write')");+ expect(settingsDialogSource).toContain('v-for="mode in mcpExecutionModeOptions"');+ expect(settingsDialogSource.match(/role="radio"/g)).toHaveLength(1);+ expect(settingsDialogSource).toContain(':aria-checked="mcpExecutionMode === mode"');+ expect(settingsDialogSource).toContain(':tabindex="mcpExecutionMode === mode ? 0 : -1"');+ expect(settingsDialogSource).toContain("onMcpExecutionModeKeydown($event, mode)");+ expect(settingsDialogSource).toContain('@keydown="onMcpExecutionModeKeydown($event, mode)"');});it("keeps MCP client config tabs on a single scrollable row", () => {diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex d15172c017..df59d358da 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -250,12 +250,20 @@ export interface McpGlobalPolicy {readOnly: boolean;allowDangerousSql: boolean;allowedConnectionIds: string[] | null;+ allowedGroupIds: string[];allowedToolNames: string[] | null;connectionPolicies: McpConnectionPolicy[];+ groupPolicies: McpGroupPolicy[];configured: boolean;queryTimeoutSecs: number | null;}+export interface McpGroupPolicy {+ groupId: string;+ readOnly: boolean;+ allowDangerousSql: boolean;+}+export interface McpConnectionPolicy {connectionId: string;readOnly: boolean;diff --git a/apps/desktop/src/lib/sidebar/sidebarLayout.ts b/apps/desktop/src/lib/sidebar/sidebarLayout.tsindex aad1571f3a..159f0c7659 100644--- a/apps/desktop/src/lib/sidebar/sidebarLayout.ts+++ b/apps/desktop/src/lib/sidebar/sidebarLayout.ts@@ -337,6 +337,24 @@ export function buildConnectionGroupPathMap(layout: SidebarLayout): Map<string,return paths;}+/** Build root-to-leaf stable group-id paths for permission inheritance. */+export function buildConnectionGroupIdPathMap(layout: SidebarLayout): Map<string, string[]> {+ const paths = new Map<string, string[]>();++ const visit = (entries: SidebarOrderEntry[], path: string[]) => {+ for (const entry of entries) {+ if (entry.type === "connection") {+ paths.set(entry.id, path);+ continue;+ }+ visit(entryChildren(entry), [...path, entry.id]);+ }+ };++ visit(layout.order, []);+ return paths;+}+export interface ConnectionGroupDestinationRow {id: string;name: string;diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.tsindex 2bd307ff01..fe90edd679 100644--- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts+++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts@@ -493,8 +493,10 @@ describe("normalizeMcpGlobalPolicy", () => {readOnly: false,allowDangerousSql: false,allowedConnectionIds: null,+ allowedGroupIds: [],allowedToolNames: null,connectionPolicies: [],+ groupPolicies: [],configured: false,queryTimeoutSecs: null,});@@ -512,8 +514,10 @@ describe("normalizeMcpGlobalPolicy", () => {readOnly: true,allowDangerousSql: true,allowedConnectionIds: ["connection-1", "connection-2"],+ allowedGroupIds: [],allowedToolNames: null,connectionPolicies: [],+ groupPolicies: [],configured: true,queryTimeoutSecs: null,});@@ -811,8 +815,10 @@ describe("settingsStore MCP policy persistence", () => {readOnly: true,allowDangerousSql: false,allowedConnectionIds: ["connection-1"],+ allowedGroupIds: [],allowedToolNames: null,connectionPolicies: [],+ groupPolicies: [],configured: true,queryTimeoutSecs: null,};@@ -826,8 +832,10 @@ describe("settingsStore MCP policy persistence", () => {readOnly: false,allowDangerousSql: false,allowedConnectionIds: [],+ allowedGroupIds: [],allowedToolNames: null,connectionPolicies: [],+ groupPolicies: [],configured: true,queryTimeoutSecs: null,});diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.tsindex c407d197f5..fff3698f23 100644--- a/apps/desktop/src/stores/settingsStore.ts+++ b/apps/desktop/src/stores/settingsStore.ts@@ -53,13 +53,21 @@ export interface McpGlobalPolicy {readOnly: boolean;allowDangerousSql: boolean;allowedConnectionIds: string[] | null;+ allowedGroupIds: string[];allowedToolNames: string[] | null;connectionPolicies: McpConnectionPolicy[];+ groupPolicies: McpGroupPolicy[];configured: boolean;/** MCP query timeout override in seconds. null/undefined = inherit the connection; 0 = no limit. */queryTimeoutSecs: number | null;}+export interface McpGroupPolicy {+ groupId: string;+ readOnly: boolean;+ allowDangerousSql: boolean;+}+export interface McpConnectionPolicy {connectionId: string;readOnly: boolean;@@ -113,14 +121,17 @@ export const DEFAULT_MCP_GLOBAL_POLICY: McpGlobalPolicy = {readOnly: false,allowDangerousSql: false,allowedConnectionIds: null,+ allowedGroupIds: [],allowedToolNames: null,connectionPolicies: [],+ groupPolicies: [],configured: false,queryTimeoutSecs: null,};export function normalizeMcpGlobalPolicy(policy: Partial<McpGlobalPolicy> | null | undefined): McpGlobalPolicy {const allowedConnectionIds = policy?.allowedConnectionIds === null || policy?.allowedConnectionIds === undefined ? null : [...new Set(policy.allowedConnectionIds.filter((id): id is string => typeof id === "string" && id.trim().length > 0).map((id) => id.trim()))];+ const allowedGroupIds = allowedConnectionIds === null ? [] : [...new Set((policy?.allowedGroupIds ?? []).filter((id): id is string => typeof id === "string" && id.trim().length > 0).map((id) => id.trim()))];const allowedToolNames = policy?.allowedToolNames === null || policy?.allowedToolNames === undefined ? null : [...new Set(policy.allowedToolNames.filter((name): name is string => typeof name === "string" && name.trim().length > 0).map((name) => name.trim()))];const connectionPolicies = Object.values((policy?.connectionPolicies ?? []).reduce<Record<string, McpConnectionPolicy>>((rules, rule) => {@@ -156,6 +167,20 @@ export function normalizeMcpGlobalPolicy(policy: Partial<McpGlobalPolicy> | nullreturn rules;}, {}),);+ const groupPolicies = Object.values(+ (policy?.groupPolicies ?? []).reduce<Record<string, McpGroupPolicy>>((rules, rule) => {+ if (!rule || typeof rule.groupId !== "string" || !rule.groupId.trim()) return rules;+ const groupId = rule.groupId.trim();+ const current = rules[groupId];+ const readOnly = current?.readOnly === true || rule.readOnly === true;+ rules[groupId] = {+ groupId,+ readOnly,+ allowDangerousSql: !readOnly && (current ? current.allowDangerousSql && rule.allowDangerousSql === true : rule.allowDangerousSql === true),+ };+ return rules;+ }, {}),+ );// null / undefined / non-positive => null (inherit connection). 0 is preserved// as an explicit "no limit" only here; the UI maps "no limit" <=> 0 and// "inherit" <=> null.@@ -164,8 +189,10 @@ export function normalizeMcpGlobalPolicy(policy: Partial<McpGlobalPolicy> | nullreadOnly: policy?.readOnly === true,allowDangerousSql: policy?.allowDangerousSql === true,allowedConnectionIds,+ allowedGroupIds,allowedToolNames,connectionPolicies,+ groupPolicies,configured: policy?.configured === true,queryTimeoutSecs,};@@ -1783,8 +1810,10 @@ export const useSettingsStore = defineStore("settings", () => {readOnly: next.readOnly,allowDangerousSql: next.allowDangerousSql,allowedConnectionIds: next.allowedConnectionIds,+ allowedGroupIds: next.allowedGroupIds,allowedToolNames: next.allowedToolNames,connectionPolicies: next.connectionPolicies,+ groupPolicies: next.groupPolicies,queryTimeoutSecs: next.queryTimeoutSecs,});} catch (error) {diff --git a/crates/dbx-core/src/mcp_policy.rs b/crates/dbx-core/src/mcp_policy.rsindex 9e96cd18eb..32a0d495c8 100644--- a/crates/dbx-core/src/mcp_policy.rs+++ b/crates/dbx-core/src/mcp_policy.rs@@ -1,10 +1,107 @@+use std::collections::HashMap;+use crate::models::connection::ConnectionConfig;use crate::production_safety::sql_references_disallowed_database;use crate::storage::McpGlobalPolicy;+use serde::Deserialize;+use serde_json::Value;/// Version used by rules that opt into scoped override semantics.pub const MCP_EXECUTION_POLICY_VERSION: u8 = 1;+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct McpConnectionGroupPath {+ pub ids: Vec<String>,+ pub names: Vec<String>,+}++#[derive(Deserialize)]+struct SidebarLayout {+ #[serde(default)]+ groups: Vec<SidebarGroup>,+ #[serde(default)]+ order: Vec<SidebarOrderEntry>,+}++#[derive(Deserialize)]+struct SidebarGroup {+ id: String,+ name: String,+}++#[derive(Deserialize)]+#[serde(tag = "type")]+enum SidebarOrderEntry {+ #[serde(rename = "group")]+ Group {+ id: String,+ children: Option<Vec<SidebarOrderEntry>>,+ #[serde(rename = "connectionIds")]+ connection_ids: Option<Vec<String>>,+ },+ #[serde(rename = "connection")]+ Connection { id: String },+}++/// Resolve each connection's stable group ids and display names from the+/// persisted sidebar tree. Legacy `connectionIds` group entries remain valid.+pub fn connection_group_paths(layout: &Value) -> Result<HashMap<String, McpConnectionGroupPath>, String> {+ let layout = serde_json::from_value::<SidebarLayout>(layout.clone())+ .map_err(|error| format!("INVALID_SIDEBAR_LAYOUT: {error}"))?;+ let groups = layout.groups.into_iter().map(|group| (group.id, group.name)).collect::<HashMap<_, _>>();+ let mut paths = HashMap::new();+ collect_connection_group_paths(&layout.order, &groups, &mut McpConnectionGroupPath::default(), &mut paths)?;+ Ok(paths)+}++fn collect_connection_group_paths(+ entries: &[SidebarOrderEntry],+ groups: &HashMap<String, String>,+ path: &mut McpConnectionGroupPath,+ paths: &mut HashMap<String, McpConnectionGroupPath>,+) -> Result<(), String> {+ for entry in entries {+ match entry {+ SidebarOrderEntry::Connection { id } => {+ paths.insert(id.clone(), path.clone());+ }+ SidebarOrderEntry::Group { id, children, connection_ids } => {+ let name =+ groups.get(id).ok_or_else(|| format!("INVALID_SIDEBAR_LAYOUT: group '{id}' has no metadata"))?;+ path.ids.push(id.clone());+ path.names.push(name.clone());+ if let Some(children) = children {+ collect_connection_group_paths(children, groups, path, paths)?;+ } else if let Some(connection_ids) = connection_ids {+ for connection_id in connection_ids {+ paths.insert(connection_id.clone(), path.clone());+ }+ }+ path.ids.pop();+ path.names.pop();+ }+ }+ }+ Ok(())+}++pub fn policy_uses_connection_groups(policy: &McpGlobalPolicy) -> bool {+ !policy.allowed_group_ids.is_empty() || !policy.group_policies.is_empty()+}++pub fn policy_allows_connection(+ policy: &McpGlobalPolicy,+ group_path: Option<&McpConnectionGroupPath>,+ connection_id: &str,+) -> bool {+ policy.allowed_connection_ids.as_ref().is_none_or(|allowed| {+ allowed.iter().any(|id| id == connection_id)+ || group_path.is_some_and(|path| {+ path.ids.iter().any(|id| policy.allowed_group_ids.iter().any(|allowed| allowed == id))+ })+ })+}+/// 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();@@ -22,8 +119,22 @@ pub fn effective_database_execution_policy(policy: &McpGlobalPolicy,connection_id: &str,database: &str,+) -> (bool, bool) {+ effective_database_execution_policy_with_groups(policy, &[], connection_id, database)+}++pub fn effective_database_execution_policy_with_groups(+ policy: &McpGlobalPolicy,+ group_ids: &[String],+ connection_id: &str,+ database: &str,) -> (bool, bool) {let mut effective = (policy.read_only, policy.allow_dangerous_sql);+ for group_id in group_ids {+ if let Some(rule) = policy.group_policies.iter().find(|rule| rule.group_id == *group_id) {+ effective = (rule.read_only, !rule.read_only && rule.allow_dangerous_sql);+ }+ }let Some(rule) = policy.connection_policies.iter().find(|rule| rule.connection_id == connection_id) else {return effective;};diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rsindex 2eb0c07172..8ffe68bdbb 100644--- a/crates/dbx-core/src/query.rs+++ b/crates/dbx-core/src/query.rs@@ -6849,7 +6849,7 @@ for line in sys.stdin:let error = execute_sql_statement(&state, "conn-1", "", "SELECT 1", None, None).await.unwrap_err();assert!(error.contains("injected Agent failure"));- assert!(!state.pool_handle("conn-1").await.is_some());+ assert!(state.pool_handle("conn-1").await.is_none());assert!(runtime.is_failed());runtime.kill();@@ -6975,7 +6975,7 @@ for line in sys.stdin:.unwrap_err();assert!(error.contains("injected Agent failure"));- assert!(!state.pool_handle("conn-1").await.is_some());+ assert!(state.pool_handle("conn-1").await.is_none());assert!(runtime.is_failed());runtime.kill();@@ -6992,7 +6992,7 @@ for line in sys.stdin:.unwrap_err();assert!(error.contains("injected Agent failure"));- assert!(!state.pool_handle("conn-1").await.is_some());+ assert!(state.pool_handle("conn-1").await.is_none());assert!(runtime.is_failed());runtime.kill();@@ -7006,7 +7006,7 @@ for line in sys.stdin:let error = execute_sql_statement(&state, "conn-1", "", "SELECT 1", None, None).await.unwrap_err();assert!(error.contains("injected Agent failure"));- assert!(!state.pool_handle("conn-1").await.is_some());+ assert!(state.pool_handle("conn-1").await.is_none());assert!(!runtime.is_failed());runtime.kill();@@ -8550,7 +8550,7 @@ for line in sys.stdin:execute_in_manual_transaction(&state, "txn-test", "SELECT 42", "dbx_test", None, Some(10)).await.unwrap();assert_eq!(results[0].rows, vec![vec![serde_json::json!(42)]]);commit_manual_transaction(&state, "txn-test").await.unwrap();- assert!(!state.pool_handle(pool_key).await.is_some());+ assert!(state.pool_handle(pool_key).await.is_none());assert_eq!(std::fs::read_to_string(&calls).unwrap(),"beginManualTransaction\nexecuteInManualTransaction\ncommitManualTransaction\n"diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rsindex 4811156124..9c6f1dadce 100644--- a/crates/dbx-core/src/schema.rs+++ b/crates/dbx-core/src/schema.rs@@ -4097,7 +4097,7 @@ mod tests {replace_metadata_runtime(&state, "conn", Some("analytics"), None).await;- assert!(!state.pool_handle("conn:analytics:role:metadata").await.is_some());+ assert!(state.pool_handle("conn:analytics:role:metadata").await.is_none());let _ = std::fs::remove_dir_all(dir);}@@ -4126,7 +4126,7 @@ mod tests {assert_eq!(result.unwrap_err(), "Agent RPC call timed out (30s)");assert_eq!(attempts, 1);- assert!(!state.pool_handle("conn:role:metadata").await.is_some());+ assert!(state.pool_handle("conn:role:metadata").await.is_none());let _ = std::fs::remove_dir_all(dir);}@@ -4159,7 +4159,7 @@ mod tests {assert_eq!(result.unwrap_err(), quarantine);assert_eq!(attempts, 2);- assert!(!state.pool_handle("conn").await.is_some());+ assert!(state.pool_handle("conn").await.is_none());let _ = std::fs::remove_dir_all(dir);}@@ -4235,7 +4235,7 @@ for line in sys.stdin:Some(crate::db::agent_driver::AgentErrorCategory::Timeout));assert_eq!(std::fs::read_to_string(call_count_path).unwrap(), "1");- assert!(!state.pool_handle(pool_key).await.is_some());+ assert!(state.pool_handle(pool_key).await.is_none());runtime.kill();let _ = std::fs::remove_dir_all(dir);}diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rsindex c405ba00a5..57bff78341 100644--- a/crates/dbx-core/src/storage.rs+++ b/crates/dbx-core/src/storage.rs@@ -234,6 +234,10 @@ pub struct McpGlobalPolicy {#[serde(default)]pub allow_dangerous_sql: bool,pub allowed_connection_ids: Option<Vec<String>>,+ /// Stable sidebar group ids whose current descendant connections are+ /// exposed when an explicit connection scope is configured.+ #[serde(default)]+ pub allowed_group_ids: Vec<String>,/// `None` exposes every built-in MCP tool. A list is an explicit/// allowlist and is enforced independently of connection permissions.#[serde(default)]@@ -242,10 +246,25 @@ pub struct McpGlobalPolicy {/// the current execution policy version remain legacy ceilings.#[serde(default)]pub connection_policies: Vec<McpConnectionPolicy>,+ /// Execution defaults inherited by every connection currently contained+ /// in the referenced sidebar group. Nested groups are resolved from root+ /// to leaf, so the closest configured group wins.+ #[serde(default)]+ pub group_policies: Vec<McpGroupPolicy>,#[serde(default)]pub query_timeout_secs: Option<u64>,}+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct McpGroupPolicy {+ pub group_id: String,+ #[serde(default)]+ pub read_only: bool,+ #[serde(default)]+ pub allow_dangerous_sql: bool,+}+fn default_mcp_connection_execution_mode_configured() -> bool {true}@@ -368,10 +387,14 @@ pub struct McpGlobalPolicyState {pub allow_dangerous_sql: bool,pub allowed_connection_ids: Option<Vec<String>>,#[serde(default)]+ pub allowed_group_ids: Vec<String>,+ #[serde(default)]pub allowed_tool_names: Option<Vec<String>>,#[serde(default)]pub connection_policies: Vec<McpConnectionPolicy>,#[serde(default)]+ pub group_policies: Vec<McpGroupPolicy>,+ #[serde(default)]pub query_timeout_secs: Option<u64>,}@@ -381,8 +404,10 @@ impl McpGlobalPolicyState {read_only: self.read_only,allow_dangerous_sql: self.allow_dangerous_sql,allowed_connection_ids: self.allowed_connection_ids.clone(),+ allowed_group_ids: self.allowed_group_ids.clone(),allowed_tool_names: self.allowed_tool_names.clone(),connection_policies: self.connection_policies.clone(),+ group_policies: self.group_policies.clone(),query_timeout_secs: self.query_timeout_secs,}}@@ -400,6 +425,8 @@ impl McpGlobalPolicy {ids.dedup();ids});+ let allowed_group_ids =+ if allowed_connection_ids.is_some() { normalize_mcp_ids(&self.allowed_group_ids) } else { Vec::new() };let allowed_tool_names = self.allowed_tool_names.as_ref().map(|tools| {let mut tools = tools.iter()@@ -481,17 +508,52 @@ impl McpGlobalPolicy {}}+ let mut group_policies = HashMap::<String, McpGroupPolicy>::new();+ for rule in &self.group_policies {+ let group_id = rule.group_id.trim();+ if group_id.is_empty() {+ continue;+ }+ group_policies+ .entry(group_id.to_string())+ .and_modify(|current| {+ current.read_only |= rule.read_only;+ current.allow_dangerous_sql &= rule.allow_dangerous_sql;+ })+ .or_insert_with(|| McpGroupPolicy {+ group_id: group_id.to_string(),+ read_only: rule.read_only,+ allow_dangerous_sql: !rule.read_only && rule.allow_dangerous_sql,+ });+ }+ let mut group_policies = group_policies.into_values().collect::<Vec<_>>();+ group_policies.sort_by(|left, right| left.group_id.cmp(&right.group_id));+ for rule in &mut group_policies {+ if rule.read_only {+ rule.allow_dangerous_sql = false;+ }+ }+Self {read_only: self.read_only,allow_dangerous_sql: !self.read_only && self.allow_dangerous_sql,allowed_connection_ids,+ allowed_group_ids,allowed_tool_names,connection_policies,+ group_policies,query_timeout_secs: self.query_timeout_secs,}}}+fn normalize_mcp_ids(ids: &[String]) -> Vec<String> {+ let mut ids = ids.iter().map(|id| id.trim()).filter(|id| !id.is_empty()).map(ToOwned::to_owned).collect::<Vec<_>>();+ ids.sort();+ ids.dedup();+ ids+}+fn normalize_mcp_database_names(databases: &[String]) -> Vec<String> {let mut databases = databases.iter()@@ -2034,8 +2096,10 @@ impl Storage {read_only: policy.read_only,allow_dangerous_sql: policy.allow_dangerous_sql,allowed_connection_ids: policy.allowed_connection_ids,+ allowed_group_ids: policy.allowed_group_ids,allowed_tool_names: policy.allowed_tool_names,connection_policies: policy.connection_policies,+ group_policies: policy.group_policies,query_timeout_secs: policy.query_timeout_secs,});};@@ -2048,8 +2112,10 @@ impl Storage {read_only: policy.read_only,allow_dangerous_sql: policy.allow_dangerous_sql,allowed_connection_ids: policy.allowed_connection_ids,+ allowed_group_ids: policy.allowed_group_ids,allowed_tool_names: policy.allowed_tool_names,connection_policies: policy.connection_policies,+ group_policies: policy.group_policies,query_timeout_secs: policy.query_timeout_secs,});};@@ -2061,8 +2127,10 @@ impl Storage {read_only: policy.read_only,allow_dangerous_sql: policy.allow_dangerous_sql,allowed_connection_ids: policy.allowed_connection_ids,+ allowed_group_ids: policy.allowed_group_ids,allowed_tool_names: policy.allowed_tool_names,connection_policies: policy.connection_policies,+ group_policies: policy.group_policies,query_timeout_secs: policy.query_timeout_secs,})})@@ -3052,7 +3120,24 @@ fn ensure_mcp_connection_change_allowed_in_tx();}if let Some(connection_id) = target_connection_id {- if policy.allowed_connection_ids.as_ref().is_some_and(|ids| !ids.iter().any(|id| id == connection_id)) {+ let group_paths = if crate::mcp_policy::policy_uses_connection_groups(&policy) {+ let layout_json: Option<String> = tx+ .query_row("SELECT layout_json FROM sidebar_layout WHERE id = 1", [], |row| row.get(0))+ .optional()+ .map_err(|error| format!("MCP_POLICY_UNAVAILABLE: {error}"))?;+ layout_json+ .map(|json| {+ let layout = serde_json::from_str(&json)+ .map_err(|error| format!("MCP_POLICY_UNAVAILABLE: invalid sidebar layout JSON: {error}"))?;+ crate::mcp_policy::connection_group_paths(&layout)+ .map_err(|error| format!("MCP_POLICY_UNAVAILABLE: {error}"))+ })+ .transpose()?+ .unwrap_or_default()+ } else {+ HashMap::new()+ };+ if !crate::mcp_policy::policy_allows_connection(&policy, group_paths.get(connection_id), connection_id) {return Err(format!("CONNECTION_OUT_OF_SCOPE: connection '{connection_id}' is not allowed by the current DBX MCP policy"));@@ -6584,8 +6669,10 @@ mod tests {read_only: false,allow_dangerous_sql: false,allowed_connection_ids: None,+ allowed_group_ids: Vec::new(),allowed_tool_names: None,connection_policies: Vec::new(),+ group_policies: Vec::new(),query_timeout_secs: None,});@@ -6609,8 +6696,10 @@ mod tests {read_only: true,allow_dangerous_sql: false,allowed_connection_ids: Some(vec!["conn-1".to_string(), "conn-2".to_string()]),+ allowed_group_ids: Vec::new(),allowed_tool_names: None,connection_policies: Vec::new(),+ group_policies: Vec::new(),query_timeout_secs: Some(120),});diff --git a/crates/dbx-core/src/table_import.rs b/crates/dbx-core/src/table_import.rsindex 1bfbc74dab..147116edb3 100644--- a/crates/dbx-core/src/table_import.rs+++ b/crates/dbx-core/src/table_import.rs@@ -10502,7 +10502,7 @@ mod tests {).await;- assert!(!state.pool_handle(pool_key).await.is_some());+ assert!(state.pool_handle(pool_key).await.is_none());}#[test]diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rsindex fc37769680..591973509b 100644--- a/crates/dbx-mcp/src/backend.rs+++ b/crates/dbx-mcp/src/backend.rs@@ -10,6 +10,7 @@ use dbx_core::{agent_tools::{self, format_query_result_as_text, AgentSqlPermissions, QueryCellWindow},connection::AppState,db::{mongo_driver::MongoIndexSpec, redis_driver::RedisCommandResult, ColumnInfo, TableInfo},+ mcp_policy::{connection_group_paths, McpConnectionGroupPath},models::connection::{ConnectionConfig, DatabaseType},storage::{DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState, Storage},};@@ -50,73 +51,6 @@ impl From<&ConnectionConfig> for ConnectionSummary {}}-#[derive(Deserialize)]-struct SidebarLayout {- #[serde(default)]- groups: Vec<SidebarGroup>,- #[serde(default)]- order: Vec<SidebarOrderEntry>,-}--#[derive(Deserialize)]-struct SidebarGroup {- id: String,- name: String,-}--#[derive(Deserialize)]-#[serde(tag = "type")]-enum SidebarOrderEntry {- #[serde(rename = "group")]- Group {- id: String,- children: Option<Vec<SidebarOrderEntry>>,- #[serde(rename = "connectionIds")]- connection_ids: Option<Vec<String>>,- },- #[serde(rename = "connection")]- Connection { id: String },-}--fn connection_group_paths(layout: Value) -> HashMap<String, Vec<String>> {- let Ok(layout) = serde_json::from_value::<SidebarLayout>(layout) else {- return HashMap::new();- };- let groups = layout.groups.into_iter().map(|group| (group.id, group.name)).collect::<HashMap<_, _>>();- let mut paths = HashMap::new();- collect_connection_group_paths(&layout.order, &groups, &mut Vec::new(), &mut paths);- paths-}--fn collect_connection_group_paths(- entries: &[SidebarOrderEntry],- groups: &HashMap<String, String>,- path: &mut Vec<String>,- paths: &mut HashMap<String, Vec<String>>,-) {- for entry in entries {- match entry {- SidebarOrderEntry::Connection { id } => {- paths.insert(id.clone(), path.clone());- }- SidebarOrderEntry::Group { id, children, connection_ids } => {- let Some(name) = groups.get(id) else {- continue;- };- path.push(name.clone());- if let Some(children) = children {- collect_connection_group_paths(children, groups, path, paths);- } else if let Some(connection_ids) = connection_ids {- for connection_id in connection_ids {- paths.insert(connection_id.clone(), path.clone());- }- }- path.pop();- }- }- }-}-fn legacy_mcp_allow_writes() -> Option<bool> {match std::env::var("DBX_MCP_ALLOW_WRITES").ok()?.trim().to_ascii_lowercase().as_str() {"1" | "true" => Some(true),@@ -141,6 +75,21 @@ fn effective_mcp_policy_with_legacy_allow_writes(// can execute unconfirmed writes through CLI providers.if legacy_allow_writes == Some(false) {policy.read_only = true;+ policy.allow_dangerous_sql = false;+ for rule in &mut policy.group_policies {+ rule.read_only = true;+ rule.allow_dangerous_sql = false;+ }+ for rule in &mut policy.connection_policies {+ rule.read_only = true;+ rule.allow_dangerous_sql = false;+ rule.execution_mode_configured = true;+ rule.execution_mode_policy_version = Some(dbx_core::mcp_policy::MCP_EXECUTION_POLICY_VERSION);+ for database_policy in &mut rule.database_policies {+ database_policy.read_only = true;+ database_policy.allow_dangerous_sql = false;+ }+ }}policy}@@ -241,6 +190,14 @@ pub trait DbxBackend: Send + Sync {async fn load_connection_group_paths(&self) -> Result<HashMap<String, Vec<String>>, String> {Ok(HashMap::new())}+ async fn load_connection_group_details(&self) -> Result<HashMap<String, McpConnectionGroupPath>, String> {+ Ok(self+ .load_connection_group_paths()+ .await?+ .into_iter()+ .map(|(connection_id, names)| (connection_id, McpConnectionGroupPath { ids: Vec::new(), names }))+ .collect())+ }async fn execute_agent_tool(&self,connection: &ConnectionConfig,@@ -732,7 +689,23 @@ impl DbxBackend for LocalBackend {}async fn load_connection_group_paths(&self) -> Result<HashMap<String, Vec<String>>, String> {- Ok(self.state.storage.load_sidebar_layout().await?.map(connection_group_paths).unwrap_or_default())+ Ok(self+ .load_connection_group_details()+ .await?+ .into_iter()+ .map(|(connection_id, path)| (connection_id, path.names))+ .collect())+ }++ async fn load_connection_group_details(&self) -> Result<HashMap<String, McpConnectionGroupPath>, String> {+ self.state+ .storage+ .load_sidebar_layout()+ .await?+ .as_ref()+ .map(connection_group_paths)+ .transpose()+ .map(Option::unwrap_or_default)}async fn execute_agent_tool(@@ -1056,13 +1029,22 @@ impl DbxBackend for WebBackend {}async fn load_connection_group_paths(&self) -> Result<HashMap<String, Vec<String>>, String> {+ Ok(self+ .load_connection_group_details()+ .await?+ .into_iter()+ .map(|(connection_id, path)| (connection_id, path.names))+ .collect())+ }++ async fn load_connection_group_details(&self) -> Result<HashMap<String, McpConnectionGroupPath>, String> {let layout = self.request(reqwest::Method::GET, "/api/layout/sidebar", None).await?.json::<Option<Value>>().await.map_err(|error| format!("Invalid sidebar layout response: {error}"))?;- Ok(layout.map(connection_group_paths).unwrap_or_default())+ layout.as_ref().map(connection_group_paths).transpose().map(Option::unwrap_or_default)}async fn execute_agent_tool(@@ -2270,8 +2252,10 @@ mod tests {read_only,allow_dangerous_sql: false,allowed_connection_ids: None,+ allowed_group_ids: Vec::new(),allowed_tool_names: None,connection_policies: Vec::new(),+ group_policies: Vec::new(),query_timeout_secs: None,}}@@ -2301,7 +2285,7 @@ mod tests {#[test]fn parses_nested_current_and_legacy_connection_group_paths() {- let paths = connection_group_paths(json!({+ let layout = json!({"groups": [{ "id": "project", "name": "Project" },{ "id": "staging", "name": "Staging" },@@ -2321,25 +2305,26 @@ mod tests {]},{ "type": "group", "id": "legacy", "connectionIds": ["legacy-connection"] },- {- "type": "group",- "id": "missing-group",- "children": [{ "type": "connection", "id": "dangling" }]- },{ "type": "connection", "id": "root" }]- }));+ });+ let paths = connection_group_paths(&layout).unwrap();- assert_eq!(paths.get("nested"), Some(&vec!["Project".to_string(), "Staging".to_string()]));- assert_eq!(paths.get("grouped"), Some(&vec!["Project".to_string()]));- assert_eq!(paths.get("legacy-connection"), Some(&vec!["Legacy".to_string()]));- assert_eq!(paths.get("root"), Some(&Vec::new()));- assert!(!paths.contains_key("dangling"));+ assert_eq!(paths["nested"].ids, vec!["project".to_string(), "staging".to_string()]);+ assert_eq!(paths["nested"].names, vec!["Project".to_string(), "Staging".to_string()]);+ assert_eq!(paths["grouped"].names, vec!["Project".to_string()]);+ assert_eq!(paths["legacy-connection"].names, vec!["Legacy".to_string()]);+ assert_eq!(paths["root"], McpConnectionGroupPath::default());}#[test]- fn malformed_sidebar_layout_has_no_group_paths() {- assert!(connection_group_paths(json!({ "groups": "invalid", "order": [] })).is_empty());+ fn malformed_sidebar_layout_is_rejected() {+ assert!(connection_group_paths(&json!({ "groups": "invalid", "order": [] })).is_err());+ assert!(connection_group_paths(&json!({+ "groups": [],+ "order": [{ "type": "group", "id": "missing-group", "children": [] }]+ }))+ .is_err());}#[tokio::test]diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rsindex 78c21f0eba..cb3d5a1e91 100644--- a/crates/dbx-mcp/src/server.rs+++ b/crates/dbx-mcp/src/server.rs@@ -1,4 +1,4 @@-use std::sync::Arc;+use std::{collections::HashMap, sync::Arc};use rmcp::{handler::server::{router::tool::ToolRouter, wrapper::Parameters},@@ -318,6 +318,7 @@ struct ResolvedConnection {connection: dbx_core::models::connection::ConnectionConfig,policy: McpGlobalPolicy,database_scope: DatabaseScope,+ group_ids: Vec<String>,}#[derive(Clone, Debug)]@@ -411,12 +412,13 @@ impl DbxMcpServer {match self.load_scoped_connections().await {Ok(connections) if connections.is_empty() => text("No connections configured in DBX."),Ok(connections) => {- let group_paths = self.backend.load_connection_group_paths().await.unwrap_or_default();+ let group_paths = self.backend.load_connection_group_details().await.unwrap_or_default();let rows = connections.iter().map(|connection| {let mut summary = ConnectionSummary::from(connection);- summary.group_path = group_paths.get(&connection.id).cloned().unwrap_or_default();+ summary.group_path =+ group_paths.get(&connection.id).map(|path| path.names.clone()).unwrap_or_default();summary}).collect::<Vec<_>>();@@ -630,7 +632,8 @@ impl DbxMcpServer {Ok(database) => database,Err(error) => return error,};- let policy = effective_policy_for_database(&resolved.policy, connection, &database);+ let policy =+ effective_policy_for_database_with_groups(&resolved.policy, &resolved.group_ids, connection, &database);if let Some(session) = &session {if session.database != database {return tool_error(@@ -643,9 +646,10 @@ impl DbxMcpServer {}}if connection.db_type == DatabaseType::MongoDb {- let command = match validate_mongo_command(+ let command = match validate_mongo_command_with_groups(connection,&resolved.policy,+ &resolved.group_ids,&resolved.database_scope,&database,&request.sql,@@ -715,6 +719,9 @@ impl DbxMcpServer {description = "Execute a SQL script containing multiple statements in one call and return a result per statement. Statements are split with a database-dialect-aware parser, so semicolons inside strings, comments and stored procedures are handled. Stops at the first failing statement unless continue_on_error is true. Pass session_id (from dbx_open_session) when statements must share one connection (e.g. temporary tables, USE/SET). When use_transaction is true and the script has multiple statements, the whole script runs in one transaction and the call returns a single merged result instead of one result per statement (single-statement scripts run normally and return that one result); use_transaction cannot be combined with session_id or continue_on_error, and is rejected when the backend cannot provide a rollbackable transaction or for MySQL-family DDL scripts (DDL implicitly commits and cannot be rolled back).")]async fn execute_batch(&self, Parameters(request): Parameters<ExecuteBatchQueryRequest>) -> CallToolResult {+ if let Err(error) = self.ensure_tool_allowed("dbx_execute_batch").await {+ return error;+ }let resolved = match self.resolve_connection(&request.selector).await {Ok(resolved) => resolved,Err(error) => return error,@@ -772,6 +779,14 @@ impl DbxMcpServer {// A pinned session makes USE/SET CATALOG meaningful, so database// switching is allowed — unless a hard database scope is configured.let allow_database_switch = session.is_some() && self.scope.database.is_none();+ let policy =+ effective_policy_for_database_with_groups(&resolved.policy, &resolved.group_ids, connection, &database);+ if let Err(error) = ensure_sql_database_scope(&resolved.database_scope, connection, &database, sql) {+ return error;+ }+ if let Err(error) = ensure_sql_database_execution_scope(&resolved.policy, connection, &database, sql) {+ return error;+ }// Split with the same dialect-aware splitter the core uses, early, so the// option-validity checks below only fire for scripts that actually enter// transaction mode (more than one statement). A single-statement script@@ -824,8 +839,7 @@ impl DbxMcpServer {// Classify the whole script as a unit so a single write/DDL statement in// the batch fails closed under read-only / dangerous-SQL / production// policy, exactly as the Web /api/query/execute-multi route does.- let permissions = match validate_sql_policy(connection, &resolved.policy, &database, sql, allow_database_switch)- {+ let permissions = match validate_sql_policy(connection, &policy, &database, sql, allow_database_switch) {Ok(permissions) => permissions,Err(error) => return error,};@@ -989,7 +1003,12 @@ impl DbxMcpServer {Err(error) => return tool_error("REDIS_COMMAND_BLOCKED", error),};let safety = classify_command(&argv[0]);- let policy = effective_policy_for_database(&resolved.policy, connection, &database.to_string());+ let policy = effective_policy_for_database_with_groups(+ &resolved.policy,+ &resolved.group_ids,+ connection,+ &database.to_string(),+ );let permissions = mcp_permissions(connection, &policy);if safety != RedisCommandSafety::Allowed && policy.read_only {return tool_error(@@ -1068,8 +1087,9 @@ impl DbxMcpServer {if request.topic.trim().is_empty() {return tool_error("MESSAGE_TOPIC_REQUIRED", "Message topic must not be empty.");}- let policy = effective_policy_for_database(+ let policy = effective_policy_for_database_with_groups(&resolved.policy,+ &resolved.group_ids,connection,connection.database.as_deref().unwrap_or(""),);@@ -1239,9 +1259,13 @@ impl DbxMcpServer {Ok(connections) => connections,Err(error) => return tool_error("CONNECTION_LOAD_ERROR", error),};+ let group_paths = match self.load_group_paths_for_policy(&policy).await {+ Ok(paths) => paths,+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),+ };let allowed = connections.iter()- .filter(|connection| policy_allows_connection(&policy, connection))+ .filter(|connection| policy_allows_connection(&policy, group_paths.get(&connection.id), connection)).cloned().collect::<Vec<_>>();let source =@@ -1326,7 +1350,11 @@ impl DbxMcpServer {}),);};- if !policy_allows_connection(&policy, &target) {+ let group_paths = match self.load_group_paths_for_policy(&policy).await {+ Ok(paths) => paths,+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),+ };+ if !policy_allows_connection(&policy, group_paths.get(&target.id), &target) {return tool_error("CONNECTION_OUT_OF_SCOPE",format!("Connection \"{}\" is not allowed by DBX MCP settings.", target.id),@@ -1396,7 +1424,8 @@ impl DbxMcpServer {Ok(database) => database,Err(error) => return error,};- let policy = effective_policy_for_database(&resolved.policy, connection, &database);+ let policy =+ effective_policy_for_database_with_groups(&resolved.policy, &resolved.group_ids, connection, &database);if connection.db_type != DatabaseType::MongoDb {if let Err(error) = ensure_sql_database_scope(&resolved.database_scope, connection, &database, &request.sql){@@ -1417,9 +1446,14 @@ impl DbxMcpServer {}};if connection.db_type == DatabaseType::MongoDb {- if let Err(error) =- validate_mongo_command(connection, &resolved.policy, &resolved.database_scope, &database, &request.sql)- {+ if let Err(error) = validate_mongo_command_with_groups(+ connection,+ &resolved.policy,+ &resolved.group_ids,+ &resolved.database_scope,+ &database,+ &request.sql,+ ) {return error;}}@@ -1462,13 +1496,27 @@ impl DbxMcpServer {async fn load_scoped_connections(&self) -> Result<Vec<dbx_core::models::connection::ConnectionConfig>, String> {let policy = self.backend.load_mcp_global_policy().await?;let connections = self.backend.load_connections().await?;+ let group_paths = self.load_group_paths_for_policy(&policy).await?;Ok(connections.into_iter()- .filter(|connection| policy_allows_connection(&policy, connection))+ .filter(|connection| policy_allows_connection(&policy, group_paths.get(&connection.id), connection)).filter(|connection| !self.scope.connection_scope_enabled() || self.scope.matches(connection)).collect())}+ async fn load_group_paths_for_policy(+ &self,+ policy: &McpGlobalPolicy,+ ) -> Result<HashMap<String, dbx_core::mcp_policy::McpConnectionGroupPath>, String> {+ match self.backend.load_connection_group_details().await {+ Ok(paths) => Ok(paths),+ Err(error) if dbx_core::mcp_policy::policy_uses_connection_groups(policy) => {+ Err(format!("MCP_POLICY_UNAVAILABLE: {error}"))+ }+ Err(_) => Ok(HashMap::new()),+ }+ }+async fn load_policy(&self) -> Result<McpGlobalPolicy, CallToolResult> {self.backend.load_mcp_global_policy().await.map_err(|error| backend_tool_error("MCP_POLICY_UNAVAILABLE", error))}@@ -1574,6 +1622,10 @@ impl DbxMcpServer {async fn resolve_connection(&self, selector: &ConnectionSelector) -> Result<ResolvedConnection, CallToolResult> {let policy = self.load_policy().await?;+ let group_paths = self+ .load_group_paths_for_policy(&policy)+ .await+ .map_err(|error| backend_tool_error("MCP_POLICY_UNAVAILABLE", error))?;let connections =self.backend.load_connections().await.map_err(|error| tool_error("CONNECTION_LOAD_ERROR", error))?;if let Some(id) = selector.connection_id.as_deref().map(str::trim).filter(|id| !id.is_empty()) {@@ -1587,13 +1639,13 @@ impl DbxMcpServer {format!("Connection \"{id}\" is outside this DBX AI session scope."),));}- if !policy_allows_connection(&policy, &connection) {+ if !policy_allows_connection(&policy, group_paths.get(&connection.id), &connection) {return Err(tool_error("CONNECTION_OUT_OF_SCOPE",format!("Connection \"{id}\" is not allowed by DBX MCP settings."),));}- return Ok(resolved_connection(policy, connection));+ return Ok(resolved_connection(policy, connection, group_paths.get(id)));}if self.scope.connection_scope_enabled() {let connection = connections@@ -1608,13 +1660,14 @@ impl DbxMcpServer {));}}- if !policy_allows_connection(&policy, &connection) {+ if !policy_allows_connection(&policy, group_paths.get(&connection.id), &connection) {return Err(tool_error("CONNECTION_OUT_OF_SCOPE","The DBX AI session scope is outside the global MCP connection allowlist.",));}- return Ok(resolved_connection(policy, connection));+ let path = group_paths.get(&connection.id);+ return Ok(resolved_connection(policy, connection, path));}let Some(name) = selector.connection_name.as_deref().map(str::trim).filter(|name| !name.is_empty()) else {return Err(tool_error("CONNECTION_NOT_FOUND", "Either connection_id or connection_name is required."));@@ -1623,7 +1676,7 @@ impl DbxMcpServer {connections.into_iter().filter(|connection| connection.name.eq_ignore_ascii_case(name)).collect::<Vec<_>>();let allowed = matching.iter()- .filter(|connection| policy_allows_connection(&policy, connection))+ .filter(|connection| policy_allows_connection(&policy, group_paths.get(&connection.id), connection)).cloned().collect::<Vec<_>>();match allowed.as_slice() {@@ -1634,7 +1687,7 @@ impl DbxMcpServer {"CONNECTION_OUT_OF_SCOPE",format!("Connection \"{name}\" is not allowed by DBX MCP settings."),)),- [connection] => Ok(resolved_connection(policy, connection.clone())),+ [connection] => Ok(resolved_connection(policy, connection.clone(), group_paths.get(&connection.id))),_ => Err(tool_error("AMBIGUOUS_CONNECTION", ambiguous_connections(name, &allowed))),}}@@ -1751,9 +1804,10 @@ fn agent_result(result: dbx_core::agent_events::ToolResult) -> CallToolResult {fn policy_allows_connection(policy: &McpGlobalPolicy,+ group_path: Option<&dbx_core::mcp_policy::McpConnectionGroupPath>,connection: &dbx_core::models::connection::ConnectionConfig,) -> bool {- policy.allowed_connection_ids.as_ref().is_none_or(|allowed| allowed.iter().any(|id| id == &connection.id))+ dbx_core::mcp_policy::policy_allows_connection(policy, group_path, &connection.id)}fn policy_allows_tool(policy: &McpGlobalPolicy, tool_name: &str) -> bool {@@ -1777,9 +1831,11 @@ fn database_scope_for_connection(fn resolved_connection(policy: McpGlobalPolicy,connection: dbx_core::models::connection::ConnectionConfig,+ group_path: Option<&dbx_core::mcp_policy::McpConnectionGroupPath>,) -> ResolvedConnection {let database_scope = database_scope_for_connection(&policy, &connection);- ResolvedConnection { connection, policy, database_scope }+ let group_ids = group_path.map(|path| path.ids.clone()).unwrap_or_default();+ ResolvedConnection { connection, policy, database_scope, group_ids }}#[allow(clippy::result_large_err)]@@ -1834,14 +1890,29 @@ fn format_database_names(databases: &[String]) -> String {/// 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.+#[cfg(test)]fn effective_policy_for_database(policy: &McpGlobalPolicy,connection: &dbx_core::models::connection::ConnectionConfig,database: &str,+) -> McpGlobalPolicy {+ effective_policy_for_database_with_groups(policy, &[], connection, database)+}++fn effective_policy_for_database_with_groups(+ policy: &McpGlobalPolicy,+ group_ids: &[String],+ connection: &dbx_core::models::connection::ConnectionConfig,+ database: &str,) -> McpGlobalPolicy {let mut policy = policy.clone();(policy.read_only, policy.allow_dangerous_sql) =- dbx_core::mcp_policy::effective_database_execution_policy(&policy, &connection.id, database);+ dbx_core::mcp_policy::effective_database_execution_policy_with_groups(+ &policy,+ group_ids,+ &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.@@ -1965,13 +2036,27 @@ fn validate_sql_policy(}// CallToolResult is the transport-native error payload; boxing it would complicate every MCP call site.+#[cfg(test)]#[allow(clippy::result_large_err)]+#[cfg(test)]fn validate_mongo_command(connection: &dbx_core::models::connection::ConnectionConfig,policy: &McpGlobalPolicy,database_scope: &DatabaseScope,database: &str,source: &str,+) -> Result<MongoCommand, CallToolResult> {+ validate_mongo_command_with_groups(connection, policy, &[], database_scope, database, source)+}++#[allow(clippy::result_large_err)]+fn validate_mongo_command_with_groups(+ connection: &dbx_core::models::connection::ConnectionConfig,+ policy: &McpGlobalPolicy,+ group_ids: &[String],+ database_scope: &DatabaseScope,+ database: &str,+ source: &str,) -> Result<MongoCommand, CallToolResult> {let command = mongo::parse(source).map_err(|error| {tool_error(@@ -2001,7 +2086,7 @@ fn validate_mongo_command(ensure_database_in_scope(database_scope, &target_database)?;}}- let effective_policy = effective_policy_for_database(policy, connection, database);+ let effective_policy = effective_policy_for_database_with_groups(policy, group_ids, connection, database);let permissions = mcp_permissions(connection, &effective_policy);let production_database = match &command {MongoCommand::Aggregate { pipeline, .. } => {@@ -2253,7 +2338,12 @@ mod tests {}fn resolved_connection_for_test(connection: ConnectionConfig) -> ResolvedConnection {- ResolvedConnection { connection, policy: McpGlobalPolicy::default(), database_scope: DatabaseScope::All }+ ResolvedConnection {+ connection,+ policy: McpGlobalPolicy::default(),+ database_scope: DatabaseScope::All,+ group_ids: Vec::new(),+ }}fn result_text(result: &CallToolResult) -> &str {@@ -2720,6 +2810,7 @@ mod tests {connection: sql,policy: McpGlobalPolicy::default(),database_scope: DatabaseScope::Selected(vec!["reporting".to_string()]),+ group_ids: Vec::new(),};let server = DbxMcpServer::with_runtime_options(Arc::new(FakeBackend::default()), McpScope::default(), false);assert_eq!(server.resolve_database(Some("reporting".to_string()), &selected).unwrap(), "reporting");@@ -2730,6 +2821,7 @@ mod tests {connection: connection("redis", "redis", "redis", "0"),policy: McpGlobalPolicy::default(),database_scope: DatabaseScope::Selected(vec!["2".to_string()]),+ group_ids: Vec::new(),};assert_eq!(server.resolve_redis_database(Some(2), &redis).unwrap(), 2);let error = server.resolve_redis_database(Some(3), &redis).unwrap_err();diff --git a/crates/dbx-mcp/tests/live_batch.rs b/crates/dbx-mcp/tests/live_batch.rsindex 12e6717ce3..091190ed47 100644--- a/crates/dbx-mcp/tests/live_batch.rs+++ b/crates/dbx-mcp/tests/live_batch.rs@@ -72,6 +72,7 @@ fn full_access_policy() -> McpGlobalPolicy {allowed_tool_names: None,connection_policies: vec![],query_timeout_secs: None,+ ..Default::default()}}@@ -85,6 +86,7 @@ fn short_timeout_policy() -> McpGlobalPolicy {allowed_tool_names: None,connection_policies: vec![],query_timeout_secs: Some(1),+ ..Default::default()}}diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rsindex c598431eaa..553e59e002 100644--- a/crates/dbx-web/src/routes/connection.rs+++ b/crates/dbx-web/src/routes/connection.rs@@ -1424,7 +1424,7 @@ mod tests {let second = state.app.mq_registry.get_or_build(&updated).await.unwrap().adapter;assert!(!Arc::ptr_eq(&first, &second));- assert!(!state.app.pool_handle(&initial.id).await.is_some());+ assert!(state.app.pool_handle(&initial.id).await.is_none());let _ = std::fs::remove_dir_all(dir);}@@ -1680,7 +1680,7 @@ mod tests {.and_then(serde_json::Value::as_str);assert_eq!(cached_admin_url, Some("http://127.0.0.1:8081"));drop(configs);- assert!(!state.app.pool_handle(&initial.id).await.is_some());+ assert!(state.app.pool_handle(&initial.id).await.is_none());let _ = std::fs::remove_dir_all(dir);}@@ -1872,7 +1872,7 @@ mod tests {.await;assert!(result.is_ok());- assert!(!state.app.pool_handle(&removed.id).await.is_some());+ assert!(state.app.pool_handle(&removed.id).await.is_none());let _ = std::fs::remove_dir_all(dir);}@@ -1942,7 +1942,7 @@ mod tests {.await;assert!(result.is_ok());- assert!(!state.app.pool_handle("conn").await.is_some());+ assert!(state.app.pool_handle("conn").await.is_none());assert!(state.app.ensure_current_connection_attempt("conn", Some(current_attempt)).await.is_err());let _ = std::fs::remove_dir_all(dir);@@ -2000,7 +2000,7 @@ mod tests {.await;assert!(result.is_ok());- assert!(!state.app.pool_handle(&config.id).await.is_some());+ assert!(state.app.pool_handle(&config.id).await.is_none());let second = state.app.mq_registry.get_or_build(&config).await.unwrap().adapter;assert!(!Arc::ptr_eq(&first, &second));diff --git a/crates/dbx-web/src/routes/mcp_policy.rs b/crates/dbx-web/src/routes/mcp_policy.rsindex 6b9431964e..7c116e44f2 100644--- a/crates/dbx-web/src/routes/mcp_policy.rs+++ b/crates/dbx-web/src/routes/mcp_policy.rs@@ -1,6 +1,7 @@-use std::sync::Arc;+use std::{collections::HashMap, sync::Arc};use axum::http::HeaderMap;+use dbx_core::mcp_policy::McpConnectionGroupPath;use dbx_core::models::connection::ConnectionConfig;use dbx_core::storage::{McpDatabaseScope, McpGlobalPolicy};@@ -231,8 +232,30 @@ async fn load_policy(state: &Arc<WebState>) -> Result<McpGlobalPolicy, AppError>state.app.storage.load_mcp_global_policy().await.map(|state| state.policy()).map_err(AppError::from)}-fn ensure_allowed(policy: &McpGlobalPolicy, connection_id: &str) -> Result<(), AppError> {- if policy.allowed_connection_ids.as_ref().is_some_and(|allowed| !allowed.iter().any(|id| id == connection_id)) {+async fn load_policy_context(+ state: &Arc<WebState>,+) -> Result<(McpGlobalPolicy, HashMap<String, McpConnectionGroupPath>), AppError> {+ let policy = load_policy(state).await?;+ let group_paths = match state.app.storage.load_sidebar_layout().await {+ Ok(Some(layout)) => dbx_core::mcp_policy::connection_group_paths(&layout),+ Ok(None) => Ok(HashMap::new()),+ Err(error) => Err(error),+ };+ match group_paths {+ Ok(paths) => Ok((policy, paths)),+ Err(error) if dbx_core::mcp_policy::policy_uses_connection_groups(&policy) => {+ Err(AppError::from(format!("MCP_POLICY_UNAVAILABLE: {error}")))+ }+ Err(_) => Ok((policy, HashMap::new())),+ }+}++fn ensure_allowed(+ policy: &McpGlobalPolicy,+ group_path: Option<&McpConnectionGroupPath>,+ connection_id: &str,+) -> Result<(), AppError> {+ if !dbx_core::mcp_policy::policy_allows_connection(policy, group_path, connection_id) {return Err(AppError::from(format!("CONNECTION_OUT_OF_SCOPE: connection '{connection_id}' is not allowed by DBX MCP settings")));@@ -257,10 +280,21 @@ fn ensure_database_in_scope(policy: &McpGlobalPolicy, connection_id: &str, datab}/// Execution modes are scoped defaults: a database setting overrides a-/// configured connection default, which in turn overrides the global default.+/// configured connection default, then the nearest configured group and the+/// global default./// Connection read-only and production protections are checked separately.+#[cfg(test)]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)+ effective_database_execution_policy_with_groups(policy, &[], connection_id, database)+}++fn effective_database_execution_policy_with_groups(+ policy: &McpGlobalPolicy,+ group_ids: &[String],+ connection_id: &str,+ database: &str,+) -> (bool, bool) {+ dbx_core::mcp_policy::effective_database_execution_policy_with_groups(policy, group_ids, connection_id, database)}fn ensure_sql_database_execution_scope(@@ -320,7 +354,8 @@ pub async fn ensure_scope(state: &Arc<WebState>, headers: &HeaderMap, connectionif !is_mcp_request(headers) {return Ok(());}- ensure_allowed(&load_policy(state).await?, connection_id)+ let (policy, group_paths) = load_policy_context(state).await?;+ ensure_allowed(&policy, group_paths.get(connection_id), connection_id)}pub async fn ensure_write(@@ -353,8 +388,9 @@ pub async fn ensure_mongo_pipeline_target(if !is_mcp_request(headers) {return Ok(database.to_string());}- let policy = load_policy(state).await?;- ensure_allowed(&policy, connection_id)?;+ let (policy, group_paths) = load_policy_context(state).await?;+ let group_path = group_paths.get(connection_id);+ ensure_allowed(&policy, group_path, 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)?;@@ -381,12 +417,15 @@ async fn ensure_write_with_risk(if !is_mcp_request(headers) {return Ok(());}- let policy = load_policy(state).await?;- ensure_allowed(&policy, connection_id)?;+ let (policy, group_paths) = load_policy_context(state).await?;+ let group_path = group_paths.get(connection_id);+ ensure_allowed(&policy, group_path, 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)?;- let (read_only, allow_dangerous_sql) = effective_database_execution_policy(&policy, connection_id, &database);+ let group_ids = group_path.map(|path| path.ids.as_slice()).unwrap_or_default();+ let (read_only, allow_dangerous_sql) =+ effective_database_execution_policy_with_groups(&policy, group_ids, 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."@@ -422,8 +461,9 @@ pub async fn ensure_sql(if !is_mcp_request(headers) {return Ok(database.to_string());}- let policy = load_policy(state).await?;- ensure_allowed(&policy, connection_id)?;+ let (policy, group_paths) = load_policy_context(state).await?;+ let group_path = group_paths.get(connection_id);+ ensure_allowed(&policy, group_path, 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)?;@@ -434,7 +474,9 @@ pub async fn ensure_sql(}let is_write = dbx_core::query_execution_sql::is_write_sql_for_database(sql, config.db_type);ensure_sql_database_execution_scope(&policy, &config, &database, sql)?;- let (read_only, allow_dangerous_sql) = effective_database_execution_policy(&policy, connection_id, &database);+ let group_ids = group_path.map(|path| path.ids.as_slice()).unwrap_or_default();+ let (read_only, allow_dangerous_sql) =+ effective_database_execution_policy_with_groups(&policy, group_ids, 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."diff --git a/docs/mcp-management-layout-redesign.md b/docs/mcp-management-layout-redesign.mdnew file mode 100644index 0000000000..4453d89bc2--- /dev/null+++ b/docs/mcp-management-layout-redesign.md@@ -0,0 +1,221 @@+# MCP 管理总体布局重设计++## 目标++将 MCP 设置从一条混合长页面重组为两个清晰的工作区:++1. **接入方式**:如何让外部 MCP 客户端接入 DBX。+2. **权限管理**:接入后可以看到什么、可以执行什么。++本轮只调整信息架构、页面层级和视觉布局,不改变权限判定、安装、HTTP 配置、客户端配置或存储字段。++## 设计原则++- **接入方式回答“怎么连”**,只放运行状态、安装/更新、监听配置、端点、Token 和客户端配置。+- **权限管理回答“能做什么”**,只放连接、数据库、操作权限和工具策略。+- 一级 Tab 只保留两个,不增加“概览”Tab。状态摘要放在 Tab 上方,避免再制造一个混合入口。+- `stdio` 与 `HTTP` 是接入方式的二级 Tab,不是权限策略的分支。+- 权限管理中的所有配置继续沿用现有四步模型,但从接入页面完全移出。+- 页面使用 DBX 现有中性设计令牌、低圆角、低阴影和边框分层,不引入新的品牌色或装饰性卡片。++## 页面骨架++```text+MCP 管理 [配置状态] [重新检查]+选择 MCP 的接入方式,或管理 MCP 可以访问的资源与操作权限。++[ 接入方式 ] [ 权限管理 ]+────────────────────────────────────────────────────────────++接入方式 Tab:+ [ 本地 stdio ] [ HTTP 服务 ]++ 当前方式的状态与说明+ ┌────────────────────────────────────────────────────────┐+ │ 方式状态 / 地址或运行环境 / 当前版本 / 最近检查 │+ └────────────────────────────────────────────────────────┘++ 方式专属配置+ ┌────────────────────────────────────────────────────────┐+ │ stdio:安装、更新、命令、运行环境 │+ │ HTTP :启停、监听、远程访问、Host/Origin、端点与 Token │+ └────────────────────────────────────────────────────────┘++ 客户端配置(复用现有客户端 Tab)+ [Claude] [Cursor] [VS Code] ...+ ┌────────────────────────────────────────────────────────┐+ │ 配置预览 [复制] │+ └────────────────────────────────────────────────────────┘++权限管理 Tab:+ 当前策略摘要:9 个连接 · 3 条数据库限制 · 默认只读 · 14/17 工具++ [连接范围] [数据库范围] [操作权限] [工具与确认]+ ┌────────────────────────────────────────────────────────┐+ │ 当前权限步骤内容 │+ └────────────────────────────────────────────────────────┘+```++## 一级 Tab++### 接入方式++Tab 图标使用 `PlugZap` 或 `Cable`,说明文本保持简短:++> 配置 MCP 客户端连接 DBX 的方式。++进入后默认显示本地 `stdio`,因为它是桌面端最低配置成本的方式。当前选择的子 Tab 应在设置窗口打开期间保留,不改变已有配置。++### 权限管理++Tab 图标使用 `ShieldCheck`,说明文本保持简短:++> 管理 MCP 可见资源、数据库范围、操作权限和工具。++进入时在顶部显示只读摘要,不在摘要中提供第二套编辑控件。编辑仍通过下方四步区域完成。++## 接入方式 Tab++### 二级 Tab:本地 stdio / HTTP 服务++二级 Tab 使用紧凑的横向 Tab strip,而不是大型卡片按钮:++- 高度 `32px`,可横向滚动。+- 活动态使用主色文字和 `2px` 底部指示线。+- 不使用大面积阴影或高饱和背景。+- Tab 切换只切换接入内容,不影响权限策略。++### 公共状态头++一级页面头只出现一次,包含:++- MCP 管理标题和一句说明。+- 一个不绑定具体传输方式的聚合状态:未配置、部分可用或已配置。+- `重新检查` 作为主要状态动作;其他动作放入溢出菜单。++当前传输方式的详细状态必须放在二级 Tab 面板内:stdio 展示安装/运行环境健康,HTTP 展示服务运行状态、端点和最近错误。不要在 HTTP 面板激活时继续显示 npm/stdio 状态。++### 本地 stdio 内容顺序++1. **运行环境状态**:当前版本、最新版本、Node.js、npm、二进制路径。+2. **安装与更新**:命令、复制、安装/更新、卸载。+3. **客户端配置**:沿用现有客户端 Tab 和配置预览。+4. **运行参数**:放置不属于权限分配的 MCP 运行级设置,例如查询超时。++安装命令是该页面最重要的动作,应靠近运行环境状态;卸载放在危险操作区域或溢出菜单中,避免与安装形成同等视觉权重。++### HTTP 服务内容顺序++1. **服务状态**:启用开关、运行中/待应用/已关闭、最近错误。+2. **监听配置**:Host、Port、Path。+3. **远程访问控制**:允许远程、Allowed Hosts、Allowed Origins。+4. **连接信息**:Endpoint、Bearer Token、轮换 Token、客户端配置预览。+5. **诊断信息**:最近日志折叠展示。++查询超时等运行级设置也放在“接入方式”下的“运行参数”区域;权限管理只负责资源范围、数据库范围、操作权限和工具可用性。++HTTP 的保存动作固定在配置内容底部,使用“保存并启动/保存并停止”;不要让每个字段单独触发保存。++### 客户端配置的归属++客户端配置属于“接入方式”,不属于权限管理。它只生成连接 DBX 的配置,不改变 DBX 的权限策略。++- stdio 选中时生成本地命令型配置。+- HTTP 选中时生成 URL + Authorization 配置。+- 保留现有客户端列表和 `mcpConfigTab` 状态。+- 客户端列表较长时横向滚动,不将每个客户端做成独立卡片。++## 权限管理 Tab++### 顶部策略摘要++在四步区域之前放一行紧凑摘要,只读展示:++```text+访问范围 9 个连接 数据库范围 3 条限制+默认权限 只读 工具 14/17 已启用+```++摘要用于回答“当前策略大致是什么”,不替代实际编辑控件。每个摘要项可点击跳转到对应步骤,但不在摘要中直接切换权限。++### 权限四步++保留当前四步交互和已有数据映射,仅调整其容器归属:++1. **连接范围**:哪些分组和连接对 MCP 可见。+2. **数据库范围**:每个已授权连接可以访问哪些库。+3. **操作权限**:全局默认、分组/连接/数据库例外。+4. **工具与确认**:可调用工具和最终权限预览。++权限 Tab 内不出现安装命令、版本信息、HTTP Host/Port、Token、客户端 JSON 配置、查询超时或服务日志。++### 权限页面视觉层级++- 一级 Tab 是页面导航,不做成内容卡片。+- 四步导航是权限工作流导航,使用轻量边框和活动底色。+- 当前步骤内容使用全宽 section;只有资源列表、配置预览、权限例外等重复项使用边框行。+- 不在四步外再包一层“授权设置”卡片,避免出现三层嵌套边框。++## 响应式规格++### 宽屏(>= 1024px)++- 内容最大宽度 `1200px`,居中,左右内边距 `24px`。+- 一级 Tab 保持单行。+- HTTP 监听配置可使用两列;Host/Port 同行,Path 独占一行。+- stdio 状态信息使用两列紧凑网格。++### 中等窗口(768–1023px)++- 一级 Tab 保持单行,内容单列。+- 二级接入 Tab 和客户端 Tab 允许横向滚动。+- 所有状态/配置区块改为单列,避免压缩输入框。++### 窄窗口(< 768px)++- 顶部状态头允许标题、状态和动作分两行。+- 一级 Tab、二级接入 Tab、客户端 Tab 各自独立横向滚动,不互相嵌套在同一滚动容器中。+- 权限四步导航改为单行横向滚动;当前步骤始终可见。+- HTTP Host、Port、Path 和远程访问配置全部单列。+- 配置预览保持水平滚动,复制按钮固定在可见区域。++## 设计令牌++采用 `Default Neutral Modern` 为基线,借鉴 Linear 的信息层级和 Cursor 的配置区排版:++- 背景、文字、边框全部复用现有 `--background`、`--foreground`、`--muted-foreground`、`--border`。+- 4px 间距基数:控件间 `8px`,区块内 `16px`,区块间 `24px`。+- 控件圆角沿用现有 `rounded-md`;不新增更大的圆角。+- 默认无阴影,仅活动 Tab 和弹层使用现有阴影。+- 状态颜色只用于成功、警告、错误和检查中,不作为导航装饰色。+- 图标使用 Lucide:`PlugZap`、`ShieldCheck`、`RefreshCw`、`Copy`、`TriangleAlert`、`CheckCircle2`。++## 不改变的内容++- MCP 策略判定与优先级。+- `allowedGroupIds`、`allowedConnectionIds`、数据库范围和工具权限字段。+- stdio 安装、更新、卸载行为。+- HTTP 服务保存、启动、停止、Token 轮换和 Host/Origin 校验。+- 客户端配置生成内容。+- Web 与 Desktop 两种运行环境的差异逻辑。++## 实现映射建议++下一轮实现只需要在 `EditorSettingsDialog.vue` 的 MCP 区域增加一个页面级 Tab 状态,并移动现有模板块:++- 现有 `mcpTransportTab` 继续作为“接入方式”的二级 Tab。+- 现有 `mcpConfigTab` 继续作为接入方式内的客户端配置 Tab。+- `McpAuthorizationStepper` 整体移动到“权限管理”一级 Tab。+- 状态头保留在一级 Tab 之上,但只显示聚合状态;stdio/HTTP 详细状态随各自面板移动。+- 查询超时从权限步骤移到接入方式的运行参数区域。+- 不修改 `saveMcpPolicy`、HTTP 保存方法、安装方法和任何后端接口。++## 验收标准++- 用户打开 MCP 设置时,能立即区分“怎么接入”和“接入后能做什么”。+- 接入方式页不出现权限编辑控件;权限管理页不出现安装、Token 或监听配置。+- 接入方式页内只需一次二级 Tab 切换即可在 stdio/HTTP 间切换。+- 当前状态在滚动时仍可见,且不重复显示多个互相竞争的状态徽章。+- 客户端配置仍可复制,且不会被误解为权限配置。+- 宽屏、窄窗口和键盘 Tab 导航都能保持一级/二级层级关系。+- 本轮布局改动不会改变任何权限、接入或存储行为。diff --git a/src-tauri/src/commands/mcp_bridge.rs b/src-tauri/src/commands/mcp_bridge.rsindex 2a060aeb2a..ce0beef9cd 100644--- a/src-tauri/src/commands/mcp_bridge.rs+++ b/src-tauri/src/commands/mcp_bridge.rs@@ -1,4 +1,5 @@use serde::{Deserialize, Serialize};+use std::collections::HashMap;use std::path::{Path, PathBuf};use std::sync::Arc;use tauri::{AppHandle, Emitter};@@ -7,6 +8,7 @@ use tokio::net::TcpListener;use super::connection::AppState;+use dbx_core::mcp_policy::McpConnectionGroupPath;use dbx_core::storage::{McpDatabaseScope, McpGlobalPolicy};const BIND_ADDR: &str = "127.0.0.1:0";@@ -601,14 +603,14 @@ async fn resolve_connection(connection_id: Option<&str>,connection_name: &str,) -> Result<crate::models::connection::ConnectionConfig, String> {- let policy = load_mcp_policy(state).await?;+ let (policy, group_paths) = load_mcp_policy_context(state).await?;let configs = state.storage.load_connections().await.map_err(|e| mcp_policy_unavailable(e.to_string()))?;let config = if let Some(id) = connection_id.filter(|s| !s.is_empty()) {configs.iter().find(|c| c.id == id).ok_or_else(|| format!("Connection with id '{}' not found", id))?} else {find_config_by_name(&configs, connection_name).ok_or_else(|| "Connection not found".to_string())?};- ensure_connection_in_mcp_scope(&policy, &config.id)?;+ ensure_connection_in_mcp_scope_with_groups(&policy, group_paths.get(&config.id), &config.id)?;let mut state_configs = state.configs.write().await;if !state_configs.contains_key(&config.id) {state_configs.insert(config.id.clone(), config.clone());@@ -626,6 +628,24 @@ async fn load_mcp_policy(state: &Arc<AppState>) -> Result<McpGlobalPolicy, Strin.map_err(|error| mcp_policy_unavailable(error.to_string()))}+async fn load_mcp_policy_context(+ state: &Arc<AppState>,+) -> Result<(McpGlobalPolicy, HashMap<String, McpConnectionGroupPath>), String> {+ let policy = load_mcp_policy(state).await?;+ let group_paths = match state.storage.load_sidebar_layout().await {+ Ok(Some(layout)) => dbx_core::mcp_policy::connection_group_paths(&layout),+ Ok(None) => Ok(HashMap::new()),+ Err(error) => Err(error),+ };+ match group_paths {+ Ok(paths) => Ok((policy, paths)),+ Err(error) if dbx_core::mcp_policy::policy_uses_connection_groups(&policy) => {+ Err(mcp_policy_unavailable(error))+ }+ Err(_) => Ok((policy, HashMap::new())),+ }+}+fn mcp_policy_unavailable(error: String) -> String {if error.starts_with("MCP_POLICY_UNAVAILABLE:") {error@@ -634,8 +654,17 @@ fn mcp_policy_unavailable(error: String) -> String {}}+#[cfg(test)]fn ensure_connection_in_mcp_scope(policy: &McpGlobalPolicy, connection_id: &str) -> Result<(), String> {- if policy.allowed_connection_ids.as_ref().is_some_and(|allowed| !allowed.iter().any(|id| id == connection_id)) {+ ensure_connection_in_mcp_scope_with_groups(policy, None, connection_id)+}++fn ensure_connection_in_mcp_scope_with_groups(+ policy: &McpGlobalPolicy,+ group_path: Option<&McpConnectionGroupPath>,+ connection_id: &str,+) -> Result<(), String> {+ if !dbx_core::mcp_policy::policy_allows_connection(policy, group_path, connection_id) {return Err(format!("CONNECTION_OUT_OF_SCOPE: connection '{connection_id}' is not allowed by DBX MCP settings"));@@ -661,8 +690,18 @@ fn ensure_database_in_mcp_scope(policy: &McpGlobalPolicy, connection_id: &str, d}}+#[cfg(test)]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)+ effective_database_execution_policy_with_groups(policy, &[], connection_id, database)+}++fn effective_database_execution_policy_with_groups(+ policy: &McpGlobalPolicy,+ group_ids: &[String],+ connection_id: &str,+ database: &str,+) -> (bool, bool) {+ dbx_core::mcp_policy::effective_database_execution_policy_with_groups(policy, group_ids, connection_id, database)}async fn ensure_mcp_write_allowed(@@ -681,10 +720,13 @@ async fn ensure_mcp_write_allowed_with_risk(action: &str,dangerous: bool,) -> Result<(), String> {- let policy = load_mcp_policy(state).await?;- ensure_connection_in_mcp_scope(&policy, &config.id)?;+ let (policy, group_paths) = load_mcp_policy_context(state).await?;+ let group_path = group_paths.get(&config.id);+ ensure_connection_in_mcp_scope_with_groups(&policy, group_path, &config.id)?;ensure_database_in_mcp_scope(&policy, &config.id, database)?;- let (read_only, allow_dangerous_sql) = effective_database_execution_policy(&policy, &config.id, database);+ let group_ids = group_path.map(|path| path.ids.as_slice()).unwrap_or_default();+ let (read_only, allow_dangerous_sql) =+ effective_database_execution_policy_with_groups(&policy, group_ids, &config.id, database);if read_only {return Err(format!("MCP_READ_ONLY: MCP execution permission for database '{database}' is read-only. {action} blocked."@@ -710,8 +752,8 @@ pub(crate) async fn ensure_mcp_read_allowed_by_id(connection_id: &str,database: &str,) -> Result<(), String> {- let policy = load_mcp_policy(state).await?;- ensure_connection_in_mcp_scope(&policy, connection_id)?;+ let (policy, group_paths) = load_mcp_policy_context(state).await?;+ ensure_connection_in_mcp_scope_with_groups(&policy, group_paths.get(connection_id), connection_id)?;ensure_database_in_mcp_scope(&policy, connection_id, database)?;let configs = state.storage.load_connections().await.map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?;let config = configs@@ -745,8 +787,8 @@ async fn ensure_mcp_mongo_pipeline_target_allowed_by_id(database: &str,pipeline_json: &str,) -> Result<(), String> {- let policy = load_mcp_policy(state).await?;- ensure_connection_in_mcp_scope(&policy, connection_id)?;+ let (policy, group_paths) = load_mcp_policy_context(state).await?;+ ensure_connection_in_mcp_scope_with_groups(&policy, group_paths.get(connection_id), 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)?;@@ -1030,8 +1072,9 @@ async fn ensure_mcp_sql_allowed(database: &str,sql: &str,) -> Result<(), String> {- let policy = load_mcp_policy(state).await?;- ensure_connection_in_mcp_scope(&policy, &config.id)?;+ let (policy, group_paths) = load_mcp_policy_context(state).await?;+ let group_path = group_paths.get(&config.id);+ ensure_connection_in_mcp_scope_with_groups(&policy, group_path, &config.id)?;ensure_database_in_mcp_scope(&policy, &config.id, database)?;if let Some(rule) = policy.connection_policies.iter().find(|rule| rule.connection_id == config.id) {if rule.database_scope == McpDatabaseScope::Selected@@ -1051,7 +1094,9 @@ 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);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);+ let group_ids = group_path.map(|path| path.ids.as_slice()).unwrap_or_default();+ let (read_only, allow_dangerous_sql) =+ effective_database_execution_policy_with_groups(&policy, group_ids, &config.id, database);if read_only && is_write {return Err(format!("MCP_READ_ONLY: MCP execution permission for database '{database}' is read-only. SQL write blocked."