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): zero-config plugin tool surface with tiered grants
Jinpye652945d399d
diff --git a/apps/desktop/src/components/mcp/McpSqlApprovalDialog.vue b/apps/desktop/src/components/mcp/McpSqlApprovalDialog.vueindex 6cec355218..8542300762 100644--- a/apps/desktop/src/components/mcp/McpSqlApprovalDialog.vue+++ b/apps/desktop/src/components/mcp/McpSqlApprovalDialog.vue@@ -1,9 +1,10 @@<script setup lang="ts">-import { computed, onMounted, onUnmounted, ref } from "vue";+import { computed, onMounted, onUnmounted, ref, watch } from "vue";import { useI18n } from "vue-i18n";import { invoke } from "@tauri-apps/api/core";import { listen, type UnlistenFn } from "@tauri-apps/api/event";import { getCurrentWindow } from "@tauri-apps/api/window";+import { ShieldAlert } from "@lucide/vue";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";@@ -11,7 +12,10 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "* Desktop confirmation for MCP calls the policy marks "ask first":* high-risk SQL (`mcp-sql-approval`, may grant a timed approval) and other* high-risk tools such as plugin tools declared `full` or dangerous Redis- * commands (`mcp-tool-approval`, always one-shot).+ * commands (`mcp-tool-approval`, always one-shot). Every request carries a+ * visible countdown; when it runs out the request is dropped and the caller+ * sees an error. A per-tool "remember" checkbox stores a 24h auto-approve+ * consent so repeated calls to the same tool skip the dialog entirely.*/interface SqlApproval {allow_timed?: boolean;@@ -31,27 +35,96 @@ interface ToolApproval {detail: string;}-type Approval = ({ type: "sql" } & SqlApproval) | ({ type: "tool" } & ToolApproval);+type Approval = (({ type: "sql" } & SqlApproval) | ({ type: "tool" } & ToolApproval)) & { deadline?: number };++const APPROVAL_WINDOW_MS = 90_000;+const AUTO_APPROVE_KEY = "dbx.mcp-tool-approval.auto-approve";+const AUTO_APPROVE_TTL_MS = 24 * 60 * 60 * 1000;++interface ToolConsent {+ tool: string;+ until: number;+}const { t } = useI18n();const pending = ref<Approval[]>([]);const current = computed(() => pending.value[0]);-const expirationTimers = new Map<string, ReturnType<typeof setTimeout>>();+const now = ref(Date.now());+const rememberTool = ref(false);+let ticker: ReturnType<typeof setInterval> | undefined;const unlisteners: UnlistenFn[] = [];+function loadToolConsents(): ToolConsent[] {+ try {+ const raw = localStorage.getItem(AUTO_APPROVE_KEY);+ return (raw ? (JSON.parse(raw) as ToolConsent[]) : []).filter((item) => typeof item?.tool === "string" && typeof item.until === "number" && item.until > Date.now());+ } catch {+ return [];+ }+}++function toolConsented(tool: string): boolean {+ return loadToolConsents().some((item) => item.tool === tool);+}++function saveToolConsent(tool: string) {+ const consents = loadToolConsents().filter((item) => item.tool !== tool);+ consents.push({ tool, until: Date.now() + AUTO_APPROVE_TTL_MS });+ try {+ localStorage.setItem(AUTO_APPROVE_KEY, JSON.stringify(consents));+ } catch {+ // Persistence is best-effort: without storage the user simply re-approves.+ }+}+function enqueue(approval: Approval) {if (pending.value.some((item) => item.id === approval.id)) return;+ // A remembered tool skips the dialog entirely: the stored consent answers+ // this call and the visible queue is not touched.+ if (approval.type === "tool" && toolConsented(approval.tool)) {+ void invoke("respond_mcp_sql_approval", { id: approval.id, decision: "once" }).catch((error) => {+ console.error("[DBX] MCP approval auto-approve failed:", error);+ });+ return;+ }+ approval.deadline = Date.now() + APPROVAL_WINDOW_MS;pending.value.push(approval);- expirationTimers.set(- approval.id,- setTimeout(() => {- pending.value = pending.value.filter((item) => item.id !== approval.id);- expirationTimers.delete(approval.id);- }, 90_000),- );void getCurrentWindow().setFocus();+ startTicker();+}++function startTicker() {+ if (ticker === undefined) {+ ticker = setInterval(() => {+ now.value = Date.now();+ const alive = pending.value.filter((item) => (item.deadline ?? 0) > now.value);+ if (alive.length !== pending.value.length) pending.value = alive;+ if (pending.value.length === 0) stopTicker();+ }, 250);+ }+}++function stopTicker() {+ if (ticker !== undefined) {+ clearInterval(ticker);+ ticker = undefined;+ }}+const remainingSeconds = computed(() => {+ if (!current.value) return 0;+ return Math.max(0, Math.ceil(((current.value.deadline ?? 0) - now.value) / 1000));+});++const remainingPercent = computed(() => {+ if (!current.value) return 0;+ return Math.max(0, Math.min(100, Math.round((((current.value.deadline ?? 0) - now.value) / APPROVAL_WINDOW_MS) * 100)));+});++watch(current, () => {+ rememberTool.value = false;+});+onMounted(async () => {unlisteners.push(await listen<SqlApproval>("mcp-sql-approval", (event) => enqueue({ type: "sql", ...event.payload })));unlisteners.push(await listen<ToolApproval>("mcp-tool-approval", (event) => enqueue({ type: "tool", ...event.payload })));@@ -59,16 +132,15 @@ onMounted(async () => {onUnmounted(() => {for (const unlisten of unlisteners) unlisten();- for (const timer of expirationTimers.values()) clearTimeout(timer);- expirationTimers.clear();+ stopTicker();});async function decide(decision: "once" | "hour" | "day" | "deny") {const approval = current.value;if (!approval) return;pending.value.shift();- clearTimeout(expirationTimers.get(approval.id));- expirationTimers.delete(approval.id);+ if (approval.type === "tool" && decision === "once" && rememberTool.value) saveToolConsent(approval.tool);+ rememberTool.value = false;try {// One response channel for both kinds; tool approvals only accept once/deny.await invoke("respond_mcp_sql_approval", { id: approval.id, decision: (approval.type === "tool" || approval.allow_timed === false) && decision !== "deny" ? "once" : decision });@@ -86,9 +158,19 @@ function toolTitle(approval: Extract<Approval, { type: "tool" }>): string {<template><Dialog :open="!!current" @update:open="(open) => !open && decide('deny')">- <DialogContent class="sm:max-w-[640px]" :data-mcp-approval="current?.type">+ <!--+ A stray click must never decide a security approval: outside clicks and+ focus moves keep the dialog open, and only the explicit buttons (or Esc /+ the close button, which land here as update:open → deny) resolve it.+ -->+ <DialogContent class="sm:max-w-[640px]" :data-mcp-approval="current?.type" @pointer-down-outside="(event) => event.preventDefault()" @interact-outside="(event) => event.preventDefault()" @focus-outside="(event) => event.preventDefault()"><DialogHeader>- <DialogTitle>{{ current?.type === "tool" ? toolTitle(current) : t("settings.mcpSqlApprovalTitle") }}</DialogTitle>+ <div class="flex items-center gap-2.5">+ <span class="grid size-8 shrink-0 place-items-center rounded-full bg-amber-500/15 text-amber-600 dark:text-amber-400" data-mcp-approval-icon>+ <ShieldAlert class="size-4" />+ </span>+ <DialogTitle>{{ current?.type === "tool" ? toolTitle(current) : t("settings.mcpSqlApprovalTitle") }}</DialogTitle>+ </div></DialogHeader><div v-if="current?.type === 'sql'" class="min-w-0 space-y-3"><p class="text-sm">{{ t("settings.mcpSqlApprovalScope", { connection: current.connection_name, database: current.database }) }}</p>@@ -98,22 +180,41 @@ function toolTitle(approval: Extract<Approval, { type: "tool" }>): string {<p class="text-sm">{{ t("settings.mcpToolApprovalDescription") }}</p><dl class="grid grid-cols-[6rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs"><dt class="text-muted-foreground">{{ t("settings.mcpToolApprovalTool") }}</dt>- <dd class="font-mono">{{ current.tool }}</dd>+ <dd>+ <span class="rounded bg-muted px-1.5 py-0.5 font-mono" data-mcp-approval-tool>{{ current.tool }}</span>+ </dd><template v-if="current.connection_name"><dt class="text-muted-foreground">{{ t("settings.mcpToolApprovalTarget") }}</dt><dd>{{ current.database ? `${current.connection_name} / ${current.database}` : current.connection_name }}</dd></template></dl>- <pre class="max-h-64 overflow-auto rounded border bg-muted/40 p-3 text-xs whitespace-pre-wrap break-all" data-mcp-approval-detail>{{ current.detail }}</pre>+ <div class="space-y-1">+ <p class="text-xs font-medium text-muted-foreground">{{ t("settings.mcpToolApprovalDetail") }}</p>+ <pre class="max-h-64 overflow-auto rounded border bg-muted/40 p-3 text-xs whitespace-pre-wrap break-all" data-mcp-approval-detail>{{ current.detail }}</pre>+ </div>+ <label class="flex items-center gap-2 text-xs text-muted-foreground" data-mcp-approval-remember>+ <input v-model="rememberTool" type="checkbox" class="size-3.5 accent-primary" />+ {{ t("settings.mcpToolApprovalAutoApprove") }}+ </label></div>- <DialogFooter class="flex-wrap gap-2">- <Button variant="outline" @click="decide('deny')">{{ t("settings.mcpSqlApprovalDeny") }}</Button>- <template v-if="current?.type === 'sql' && current.allow_timed !== false">- <Button variant="outline" @click="decide('once')">{{ t("settings.mcpSqlApprovalOnce") }}</Button>- <Button variant="outline" @click="decide('hour')">{{ t("settings.mcpSqlApprovalHour") }}</Button>- <Button variant="destructive" @click="decide('day')">{{ t("settings.mcpSqlApprovalDay") }}</Button>- </template>- <Button v-else variant="destructive" data-mcp-approval-allow-once @click="decide('once')">{{ t("settings.mcpSqlApprovalOnce") }}</Button>+ <DialogFooter class="flex-col items-stretch gap-3 sm:flex-col">+ <div class="space-y-1.5" data-mcp-approval-countdown>+ <div class="h-1 w-full overflow-hidden rounded-full bg-muted">+ <div class="h-full rounded-full transition-[width] duration-300 ease-linear" :class="remainingSeconds <= 10 ? 'bg-red-500' : 'bg-amber-500'" :style="{ width: `${remainingPercent}%` }" data-mcp-approval-remaining-bar />+ </div>+ <p class="text-right text-xs" :class="remainingSeconds <= 10 ? 'font-medium text-red-500' : 'text-muted-foreground'" data-mcp-approval-remaining>+ {{ t("settings.mcpApprovalExpires", { seconds: remainingSeconds }) }}+ </p>+ </div>+ <div class="flex flex-wrap gap-2">+ <Button variant="outline" @click="decide('deny')">{{ t("settings.mcpSqlApprovalDeny") }}</Button>+ <template v-if="current?.type === 'sql' && current.allow_timed !== false">+ <Button variant="outline" @click="decide('once')">{{ t("settings.mcpSqlApprovalOnce") }}</Button>+ <Button variant="outline" @click="decide('hour')">{{ t("settings.mcpSqlApprovalHour") }}</Button>+ <Button variant="destructive" @click="decide('day')">{{ t("settings.mcpSqlApprovalDay") }}</Button>+ </template>+ <Button v-else variant="destructive" data-mcp-approval-allow-once @click="decide('once')">{{ t("settings.mcpSqlApprovalOnce") }}</Button>+ </div></DialogFooter></DialogContent></Dialog>diff --git a/apps/desktop/src/components/mcp/__tests__/McpSqlApprovalDialog.spec.ts b/apps/desktop/src/components/mcp/__tests__/McpSqlApprovalDialog.spec.tsindex fd22bdb323..6b49205672 100644--- a/apps/desktop/src/components/mcp/__tests__/McpSqlApprovalDialog.spec.ts+++ b/apps/desktop/src/components/mcp/__tests__/McpSqlApprovalDialog.spec.ts@@ -21,20 +21,31 @@ vi.mock("@tauri-apps/api/window", () => ({ getCurrentWindow: () => ({ setFocus:vi.mock("@/components/ui/button", () => ({ Button: { template: "<button><slot /></button>" } }));vi.mock("@/components/ui/dialog", () => ({Dialog: { props: ["open"], template: '<div v-if="open"><slot /></div>' },- DialogContent: { template: "<div><slot /></div>" },+ DialogContent: {+ inheritAttrs: false,+ setup(_: Record<string, never>, { slots, attrs }: { slots: { default?: () => unknown }; attrs: Record<string, unknown> }) {+ dialogContentAttrs = attrs as Record<string, ((event: { preventDefault: () => void }) => void) | undefined>;+ return () => slots.default?.() ?? null;+ },+ },DialogFooter: { template: "<div><slot /></div>" },DialogHeader: { template: "<div><slot /></div>" },DialogTitle: { template: "<div><slot /></div>" },}));+import { h } from "vue";import McpSqlApprovalDialog from "../McpSqlApprovalDialog.vue";+let dialogContentAttrs: Record<string, ((event: { preventDefault: () => void }) => void) | undefined> = {};+let host: HTMLDivElement;let app: ReturnType<typeof createApp>;beforeEach(async () => {vi.useFakeTimers();bridge.handlers = {};+ dialogContentAttrs = {};+ localStorage.clear();bridge.invoke.mockClear();bridge.focus.mockClear();bridge.unlisten.mockClear();@@ -60,6 +71,9 @@ beforeEach(async () => {mcpToolApprovalDescription: "Review the call",mcpToolApprovalTool: "Tool",mcpToolApprovalTarget: "Target",+ mcpToolApprovalDetail: "Call payload",+ mcpToolApprovalAutoApprove: "Remember this tool and auto-approve its calls for 24 hours",+ mcpApprovalExpires: "Auto-deny in {seconds}s",},},},@@ -98,6 +112,20 @@ it("shows the exact SQL and sends a one-time decision for its request ID", asyncexpect(host.textContent).not.toContain("DROP TABLE important;");});+it("keeps the dialog open on outside clicks or focus moves instead of denying", async () => {+ request("approval-outside");+ await nextTick();+ expect(host.textContent).toContain("DROP TABLE important;");+ for (const key of ["onPointerDownOutside", "onInteractOutside", "onFocusOutside"]) {+ const event = { preventDefault: vi.fn() };+ dialogContentAttrs[key]?.(event);+ expect(event.preventDefault).toHaveBeenCalledOnce();+ }+ // No decision was sent and the approval is still on screen.+ expect(bridge.invoke).not.toHaveBeenCalled();+ expect(host.textContent).toContain("DROP TABLE important;");+});+it("removes an unanswered request when the desktop approval times out", async () => {request("approval-2");await nextTick();@@ -107,6 +135,41 @@ it("removes an unanswered request when the desktop approval times out", async ()expect(bridge.invoke).not.toHaveBeenCalled();});+it("shows a visible countdown and drops the request when it expires", async () => {+ request("approval-cd");+ await nextTick();+ expect(host.querySelector("[data-mcp-approval-remaining]")?.textContent).toContain("Auto-deny in 90s");+ vi.advanceTimersByTime(2000);+ await nextTick();+ expect(host.querySelector("[data-mcp-approval-remaining]")?.textContent).toContain("Auto-deny in 88s");+ vi.advanceTimersByTime(90_000);+ await nextTick();+ expect(host.textContent).not.toContain("DROP TABLE important;");+ expect(bridge.invoke).not.toHaveBeenCalled();+});++it("auto-approves remembered tools without showing the dialog", async () => {+ localStorage.setItem("dbx.mcp-tool-approval.auto-approve", JSON.stringify([{ tool: "dbx_ssh__exec", until: Date.now() + 60_000 }]));+ toolRequest("tool-auto");+ await nextTick();+ expect(bridge.invoke).toHaveBeenCalledWith("respond_mcp_sql_approval", { id: "tool-auto", decision: "once" });+ expect(host.textContent).not.toContain("Confirm Terminal tool");+});++it("stores a 24h consent when remembering is checked before allowing once", async () => {+ toolRequest("tool-remember");+ await nextTick();+ host.querySelector<HTMLInputElement>("[data-mcp-approval-remember] input")!.click();+ await nextTick();+ Array.from(host.querySelectorAll("button"))+ .find((button) => button.textContent === "Once")+ ?.click();+ await nextTick();+ expect(bridge.invoke).toHaveBeenCalledWith("respond_mcp_sql_approval", { id: "tool-remember", decision: "once" });+ const consents = JSON.parse(localStorage.getItem("dbx.mcp-tool-approval.auto-approve")!) as { tool: string }[];+ expect(consents.map((consent) => consent.tool)).toContain("dbx_ssh__exec");+});+it("confirms high-risk tool calls once only and queues them with SQL approvals", async () => {toolRequest("tool-1");request("approval-3");diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex be1941957f..05f141c3f3 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -8679,6 +8679,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "Təhlükəli Redis əmrini təsdiqləyin",mcpToolApprovalDescription: "An MCP müştərisi wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "Alət",+ mcpToolApprovalDetail: "Çağrı məzmunu",+ mcpToolApprovalAutoApprove: "Bu aləti yadda saxla və 24 saat ərzində çağrışları avtomatik təsdiqlə",+ mcpApprovalExpires: "{seconds} san sonra avtomatik rədd",mcpToolApprovalTarget: "Hədəf",mcpManagementCapabilities: "Qabiliyyətlər",mcpOpenCallHistory: "MCP çağırış tarixçəsinə bax",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 4902dd7ecd..7dc5dd6c1f 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -11290,6 +11290,9 @@ export default {mcpToolApprovalRedisTitle: "Confirm dangerous Redis command",mcpToolApprovalDescription: "An MCP client wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "Tool",+ mcpToolApprovalDetail: "Call payload",+ mcpToolApprovalAutoApprove: "Remember this tool and auto-approve its calls for 24 hours",+ mcpApprovalExpires: "Auto-deny in {seconds}s",mcpToolApprovalTarget: "Target",mcpSqlApprovalScope: "Connection: {connection} · Database: {database}",mcpSqlApprovalOnce: "This request only",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 9f5d188b60..ec32398f9b 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -9974,6 +9974,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "Confirmar comando Redis peligroso",mcpToolApprovalDescription: "An Cliente MCP wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "Herramienta",+ mcpToolApprovalDetail: "Contenido de la llamada",+ mcpToolApprovalAutoApprove: "Recordar esta herramienta y aprobar automáticamente sus llamadas durante 24 horas",+ mcpApprovalExpires: "Denegación automática en {seconds}s",mcpToolApprovalTarget: "Destino",mcpManagementCapabilities: "Capacidades",mcpOpenCallHistory: "Ver historial de llamadas MCP",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex 7f113eed70..91ffbb5d98 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -9499,6 +9499,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "Konfirmasi perintah Redis berbahaya",mcpToolApprovalDescription: "An Klien MCP wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "Alat",+ mcpToolApprovalDetail: "Isi panggilan",+ mcpToolApprovalAutoApprove: "Ingat alat ini dan setujui otomatis panggilannya selama 24 jam",+ mcpApprovalExpires: "Tolak otomatis dalam {seconds} detik",mcpToolApprovalTarget: "Target operasi",mcpManagementCapabilities: "Kapabilitas",mcpOpenCallHistory: "Lihat riwayat panggilan MCP",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex d22e1ac12a..38d1587967 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -9726,6 +9726,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "Conferma il comando Redis pericoloso",mcpToolApprovalDescription: "An Client MCP wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "Strumento",+ mcpToolApprovalDetail: "Contenuto della chiamata",+ mcpToolApprovalAutoApprove: "Ricorda questo strumento e approva automaticamente le chiamate per 24 ore",+ mcpApprovalExpires: "Rifiuto automatico tra {seconds}s",mcpToolApprovalTarget: "Destinazione",mcpManagementCapabilities: "Funzionalità",mcpOpenCallHistory: "Visualizza cronologia chiamate MCP",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 568130bc0f..c4eeb956b0 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -9704,6 +9704,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "危険な Redis コマンドを確認",mcpToolApprovalDescription: "An MCP クライアント wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "ツール",+ mcpToolApprovalDetail: "呼び出し内容",+ mcpToolApprovalAutoApprove: "このツールを記憶し、24 時間以内の呼び出しを自動承認します",+ mcpApprovalExpires: "{seconds} 秒後に自動拒否",mcpToolApprovalTarget: "対象",mcpManagementCapabilities: "機能",mcpOpenCallHistory: "MCP 呼び出し履歴を表示",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 972747669c..fd1c188f71 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -9873,6 +9873,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "위험한 Redis 명령 확인",mcpToolApprovalDescription: "An MCP 클라이언트 wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "도구",+ mcpToolApprovalDetail: "호출 내용",+ mcpToolApprovalAutoApprove: "이 도구를 기억하고 24시간 동안 호출을 자동 승인합니다",+ mcpApprovalExpires: "{seconds}초 후 자동 거부",mcpToolApprovalTarget: "대상",mcpManagementCapabilities: "기능",mcpOpenCallHistory: "MCP 호출 기록 보기",diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.tsindex 5cb2ae9c6c..ef6cb06893 100644--- a/apps/desktop/src/i18n/locales/pl.ts+++ b/apps/desktop/src/i18n/locales/pl.ts@@ -8271,6 +8271,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "Potwierdź niebezpieczne polecenie Redis",mcpToolApprovalDescription: "Klient MCP chce wykonać operację wysokiego ryzyka. Zezwól tylko wtedy, gdy oczekujesz tego wywołania.",mcpToolApprovalTool: "Narzędzie",+ mcpToolApprovalDetail: "Treść wywołania",+ mcpToolApprovalAutoApprove: "Zapamiętaj to narzędzie i automatycznie zatwierdzaj jego wywołania przez 24 godziny",+ mcpApprovalExpires: "Automatyczna odmowa za {seconds}s",mcpToolApprovalTarget: "Cel",mcpCapabilityConnectionCreate: "Dodawanie/powielanie połączeń MCP (globalne uprawnienia domyślne)",mcpCapabilityConnectionRemove: "Usuwanie połączeń MCP (globalne uprawnienia domyślne)",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 9fc55f18ad..f4e5fc9182 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -9722,6 +9722,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "Confirmar comando Redis perigoso",mcpToolApprovalDescription: "An Cliente MCP wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "Ferramenta",+ mcpToolApprovalDetail: "Conteúdo da chamada",+ mcpToolApprovalAutoApprove: "Lembrar esta ferramenta e aprovar automaticamente suas chamadas por 24 horas",+ mcpApprovalExpires: "Negação automática em {seconds}s",mcpToolApprovalTarget: "Destino",mcpManagementCapabilities: "Capacidades",mcpOpenCallHistory: "Ver histórico de chamadas MCP",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 1733dbbd73..42a62e5c4f 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -11359,6 +11359,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "Подтвердить опасную команду Redis",mcpToolApprovalDescription: "An Клиент MCP wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "Инструмент",+ mcpToolApprovalDetail: "Содержимое вызова",+ mcpToolApprovalAutoApprove: "Запомнить этот инструмент и автоматически одобрять его вызовы в течение 24 часов",+ mcpApprovalExpires: "Автоотказ через {seconds} с",mcpToolApprovalTarget: "Цель",mcpManagementCapabilities: "Возможности",mcpOpenCallHistory: "Просмотреть историю вызовов MCP",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex 68dc80d025..f105afe8f9 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -11731,6 +11731,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "ยืนยันคำสั่ง Redis ที่อันตราย",mcpToolApprovalDescription: "An Client MCP wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "เครื่องมือ",+ mcpToolApprovalDetail: "เนื้อหาการเรียก",+ mcpToolApprovalAutoApprove: "จดจำเครื่องมือนี้และอนุมัติการเรียกโดยอัตโนมัติเป็นเวลา 24 ชั่วโมง",+ mcpApprovalExpires: "ปฏิเสธอัตโนมัติในอีก {seconds} วินาที",mcpToolApprovalTarget: "เป้าหมาย",mcpManagementCapabilities: "ความสามารถ",mcpOpenCallHistory: "ดูประวัติการเรียก MCP",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex 199ba28153..d89a88b25a 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -8591,6 +8591,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "Tehlikeli Redis komutunu onayla",mcpToolApprovalDescription: "An MCP istemcisi wants to run a high-risk operation. Allow it only if you expect this call.",mcpToolApprovalTool: "Araç",+ mcpToolApprovalDetail: "Çağrı içeriği",+ mcpToolApprovalAutoApprove: "Bu aracı hatırla ve 24 saat boyunca çağrılarını otomatik onayla",+ mcpApprovalExpires: "{seconds} sn sonra otomatik red",mcpToolApprovalTarget: "Hedef",mcpManagementCapabilities: "Yetenekler",mcpOpenCallHistory: "MCP çağrı geçmişini görüntüle",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 1567fc0b67..5c6bb5653a 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -11256,6 +11256,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "确认高危 Redis 命令",mcpToolApprovalDescription: "MCP 客户端请求执行一个高危操作。只有在你预期这次调用时才允许。",mcpToolApprovalTool: "工具",+ mcpToolApprovalDetail: "调用内容",+ mcpToolApprovalAutoApprove: "记住此工具,24 小时内自动批准其调用",+ mcpApprovalExpires: "{seconds} 秒后自动拒绝",mcpToolApprovalTarget: "目标",mcpSqlApprovalScope: "连接:{connection} · 数据库:{database}",mcpSqlApprovalOnce: "仅本次",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex b6b5e55527..24d46dd64b 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -8921,6 +8921,9 @@ export default withEnglishFallback({mcpToolApprovalRedisTitle: "確認高危 Redis 命令",mcpToolApprovalDescription: "MCP 用戶端請求執行一個高危操作。只有在你預期這次呼叫時才允許。",mcpToolApprovalTool: "工具",+ mcpToolApprovalDetail: "呼叫內容",+ mcpToolApprovalAutoApprove: "記住此工具,24 小時內自動批准其呼叫",+ mcpApprovalExpires: "{seconds} 秒後自動拒絕",mcpToolApprovalTarget: "目標",mcpSqlApprovalScope: "連線:{connection} · 資料庫:{database}",mcpSqlApprovalOnce: "僅本次請求",diff --git a/crates/dbx-core/src/ai/mcp_access.rs b/crates/dbx-core/src/ai/mcp_access.rsindex 91554c0bde..35477bca3f 100644--- a/crates/dbx-core/src/ai/mcp_access.rs+++ b/crates/dbx-core/src/ai/mcp_access.rs@@ -25,7 +25,7 @@ use crate::storage::{McpDatabaseScope, McpGlobalPolicy};pub const MCP_ACCESS_POLICY_VERSION: u8 = 2;/// How plugin MCP tools are exposed to clients.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]#[serde(rename_all = "lowercase")]pub enum McpPluginToolsMode {Auto,@@ -34,6 +34,25 @@ pub enum McpPluginToolsMode {Lazy,}+// Tolerant on purpose: the desktop app and the standalone `dbx-mcp` binary+// version independently, so a policy written by a newer build may carry a+// mode this build does not know. Rejecting the whole policy would take down+// every MCP tool; fall back to `auto` and let Auto resolve instead.+impl<'de> Deserialize<'de> for McpPluginToolsMode {+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let text = String::deserialize(deserializer)?;+ Ok(match text.as_str() {+ "auto" => Self::Auto,+ "flat" => Self::Flat,+ "lazy" => Self::Lazy,+ unknown => {+ log::warn!("[mcp] unknown pluginToolsMode {unknown:?} in saved policy; falling back to auto");+ Self::Auto+ }+ })+ }+}+impl McpPluginToolsMode {/// Preserve the behavior of saved policies written without this field./// New policies use `Default` (flat); explicit saved modes always win.@@ -387,6 +406,27 @@ impl McpAccessPolicy {self.connection_rule(connection_id).and_then(|rule| rule.sub_scope).unwrap_or_default()}+ /// Effective level for a plugin connection. Identical to [`Self::resolve`]+ /// except that a connection with no explicit connection/group rule falls+ /// back to its own protection level instead of the global default:+ /// read-only connections stay read, writable ones resolve to at least+ /// write. Explicit rules (connection or group) always win.+ pub fn resolve_plugin_connection(+ &self,+ group_ids: &[String],+ connection_id: &str,+ connection_read_only: bool,+ ) -> McpResolvedAccess {+ let mut resolved = self.resolve(group_ids, connection_id, None);+ if resolved.source == McpAccessSource::Default+ && !connection_read_only+ && resolved.level < McpAccessLevel::Write+ {+ resolved.level = McpAccessLevel::Write;+ }+ resolved+ }+/// Whether a request that enumerates every value of a sub-scope can be/// admitted without evaluating each value separately. This is only safe/// when the connection explicitly permits all sub-scopes and no rule@@ -1587,3 +1627,26 @@ mod tests {assert!(serde_json::to_value(&policy).unwrap()["rules"].is_array());}}++#[cfg(test)]+mod plugin_tools_mode_tests {+ use super::McpPluginToolsMode;++ #[test]+ fn plugin_tools_mode_serializes_lowercase_and_tolerates_unknown_values() {+ assert_eq!(serde_json::to_value(McpPluginToolsMode::Flat).unwrap(), serde_json::json!("flat"));+ assert_eq!(+ serde_json::from_value::<McpPluginToolsMode>(serde_json::json!("flat")).unwrap(),+ McpPluginToolsMode::Flat+ );+ assert_eq!(+ serde_json::from_value::<McpPluginToolsMode>(serde_json::json!("lazy")).unwrap(),+ McpPluginToolsMode::Lazy+ );+ // A mode written by a newer build must not take the whole policy down.+ assert_eq!(+ serde_json::from_value::<McpPluginToolsMode>(serde_json::json!("both")).unwrap(),+ McpPluginToolsMode::Auto+ );+ }+}diff --git a/crates/dbx-core/src/ai/plugin_mcp.rs b/crates/dbx-core/src/ai/plugin_mcp.rsindex 7cac777a08..a925cb6f59 100644--- a/crates/dbx-core/src/ai/plugin_mcp.rs+++ b/crates/dbx-core/src/ai/plugin_mcp.rs@@ -81,14 +81,21 @@ pub fn author_allows_external(manifest: &PluginManifest) -> bool {manifest.mcp_contribution().is_some_and(|mcp| mcp.external_tools)}-/// The grant in force for a plugin: the saved one, or "not authorized".-pub fn effective_grant(saved: Option<&PluginMcpGrant>) -> PluginMcpGrant {- saved.cloned().unwrap_or(PluginMcpGrant {- external: false,- ceiling: PluginMcpAccessLevel::Read,- approved_tools: Default::default(),- disabled_tools: Vec::new(),- })+/// The grant in force for a plugin. A saved grant always wins. Without one,+/// a plugin whose author opted into the external server (`external_tools`)+/// runs under a read-only default: its declared read tools are exposed with+/// zero setup, while write/full tools stay above the ceiling until the user+/// grants them. Plugins that did not opt in stay fully unauthorized.+pub fn effective_grant(manifest: &PluginManifest, saved: Option<&PluginMcpGrant>) -> PluginMcpGrant {+ match saved {+ Some(saved) => saved.clone(),+ None => PluginMcpGrant {+ external: author_allows_external(manifest),+ ceiling: PluginMcpAccessLevel::Read,+ approved_tools: Default::default(),+ disabled_tools: Vec::new(),+ },+ }}/// Decides one tool's exposure under an effective grant.@@ -148,7 +155,7 @@ pub fn exposed_tools(saved: Option<&PluginMcpGrant>,tools: Vec<RawPluginTool>,) -> Vec<RawPluginTool> {- let grant = effective_grant(saved);+ let grant = effective_grant(manifest, saved);tools.into_iter().filter(|tool| tool_exposure(manifest, &grant, &tool.name).is_exposed())@@ -233,7 +240,7 @@ pub fn plugin_view(Err(error) => (Vec::new(), Some(error)),};let contribution = manifest.mcp_contribution();- let grant = effective_grant(saved);+ let grant = effective_grant(manifest, saved);let tool_views = tools.iter().map(|tool| PluginMcpToolView {@@ -561,11 +568,27 @@ mod tests {}#[test]- fn nothing_is_exposed_before_the_user_authorizes() {- assert!(exposed(&declared(), None).is_empty());+ fn read_tools_work_without_a_grant_when_the_author_opts_in() {+ // Zero-setup default: the author's `external_tools` opt-in exposes the+ // declared read tier immediately; write/full wait above the ceiling.+ assert_eq!(exposed(&declared(), None), ["list_dir"]);let view = plugin_view(&declared(), None, Ok(tools()));+ assert!(!view.has_saved_grant);+ assert!(view.grant.external);+ assert_eq!(view.grant.ceiling, PluginMcpAccessLevel::Read);+ assert_eq!(view.tools[0].exposure, PluginToolExposure::Exposed);+ assert_eq!(view.tools[1].exposure, PluginToolExposure::AboveCeiling);+ assert_eq!(view.tools[2].exposure, PluginToolExposure::AboveCeiling);+ }++ #[test]+ fn nothing_is_exposed_when_the_author_did_not_opt_in() {+ let legacy = manifest(serde_json::Value::Null);+ assert!(exposed(&legacy, None).is_empty());+ let view = plugin_view(&legacy, None, Ok(tools()));assert!(!view.has_saved_grant && !view.grant.external);- assert!(view.tools.iter().all(|tool| tool.exposure == PluginToolExposure::PluginDisabled));+ // No contribution means no declarations: Undeclared, never Exposed.+ assert!(view.tools.iter().all(|tool| tool.exposure == PluginToolExposure::Undeclared));}#[test]diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rsindex 742020ee29..4b1e423662 100644--- a/crates/dbx-mcp/src/backend.rs+++ b/crates/dbx-mcp/src/backend.rs@@ -310,6 +310,16 @@ pub trait DbxBackend: Send + Sync {}async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String>;++ /// Whether the user has saved any MCP policy. Fresh installs have none,+ /// in which case writable plugin connections fall back to their own+ /// protection level (at least write) instead of the global default. Once+ /// a policy is saved, its explicit settings are authoritative everywhere.+ /// Unreadable storage counts as configured: unreadable hides, never widens.+ async fn mcp_policy_configured(&self) -> bool {+ false+ }+async fn save_history_entry(&self, entry: &HistoryEntry) -> Result<(), String> {let _ = entry;Err("Query history is not supported by this backend.".to_string())@@ -1298,6 +1308,10 @@ impl DbxBackend for LocalBackend {self.state.storage.load_mcp_access_policy().await.map(effective_mcp_access_policy)}+ async fn mcp_policy_configured(&self) -> bool {+ self.state.storage.load_enforced_mcp_policy().await.map(|state| state.configured).unwrap_or(true)+ }+async fn list_plugin_mcp_tools(&self) -> Result<Vec<crate::plugin_tools::PluginToolProvider>, String> {self.detect_plugin_tool_providers().await}@@ -1781,6 +1795,16 @@ impl DbxBackend for WebBackend {.map_err(|error| format!("Invalid MCP policy response: {error}"))}+ async fn mcp_policy_configured(&self) -> bool {+ // Same source as `load_mcp_global_policy` and as LocalBackend: the+ // enforced global policy state's `configured` flag. Transport or+ // parse failures count as configured — unreadable hides, never widens.+ match self.request(reqwest::Method::GET, "/api/app-settings/mcp-policy", None).await {+ Ok(response) => response.json::<McpGlobalPolicyState>().await.map(|state| state.configured).unwrap_or(true),+ Err(_) => true,+ }+ }+async fn load_mcp_access_policy(&self) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {let body = self.request(reqwest::Method::GET, "/api/app-settings/mcp-access-policy", None)@@ -3619,6 +3643,56 @@ mod tests {assert_eq!(paths.get("web-db"), Some(&vec!["Project".to_string()]));}+ #[tokio::test]+ async fn web_backend_policy_configured_follows_the_enforced_state() {+ // `mcp_policy_configured` must mirror the same source the local+ // backend uses: the enforced global policy state's `configured` flag.+ // A configured (or unreadable) web source keeps the saved policy+ // authoritative — unreadable hides, never widens.+ for (body, expected) in [+ (r#"{"configured":true,"readOnly":false,"allowDangerousSql":false}"#, true),+ (r#"{"configured":false,"readOnly":true,"allowDangerousSql":false}"#, false),+ ] {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ let (request_sender, request_receiver) = mpsc::channel();+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();+ let mut request = Vec::new();+ let mut buffer = [0_u8; 1024];+ loop {+ let count = stream.read(&mut buffer).unwrap();+ request.extend_from_slice(&buffer[..count]);+ if count == 0 || request.windows(4).any(|window| window == b"\r\n\r\n") {+ break;+ }+ }+ request_sender.send(String::from_utf8(request).unwrap().lines().next().unwrap().to_string()).unwrap();+ write!(+ stream,+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ )+ .unwrap();+ });++ let backend = WebBackend::new(format!("http://{address}"), String::new()).unwrap();+ backend.auth.lock().await.checked = true;+ let configured = backend.mcp_policy_configured().await;++ server.join().unwrap();+ assert_eq!(request_receiver.recv().unwrap(), "GET /api/app-settings/mcp-policy HTTP/1.1");+ assert_eq!(configured, expected, "body: {body}");+ }++ // Unreachable desktop (transport error) counts as configured.+ let backend = WebBackend::new("http://127.0.0.1:1".to_string(), String::new()).unwrap();+ backend.auth.lock().await.checked = true;+ assert!(backend.mcp_policy_configured().await);+ }+#[tokio::test]async fn web_backend_loads_v2_access_policy_with_plugin_scope_rules() {// The desktop test suite normally exercises the HTTP path below. Somediff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rsindex dccc2fb40b..347d49202c 100644--- a/crates/dbx-mcp/src/server.rs+++ b/crates/dbx-mcp/src/server.rs@@ -2229,6 +2229,7 @@ impl DbxMcpServer {Ok(allowed) => allowed,Err(error) => return error,};+ let read_only_by_connection = self.plugin_connection_read_only_if_unconfigured().await;if self.scope.enabled() && allowed_connections.is_empty() {return tool_error("PLUGIN_OUT_OF_SCOPE",@@ -2243,12 +2244,24 @@ impl DbxMcpServer {let connection_hidden = owned.iter().filter(|entry| {- !plugin_entry_has_allowed_connection(access.as_ref(), group_paths.as_ref(), entry, &allowed_connections)+ !plugin_entry_has_allowed_connection(+ access.as_ref(),+ group_paths.as_ref(),+ entry,+ &allowed_connections,+ &read_only_by_connection,+ )}).count();hidden += connection_hidden;owned.retain(|entry| {- plugin_entry_has_allowed_connection(access.as_ref(), group_paths.as_ref(), entry, &allowed_connections)+ plugin_entry_has_allowed_connection(+ access.as_ref(),+ group_paths.as_ref(),+ entry,+ &allowed_connections,+ &read_only_by_connection,+ )});if owned.is_empty() {// An all-allowlist-hidden plugin, a plugin with no usable@@ -2273,6 +2286,7 @@ impl DbxMcpServer {group_paths.get(connection_id).map(|path| path.ids.as_slice()).unwrap_or(&[]),entry,connection_id,+ read_only_by_connection.get(connection_id).copied(),)}).cloned()@@ -5050,7 +5064,7 @@ impl DbxMcpServer {.await.map_err(|error| backend_tool_error("MCP_POLICY_UNAVAILABLE", error))?;if entry.scope.is_none() && connection_id.is_none() {- return ensure_plugin_scope(&access, entry, &[], None, arguments);+ return ensure_plugin_scope(&access, entry, &[], None, None, arguments);}let policy = self.load_policy().await?;let group_paths = self@@ -5059,7 +5073,21 @@ impl DbxMcpServer {.map_err(|error| backend_tool_error("MCP_POLICY_UNAVAILABLE", error))?;let group_ids =connection_id.and_then(|id| group_paths.get(id)).map(|path| path.ids.clone()).unwrap_or_default();- ensure_plugin_scope(&access, entry, &group_ids, connection_id, arguments)+ // The connection's own protection level feeds the plugin-connection+ // default (writable plugin connections resolve to at least write when+ // no explicit rule says otherwise). The default only applies to fresh+ // installs: once the user saves any MCP policy, its explicit settings+ // are authoritative. The same configured-aware map the listings use+ // keeps advertised visibility and call decisions identical. Unknown+ // facts keep the plain policy default.+ let connection_read_only = match connection_id {+ Some(id) => {+ let read_only_by_connection = self.plugin_connection_read_only_if_unconfigured().await;+ read_only_by_connection.get(id).copied()+ }+ None => None,+ };+ ensure_plugin_scope(&access, entry, &group_ids, connection_id, connection_read_only, arguments)}/// The advertised `tools/list` view: router-enabled tools narrowed to the@@ -5410,6 +5438,7 @@ impl DbxMcpServer {let entries = crate::plugin_tools::build_catalog(&providers);// Tool calls fail closed on policy errors anyway; keep the view.let allowed = self.allowed_plugin_connections().await.unwrap_or_default();+ let read_only_by_connection = self.plugin_connection_read_only_if_unconfigured().await;let access = self.backend.load_mcp_access_policy().await.ok();let policy = policy.cloned();let group_paths = match policy.as_ref() {@@ -5424,7 +5453,13 @@ impl DbxMcpServer {return None;}let connections = allowed.get(&entry.plugin_id).cloned().unwrap_or_default();- if !plugin_entry_has_allowed_connection(access.as_ref(), group_paths.as_ref(), &entry, &connections) {+ if !plugin_entry_has_allowed_connection(+ access.as_ref(),+ group_paths.as_ref(),+ &entry,+ &connections,+ &read_only_by_connection,+ ) {return None;}let connections = match (&access, &group_paths) {@@ -5436,6 +5471,7 @@ impl DbxMcpServer {group_paths.get(connection_id).map(|path| path.ids.as_slice()).unwrap_or(&[]),&entry,connection_id,+ read_only_by_connection.get(connection_id).copied(),)}).collect(),@@ -5558,6 +5594,7 @@ impl DbxMcpServer {// Listing degrades on policy errors the same way the flat view does;// `dbx_plugin_tools`/`dbx_plugin_call` still fail closed.let allowed = self.allowed_plugin_connections().await.unwrap_or_default();+ let read_only_by_connection = self.plugin_connection_read_only_if_unconfigured().await;let policy = self.load_policy().await.ok();let access = self.backend.load_mcp_access_policy().await.ok();let group_paths = match policy.as_ref() {@@ -5598,6 +5635,7 @@ impl DbxMcpServer {group_paths.as_ref(),entry,connections,+ &read_only_by_connection,)}).collect::<Vec<_>>();@@ -5615,6 +5653,7 @@ impl DbxMcpServer {group_paths.get(connection_id).map(|path| path.ids.as_slice()).unwrap_or(&[]),entry,connection_id,+ read_only_by_connection.get(connection_id).copied(),),_ => true,}@@ -5634,6 +5673,35 @@ impl DbxMcpServer {Ok(allowed.get(plugin_id).cloned().unwrap_or_default())}+ /// Read-only flag per plugin connection. Feeds the plugin-connection+ /// access default (writable plugin connections resolve to at least write+ /// when no explicit rule says otherwise) on both the listing and the call+ /// path so a tool never advertises where it cannot run, and never hides+ /// where it can.+ async fn plugin_connection_read_only(&self) -> Result<HashMap<String, bool>, CallToolResult> {+ let connections =+ self.backend.load_connections().await.map_err(|error| tool_error("CONNECTION_LOAD_ERROR", error))?;+ Ok(connections+ .into_iter()+ .filter(|config| config.plugin_id.as_deref().is_some_and(|id| !id.trim().is_empty()))+ .map(|config| (config.id, config.read_only))+ .collect())+ }++ /// The configured-aware plugin-connection read-only map: the single+ /// source every listing and the call path share. The write-widening+ /// default only applies to fresh installs — once the user saves any MCP+ /// policy its explicit settings are authoritative, so the map stays empty+ /// and resolution falls back to the plain policy default on listings and+ /// calls alike. Backends map unreadable storage to configured, so this+ /// fails closed (never widens) there too.+ async fn plugin_connection_read_only_if_unconfigured(&self) -> HashMap<String, bool> {+ if self.backend.mcp_policy_configured().await {+ return HashMap::new();+ }+ self.plugin_connection_read_only().await.unwrap_or_default()+ }+/// Shared call core for `dbx_plugin_call`: locates the tool by/// `(plugin_id, tool name)` over a fresh discovery pass, strips/// selector arguments, binds the connection, and forwards to the@@ -6326,8 +6394,21 @@ fn plugin_connection_level_allowed(group_ids: &[String],entry: &crate::plugin_tools::PluginToolEntry,connection_id: &str,+ connection_read_only: Option<bool>,) -> bool {let required = plugin_tool_required_access(entry);+ // Scope-less entries resolve directly so the plugin-connection default+ // (writable plugin connections count as write) applies to the listing+ // exactly as it does at call time. Scope-bound entries keep the+ // sub-scope-aware check.+ if entry.scope.is_none() {+ let resolved = match connection_read_only {+ Some(read_only) => access.resolve_plugin_connection(group_ids, connection_id, read_only),+ None => access.resolve(group_ids, connection_id, None),+ };+ let ceiling = access.toolset_ceiling(connection_id, &entry.toolset);+ return resolved.visible && ceiling.map_or(resolved.level, |c| resolved.level.min(c)) >= required;+ }let scopes = entry.scope.as_ref().map(|(kind, _)| [kind.as_str()]);connection_has_tool_access(access,@@ -6355,6 +6436,7 @@ fn plugin_entry_has_allowed_connection(group_paths: Option<&HashMap<String, dbx_core::mcp_policy::McpConnectionGroupPath>>,entry: &crate::plugin_tools::PluginToolEntry,connections: &[(String, String)],+ read_only_by_connection: &HashMap<String, bool>,) -> bool {if !entry.requires_connection() {return access.is_none_or(|access| access.default_access >= plugin_tool_required_access(entry));@@ -6369,6 +6451,7 @@ fn plugin_entry_has_allowed_connection(group_paths.get(connection_id).map(|path| path.ids.as_slice()).unwrap_or(&[]),entry,connection_id,+ read_only_by_connection.get(connection_id).copied(),)}),_ => true,@@ -6385,6 +6468,7 @@ fn ensure_plugin_scope(entry: &crate::plugin_tools::PluginToolEntry,group_ids: &[String],connection_id: Option<&str>,+ connection_read_only: Option<bool>,arguments: &serde_json::Value,) -> Result<dbx_core::mcp_access::McpAccessLevel, CallToolResult> {let Some(connection_id) = connection_id else {@@ -6394,10 +6478,16 @@ fn ensure_plugin_scope(format!("Plugin tool \"{}\" requires a policy-bound connection.", entry.exposed_name),));}- if access.default_access < plugin_tool_required_access(entry) {+ let needed = plugin_tool_required_access(entry);+ if access.default_access < needed {return Err(tool_error("MCP_READ_ONLY",- format!("Plugin tool \"{}\" is above the effective DBX MCP access level.", entry.exposed_name),+ format!(+ "Plugin tool \"{}\" needs {} access but the global default is {}. Raise the connection's access level in DBX Settings → MCP, or call it with an authorized connectionId.",+ entry.exposed_name,+ access_level_name(needed),+ access_level_name(access.default_access)+ ),));}return Ok(access.default_access);@@ -6426,7 +6516,10 @@ fn ensure_plugin_scope(}}} else {- access.resolve(group_ids, connection_id, None)+ match connection_read_only {+ Some(read_only) => access.resolve_plugin_connection(group_ids, connection_id, read_only),+ None => access.resolve(group_ids, connection_id, None),+ }};if !resolved.visible {return Err(tool_error(@@ -6437,12 +6530,28 @@ fn ensure_plugin_scope(if cap(resolved.level) < needed {return Err(tool_error("MCP_READ_ONLY",- format!("Plugin tool \"{}\" is above the effective DBX MCP access level.", entry.exposed_name),+ format!(+ "Plugin tool \"{}\" needs {} access; connection \"{}\" resolves to {} in the DBX MCP settings. Raise that connection's access level in DBX Settings → MCP.",+ entry.exposed_name,+ access_level_name(needed),+ connection_id,+ access_level_name(resolved.level)+ ),));}Ok(cap(resolved.level))}+/// Lowercase stable names for error messages and audits.+fn access_level_name(level: dbx_core::mcp_access::McpAccessLevel) -> &'static str {+ match level {+ dbx_core::mcp_access::McpAccessLevel::None => "none",+ dbx_core::mcp_access::McpAccessLevel::Read => "read",+ dbx_core::mcp_access::McpAccessLevel::Write => "write",+ dbx_core::mcp_access::McpAccessLevel::Full => "full",+ }+}+/// The exposed tool is declared `full`: `exposed_tools` rewrites/// `destructiveHint` from the manifest level, so the hint is authoritative here.fn plugin_tool_is_destructive(tool: &dbx_core::ai::plugin_tools::RawPluginTool) -> bool {@@ -7674,6 +7783,7 @@ mod tests {struct FakeBackend {connections: Vec<ConnectionConfig>,policy: McpGlobalPolicy,+ mcp_policy_configured: bool,recorded_arguments: std::sync::Mutex<Vec<(String, serde_json::Value)>>,history: std::sync::Mutex<Vec<dbx_core::history::HistoryEntry>>,closed_sessions: std::sync::Mutex<Vec<String>>,@@ -7712,6 +7822,7 @@ mod tests {Self {connections: Vec::new(),policy: McpGlobalPolicy::default(),+ mcp_policy_configured: true,recorded_arguments: std::sync::Mutex::new(Vec::new()),history: std::sync::Mutex::new(Vec::new()),closed_sessions: std::sync::Mutex::new(Vec::new()),@@ -8090,6 +8201,10 @@ mod tests {Ok(self.policy_override.lock().unwrap().clone().unwrap_or_else(|| self.policy.clone()))}+ async fn mcp_policy_configured(&self) -> bool {+ self.mcp_policy_configured+ }+async fn load_mcp_access_policy(&self) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {self.access_policy_loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);if !self.tool_approvals.lock().unwrap().is_empty() {@@ -9612,11 +9727,102 @@ mod tests {McpRuleTarget::Scope { connection_id: "k1".into(), scope: "namespace".into(), value: "prod".into() },rule,);- let error = ensure_plugin_scope(&access, &entry, &[], Some("k1"), &json!({})).unwrap_err();+ let error = ensure_plugin_scope(&access, &entry, &[], Some("k1"), None, &json!({})).unwrap_err();assert!(result_text(&error).contains("SCOPE_REQUIRED"));}}+ #[test]+ fn writable_plugin_connections_default_to_write_without_explicit_rules() {+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};+ let provider = plugin_provider("io.dbx.ssh", "Terminal", json!({"tools": [{"name": "exec"}]}));+ let entry = crate::plugin_tools::build_catalog(&[provider]).remove(0);+ let access = McpAccessPolicy::default(); // default_access: Read++ // No rule + writable plugin connection: the connection's own+ // protection level replaces the global read default.+ let level = ensure_plugin_scope(&access, &entry, &[], Some("c1"), Some(false), &json!({})).unwrap();+ assert_eq!(level, McpAccessLevel::Write);++ // Read-only plugin connection keeps the read default.+ let error = ensure_plugin_scope(&access, &entry, &[], Some("c1"), Some(true), &json!({})).unwrap_err();+ assert!(result_text(&error).contains("MCP_READ_ONLY"), "{}", result_text(&error));++ // Unknown facts (older call paths) keep the plain policy default.+ let error = ensure_plugin_scope(&access, &entry, &[], Some("c1"), None, &json!({})).unwrap_err();+ assert!(result_text(&error).contains("MCP_READ_ONLY"), "{}", result_text(&error));++ // An explicit connection rule always wins over the default.+ let mut explicit = McpAccessPolicy::default();+ explicit.rules.insert(+ McpRuleTarget::Connection { id: "c1".into() },+ McpAccessRule { access: Some(McpAccessLevel::Read), ..Default::default() },+ );+ let error = ensure_plugin_scope(&explicit, &entry, &[], Some("c1"), Some(false), &json!({})).unwrap_err();+ assert!(result_text(&error).contains("resolves to read"), "{}", result_text(&error));+ explicit.rules.insert(+ McpRuleTarget::Connection { id: "c1".into() },+ McpAccessRule { access: Some(McpAccessLevel::Full), ..Default::default() },+ );+ let level = ensure_plugin_scope(&explicit, &entry, &[], Some("c1"), Some(false), &json!({})).unwrap();+ assert_eq!(level, McpAccessLevel::Full);+ }++ #[tokio::test]+ async fn saved_policy_keeps_plugin_write_tools_out_of_every_listing() {+ // A saved policy with a read default must stay authoritative on every+ // surface: the write-widening plugin-connection default (writable+ // connection => at least write) only applies to fresh installs with+ // no saved policy. Here the connection IS writable, so the raw map+ // would widen — the listings must not advertise what the call denies.+ let backend = |configured: bool| {+ Arc::new(FakeBackend {+ connections: vec![plugin_connection("k1", "prod", "io.dbx.kafka")],+ // A saved read-default policy: from_v1 maps read_only => Read.+ policy: McpGlobalPolicy { read_only: true, ..Default::default() },+ plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())],+ mcp_policy_configured: configured,+ ..Default::default()+ })+ };++ // Saved policy: the write-tier tool disappears from the flat+ // tools/list and the call denies it, while the read-only one stays.+ let server = DbxMcpServer::with_runtime_options(backend(true), McpScope::default(), false);+ let names =+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<HashSet<_>>();+ assert!(!names.contains("dbx_kafka__kafka_topics_delete"), "flat listing must not widen: {names:?}");+ assert!(names.contains("dbx_kafka__kafka_topics_list"), "read-only tool stays visible: {names:?}");++ let list = server.plugin_list(Parameters(PluginListRequest { filter: None })).await;+ let text = result_text(&list);+ assert!(text.contains("1 tool(s)"), "dbx_plugin_list counts only the read tool: {text}");++ let tools = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.kafka".into() })).await;+ let text = result_text(&tools);+ assert!(!text.contains("kafka_topics_delete"), "dbx_plugin_tools must not widen: {text}");+ assert!(text.contains("kafka_topics_list"), "{text}");++ let call = server+ .plugin_call(Parameters(PluginCallRequest {+ plugin_id: "io.dbx.kafka".into(),+ tool: "kafka_topics_delete".into(),+ arguments: Some(json!({ "topics": ["t"] })),+ dbx_connection: None,+ }))+ .await;+ assert!(result_text(&call).contains("MCP_READ_ONLY"), "{}", result_text(&call));++ // Fresh install (no saved policy): the widening default applies again+ // and listings stay consistent with calls.+ let server = DbxMcpServer::with_runtime_options(backend(false), McpScope::default(), false);+ let names =+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<HashSet<_>>();+ assert!(names.contains("dbx_kafka__kafka_topics_delete"), "zero-config widening expected: {names:?}");+ let tools = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.kafka".into() })).await;+ assert!(result_text(&tools).contains("kafka_topics_delete"), "{}", result_text(&tools));+ }+#[tokio::test]async fn plugin_writes_honor_connection_hard_protections() {for production in [false, true] {