Skip to content

armgit / dbx

Public Imported from GitHub
0

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

feat(mcp): improve capability management and call safety

二丫讲梵c2e196316829
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 2c8ab72930..518c0d7836 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -2,6 +2,7 @@
import { blockingDesktopAiRunsForUpdate } from "@/lib/ai/desktopAiRunRegistry";
import { setupUpdatePreparation, prepareUpdateWithDraftRecovery, isUpdatePreparationActive } from "@/lib/app/updatePreparation";
import { ref, computed, watch, onMounted, onUnmounted, nextTick, defineAsyncComponent, provide } from "vue";
+import { MCP_CALL_HISTORY_OPEN_EVENT, type McpCallHistoryRequest } from "@/lib/mcp/mcpCallHistory";
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
import { checkStartupAuthentication, logoutWeb, type StartupAuthentication } from "@/lib/startup/startupAuthentication";
import { markStartupPhase } from "@/lib/startup/startupTiming";
@@ -489,6 +490,24 @@ const showTabSwitcher = ref(false);
const tabSwitcherIndex = ref(0);
const agentDriverUpdateCount = ref(0);
const showHistory = ref(false);
+const mcpHistoryRequest = ref<McpCallHistoryRequest | null>(null);
+
+/** Settings → MCP asks for the call history: open the panel on its MCP view. */
+function openMcpCallHistory(event?: Event) {
+ // Keep the request across the async component's first load; nextTick alone
+ // does not wait for QueryHistory to mount and receive an event.
+ mcpHistoryRequest.value = { resource: event instanceof CustomEvent ? event.detail : undefined };
+ openRightSidebarPanel("history");
+}
+
+watch(
+ showHistory,
+ (open) => {
+ if (!open) mcpHistoryRequest.value = null;
+ },
+ // Also cancel a close/reopen in the same tick before the lazy panel mounts.
+ { flush: "sync" },
+);
const showAiPanel = ref(safeLocalStorageGet("dbx-ai-panel-open") === "true");
const isAiPanelMaximized = ref(false);
const isHistoryPanelMaximized = ref(false);
@@ -5283,6 +5302,7 @@ onMounted(async () => {
window.addEventListener("dbx-open-driver-store", openDriverStoreFromEvent);
window.addEventListener(COMPONENT_UPDATES_CHANGED_EVENT, handleComponentUpdatesChanged);
window.addEventListener("dbx:activate-query-surface", activateQuerySurface);
+ window.addEventListener(MCP_CALL_HISTORY_OPEN_EVENT, openMcpCallHistory);
window.addEventListener(OBJECT_BROWSER_SEARCH_FOCUS_EVENT, focusRequestedObjectBrowserSearch);
window.addEventListener("dbx-mcp-status-changed", handleMcpStatusChanged);
window.addEventListener("dbx:ai-run-notify", handleAiRunNotify);
@@ -5383,6 +5403,7 @@ onUnmounted(() => {
window.removeEventListener("dbx-open-driver-store", openDriverStoreFromEvent);
window.removeEventListener(COMPONENT_UPDATES_CHANGED_EVENT, handleComponentUpdatesChanged);
window.removeEventListener("dbx:activate-query-surface", activateQuerySurface);
+ window.removeEventListener(MCP_CALL_HISTORY_OPEN_EVENT, openMcpCallHistory);
window.removeEventListener(OBJECT_BROWSER_SEARCH_FOCUS_EVENT, focusRequestedObjectBrowserSearch);
window.removeEventListener("dbx-mcp-status-changed", handleMcpStatusChanged);
window.removeEventListener("dbx:ai-run-notify", handleAiRunNotify);
@@ -5819,6 +5840,8 @@ onUnmounted(() => {
<div class="h-full min-h-0 overflow-hidden rounded-[inherit]" @mousedown="rememberAuxiliarySearchSurface('history')">
<div data-history-panel class="h-full min-h-0">
<QueryHistory
+ :mcp-request="mcpHistoryRequest"
+ @mcp-request-handled="mcpHistoryRequest = null"
:maximized="isHistoryPanelMaximized"
@toggle-maximize="isHistoryPanelMaximized = !isHistoryPanelMaximized"
:current-connection-id="activeTab?.connectionId"
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 6666aa8539..db8575dabd 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -10,6 +10,7 @@ import { MAX_CONNECT_TIMEOUT_SECS, MAX_QUERY_TIMEOUT_SECS } from "@/lib/connecti
import {
AlertTriangle,
ArrowLeft,
+ History,
Check,
CheckCircle2,
ChevronDown,
@@ -213,6 +214,16 @@ import {
webdavSyncUpload,
listInstalledAgentsLocal,
listPlugins,
+ loadMcpToolCatalog,
+ listPluginMcpViews,
+ savePluginMcpGrant,
+ loadMcpAccessPolicy,
+ resetInvalidMcpAccessPolicy,
+ setMcpPluginScopeRule,
+ listMcpPluginScopes,
+ listDatabases as listMcpTreeDatabases,
+ mongoListDatabases as mongoListMcpTreeDatabases,
+ redisListDatabases as redisListMcpTreeDatabases,
type AppSupportInfo,
type McpHttpServerSettings,
type McpHttpServerStatus,
@@ -302,22 +313,16 @@ import {
} from "@/lib/mcp/mcpConfigTemplates";
import { beginMcpStatusRequest, mcpUpdateAvailability } from "@/lib/mcp/mcpUpdateStatus";
import { notifyComponentUpdatesChanged } from "@/lib/updates/componentUpdateEvents";
-import {
- addMcpAllowedToolName,
- customMcpAllowedToolNames,
- isMcpPolicyMutationBlocked,
- MCP_CAPABILITY_ROWS,
- MCP_EXECUTION_MODE_COLUMNS,
- MCP_TOOL_OPTIONS,
- mcpExecutionModeFromPolicy,
- mcpPolicyFieldsForExecutionMode,
- toggleMcpAllowedToolName,
- type McpExecutionMode,
-} from "@/lib/mcp/mcpPolicySelection";
+import { addMcpAllowedToolName, customMcpAllowedToolNames, isMcpPolicyMutationBlocked, mcpExecutionModeFromPolicy, mcpPolicyFieldsForExecutionMode, MCP_PLUGIN_TOOLS_WILDCARD, toggleMcpAllowedToolName, type McpExecutionMode } from "@/lib/mcp/mcpPolicySelection";
+import { mergeMcpToolsetSelection, setMcpToolsetEnabled, setMcpToolsEnabled, setMcpCategoryEnabled, type McpCapabilityCategoryId } from "@/lib/mcp/mcpToolCatalog";
+import { initialMcpCapabilityBrowserState, type McpCapabilityNavigator } from "@/lib/mcp/mcpCapabilitySearch";
+import type { McpAccessPolicy, McpToolCatalog, McpToolCatalogToolset, PluginMcpView } from "@/types/mcpCatalog";
+import { pluginMcpContribution } from "@/lib/plugins/pluginMcpMark";
+import { openMcpCallHistory } from "@/lib/mcp/mcpCallHistory";
import { getPlatform, isMacOS, isWindows } from "@/lib/backend/platform";
import { combineDataTypeForDatabase, dataTypeLengthInputValue, getDataTypeOptions, getDefaultLengthForType, isDataTypeLengthDisabled, splitDataType } from "@/lib/table/tableStructureEditorState";
import { useToast } from "@/composables/useToast";
-import type { InstalledPlugin, DatabaseType, SqlShortcutAction, SqlSnippet } from "@/types/database";
+import type { ConnectionConfig, InstalledPlugin, DatabaseType, SqlShortcutAction, SqlSnippet } from "@/types/database";
import { getCcSwitchPluginStatus, isCcSwitchPluginAvailable, isMagpieImportAvailable, MAGPIE_IMPORT_MINIMUM_PLUGIN_VERSION } from "@/lib/ai/ccSwitch";
import { uuid } from "@/lib/common/utils";
import { DEFAULT_SQL_SHORTCUT_SELECT_LIMIT } from "@/lib/sql/sqlDialectSelectLimit";
@@ -342,9 +347,13 @@ import AiProviderLogo from "@/components/icons/AiProviderLogo.vue";
import AppLogo from "@/components/icons/AppLogo.vue";
import ChangelogPanel from "@/components/settings/ChangelogPanel.vue";
import SettingsTransferPanel from "@/components/settings/SettingsTransferPanel.vue";
-import McpResourceScopePicker from "@/components/settings/McpResourceScopePicker.vue";
-import McpDatabaseScopePicker from "@/components/settings/McpDatabaseScopePicker.vue";
-import McpAuthorizationTabs from "@/components/settings/McpAuthorizationTabs.vue";
+import McpCapabilityBrowser from "@/components/settings/McpCapabilityBrowser.vue";
+import McpPluginToolsModeSetting from "@/components/settings/McpPluginToolsModeSetting.vue";
+import { editableDatabaseAccess, mergeDatabaseAccess, type McpDatabaseAccess } from "@/lib/mcp/mcpDatabaseAccess";
+import McpAccessTree from "@/components/settings/McpAccessTree.vue";
+import McpCallSafetyPanel from "@/components/settings/McpCallSafetyPanel.vue";
+import McpDefaultAccessPanel from "@/components/settings/McpDefaultAccessPanel.vue";
+import { buildMcpResourceTree } from "@/lib/mcp/mcpAccessTree";
import ScheduledDatabaseBackupSettings from "@/components/backup/ScheduledDatabaseBackupSettings.vue";
import SqlFormatterSettingsPanel from "./SqlFormatterSettingsPanel.vue";
import { APP_CUSTOM_UI_COLOR_DEFS, APP_THEME_PALETTES, type AppCornerStyle, type AppCustomUiColors, type AppThemeAppearance, type AppThemeMode, type AppThemePalette } from "@/lib/app/appTheme";
@@ -429,7 +438,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";
+import { buildConnectionGroupIdPathMap, connectionGroupDestinationRows } from "@/lib/sidebar/sidebarLayout";
const { t, locale } = useI18n();
const { toast } = useToast();
@@ -636,6 +645,20 @@ const settingsContentClass = computed(() =>
const settingsTitleComponent = computed(() => (isSettingsPage.value ? "h2" : DialogTitle));
const showUnsavedSettingsCloseConfirm = ref(false);
+const pendingMcpCallHistory = ref(false);
+
+function requestMcpCallHistory() {
+ pendingMcpCallHistory.value = true;
+ requestCloseSettings(false);
+}
+
+function finishSettingsClose(nextOpen: boolean) {
+ const openHistory = !nextOpen && pendingMcpCallHistory.value;
+ pendingMcpCallHistory.value = false;
+ if (!nextOpen) mcpPolicyConfirmation.value = null;
+ emit("update:open", nextOpen);
+ if (openHistory) openMcpCallHistory();
+}
function requestCloseSettings(nextOpen: boolean) {
// Fold a timeout typed immediately before close into the draft so the unsaved
@@ -645,7 +668,7 @@ function requestCloseSettings(nextOpen: boolean) {
showUnsavedSettingsCloseConfirm.value = true;
return;
}
- emit("update:open", nextOpen);
+ finishSettingsClose(nextOpen);
}
function onSettingsRootOpenChange(value: boolean) {
@@ -660,13 +683,14 @@ function closeSettings() {
defineExpose({ requestClose: closeSettings, applySettingsFromShortcut });
function cancelUnsavedSettingsClose() {
+ pendingMcpCallHistory.value = false;
showUnsavedSettingsCloseConfirm.value = false;
}
function discardUnsavedSettingsAndClose() {
showUnsavedSettingsCloseConfirm.value = false;
syncMcpPolicyBaseline(mcpPolicyBaseline.value);
- emit("update:open", false);
+ finishSettingsClose(false);
}
interface TableColumnTemplateOverrideRow {
@@ -3766,6 +3790,7 @@ const settingsSearchInputContainerRef = ref<HTMLElement | null>(null);
const highlightedSettingsSearchTargetId = ref("");
let highlightedSettingsSearchElement: HTMLElement | null = null;
let pendingSettingsSearchResult: SettingsSearchEntry | null = null;
+const pendingSettingsSearchNavigation = shallowRef<{ result: SettingsSearchEntry; delivered: boolean } | null>(null);
let settingsSearchHighlightTimer: ReturnType<typeof window.setTimeout> | null = null;
let settingsSearchHighlightAnimationHandler: ((event: AnimationEvent) => void) | null = null;
const settingsSearchHighlightClasses = ["rounded-md", "bg-primary/5", "transition-[box-shadow,background-color]", "duration-200", "settings-search-highlight-breathe"];
@@ -3816,9 +3841,10 @@ function resetSettingsSearchState() {
settingsSearchOpen.value = false;
settingsSearchActiveIndex.value = 0;
pendingSettingsSearchResult = null;
+ pendingSettingsSearchNavigation.value = null;
+ mcpCapabilityBrowserRef.value?.revealSearchTarget();
shortcutSearchQuery.value = "";
applyShortcutRecording(false);
- mcpPermissionPreviewSearchQuery.value = "";
clearSettingsSearchHighlight();
}
@@ -3845,14 +3871,72 @@ function applySettingsSearchRoute(result: SettingsSearchEntry) {
if (result.route?.syncMethodTab) syncMethodTab.value = result.route.syncMethodTab;
if (result.route?.mcpManagementTab) mcpManagementTab.value = result.route.mcpManagementTab;
if (result.route?.mcpTransportTab) mcpTransportTab.value = result.route.mcpTransportTab;
- if (result.route?.mcpAuthorizationTab) mcpAuthorizationTab.value = result.route.mcpAuthorizationTab;
if (result.route?.formatterMode) formatterMode.value = result.route.formatterMode;
}
-async function revealSettingsSearchTarget(result: SettingsSearchEntry) {
- await nextTick();
- const searchRoot = settingsContentScrollRef.value?.querySelector<HTMLElement>(`[data-settings-search-id="${result.targetId}"]`);
- if (!searchRoot) return;
+function revealSettingsSearchTarget(result: SettingsSearchEntry) {
+ pendingSettingsSearchNavigation.value = { result, delivered: false };
+}
+
+function settingsSearchRouteIsActive(result: SettingsSearchEntry): boolean {
+ return (
+ settingsVisible.value &&
+ activeSettingsTab.value === result.category &&
+ (!result.route?.mcpManagementTab || mcpManagementTab.value === result.route.mcpManagementTab) &&
+ (!result.route?.mcpTransportTab || mcpTransportTab.value === result.route.mcpTransportTab) &&
+ (!result.route?.syncMethodTab || syncMethodTab.value === result.route.syncMethodTab) &&
+ (!result.route?.formatterMode || formatterMode.value === result.route.formatterMode)
+ );
+}
+
+function watchSettingsSearchNavigation() {
+ // Cancel synchronously, including a leave-and-return within one render cycle.
+ watch(
+ [settingsVisible, activeSettingsTab, mcpManagementTab, mcpTransportTab, syncMethodTab, formatterMode],
+ () => {
+ const request = pendingSettingsSearchNavigation.value;
+ if (request && !settingsSearchRouteIsActive(request.result)) pendingSettingsSearchNavigation.value = null;
+ if (pendingSettingsSearchResult && !settingsSearchRouteIsActive(pendingSettingsSearchResult)) pendingSettingsSearchResult = null;
+ if (!settingsVisible.value || activeSettingsTab.value !== "mcp" || mcpManagementTab.value !== "capabilities") mcpCapabilityBrowserRef.value?.revealSearchTarget();
+ },
+ { flush: "sync" },
+ );
+ watch(
+ [pendingSettingsSearchNavigation, settingsContentScrollRef, mcpCapabilityBrowserRef],
+ ([request, root, browser], _previous, onCleanup) => {
+ if (!request || request.delivered || !root || !settingsSearchRouteIsActive(request.result)) return;
+ const navigation = request;
+ const container = root;
+ let cancelled = false;
+ const observer = new MutationObserver(() => void revealMountedTarget());
+ onCleanup(() => {
+ cancelled = true;
+ observer.disconnect();
+ });
+ async function revealMountedTarget() {
+ if (cancelled || navigation.delivered || pendingSettingsSearchNavigation.value !== navigation || !settingsSearchRouteIsActive(navigation.result)) return;
+ const result = navigation.result;
+ const searchRoot = container.querySelector<HTMLElement>(`[data-settings-search-id="${result.targetId}"]`);
+ // Reka Presence mounts tab children after an additional render. Wait for
+ // the real DOM and component ref rather than guessing a number of ticks.
+ if (!searchRoot || searchRoot.closest("[hidden]") || (result.route?.mcpManagementTab === "capabilities" && (!browser || browser !== mcpCapabilityBrowserRef.value))) return;
+ navigation.delivered = true;
+ observer.disconnect();
+ if (result.route?.mcpManagementTab === "capabilities") {
+ browser!.revealSearchTarget(result.route.mcpCapabilityTarget);
+ await nextTick();
+ }
+ if (cancelled || pendingSettingsSearchNavigation.value !== request || !settingsSearchRouteIsActive(result) || !container.contains(searchRoot)) return;
+ highlightSettingsSearchTarget(result, searchRoot);
+ }
+ observer.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: ["hidden"] });
+ void revealMountedTarget();
+ },
+ { flush: "post" },
+ );
+}
+
+function highlightSettingsSearchTarget(result: SettingsSearchEntry, searchRoot: HTMLElement) {
const target = findSettingsSearchHighlightTarget(searchRoot, result.title);
target.scrollIntoView({ block: "center", behavior: "smooth" });
clearSettingsSearchHighlight();
@@ -3873,7 +3957,9 @@ async function revealSettingsSearchTarget(result: SettingsSearchEntry) {
}
async function selectSettingsSearchResult(result: SettingsSearchEntry) {
- pendingSettingsSearchResult = result;
+ pendingSettingsSearchNavigation.value = null;
+ mcpCapabilityBrowserRef.value?.revealSearchTarget();
+ pendingSettingsSearchResult = null;
if (result.shortcutId) shortcutSearchQuery.value = result.title;
if (result.category === "ai") aiConfigListMode.value = "list";
applySettingsSearchRoute(result);
@@ -3881,11 +3967,11 @@ async function selectSettingsSearchResult(result: SettingsSearchEntry) {
settingsSearchOpen.value = false;
settingsSearchActiveIndex.value = 0;
if (activeSettingsTab.value === result.category) {
- pendingSettingsSearchResult = null;
await revealSettingsSearchTarget(result);
return;
}
activeSettingsTab.value = result.category;
+ pendingSettingsSearchResult = result;
}
function onSettingsSearchKeydown(event: KeyboardEvent) {
@@ -4113,7 +4199,7 @@ async function exportDebugLogs() {
type McpConfigTab = "claude" | "cursor" | "codebuddy" | "zcode" | "trae" | "vscode" | "windsurf" | "codex" | "deepseek-harness" | "opencode" | "pi" | "cherry-studio" | "qoder" | "workbuddy";
type McpCopyKind = "install" | "uninstall" | "http-endpoint" | "http-token" | "http-config" | `${McpConfigTab}-config`;
type McpTransportTab = "stdio" | "http";
-type McpManagementTab = "access" | "permissions";
+type McpManagementTab = "access" | "capabilities" | "permissions";
const mcpStatus = ref<McpServerStatus | null>(null);
const mcpStatusLoading = ref(false);
@@ -4127,7 +4213,6 @@ const mcpCopied = ref<"" | McpCopyKind>("");
const mcpConfigTab = ref<McpConfigTab>("claude");
const mcpTransportTab = ref<McpTransportTab>("stdio");
const mcpManagementTab = ref<McpManagementTab>("access");
-const mcpAuthorizationTab = ref<"overrides" | "connections" | "databases" | "capabilities">("overrides");
const formatterMode = ref<"form" | "json">("form");
const mcpHttpSettings = ref<McpHttpServerSettings>({
enabled: false,
@@ -4162,8 +4247,10 @@ const mcpInstallMessage = ref("");
const mcpInstallError = ref(false);
const mcpPolicyDraft = ref<McpGlobalPolicy>(normalizeMcpGlobalPolicy(settingsStore.mcpGlobalPolicy));
const mcpPolicyBaseline = ref<McpGlobalPolicy>(normalizeMcpGlobalPolicy(settingsStore.mcpGlobalPolicy));
+const mcpDatabaseEditedOverrides = new Map<string, Set<string>>();
function syncMcpPolicyBaseline(policy: McpGlobalPolicy) {
+ mcpDatabaseEditedOverrides.clear();
const next = normalizeMcpGlobalPolicy(policy);
mcpPolicyBaseline.value = next;
mcpPolicyDraft.value = normalizeMcpGlobalPolicy(next);
@@ -4191,9 +4278,6 @@ function mcpPolicyHasUnsavedChanges(): boolean {
}
const mcpExecutionMode = computed(() => mcpExecutionModeFromPolicy(mcpPolicyDraft.value));
-const mcpExecutionModeOptions: McpExecutionMode[] = ["read_only", "safe_write", "high_risk_write"];
-const mcpAllowedConnectionIds = computed(() => mcpPolicyDraft.value.allowedConnectionIds);
-const mcpAllowedGroupIds = computed(() => mcpPolicyDraft.value.allowedGroupIds);
const mcpQueryTimeoutInput = ref<string>(mcpPolicyDraft.value.queryTimeoutSecs === null ? "" : String(mcpPolicyDraft.value.queryTimeoutSecs));
watch(
@@ -4259,16 +4343,11 @@ function stageMcpQueryTimeoutDraft() {
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,
- saving: mcpPolicySaving.value,
- loadError: mcpPolicyLoadError.value,
+ loading: mcpPolicyLoading.value || mcpAccessPolicyLoading.value,
+ saving: mcpPolicySaving.value || mcpPolicyRecovering.value,
+ loadError: mcpPolicyLoadError.value || mcpAccessPolicyError.value,
}),
);
@@ -4319,12 +4398,14 @@ async function commitMcpPolicyDraft(): Promise<void> {
readOnly: snapshot.readOnly,
allowDangerousSql: snapshot.allowDangerousSql,
promptHighRiskSql: snapshot.promptHighRiskSql,
+ callConfirmation: snapshot.callConfirmation ?? (snapshot.promptHighRiskSql ? "full" : "off"),
allowedConnectionIds: snapshot.allowedConnectionIds,
allowedGroupIds: snapshot.allowedGroupIds,
allowedToolNames: snapshot.allowedToolNames,
connectionPolicies: snapshot.connectionPolicies,
groupPolicies: snapshot.groupPolicies,
queryTimeoutSecs: snapshot.queryTimeoutSecs,
+ pluginToolsMode: snapshot.pluginToolsMode,
});
if (mcpPoliciesEqual(mcpPolicyDraft.value, snapshot)) syncMcpPolicyBaseline(settingsStore.mcpGlobalPolicy);
} finally {
@@ -4332,52 +4413,248 @@ async function commitMcpPolicyDraft(): Promise<void> {
}
}
-function onMcpExecutionModeChange(mode: McpExecutionMode) {
- if (mode === mcpExecutionMode.value) return;
- if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) {
+// WKWebView does not reliably present synchronous window.confirm prompts.
+// Stage permission edits only after the shared in-app dialog is accepted.
+const mcpPolicyConfirmation = shallowRef<{ message: string; apply: () => void } | null>(null);
+
+function requestMcpPolicyConfirmation(message: string, apply: () => void) {
+ if (!mcpPolicyControlsDisabled.value && !mcpPolicyConfirmation.value) mcpPolicyConfirmation.value = { message, apply };
+}
+
+function confirmMcpPolicyChange() {
+ if (mcpPolicyRecoveryConfirmation.value) return recoverMcpAccessPolicy();
+ const pending = mcpPolicyConfirmation.value;
+ mcpPolicyConfirmation.value = null;
+ if (!mcpPolicyControlsDisabled.value) pending?.apply();
+}
+
+function onMcpExecutionModeChange(mode: McpExecutionMode, confirmed = false) {
+ if (mcpPolicyControlsDisabled.value || mode === mcpExecutionMode.value) return;
+ if (mode === "high_risk_write" && !confirmed) {
+ requestMcpPolicyConfirmation(t("settings.mcpExecutionModeHighRiskConfirm"), () => onMcpExecutionModeChange(mode, true));
return;
}
- stageMcpPolicy({ ...mcpPolicyFieldsForExecutionMode(mode), promptHighRiskSql: mode === "safe_write" && mcpPolicyDraft.value.promptHighRiskSql });
+ stageMcpPolicy(mcpPolicyFieldsForExecutionMode(mode));
}
-function onMcpExecutionModeKeydown(event: KeyboardEvent, mode: McpExecutionMode) {
+function onMcpHighRiskConfirmationChange(enabled: boolean) {
if (mcpPolicyControlsDisabled.value) return;
- const currentIndex = mcpExecutionModeOptions.indexOf(mode);
- let nextIndex: number | undefined;
- if (event.key === "Home") nextIndex = 0;
- else if (event.key === "End") nextIndex = mcpExecutionModeOptions.length - 1;
- else if (event.key === "ArrowRight" || event.key === "ArrowDown") nextIndex = (currentIndex + 1) % mcpExecutionModeOptions.length;
- else if (event.key === "ArrowLeft" || event.key === "ArrowUp") nextIndex = (currentIndex - 1 + mcpExecutionModeOptions.length) % mcpExecutionModeOptions.length;
- if (nextIndex === undefined || nextIndex === currentIndex) return;
+ stageMcpPolicy({ callConfirmation: enabled ? "high_risk" : "off", promptHighRiskSql: false });
+}
- event.preventDefault();
- event.stopPropagation();
- const nextMode = mcpExecutionModeOptions[nextIndex];
- // These cards visually replace native radios, so preserve the radio-group keyboard contract.
- const currentTarget = event.currentTarget;
- const group = currentTarget instanceof HTMLElement ? currentTarget.closest<HTMLElement>('[role="radiogroup"]') : null;
- group?.querySelector<HTMLElement>(`[data-mcp-execution-mode="${nextMode}"]`)?.focus();
- onMcpExecutionModeChange(nextMode);
+type McpConnectionExecutionMode = "read_only" | "safe_write" | "high_risk_write";
+
+const mcpAllowedToolNames = computed(() => mcpPolicyDraft.value.allowedToolNames);
+
+function onMcpToolAllowedChange(name: string, allowed: boolean) {
+ if (!mcpToolCatalog.value || mcpToolCatalogLoading.value || mcpToolCatalogError.value || mcpPolicyControlsDisabled.value) return;
+ stageMcpPolicy({ allowedToolNames: setMcpToolsEnabled(mcpAllowedToolNames.value, mcpToolCatalog.value, [name], allowed) });
}
-function onMcpResourceScopeChange(scope: { allowedGroupIds: string[]; allowedConnectionIds: string[] | null }) {
- stageMcpPolicy(scope);
+function onMcpToolsetAllowedChange(toolset: McpToolCatalogToolset, allowed: boolean) {
+ if (!mcpToolCatalog.value || mcpToolCatalogLoading.value || mcpToolCatalogError.value || mcpPolicyControlsDisabled.value) return;
+ stageMcpPolicy({ allowedToolNames: setMcpToolsetEnabled(mcpAllowedToolNames.value, toolset, allowed, mcpToolCatalog.value) });
}
-type McpConnectionExecutionMode = "read_only" | "safe_write" | "high_risk_write";
+async function applyMcpToolset(toolsetId: string): Promise<void> {
+ const catalog = mcpToolCatalog.value;
+ const toolset = catalog?.toolsets.find((entry) => entry.id === toolsetId);
+ if (mcpPolicySaving.value || mcpCatalogControlsDisabled.value || !catalog || !toolset) throw new Error(t("settings.mcpToolsetApplyUnavailable"));
+ const allowedToolNames = mergeMcpToolsetSelection(settingsStore.mcpGlobalPolicy.allowedToolNames, mcpPolicyDraft.value.allowedToolNames, toolset, catalog);
+ mcpPolicySaving.value = true;
+ try {
+ // The store merges this patch with saved settings, never with the page draft.
+ // Storage retains immediately saved v2 sub-scopes through its existing merge.
+ await settingsStore.updateMcpGlobalPolicy({ allowedToolNames });
+ const saved = normalizeMcpGlobalPolicy(settingsStore.mcpGlobalPolicy);
+ mcpPolicyBaseline.value = normalizeMcpGlobalPolicy({ ...mcpPolicyBaseline.value, configured: saved.configured, allowedToolNames: saved.allowedToolNames });
+ const draftTools = mcpPolicyDraft.value.allowedToolNames;
+ const savedTools = saved.allowedToolNames;
+ // List ordering is immaterial. Reuse the persisted representation once all
+ // remaining tool edits match, so Apply does not stay enabled spuriously.
+ const sameTools = draftTools === savedTools || (draftTools !== null && savedTools !== null && draftTools.length === savedTools.length && draftTools.every((name) => savedTools.includes(name)));
+ mcpPolicyDraft.value = normalizeMcpGlobalPolicy({ ...mcpPolicyDraft.value, configured: saved.configured, allowedToolNames: sameTools ? savedTools : draftTools });
+ } finally {
+ mcpPolicySaving.value = false;
+ }
+}
-const mcpToolOptions = MCP_TOOL_OPTIONS;
+// Built-in tool catalog (toolsets, access levels, database coverage) served by
+// the backend. It is static per build, so one successful load per dialog
+// session is enough.
+const mcpToolCatalog = ref<McpToolCatalog | null>(null);
+const mcpToolCatalogLoading = ref(false);
+const mcpToolCatalogError = ref("");
+const mcpCatalogControlsDisabled = computed(() => mcpPolicyControlsDisabled.value || !mcpToolCatalog.value || mcpToolCatalogLoading.value || !!mcpToolCatalogError.value);
+const mcpCapabilityBrowserState = ref(initialMcpCapabilityBrowserState());
+const mcpCapabilityBrowserRef = ref<McpCapabilityNavigator>();
-const mcpAllowedToolNames = computed(() => mcpPolicyDraft.value.allowedToolNames);
+function onMcpCategoryAllowedChange(category: McpCapabilityCategoryId, allowed: boolean) {
+ if (!mcpToolCatalog.value || mcpToolCatalogLoading.value || mcpToolCatalogError.value || mcpPolicyControlsDisabled.value) return;
+ stageMcpPolicy({ allowedToolNames: setMcpCategoryEnabled(mcpAllowedToolNames.value, mcpToolCatalog.value, category, allowed) });
+}
-function mcpToolAllowed(name: string): boolean {
- return mcpAllowedToolNames.value === null || mcpAllowedToolNames.value.includes(name);
+async function ensureMcpToolCatalog() {
+ if (mcpToolCatalog.value || mcpToolCatalogLoading.value) return;
+ mcpToolCatalogLoading.value = true;
+ mcpToolCatalogError.value = "";
+ try {
+ mcpToolCatalog.value = await loadMcpToolCatalog();
+ } catch (e: any) {
+ mcpToolCatalogError.value = e?.message || String(e);
+ } finally {
+ mcpToolCatalogLoading.value = false;
+ }
}
-function onMcpToolAllowedChange(name: string, allowed: boolean) {
- stageMcpPolicy({ allowedToolNames: toggleMcpAllowedToolName(mcpAllowedToolNames.value, name, allowed) });
+// Plugin cards: loading probes plugin sidecars, so it runs when the tab
+// opens (and on refresh) rather than with the dialog. Grants save
+// immediately and are not part of the staged MCP policy draft.
+const mcpPluginViews = ref<PluginMcpView[] | null>(null);
+const mcpPluginViewsLoading = ref(false);
+const mcpPluginViewsError = ref("");
+const mcpPluginViewRevisions = new Map<string, number>();
+const mcpPluginSavingIds = ref(new Set<string>());
+
+async function loadMcpPluginViews() {
+ if (mcpPluginViewsLoading.value) return;
+ mcpPluginViewsLoading.value = true;
+ mcpPluginViewsError.value = "";
+ const revisions = new Map(mcpPluginViewRevisions);
+ try {
+ const views = await listPluginMcpViews();
+ // Discovery probes may finish after an immediate grant save. Merge the
+ // untouched plugins, retaining each grant saved since this refresh began.
+ mcpPluginViews.value = views.map((view) => (mcpPluginViewRevisions.get(view.pluginId) === revisions.get(view.pluginId) ? view : (mcpPluginViews.value?.find((current) => current.pluginId === view.pluginId) ?? view)));
+ } catch (e: any) {
+ mcpPluginViewsError.value = e?.message || String(e);
+ } finally {
+ mcpPluginViewsLoading.value = false;
+ }
+}
+
+// The global tool allowlist still gates plugin tools on top of the plugin
+// grants. A materialized allowlist without any plugin wildcard hides every
+// plugin tool, which would make the plugin switches look broken.
+const mcpPluginToolsBlockedByAllowlist = computed(() => {
+ const allowed = mcpAllowedToolNames.value;
+ // Any plugin-namespace entry (a wildcard or an explicit `dbx_<prefix>__<tool>`) means
+ // the user curated plugin tools on purpose.
+ return allowed !== null && !allowed.some((name) => /^dbx_.+__/.test(name));
+});
+
+const mcpPluginAllowlistPending = computed(() => {
+ const baseline = mcpPolicyBaseline.value.allowedToolNames;
+ return baseline !== null && !baseline.some((name) => /^dbx_.+__/.test(name)) && !mcpPluginToolsBlockedByAllowlist.value;
+});
+
+function onMcpAllowPluginTools() {
+ stageMcpPolicy({ allowedToolNames: addMcpAllowedToolName(mcpAllowedToolNames.value, MCP_PLUGIN_TOOLS_WILDCARD).names });
+}
+
+function onMcpPluginViewSaved(view: PluginMcpView) {
+ mcpPluginViewRevisions.set(view.pluginId, (mcpPluginViewRevisions.get(view.pluginId) ?? 0) + 1);
+ mcpPluginViews.value = (mcpPluginViews.value ?? []).map((existing) => (existing.pluginId === view.pluginId ? view : existing));
+}
+
+async function persistMcpPluginGrant(...args: Parameters<typeof savePluginMcpGrant>) {
+ const pluginId = args[0];
+ if (mcpPluginSavingIds.value.has(pluginId)) throw new Error(t("settings.mcpBrowser.pluginSaving"));
+ mcpPluginSavingIds.value.add(pluginId);
+ try {
+ const view = await savePluginMcpGrant(...args);
+ // A plugin save can finish after the capability tab is unmounted. Keep the
+ // settings session's cached grant current even when the child cannot emit.
+ onMcpPluginViewSaved(view);
+ return view;
+ } finally {
+ mcpPluginSavingIds.value.delete(pluginId);
+ }
+}
+
+// Plugin sub-scope rules live only in the v2 policy; they are loaded with the
+// permissions tab and saved immediately by the tree's scope editor.
+const mcpAccessPolicy = ref<McpAccessPolicy | null>(null);
+const mcpAccessPolicyError = ref("");
+const mcpAccessPolicyLoading = ref(false);
+const mcpPolicyRecovering = ref(false);
+const mcpPolicyRecoveryConfirmation = ref(false);
+const mcpPolicyConfirmationDialog = computed(() => ({
+ open: mcpPolicyConfirmation.value !== null || mcpPolicyRecoveryConfirmation.value,
+ message: mcpPolicyRecoveryConfirmation.value ? t("settings.mcpPolicyRecoverConfirm") : mcpPolicyConfirmation.value?.message,
+ confirmLabel: mcpPolicyRecoveryConfirmation.value ? t("settings.mcpPolicyRecover") : t("common.confirm"),
+}));
+function onMcpPolicyConfirmationOpenChange(open: boolean) {
+ if (!open) {
+ mcpPolicyConfirmation.value = null;
+ mcpPolicyRecoveryConfirmation.value = false;
+ }
+}
+const mcpInstalledPluginsForScopes = ref<InstalledPlugin[]>([]);
+const mcpPluginScopeLoadRevision = ref(0);
+const mcpPluginScopes = computed(() => {
+ const scopes: Record<string, { kind: string; title: string }> = {};
+ for (const plugin of mcpInstalledPluginsForScopes.value) {
+ const scope = pluginMcpContribution(plugin)?.scope;
+ if (scope) scopes[plugin.manifest.id] = { kind: scope.kind, title: scope.title };
+ }
+ return scopes;
+});
+
+async function loadMcpPluginScopeContext() {
+ const revision = ++mcpPluginScopeLoadRevision.value;
+ const policyAtStart = mcpAccessPolicy.value;
+ const pluginsRequest = listPlugins()
+ .then((plugins) => {
+ if (revision === mcpPluginScopeLoadRevision.value) mcpInstalledPluginsForScopes.value = plugins;
+ })
+ .catch((e: any) => {
+ console.warn("[DBX] MCP plugin scope discovery unavailable:", e?.message || e);
+ });
+ mcpAccessPolicyLoading.value = true;
+ try {
+ const access = await loadMcpAccessPolicy();
+ if (revision !== mcpPluginScopeLoadRevision.value) return;
+ if (mcpAccessPolicy.value === policyAtStart) mcpAccessPolicy.value = access;
+ mcpAccessPolicyError.value = "";
+ } catch (e: any) {
+ if (revision !== mcpPluginScopeLoadRevision.value) return;
+ if (mcpAccessPolicy.value !== policyAtStart) return;
+ // Do not render a stale/default permission tree as an authoritative view.
+ mcpAccessPolicy.value = null;
+ mcpAccessPolicyError.value = e?.message || String(e);
+ } finally {
+ if (revision === mcpPluginScopeLoadRevision.value) mcpAccessPolicyLoading.value = false;
+ await pluginsRequest;
+ }
+}
+
+async function recoverMcpAccessPolicy() {
+ if (!mcpPolicyRecoveryConfirmation.value || mcpPolicyRecovering.value || mcpPolicySaving.value) return;
+ mcpPolicyRecoveryConfirmation.value = false;
+ mcpPolicyRecovering.value = true;
+ try {
+ await resetInvalidMcpAccessPolicy();
+ await settingsStore.initMcpGlobalPolicy(true);
+ syncMcpPolicyBaseline(settingsStore.mcpGlobalPolicy);
+ mcpPolicyLoadError.value = "";
+ await loadMcpPluginScopeContext();
+ } catch (e: any) {
+ mcpAccessPolicyError.value = e?.message || String(e);
+ } finally {
+ mcpPolicyRecovering.value = false;
+ }
}
+watch(mcpManagementTab, (tab) => {
+ if (tab === "permissions") void loadMcpPluginScopeContext();
+ if (tab !== "capabilities") return;
+ void ensureMcpToolCatalog();
+ if (!isWeb && mcpPluginViews.value === null) void loadMcpPluginViews();
+});
+
+const mcpCoverageConnections = computed(() => mcpSelectableConnections.value.map((connection) => ({ id: connection.id, name: connection.name, dbType: connection.db_type })));
+
// Entries beyond the static options: discovered plugin tool names and the
// `dbx_<prefix>__*` / `dbx_*__*` wildcards the backend matcher expands. They
// are invisible in the checkbox grid, so they render as removable chips.
@@ -4385,9 +4662,11 @@ const mcpCustomToolEntries = computed(() => customMcpAllowedToolNames(mcpAllowed
const mcpCustomToolInput = ref("");
function onMcpCustomToolAdd() {
+ if (mcpCatalogControlsDisabled.value || !mcpToolCatalog.value) return;
const rawName = mcpCustomToolInput.value;
if (!rawName.trim()) return;
- const { names, added } = addMcpAllowedToolName(mcpAllowedToolNames.value, rawName);
+ const current = mcpAllowedToolNames.value ?? setMcpToolsEnabled(null, mcpToolCatalog.value, [], true);
+ const { names, added } = addMcpAllowedToolName(current, rawName);
mcpCustomToolInput.value = "";
if (added) stageMcpPolicy({ allowedToolNames: names });
}
@@ -4396,10 +4675,6 @@ function onMcpCustomToolRemove(name: string) {
stageMcpPolicy({ allowedToolNames: toggleMcpAllowedToolName(mcpAllowedToolNames.value, name, false) });
}
-const mcpConnectionPolicyConnections = computed(() => {
- const allowed = mcpEffectiveAllowedConnectionIds.value;
- return allowed === null ? mcpSelectableConnections.value : mcpSelectableConnections.value.filter((connection) => allowed.includes(connection.id));
-});
function mcpConnectionExecutionMode(connectionId: string): McpConnectionExecutionMode | "inherit" {
const rule = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId);
if (!rule || !rule.executionModeConfigured) return "inherit";
@@ -4457,54 +4732,16 @@ function migrateLegacyMcpConnectionPolicy(policy: McpConnectionPolicy) {
};
}
-function mcpExecutionModeLabel(mode: McpConnectionExecutionMode): string {
- return t(mode === "read_only" ? "settings.mcpExecutionModeReadOnly" : mode === "safe_write" ? "settings.mcpExecutionModeSafeWrite" : "settings.mcpExecutionModeHighRiskWrite");
-}
-
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("");
-const mcpPermissionPreviewRows = computed(() =>
- mcpConnectionPolicyConnections.value.flatMap((connection) => {
- const rule = mcpPolicyDraft.value.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(groupMode, connectionMode, databaseMode),
- };
- });
- }),
-);
-const filteredMcpPermissionPreviewRows = computed(() => {
- const query = mcpPermissionPreviewSearchQuery.value.trim().toLocaleLowerCase();
- if (!query) return mcpPermissionPreviewRows.value;
- return mcpPermissionPreviewRows.value.filter((row) => [row.connection, row.database, 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;
+function onMcpGroupExecutionModeChange(groupId: string, mode: McpConnectionExecutionMode | "inherit", confirmed = false) {
+ if (mcpPolicyControlsDisabled.value) return;
+ if (mode === "high_risk_write" && !confirmed) {
+ requestMcpPolicyConfirmation(t("settings.mcpGroupPolicyHighRiskConfirm"), () => onMcpGroupExecutionModeChange(groupId, mode, true));
+ return;
+ }
const groupPolicies = mcpPolicyDraft.value.groupPolicies.filter((item) => item.groupId !== groupId);
if (mode !== "inherit") {
groupPolicies.push({
@@ -4524,8 +4761,12 @@ function mcpConnectionPolicyIsMeaningful(rule: McpConnectionPolicy): boolean {
return rule.executionModeConfigured || rule.databaseScope !== "all" || rule.databasePolicies.length > 0 || rule.allowSalesforceDml;
}
-function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConnectionExecutionMode | "inherit") {
- if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) return;
+function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConnectionExecutionMode | "inherit", confirmed = false) {
+ if (mcpPolicyControlsDisabled.value) return;
+ if (mode === "high_risk_write" && !confirmed) {
+ requestMcpPolicyConfirmation(t("settings.mcpExecutionModeHighRiskConfirm"), () => onMcpConnectionExecutionModeChange(connectionId, mode, true));
+ return;
+ }
const existing = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId);
const rules = mcpPolicyDraft.value.connectionPolicies.filter((item) => item.connectionId !== connectionId);
const migrated = existing && existing.executionModePolicyVersion !== 1 ? migrateLegacyMcpConnectionPolicy(existing) : null;
@@ -4582,8 +4823,12 @@ function onMcpConnectionSalesforceDmlChange(connectionId: string, allowed: boole
stageMcpPolicy({ connectionPolicies: rules });
}
-function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: string, mode: McpConnectionExecutionMode | "inherit") {
- if (mode === "high_risk_write" && !window.confirm(t("settings.mcpDatabasePolicyHighRiskConfirm"))) return;
+function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: string, mode: McpConnectionExecutionMode | "inherit", confirmed = false) {
+ if (mcpPolicyControlsDisabled.value) return;
+ if (mode === "high_risk_write" && !confirmed) {
+ requestMcpPolicyConfirmation(t("settings.mcpDatabasePolicyHighRiskConfirm"), () => onMcpDatabaseExecutionModeChange(connectionId, databaseName, mode, true));
+ return;
+ }
const existing = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId);
if (!existing || existing.databaseScope !== "selected" || !existing.allowedDatabases.includes(databaseName)) return;
const migrated = existing.executionModePolicyVersion === 1 ? null : migrateLegacyMcpConnectionPolicy(existing);
@@ -4602,8 +4847,176 @@ function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: st
stageMcpPolicy({ connectionPolicies: rules });
}
-function onMcpConnectionPoliciesChange(connectionPolicies: typeof mcpPolicyDraft.value.connectionPolicies) {
- stageMcpPolicy({ connectionPolicies });
+// ---------- Access-control tree ----------
+// The tree edits the same v1 policy fields as the former wizard steps; level
+// edits reuse the handlers above, visibility and database scope live here.
+let mcpLastCustomScope: { allowedGroupIds: string[]; allowedConnectionIds: string[] } | null = null;
+
+function mcpTreeGroupDescendants(groupId: string): { groupIds: string[]; connectionIds: string[] } {
+ const groupIds: string[] = [];
+ const connectionIds: string[] = [];
+ type Node = ReturnType<typeof buildMcpResourceTree>[number];
+ const find = (nodes: Node[]): Node | undefined => {
+ for (const node of nodes) {
+ if (node.type === "group" && node.id === groupId) return node;
+ if (node.type === "group") {
+ const found = find(node.children);
+ if (found) return found;
+ }
+ }
+ return undefined;
+ };
+ const collect = (nodes: Node[]) => {
+ for (const node of nodes) {
+ if (node.type === "connection") connectionIds.push(node.connection.id);
+ else {
+ groupIds.push(node.id);
+ collect(node.children);
+ }
+ }
+ };
+ const group = find(buildMcpResourceTree(connectionStore.sidebarLayout, mcpSelectableConnections.value));
+ if (group?.type === "group") collect(group.children);
+ return { groupIds, connectionIds };
+}
+
+function onMcpTreeScopeMode(mode: "all" | "custom", confirmed = false) {
+ if (mcpPolicyControlsDisabled.value) return;
+ const custom = mcpPolicyDraft.value.allowedConnectionIds !== null;
+ if ((mode === "custom") === custom) return;
+ if (mode === "all") {
+ if ((mcpPolicyDraft.value.allowedGroupIds.length > 0 || (mcpPolicyDraft.value.allowedConnectionIds?.length ?? 0) > 0) && !confirmed) {
+ requestMcpPolicyConfirmation(t("settings.mcpResourceScopeAllConfirm"), () => onMcpTreeScopeMode(mode, true));
+ return;
+ }
+ mcpLastCustomScope = { allowedGroupIds: [...mcpPolicyDraft.value.allowedGroupIds], allowedConnectionIds: [...(mcpPolicyDraft.value.allowedConnectionIds ?? [])] };
+ stageMcpPolicy({ allowedGroupIds: [], allowedConnectionIds: null });
+ return;
+ }
+ stageMcpPolicy({ allowedGroupIds: [...(mcpLastCustomScope?.allowedGroupIds ?? [])], allowedConnectionIds: [...(mcpLastCustomScope?.allowedConnectionIds ?? [])] });
+}
+
+function onMcpTreeGroupVisible(groupId: string, visible: boolean) {
+ const descendants = mcpTreeGroupDescendants(groupId);
+ // Selecting a group subsumes the explicit selections below it.
+ const allowedGroupIds = mcpPolicyDraft.value.allowedGroupIds.filter((id) => id !== groupId && (!visible || !descendants.groupIds.includes(id)));
+ const allowedConnectionIds = (mcpPolicyDraft.value.allowedConnectionIds ?? []).filter((id) => !visible || !descendants.connectionIds.includes(id));
+ if (visible) allowedGroupIds.push(groupId);
+ stageMcpPolicy({ allowedGroupIds, allowedConnectionIds });
+}
+
+function onMcpTreeConnectionVisible(connectionId: string, visible: boolean) {
+ const next = new Set(mcpPolicyDraft.value.allowedConnectionIds ?? []);
+ if (visible) next.add(connectionId);
+ else next.delete(connectionId);
+ stageMcpPolicy({ allowedConnectionIds: [...next] });
+}
+
+function mcpTreeConnectionRule(connectionId: string): McpConnectionPolicy {
+ return (
+ mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId) ?? {
+ connectionId,
+ readOnly: false,
+ allowDangerousSql: false,
+ executionModeConfigured: false,
+ executionModePolicyVersion: 1,
+ databaseScope: "all",
+ allowedDatabases: [],
+ databasePolicies: [],
+ allowSalesforceDml: false,
+ }
+ );
+}
+
+function stageMcpTreeConnectionRule(next: McpConnectionPolicy) {
+ const rules = mcpPolicyDraft.value.connectionPolicies.filter((item) => item.connectionId !== next.connectionId);
+ if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next);
+ stageMcpPolicy({ connectionPolicies: rules });
+}
+
+function onMcpTreeDatabaseScope(connectionId: string, scope: McpConnectionPolicy["databaseScope"], confirmed = false) {
+ if (mcpPolicyControlsDisabled.value) return;
+ const existing = mcpTreeConnectionRule(connectionId);
+ if (scope === existing.databaseScope) return;
+ if (scope !== "selected" && existing.databasePolicies.length > 0 && !confirmed) {
+ requestMcpPolicyConfirmation(t("settings.mcpDatabaseScopeClearsPermissionExceptions"), () => onMcpTreeDatabaseScope(connectionId, scope, true));
+ return;
+ }
+ stageMcpTreeConnectionRule({
+ ...existing,
+ databaseScope: scope,
+ allowedDatabases: scope === "selected" ? existing.allowedDatabases : [],
+ databasePolicies: scope === "selected" ? existing.databasePolicies : [],
+ });
+}
+
+function onMcpTreeDatabaseAllowed(connectionId: string, database: string, allowed: boolean, confirmed = false) {
+ if (mcpPolicyControlsDisabled.value) return;
+ const existing = mcpTreeConnectionRule(connectionId);
+ if (!allowed && existing.databasePolicies.some((policy) => policy.databaseName === database) && !confirmed) {
+ requestMcpPolicyConfirmation(t("settings.mcpDatabaseScopeClearsPermissionExceptions"), () => onMcpTreeDatabaseAllowed(connectionId, database, allowed, true));
+ return;
+ }
+ const allowedDatabases = allowed ? [...new Set([...existing.allowedDatabases, database])] : existing.allowedDatabases.filter((item) => item !== database);
+ stageMcpTreeConnectionRule({
+ ...existing,
+ databaseScope: "selected",
+ allowedDatabases,
+ databasePolicies: existing.databasePolicies.filter((policy) => allowedDatabases.includes(policy.databaseName)),
+ });
+}
+
+function onMcpDatabaseAccessChange(connectionId: string, value: McpDatabaseAccess) {
+ if (mcpPolicyControlsDisabled.value) return;
+ const before = editableDatabaseAccess(mcpPolicyDraft.value, connectionId, connectionStore.sidebarLayout, mcpSelectableConnections.value);
+ const edited = mcpDatabaseEditedOverrides.get(connectionId) ?? new Set<string>();
+ const names = new Set([...before.databasePolicies, ...value.databasePolicies].map((entry) => entry.databaseName));
+ for (const name of names) {
+ if (JSON.stringify(before.databasePolicies.find((entry) => entry.databaseName === name)) !== JSON.stringify(value.databasePolicies.find((entry) => entry.databaseName === name))) edited.add(name);
+ }
+ mcpDatabaseEditedOverrides.set(connectionId, edited);
+ stageMcpPolicy({ connectionPolicies: mergeDatabaseAccess(mcpPolicyDraft.value, connectionId, value, connectionStore.sidebarLayout, mcpSelectableConnections.value) });
+}
+
+async function applyMcpDatabaseAccess(connectionId: string): Promise<void> {
+ if (mcpPolicySaving.value || mcpPolicyControlsDisabled.value || !mcpSelectableConnections.value.some((connection) => connection.id === connectionId)) throw new Error(t("settings.mcpDatabaseUnavailable"));
+ const layout = connectionStore.sidebarLayout;
+ const connections = mcpSelectableConnections.value;
+ const access = editableDatabaseAccess(mcpPolicyDraft.value, connectionId, layout, connections);
+ const savedRule = settingsStore.mcpGlobalPolicy.connectionPolicies.find((entry) => entry.connectionId === connectionId);
+ if (savedRule && savedRule.executionModePolicyVersion !== 1) {
+ const persisted = editableDatabaseAccess(settingsStore.mcpGlobalPolicy, connectionId, layout, connections);
+ // Legacy ceilings may appear wider solely because a parent permission is
+ // pending. Only explicitly edited database overrides may carry that change
+ // into a partial save; unchanged overrides retain their saved effective level.
+ access.databasePolicies = access.databasePolicies.map((entry) => {
+ if (mcpDatabaseEditedOverrides.get(connectionId)?.has(entry.databaseName)) return entry;
+ return persisted.databasePolicies.find((saved) => saved.databaseName === entry.databaseName) ?? entry;
+ });
+ }
+ const connectionPolicies = mergeDatabaseAccess(settingsStore.mcpGlobalPolicy, connectionId, access, layout, connections);
+ mcpPolicySaving.value = true;
+ try {
+ await settingsStore.updateMcpGlobalPolicy({ connectionPolicies });
+ await settingsStore.initMcpGlobalPolicy(true);
+ const saved = normalizeMcpGlobalPolicy(settingsStore.mcpGlobalPolicy);
+ const savedAccess = editableDatabaseAccess(saved, connectionId, layout, connections);
+ // Advance only this scope's baseline. The connection's default permission,
+ // visibility, other connections and runtime/tool drafts remain untouched.
+ mcpPolicyBaseline.value = normalizeMcpGlobalPolicy({ ...mcpPolicyBaseline.value, configured: saved.configured, connectionPolicies: mergeDatabaseAccess(mcpPolicyBaseline.value, connectionId, savedAccess, layout, connections) });
+ mcpPolicyDraft.value = normalizeMcpGlobalPolicy({ ...mcpPolicyDraft.value, configured: saved.configured, connectionPolicies: mergeDatabaseAccess(mcpPolicyDraft.value, connectionId, savedAccess, layout, connections) });
+ mcpDatabaseEditedOverrides.delete(connectionId);
+ } finally {
+ mcpPolicySaving.value = false;
+ }
+}
+
+async function loadMcpTreeDatabases(connection: ConnectionConfig): Promise<string[]> {
+ // SQL list_databases reads the live pool; connect first like the sidebar does.
+ await connectionStore.ensureConnected(connection.id, { activate: false });
+ const databases =
+ connection.db_type === "mongodb" ? await mongoListMcpTreeDatabases(connection.id) : connection.db_type === "redis" ? (await redisListMcpTreeDatabases(connection.id)).map((database) => String(database.db)) : (await listMcpTreeDatabases(connection.id)).map((database) => database.name);
+ return [...new Set(databases.map((database) => database.trim()).filter(Boolean))];
}
function mcpHttpList(value: string): string[] {
@@ -5718,6 +6131,8 @@ const aiEditConfigId = ref<string | null>(null);
let handledAiConfigRequestId = 0;
const displayedAiConfigs = computed(() => orderAiConfigsForDisplay(settingsStore.aiConfigs));
+watchSettingsSearchNavigation();
+
watch(
() => settingsVisible.value,
async (open) => {
@@ -5742,6 +6157,7 @@ watch(
if (settingsStore.mcpGlobalPolicy.configured) localStorage.removeItem(MCP_READONLY_STORAGE_KEY);
localStorage.removeItem(MCP_SCOPE_CONNECTION_STORAGE_KEY);
syncMcpPolicyBaseline(settingsStore.mcpGlobalPolicy);
+ await loadMcpPluginScopeContext();
await loadMcpHttpSettings();
} catch (e: any) {
mcpPolicyLoadError.value = e?.message || String(e);
@@ -5788,6 +6204,8 @@ watch(
await scrollToInitialSettingsSection();
} else {
resetSettingsSearchState();
+ mcpPolicyRecoveryConfirmation.value = false;
+ mcpCapabilityBrowserState.value = initialMcpCapabilityBrowserState();
syncMcpPolicyBaseline(mcpPolicyBaseline.value);
}
},
@@ -12399,8 +12817,9 @@ LIMIT 100;</pre>
</div>
<Tabs v-model="mcpManagementTab" class="space-y-4">
- <TabsList class="grid h-9 w-full grid-cols-2">
+ <TabsList class="grid h-9 w-full grid-cols-3">
<TabsTrigger value="access">{{ t("settings.mcpManagementAccess") }}</TabsTrigger>
+ <TabsTrigger value="capabilities">{{ t("settings.mcpManagementCapabilities") }}</TabsTrigger>
<TabsTrigger value="permissions">{{ t("settings.mcpManagementPermissions") }}</TabsTrigger>
</TabsList>
@@ -12412,10 +12831,19 @@ LIMIT 100;</pre>
</div>
</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>
+ <div class="@container/mcp-transport flex min-w-0 items-center justify-between gap-2">
+ <TabsList variant="line" class="h-8 w-fit min-w-0 shrink justify-start gap-1 border-b border-border/60 bg-transparent p-0">
+ <TabsTrigger value="stdio" class="min-w-0 flex-initial px-3" :title="t('settings.mcpTransportLocalStdio')"
+ ><span class="truncate">{{ t("settings.mcpTransportLocalStdio") }}</span></TabsTrigger
+ >
+ <TabsTrigger value="http" class="min-w-0 flex-initial px-3" :title="t('settings.mcpTransportHttpService')"
+ ><span class="truncate">{{ t("settings.mcpTransportHttpService") }}</span></TabsTrigger
+ >
+ </TabsList>
+ <Button type="button" variant="ghost" size="sm" class="h-7 min-w-8 shrink gap-1.5 text-xs" :aria-label="t('settings.mcpOpenCallHistory')" :title="t('settings.mcpOpenCallHistory')" data-mcp-open-call-history @click="requestMcpCallHistory()">
+ <History class="size-3.5" /><span class="hidden truncate @min-[480px]/mcp-transport:inline">{{ t("settings.mcpOpenCallHistory") }}</span>
+ </Button>
+ </div>
<TabsContent value="http" data-settings-search-id="mcp-http" class="m-0 space-y-4">
<div v-if="isWeb" class="space-y-4">
<div class="space-y-3 border-t border-border/60 pt-3">
@@ -12753,176 +13181,111 @@ LIMIT 100;</pre>
</div>
</TabsContent>
- <TabsContent value="permissions" class="m-0 space-y-4">
- <McpAuthorizationTabs v-model="mcpAuthorizationTab">
- <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="mcpPolicyDraft.groupPolicies"
- :connection-policies="mcpPolicyDraft.connectionPolicies"
- :disabled="mcpPolicyControlsDisabled"
- :busy="mcpPolicyLoading || mcpPolicySaving"
- @update:scope="onMcpResourceScopeChange"
- @set:group-policy="onMcpGroupExecutionModeChange"
- @set:connection-policy="onMcpConnectionExecutionModeChange"
- @set:connection-salesforce-dml="onMcpConnectionSalesforceDmlChange"
- />
- </div>
- </template>
- <template #databases>
- <McpDatabaseScopePicker
- :connections="mcpSelectableConnections"
- :allowed-connection-ids="mcpEffectiveAllowedConnectionIds"
- :connection-policies="mcpPolicyDraft.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>
- <label class="flex items-center gap-2 text-xs">
- <input type="checkbox" :checked="mcpPolicyDraft.promptHighRiskSql" :disabled="mcpPolicyControlsDisabled || mcpExecutionMode !== 'safe_write'" @change="stageMcpPolicy({ promptHighRiskSql: ($event.target as HTMLInputElement).checked })" />
- {{ t("settings.mcpPromptHighRiskSql") }}
- </label>
- <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>
- </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>
- <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" />
- <X v-else class="h-4 w-4" aria-hidden="true" />
- <span class="sr-only">{{ t(row[column.mode] ? "settings.mcpCapabilityAllowed" : "settings.mcpCapabilityBlocked") }}</span>
- </span>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- <p class="text-[11px] leading-relaxed text-muted-foreground">{{ t("settings.mcpCapabilityAlwaysEnforced") }}</p>
- </div>
- </section>
+ <TabsContent data-settings-search-id="mcp-capabilities" value="capabilities" class="m-0 space-y-4">
+ <McpCapabilityBrowser
+ ref="mcpCapabilityBrowserRef"
+ v-model="mcpCapabilityBrowserState"
+ :catalog="mcpToolCatalog"
+ :loading="mcpToolCatalogLoading"
+ :load-error="mcpToolCatalogError"
+ :allowed-tool-names="mcpAllowedToolNames"
+ :saved-tool-names="mcpPolicyBaseline.allowedToolNames"
+ :save-toolset="applyMcpToolset"
+ :connections="mcpCoverageConnections"
+ :disabled="mcpPolicyControlsDisabled"
+ :plugins="mcpPluginViews"
+ :plugins-loading="mcpPluginViewsLoading"
+ :plugins-error="mcpPluginViewsError"
+ :pending-plugin-ids="[...mcpPluginSavingIds]"
+ :show-plugins="!isWeb"
+ :save-plugin="persistMcpPluginGrant"
+ @set:toolset="onMcpToolsetAllowedChange"
+ @set:tool="onMcpToolAllowedChange"
+ @set:category="onMcpCategoryAllowedChange"
+ @retry="ensureMcpToolCatalog"
+ @refresh:plugins="loadMcpPluginViews"
+ >
+ <template #plugin-warning>
+ <div v-if="!isWeb && mcpPluginToolsBlockedByAllowlist" class="flex flex-wrap items-center gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-800 dark:text-amber-200" data-mcp-plugin-allowlist-blocked>
+ <AlertTriangle class="size-3.5 shrink-0" />
+ <div class="min-w-0 flex-1 space-y-1">
+ <p>{{ t("settings.mcpPluginAllowlistBlocked") }}</p>
+ <p>{{ t("settings.mcpBrowser.draftHint") }}</p>
+ </div>
+ <Button variant="outline" size="sm" class="h-7 shrink-0 text-xs" :disabled="mcpPolicyControlsDisabled" @click="onMcpAllowPluginTools">{{ t("settings.mcpPluginAllowlistAllow") }}</Button>
</div>
+ <p v-if="mcpPluginAllowlistPending" role="status" class="text-xs text-muted-foreground" data-mcp-plugin-allowlist-pending>{{ t("settings.mcpBrowser.draftHint") }}</p>
</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>
+ <template #advanced>
+ <McpPluginToolsModeSetting :model-value="mcpPolicyDraft.pluginToolsMode" :disabled="mcpPolicyControlsDisabled" @update:model-value="(value) => stageMcpPolicy({ pluginToolsMode: value })" />
+ <section class="rounded-md border p-3" data-mcp-plugin-tool-entries>
+ <h4 class="text-sm font-medium">
+ {{ t("settings.mcpPluginToolEntriesTitle") }} <span class="font-normal text-muted-foreground">({{ mcpCustomToolEntries.length }})</span>
+ </h4>
+ <div class="mt-2 space-y-2">
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpPluginToolEntriesHint") }}</p>
+ <div class="flex gap-2">
+ <Input v-model="mcpCustomToolInput" class="h-8 flex-1 font-mono text-xs" :placeholder="t('settings.mcpToolCustomPlaceholder')" :disabled="mcpCatalogControlsDisabled" spellcheck="false" @keydown.enter.prevent="onMcpCustomToolAdd" />
+ <Button variant="outline" size="sm" class="h-8 shrink-0" :disabled="mcpCatalogControlsDisabled || !mcpCustomToolInput.trim()" @click="onMcpCustomToolAdd">{{ t("settings.mcpToolCustomAdd") }}</Button>
</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>
- <div class="space-y-2">
- <div class="flex gap-2">
- <Input v-model="mcpCustomToolInput" class="h-8 flex-1 font-mono text-xs" :placeholder="t('settings.mcpToolCustomPlaceholder')" :disabled="mcpPolicyControlsDisabled" spellcheck="false" @keydown.enter.prevent="onMcpCustomToolAdd" />
- <Button variant="outline" size="sm" class="h-8 shrink-0" :disabled="mcpPolicyControlsDisabled || !mcpCustomToolInput.trim()" @click="onMcpCustomToolAdd">{{ t("settings.mcpToolCustomAdd") }}</Button>
- </div>
- <p class="text-xs text-muted-foreground">{{ t("settings.mcpToolCustomHint") }}</p>
- <div v-if="mcpCustomToolEntries.length" class="flex flex-wrap gap-1.5">
- <span v-for="name in mcpCustomToolEntries" :key="name" class="flex items-center gap-1 rounded border bg-background px-2 py-1 font-mono text-xs">
- {{ name }}
- <button type="button" class="text-muted-foreground transition-colors hover:text-destructive" :disabled="mcpPolicyControlsDisabled" :aria-label="t('settings.mcpToolCustomRemove')" @click="onMcpCustomToolRemove(name)">
- <X class="size-3" />
- </button>
- </span>
- </div>
+ <div v-if="mcpCustomToolEntries.length" class="flex flex-wrap gap-1.5">
+ <span v-for="name in mcpCustomToolEntries" :key="name" class="flex min-w-0 max-w-full items-center gap-1 rounded border bg-background px-2 py-1 font-mono text-xs">
+ <span class="min-w-0 break-all">{{ name }}</span>
+ <button type="button" class="text-muted-foreground transition-colors hover:text-destructive" :disabled="mcpCatalogControlsDisabled" :aria-label="t('settings.mcpToolCustomRemove')" @click="onMcpCustomToolRemove(name)">
+ <X class="size-3" />
+ </button>
+ </span>
</div>
- </section>
- </div>
+ </div>
+ </section>
</template>
- </McpAuthorizationTabs>
+ </McpCapabilityBrowser>
+ </TabsContent>
+
+ <TabsContent value="permissions" class="m-0 space-y-4">
+ <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>
+ <div v-if="mcpAccessPolicyError" role="alert" class="space-y-2 rounded-md border border-red-500/30 bg-red-500/5 px-3 py-2 text-xs text-red-600 dark:text-red-400">
+ <p>{{ t("settings.mcpPolicyLoadFailed", { error: mcpAccessPolicyError }) }}</p>
+ <Button variant="outline" size="sm" :disabled="mcpAccessPolicyLoading || mcpPolicyRecovering" @click="loadMcpPluginScopeContext">{{ t("settings.mcpPolicyRetry") }}</Button>
+ <Button v-if="mcpAccessPolicyError.includes('invalid MCP access policy')" variant="outline" size="sm" :disabled="mcpPolicyRecovering || mcpPolicySaving" @click="mcpPolicyRecoveryConfirmation = true">{{ t("settings.mcpPolicyRecover") }}</Button>
+ </div>
+ <McpDefaultAccessPanel v-if="!mcpAccessPolicyError" data-settings-search-id="mcp-overrides" :mode="mcpExecutionMode" :disabled="mcpPolicyControlsDisabled" @set:mode="onMcpExecutionModeChange" />
+ <section v-if="!mcpAccessPolicyError" data-settings-search-id="mcp-connections" class="rounded-md border bg-background p-3 sm:p-4">
+ <McpAccessTree
+ :policy="mcpPolicyDraft"
+ :layout="connectionStore.sidebarLayout"
+ :connections="mcpSelectableConnections"
+ :disabled="mcpPolicyControlsDisabled"
+ :load-databases="loadMcpTreeDatabases"
+ :saved-policy="mcpPolicyBaseline"
+ :save-database-access="applyMcpDatabaseAccess"
+ @set:database-access="onMcpDatabaseAccessChange"
+ @set:scope-mode="onMcpTreeScopeMode"
+ @set:group-visible="onMcpTreeGroupVisible"
+ @set:connection-visible="onMcpTreeConnectionVisible"
+ @set:group-level="onMcpGroupExecutionModeChange"
+ @set:connection-level="onMcpConnectionExecutionModeChange"
+ @set:database-scope="onMcpTreeDatabaseScope"
+ @set:database-allowed="onMcpTreeDatabaseAllowed"
+ @set:database-level="onMcpDatabaseExecutionModeChange"
+ @set:salesforce-dml="onMcpConnectionSalesforceDmlChange"
+ :plugin-scopes="mcpPluginScopes"
+ :access-policy="mcpAccessPolicy"
+ :save-plugin-scope="setMcpPluginScopeRule"
+ :list-plugin-scopes="listMcpPluginScopes"
+ @plugin-scope-saved="mcpAccessPolicy = $event"
+ />
+ </section>
+ <McpCallSafetyPanel
+ v-if="!mcpAccessPolicyError"
+ data-settings-search-id="mcp-call-safety"
+ :mode="mcpPolicyDraft.callConfirmation === 'high_risk' ? 'high_risk' : mcpPolicyDraft.promptHighRiskSql ? 'full' : 'off'"
+ :disabled="mcpPolicyControlsDisabled"
+ @set:confirmation="onMcpHighRiskConfirmationChange"
+ />
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpPermissionsDraftHint") }}</p>
</TabsContent>
<div v-if="mcpManagementTab === 'access'" class="space-y-5 border-t border-border/60 pt-5 sm:ml-1">
<div data-settings-search-id="mcp-query-timeout" class="space-y-3">
@@ -13603,6 +13966,16 @@ LIMIT 100;</pre>
</DialogFooter>
</component>
+ <DangerConfirmDialog
+ :open="mcpPolicyConfirmationDialog.open"
+ :message="mcpPolicyConfirmationDialog.message"
+ :confirm-label="mcpPolicyConfirmationDialog.confirmLabel"
+ :close-on-confirm="false"
+ initial-focus="cancel"
+ @update:open="onMcpPolicyConfirmationOpenChange"
+ @confirm="confirmMcpPolicyChange"
+ />
+
<!-- Unsaved settings confirmation: guards every close path (Escape, outside click, the X button, and the footer "Close" button) so an unapplied draft is never silently discarded. -->
<Dialog :open="showUnsavedSettingsCloseConfirm" @update:open="(value: boolean) => !value && cancelUnsavedSettingsClose()">
<DialogContent class="sm:max-w-[420px]" @interact-outside.prevent>
diff --git a/apps/desktop/src/components/editor/QueryHistory.vue b/apps/desktop/src/components/editor/QueryHistory.vue
index 39d312a3df..d8ba1f1078 100644
--- a/apps/desktop/src/components/editor/QueryHistory.vue
+++ b/apps/desktop/src/components/editor/QueryHistory.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { ref, computed, nextTick, onBeforeUnmount, onMounted, watch } from "vue";
+import type { McpCallHistoryRequest, McpCallHistoryResource } from "@/lib/mcp/mcpCallHistory";
import { useI18n } from "vue-i18n";
import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
import { CalendarClock, Check, Copy, Database, ListFilter, LoaderCircle, Maximize2, Minimize2, Minus, RefreshCw, RotateCcw, Search, Sparkles, Trash2, X } from "@lucide/vue";
@@ -35,6 +36,7 @@ const props = defineProps<{
currentConnectionId?: string;
currentDatabase?: string;
maximized?: boolean;
+ mcpRequest?: McpCallHistoryRequest | null;
}>();
const emit = defineEmits<{
@@ -42,6 +44,7 @@ const emit = defineEmits<{
analyzeAi: [entry: HistoryEntry];
close: [];
toggleMaximize: [];
+ mcpRequestHandled: [];
}>();
type HistoryFilter = "all" | "query" | "data_change" | "schema_change" | "failed" | "mcp_success";
@@ -400,11 +403,43 @@ function detailsRows(entry: HistoryEntry) {
[t("history.detail.rollback"), canRollbackHistoryEntry(entry) ? t("history.rollbackAvailable") : t("history.rollbackUnavailable")],
[t("history.detail.status"), entry.success ? t("history.success") : t("history.failed")],
];
- if (entry.source === "mcp" || historyEntrySource(entry) === "MCP") rows.splice(1, 0, [t("history.detail.mcpTool"), entry.mcp_tool_name || entry.operation || "-"]);
+ if (entry.source === "mcp" || historyEntrySource(entry) === "MCP") {
+ rows.splice(1, 0, [t("history.detail.mcpTool"), entry.mcp_tool_name || entry.operation || "-"]);
+ const client = mcpClientLabel(entry);
+ if (client) rows.splice(2, 0, [t("history.detail.mcpClient"), client]);
+ const audit = mcpAuditDetails(entry);
+ if (audit.transport) rows.splice(3, 0, [t("history.detail.mcpTransport"), audit.transport]);
+ if (audit.accessLevel) rows.splice(4, 0, [t("history.detail.mcpAccess"), audit.accessLevel]);
+ if (audit.confirmation) rows.splice(5, 0, [t("history.detail.mcpConfirmation"), audit.confirmation]);
+ }
if (entry.error) rows.push([t("history.detail.error"), entry.error]);
return rows;
}
+/** The MCP client recorded in `details_json` (`{ client: { name, version } }`), if any. */
+function mcpClientLabel(entry: HistoryEntry): string {
+ try {
+ const client = JSON.parse(entry.details_json || "{}")?.client;
+ if (!client?.name) return "";
+ return client.version ? `${client.name} ${client.version}` : String(client.name);
+ } catch {
+ return "";
+ }
+}
+
+function mcpAuditDetails(entry: HistoryEntry): { transport?: string; accessLevel?: string; confirmation?: string } {
+ try {
+ const details = JSON.parse(entry.details_json || "{}");
+ return {
+ transport: typeof details?.transport === "string" ? details.transport : undefined,
+ accessLevel: typeof details?.accessLevel === "string" ? details.accessLevel : undefined,
+ confirmation: typeof details?.confirmation === "string" ? details.confirmation : undefined,
+ };
+ } catch {
+ return {};
+ }
+}
+
async function recordRollback(entry: HistoryEntry, affectedRows: number, executionTime: number) {
await store.add({
connection_id: entry.connection_id,
@@ -554,6 +589,30 @@ watch(
watch([searchText, mcpToolName, activeSource, activeFilter, () => dateRange.value.startDate, () => dateRange.value.endDate, () => selectedConnections.value.map(connectionKey).join("\0"), () => selectedDatabases.value.map(databaseKey).join("\0")], scheduleHistorySearch);
+function applyMcpResource(resource?: McpCallHistoryResource) {
+ activeSource.value = "mcp";
+ activeFilter.value = "all";
+ resetScopeFilter();
+ scopeFilterOpen.value = false;
+ if (!resource?.connectionId) return;
+ // Scope by the requested IDs immediately. History options contain only resources
+ // with existing records and must not widen the scope or replay navigation later.
+ const connection = store.connectionOptions.find((option) => option.connection_id === resource.connectionId);
+ const target = { connection_id: resource.connectionId, connection_name: connection?.connection_name ?? connectionStore.getConfig(resource.connectionId)?.name ?? "" };
+ selectedConnections.value = [target];
+ selectedDatabases.value = resource.database ? [{ ...target, database: resource.database }] : [];
+}
+
+watch(
+ () => props.mcpRequest,
+ (request) => {
+ if (!request) return;
+ applyMcpResource(request.resource);
+ emit("mcpRequestHandled");
+ },
+ { immediate: true },
+);
+
onMounted(() => {
store.setHistoryPanelActive(true);
void store.loadConnectionOptions().catch(() => {});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpCapabilities.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpCapabilities.integration.spec.ts
new file mode 100644
index 0000000000..5f94b8a314
--- /dev/null
+++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpCapabilities.integration.spec.ts
@@ -0,0 +1,1176 @@
+import ts from "typescript";
+import { computed, ref, shallowRef, type Ref } from "vue";
+import { describe, expect, it, vi } from "vitest";
+import dialogSource from "../EditorSettingsDialog.vue?raw";
+import { DEFAULT_DESKTOP_SETTINGS, DEFAULT_SIDEBAR_TABLE_PAGE_SIZE, normalizeMcpGlobalPolicy, type McpGlobalPolicy } from "@/stores/settingsStore";
+import { shouldConfirmEditorSettingsDialogClose } from "@/lib/settings/editorSettingsDraft";
+import { mergeMcpToolsetSelection, setMcpCategoryEnabled, setMcpToolsEnabled, setMcpToolsetEnabled, type McpCapabilityCategoryId } from "@/lib/mcp/mcpToolCatalog";
+import { addMcpAllowedToolName, MCP_PLUGIN_TOOLS_WILDCARD, mcpExecutionModeFromPolicy, mcpPolicyFieldsForExecutionMode, type McpExecutionMode } from "@/lib/mcp/mcpPolicySelection";
+import { editableDatabaseAccess, mergeDatabaseAccess, type McpDatabaseAccess } from "@/lib/mcp/mcpDatabaseAccess";
+import { buildMcpAccessTreeRows } from "@/lib/mcp/mcpAccessTree";
+import type { ConnectionConfig, SidebarLayout } from "@/types/database";
+import type { McpAccessPolicy, McpToolCatalog, McpToolCatalogToolset, PluginMcpGrant, PluginMcpView } from "@/types/mcpCatalog";
+
+// Run the actual dialog handlers and Apply/Discard path without mounting the
+// unrelated editors, charts and plugin workbenches in the settings dialog.
+// Only external persistence and non-MCP settings dependencies are replaced.
+const script = dialogSource.match(/<script setup[^>]*>([\s\S]*?)<\/script>/)?.[1];
+if (!script) throw new Error("EditorSettingsDialog script setup was not found");
+const source = ts.createSourceFile("EditorSettingsDialog.ts", script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
+
+function declaration(name: string): string {
+ for (const statement of source.statements) {
+ if (ts.isFunctionDeclaration(statement) && statement.name?.text === name) return statement.getText(source);
+ if (ts.isVariableStatement(statement)) {
+ const target = statement.declarationList.declarations.find((item) => ts.isIdentifier(item.name) && item.name.text === name);
+ if (target) return `const ${target.getText(source)};`;
+ }
+ }
+ throw new Error(`Missing real settings declaration: ${name}`);
+}
+
+const exposedNames = [
+ "mcpAccessPolicy",
+ "mcpAccessPolicyError",
+ "mcpAccessPolicyLoading",
+ "mcpPolicyRecovering",
+ "mcpPolicyRecoveryConfirmation",
+ "recoverMcpAccessPolicy",
+ "mcpInstalledPluginsForScopes",
+ "loadMcpPluginScopeContext",
+ "mcpPolicyConfirmation",
+ "confirmMcpPolicyChange",
+ "onMcpPolicyConfirmationOpenChange",
+ "onMcpTreeScopeMode",
+ "onMcpTreeDatabaseScope",
+ "onMcpTreeDatabaseAllowed",
+ "onMcpExecutionModeChange",
+ "onMcpHighRiskConfirmationChange",
+ "onMcpGroupExecutionModeChange",
+ "onMcpConnectionExecutionModeChange",
+ "onMcpDatabaseExecutionModeChange",
+ "stageMcpPolicy",
+ "mcpPolicyDraft",
+ "mcpPolicyBaseline",
+ "mcpPolicySaving",
+ "mcpToolCatalog",
+ "mcpToolCatalogLoading",
+ "mcpToolCatalogError",
+ "mcpPluginViews",
+ "mcpPluginViewsLoading",
+ "mcpPluginViewsError",
+ "loadMcpPluginViews",
+ "showUnsavedSettingsCloseConfirm",
+ "cancelUnsavedSettingsClose",
+ "onMcpCategoryAllowedChange",
+ "onMcpToolAllowedChange",
+ "onMcpToolsetAllowedChange",
+ "applyMcpToolset",
+ "loadMcpTreeDatabases",
+ "applyMcpDatabaseAccess",
+ "onMcpDatabaseAccessChange",
+ "mcpPolicyHasUnsavedChanges",
+ "requestCloseSettings",
+ "discardUnsavedSettingsAndClose",
+ "applySettingsForResult",
+ "applySettingsAndClose",
+ "persistMcpPluginGrant",
+ "mcpCustomToolInput",
+ "onMcpCustomToolAdd",
+];
+const declarationNames = [
+ ...exposedNames,
+ "mcpDatabaseEditedOverrides",
+ "mcpPluginScopeLoadRevision",
+ "pendingMcpCallHistory",
+ "requestMcpPolicyConfirmation",
+ "mcpTreeConnectionRule",
+ "stageMcpTreeConnectionRule",
+ "requestMcpCallHistory",
+ "finishSettingsClose",
+ "mcpExecutionMode",
+ "mcpConnectionPolicyIsMeaningful",
+ "migrateLegacyMcpConnectionPolicy",
+ "mcpConnectionExecutionMode",
+ "mcpInheritedGroupExecutionMode",
+ "mcpInheritedGroupPolicy",
+ "mcpGroupExecutionMode",
+ "mcpExecutionModeRank",
+ "mcpPluginViewRevisions",
+ "mcpPluginSavingIds",
+ "mcpAllowedToolNames",
+ "mcpCatalogControlsDisabled",
+ "mcpPoliciesEqual",
+ "syncMcpPolicyBaseline",
+ "stageMcpQueryTimeoutDraft",
+ "commitMcpPolicyDraft",
+ "persistSettings",
+ "applySettingsErrorToast",
+ "closeSettings",
+ "onMcpPluginViewSaved",
+];
+const compiledHandlers = ts.transpileModule(declarationNames.map(declaration).join("\n"), {
+ compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 },
+}).outputText;
+const historyClick = dialogSource.match(/data-mcp-open-call-history\s+@click="([^"]+)"/)?.[1];
+if (!historyClick) throw new Error("MCP history button handler was not found");
+
+function toolset(id: string, names: string[]): McpToolCatalogToolset {
+ return { id, provider: `builtin:${id.split(".")[0]}`, resourceKinds: [], scopeKinds: [], tools: names.map((name) => ({ name, access: "read", accessMode: "static", coverageKind: "none", databaseTypes: [], description: "", parameters: [] })) };
+}
+
+const catalog: McpToolCatalog = { toolsets: [toolset("sql.query", ["dbx_execute_query", "dbx_future_query"]), toolset("nacos.config", ["dbx_nacos_get_config", "dbx_nacos_publish_config"]), toolset("nacos.service", ["dbx_nacos_list_services"]), toolset("admin.connections", ["dbx_add_connection"])] };
+
+const plugin: PluginMcpView = {
+ pluginId: "io.dbx.helper",
+ pluginName: "Helper",
+ version: "1.0.0",
+ authorAllowsExternal: true,
+ hasSavedGrant: true,
+ grant: { external: false, ceiling: "read", approvedTools: { dbx_helper__inspect: "read" }, disabledTools: [] },
+ toolsets: [{ id: "default", title: null, description: null }],
+ tools: [],
+ discoveryError: null,
+};
+
+interface SettingsHarness {
+ mcpAccessPolicyError: Ref<string>;
+ mcpAccessPolicyLoading: Ref<boolean>;
+ mcpPolicyRecovering: Ref<boolean>;
+ mcpPolicyRecoveryConfirmation: Ref<boolean>;
+ recoverMcpAccessPolicy: () => Promise<void>;
+ mcpAccessPolicy: Ref<McpAccessPolicy | null>;
+ mcpInstalledPluginsForScopes: Ref<Array<{ manifest: { id: string } }>>;
+ loadMcpPluginScopeContext: () => Promise<void>;
+ mcpPolicyConfirmation: Ref<{ message: string; apply: () => void } | null>;
+ confirmMcpPolicyChange: () => void | Promise<void>;
+ onMcpPolicyConfirmationOpenChange: (open: boolean) => void;
+ onMcpTreeScopeMode: (mode: "all" | "custom") => void;
+ onMcpTreeDatabaseScope: (id: string, scope: "all" | "selected" | "none") => void;
+ onMcpTreeDatabaseAllowed: (id: string, database: string, allowed: boolean) => void;
+ onMcpExecutionModeChange: (mode: McpExecutionMode) => void;
+ onMcpHighRiskConfirmationChange: (enabled: boolean) => void;
+ onMcpGroupExecutionModeChange: (id: string, mode: McpExecutionMode | "inherit") => void;
+ onMcpConnectionExecutionModeChange: (id: string, mode: McpExecutionMode | "inherit") => void;
+ onMcpDatabaseExecutionModeChange: (id: string, database: string, mode: McpExecutionMode | "inherit") => void;
+ stageMcpPolicy: (patch: Partial<McpGlobalPolicy>) => void;
+ mcpPolicyDraft: Ref<McpGlobalPolicy>;
+ mcpPolicyBaseline: Ref<McpGlobalPolicy>;
+ mcpPolicySaving: Ref<boolean>;
+ mcpToolCatalog: Ref<McpToolCatalog | null>;
+ mcpToolCatalogLoading: Ref<boolean>;
+ mcpToolCatalogError: Ref<string>;
+ mcpPluginViews: Ref<PluginMcpView[] | null>;
+ mcpPluginViewsLoading: Ref<boolean>;
+ mcpPluginViewsError: Ref<string>;
+ loadMcpPluginViews: () => Promise<void>;
+ showUnsavedSettingsCloseConfirm: Ref<boolean>;
+ cancelUnsavedSettingsClose: () => void;
+ clickMcpCallHistory: () => void;
+ onMcpCategoryAllowedChange: (id: McpCapabilityCategoryId, enabled: boolean) => void;
+ onMcpToolAllowedChange: (name: string, enabled: boolean) => void;
+ onMcpToolsetAllowedChange: (toolset: McpToolCatalogToolset, enabled: boolean) => void;
+ applyMcpToolset: (toolsetId: string) => Promise<void>;
+ loadMcpTreeDatabases: (connection: ConnectionConfig) => Promise<string[]>;
+ applyMcpDatabaseAccess: (id: string) => Promise<void>;
+ onMcpDatabaseAccessChange: (id: string, access: McpDatabaseAccess) => void;
+ mcpPolicyHasUnsavedChanges: () => boolean;
+ requestCloseSettings: (open: boolean) => void;
+ discardUnsavedSettingsAndClose: () => void;
+ applySettingsForResult: () => Promise<boolean>;
+ applySettingsAndClose: () => Promise<void>;
+ persistMcpPluginGrant: (id: string, grant: PluginMcpGrant, approveCurrent: boolean) => Promise<PluginMcpView>;
+ mcpCustomToolInput: Ref<string>;
+ onMcpCustomToolAdd: () => void;
+}
+
+function createHarness(initial: Partial<McpGlobalPolicy> = {}) {
+ const loadMcpAccessPolicy = vi.fn(async (): Promise<McpAccessPolicy> => ({ version: 2, defaultAccess: "read", rules: [] }));
+ const resetInvalidMcpAccessPolicy = vi.fn(async () => {});
+ const listPlugins = vi.fn(async (): Promise<Array<{ manifest: { id: string } }>> => []);
+ const persistedPlugin = ref<PluginMcpView>(structuredClone(plugin));
+ const listPluginMcpViews = vi.fn(async () => [structuredClone(plugin)]);
+ const savePluginMcpGrant = vi.fn(async (_id: string, grant: PluginMcpGrant, _approveCurrent: boolean) => {
+ const next = { ...structuredClone(plugin), grant: structuredClone(grant) };
+ persistedPlugin.value = next;
+ return next;
+ });
+ const settingsStore = {
+ mcpGlobalPolicy: normalizeMcpGlobalPolicy(initial),
+ editorSettings: { sidebarObjectDisplay: "all" },
+ desktopSettings: { ...DEFAULT_DESKTOP_SETTINGS },
+ initMcpGlobalPolicy: vi.fn(async () => {}),
+ updateDesktopSettings: vi.fn(async (patch: object) => {
+ Object.assign(settingsStore.desktopSettings, patch);
+ }),
+ updateMcpGlobalPolicy: vi.fn(async (patch: Partial<McpGlobalPolicy>) => {
+ settingsStore.mcpGlobalPolicy = normalizeMcpGlobalPolicy({ ...settingsStore.mcpGlobalPolicy, ...patch, configured: true });
+ }),
+ };
+ const databaseNames = Array.from({ length: 260 }, (_, index) => `db_${index}`);
+ const listMcpTreeDatabases = vi.fn(async () => databaseNames.map((name) => ({ name })));
+ const mongoListMcpTreeDatabases = vi.fn(async () => databaseNames);
+ const redisListMcpTreeDatabases = vi.fn(async () => databaseNames.map((_, db) => ({ db })));
+ const ensureConnected = vi.fn(async () => {});
+ const emit = vi.fn();
+ const toast = vi.fn();
+ const confirm = vi.fn(() => true);
+ const openMcpCallHistory = vi.fn();
+ const context = {
+ ref,
+ shallowRef,
+ computed,
+ settingsStore,
+ normalizeMcpGlobalPolicy,
+ mcpExecutionModeFromPolicy,
+ mcpPolicyFieldsForExecutionMode,
+ window: { confirm },
+ mcpConnectionGroupIdPaths: ref(new Map()),
+ mcpGroupRows: ref([]),
+ setMcpCategoryEnabled,
+ setMcpToolsEnabled,
+ setMcpToolsetEnabled,
+ mergeMcpToolsetSelection,
+ listMcpTreeDatabases,
+ mongoListMcpTreeDatabases,
+ redisListMcpTreeDatabases,
+ editableDatabaseAccess,
+ mergeDatabaseAccess,
+ mcpSelectableConnections: ref([
+ { id: "c1", name: "First", db_type: "mysql" },
+ { id: "c2", name: "Second", db_type: "mysql" },
+ ] as ConnectionConfig[]),
+ addMcpAllowedToolName,
+ savePluginMcpGrant,
+ listPluginMcpViews,
+ loadMcpAccessPolicy,
+ resetInvalidMcpAccessPolicy,
+ listPlugins,
+ shouldConfirmEditorSettingsDialogClose,
+ emit,
+ openMcpCallHistory,
+ toast,
+ t: (key: string) => key,
+ mcpPolicyControlsDisabled: ref(false),
+ mcpPolicyLoadError: ref(""),
+ hasApplyBlocker: ref(false),
+ historyRetention: { save: vi.fn(async () => {}) },
+ mcpHistoryRetention: { save: vi.fn(async () => {}) },
+ editorSettingsPatchFromDraft: () => ({}),
+ currentEditorSettingsDraft: () => ({}),
+ editEditorSettingsBase: ref({}),
+ editSidebarTablePageSize: ref(DEFAULT_SIDEBAR_TABLE_PAGE_SIZE),
+ DEFAULT_SIDEBAR_TABLE_PAGE_SIZE,
+ editMetadataCacheMaxMemoryMb: ref(DEFAULT_DESKTOP_SETTINGS.metadata_cache_max_memory_mb),
+ normalizeMetadataCacheMemoryMb: (value: number) => value,
+ editShowTrayIcon: ref(false),
+ editLinuxFloatingFrameEnabled: ref(DEFAULT_DESKTOP_SETTINGS.linux_floating_frame_enabled ?? true),
+ editQuitOnClose: ref(false),
+ desktopCloseBehaviorResetPending: ref(false),
+ editIconTheme: ref("default"),
+ editDebugLoggingEnabled: ref(false),
+ editDuckDbWorkerProcessIsolation: ref(false),
+ editDuckDbWorkerMaxProcesses: ref(4),
+ normalizeDuckDbWorkerMaxProcesses: (value: number) => value,
+ hasImportedSettingsPendingApply: ref(false),
+ connectionStore: { ensureConnected, sidebarLayout: { groups: [], order: [] } as SidebarLayout, refreshAllTree: vi.fn(), refreshSidebarObjectPagination: vi.fn() },
+ };
+ const factory = new Function(
+ ...Object.keys(context),
+ `
+ let mcpLastCustomScope = null;
+ let mcpQueryTimeoutPendingValue;
+ let mcpQueryTimeoutSaveTimer = null;
+ const mcpQueryTimeoutInput = ref("");
+ let pendingBackgroundImageCleanup = null;
+ function hasChanges() { return mcpPolicyHasUnsavedChanges(); }
+ ${compiledHandlers}
+ return { ${exposedNames.join(",")}, clickMcpCallHistory: () => { ${historyClick} } };
+ `,
+ );
+ const handlers = factory(...Object.values(context)) as SettingsHarness;
+ handlers.mcpToolCatalog.value = catalog;
+ handlers.mcpPluginViews.value = [structuredClone(plugin)];
+ return {
+ ...handlers,
+ listMcpTreeDatabases,
+ mongoListMcpTreeDatabases,
+ redisListMcpTreeDatabases,
+ ensureConnected,
+ databaseNames,
+ settingsStore,
+ savePluginMcpGrant,
+ listPluginMcpViews,
+ loadMcpAccessPolicy,
+ resetInvalidMcpAccessPolicy,
+ listPlugins,
+ persistedPlugin,
+ emit,
+ toast,
+ confirm,
+ openMcpCallHistory,
+ controlsDisabled: context.mcpPolicyControlsDisabled,
+ };
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+describe("EditorSettingsDialog MCP capability persistence integration", () => {
+ it("places plugin tool delivery only in the capabilities advanced slot", () => {
+ const advanced = dialogSource.match(/<template #advanced>([\s\S]*?)<\/template>/)?.[1];
+ expect(advanced).toContain('<McpPluginToolsModeSetting :model-value="mcpPolicyDraft.pluginToolsMode" :disabled="mcpPolicyControlsDisabled" @update:model-value="(value) => stageMcpPolicy({ pluginToolsMode: value })"');
+ expect(dialogSource.match(/<McpPluginToolsModeSetting\b/g)).toHaveLength(1);
+ expect(dialogSource).not.toContain('id="mcp-plugin-tools-mode-label"');
+ });
+
+ it.each(["auto", "flat", "lazy"] as const)("keeps a saved %s delivery mode when applying unrelated settings", async (pluginToolsMode) => {
+ const h = createHarness({ configured: true, pluginToolsMode });
+ expect(h.mcpPolicyDraft.value.pluginToolsMode).toBe(pluginToolsMode);
+ h.onMcpHighRiskConfirmationChange(true);
+ expect(await h.applySettingsForResult()).toBe(true);
+ expect(h.settingsStore.updateMcpGlobalPolicy).toHaveBeenCalledWith(expect.objectContaining({ pluginToolsMode }));
+ });
+
+ it("stages delivery changes until Apply and discards them without changing plugin grants", async () => {
+ const h = createHarness();
+ expect(h.mcpPolicyDraft.value.pluginToolsMode).toBe("flat");
+ h.stageMcpPolicy({ pluginToolsMode: "lazy" });
+ expect(h.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ expect(h.savePluginMcpGrant).not.toHaveBeenCalled();
+ h.requestCloseSettings(false);
+ expect(h.showUnsavedSettingsCloseConfirm.value).toBe(true);
+ h.cancelUnsavedSettingsClose();
+ expect(h.mcpPolicyDraft.value.pluginToolsMode).toBe("lazy");
+ h.discardUnsavedSettingsAndClose();
+ expect(h.mcpPolicyDraft.value.pluginToolsMode).toBe("flat");
+ expect(h.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ h.stageMcpPolicy({ pluginToolsMode: "lazy" });
+ expect(await h.applySettingsForResult()).toBe(true);
+ expect(h.settingsStore.mcpGlobalPolicy.pluginToolsMode).toBe("lazy");
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(false);
+ });
+
+ it("keeps delivery and permission drafts retryable after a failed Apply", async () => {
+ const h = createHarness({ configured: true, pluginToolsMode: "auto", readOnly: true });
+ h.stageMcpPolicy({ pluginToolsMode: "flat" });
+ h.onMcpHighRiskConfirmationChange(true);
+ h.settingsStore.updateMcpGlobalPolicy.mockRejectedValueOnce(new Error("disk unavailable"));
+ expect(await h.applySettingsForResult()).toBe(false);
+ expect(h.settingsStore.mcpGlobalPolicy.pluginToolsMode).toBe("auto");
+ expect(h.mcpPolicyDraft.value).toMatchObject({ pluginToolsMode: "flat", promptHighRiskSql: false, callConfirmation: "high_risk" });
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(true);
+ expect(await h.applySettingsForResult()).toBe(true);
+ expect(h.settingsStore.mcpGlobalPolicy).toMatchObject({ pluginToolsMode: "flat", promptHighRiskSql: false, callConfirmation: "high_risk" });
+ expect(h.savePluginMcpGrant).not.toHaveBeenCalled();
+ });
+
+ it.each(["mysql", "mongodb", "redis"])("loads all %s databases through the metadata API without sidebar filtering or a page limit", async (dbType) => {
+ const h = createHarness();
+ const result = await h.loadMcpTreeDatabases({ id: "c1", db_type: dbType } as ConnectionConfig);
+ expect(result).toHaveLength(260);
+ expect(result).toEqual(dbType === "redis" ? h.databaseNames.map((_, index) => String(index)) : h.databaseNames);
+ expect(h.ensureConnected).toHaveBeenCalledExactlyOnceWith("c1", { activate: false });
+ expect(dbType === "redis" ? h.redisListMcpTreeDatabases : dbType === "mongodb" ? h.mongoListMcpTreeDatabases : h.listMcpTreeDatabases).toHaveBeenCalledExactlyOnceWith("c1");
+ });
+ it("applies only one connection's database access, keeping its parent, tools, runtime and other connection drafts", async () => {
+ const h = createHarness({ configured: true, readOnly: true, queryTimeoutSecs: 30, pluginToolsMode: "auto" });
+ h.stageMcpPolicy({ pluginToolsMode: "lazy" });
+ h.onMcpExecutionModeChange("safe_write");
+ h.onMcpConnectionExecutionModeChange("c1", "safe_write");
+ h.onMcpGroupExecutionModeChange("group", "safe_write");
+ h.onMcpToolAllowedChange("dbx_execute_query", false);
+ h.mcpPolicyDraft.value.queryTimeoutSecs = 99;
+ const access: McpDatabaseAccess = { databaseScope: "selected", allowedDatabases: ["aaa", "abc"], databasePolicies: [{ databaseName: "aaa", readOnly: true, allowDangerousSql: false }] };
+ h.onMcpDatabaseAccessChange("c2", { ...access, allowedDatabases: ["other"], databasePolicies: [] });
+ h.onMcpDatabaseAccessChange("c1", access);
+ await h.applyMcpDatabaseAccess("c1");
+ const saved = h.settingsStore.mcpGlobalPolicy;
+ expect(saved.readOnly).toBe(true);
+ expect(saved.queryTimeoutSecs).toBe(30);
+ expect(saved.pluginToolsMode).toBe("auto");
+ expect(h.mcpPolicyDraft.value.pluginToolsMode).toBe("lazy");
+ expect(saved.allowedToolNames).toBeNull();
+ expect(saved.groupPolicies).toEqual([]);
+ expect(h.mcpPolicyDraft.value.groupPolicies).toHaveLength(1);
+ expect(saved.connectionPolicies).toHaveLength(1);
+ expect(saved.connectionPolicies[0]).toMatchObject({ connectionId: "c1", executionModeConfigured: false, ...access });
+ expect(h.mcpPolicyDraft.value.connectionPolicies.find((r) => r.connectionId === "c1")).toMatchObject({ executionModeConfigured: true, readOnly: false });
+ expect(h.mcpPolicyDraft.value.connectionPolicies.find((r) => r.connectionId === "c2")?.allowedDatabases).toEqual(["other"]);
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(true);
+ await h.applySettingsForResult();
+ expect(h.settingsStore.mcpGlobalPolicy.readOnly).toBe(false);
+ expect(h.settingsStore.mcpGlobalPolicy.queryTimeoutSecs).toBe(99);
+ expect(h.settingsStore.mcpGlobalPolicy.pluginToolsMode).toBe("lazy");
+ expect(h.settingsStore.mcpGlobalPolicy.connectionPolicies).toHaveLength(2);
+ });
+ it("discarding remaining drafts does not undo applied database permissions", async () => {
+ const h = createHarness({ configured: true, readOnly: true });
+ h.onMcpDatabaseAccessChange("c1", { databaseScope: "none", allowedDatabases: [], databasePolicies: [] });
+ h.onMcpExecutionModeChange("safe_write");
+ await h.applyMcpDatabaseAccess("c1");
+ h.discardUnsavedSettingsAndClose();
+ expect(h.mcpPolicyDraft.value.readOnly).toBe(true);
+ expect(h.mcpPolicyDraft.value.connectionPolicies[0].databaseScope).toBe("none");
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(false);
+ });
+ it("clears the dirty state when multiple connection scopes are applied in reverse editing order", async () => {
+ const h = createHarness({ configured: true });
+ const value: McpDatabaseAccess = { databaseScope: "none", allowedDatabases: [], databasePolicies: [] };
+ h.onMcpDatabaseAccessChange("c2", value);
+ h.onMcpDatabaseAccessChange("c1", value);
+ await h.applyMcpDatabaseAccess("c1");
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(true);
+ await h.applyMcpDatabaseAccess("c2");
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(false);
+ });
+ it("database save failure leaves baseline and draft intact and retry succeeds", async () => {
+ const h = createHarness({ configured: true });
+ h.onMcpDatabaseAccessChange("c1", { databaseScope: "selected", allowedDatabases: ["aaa"], databasePolicies: [] });
+ const draft = normalizeMcpGlobalPolicy(h.mcpPolicyDraft.value);
+ const baseline = normalizeMcpGlobalPolicy(h.mcpPolicyBaseline.value);
+ h.settingsStore.updateMcpGlobalPolicy.mockRejectedValueOnce(new Error("offline"));
+ await expect(h.applyMcpDatabaseAccess("c1")).rejects.toThrow("offline");
+ expect(h.mcpPolicyDraft.value).toEqual(draft);
+ expect(h.mcpPolicyBaseline.value).toEqual(baseline);
+ expect(h.mcpPolicySaving.value).toBe(false);
+ await h.applyMcpDatabaseAccess("c1");
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(false);
+ });
+ it("rejects database saves while controls are blocked or another save is pending", async () => {
+ const h = createHarness();
+ await expect(h.applyMcpDatabaseAccess("missing")).rejects.toThrow();
+ h.controlsDisabled.value = true;
+ await expect(h.applyMcpDatabaseAccess("c1")).rejects.toThrow();
+ h.controlsDisabled.value = false;
+ const pending = deferred<void>();
+ h.settingsStore.updateMcpGlobalPolicy.mockImplementationOnce(() => pending.promise);
+ const first = h.applyMcpDatabaseAccess("c1");
+ await expect(h.applyMcpDatabaseAccess("c2")).rejects.toThrow();
+ pending.resolve();
+ await first;
+ expect(h.settingsStore.updateMcpGlobalPolicy).toHaveBeenCalledOnce();
+ });
+ it("does not widen legacy saved permissions when applying database scope with an unrelated permissive draft", async () => {
+ const h = createHarness({
+ configured: true,
+ readOnly: true,
+ connectionPolicies: [{ connectionId: "c1", readOnly: false, allowDangerousSql: true, executionModeConfigured: true, executionModePolicyVersion: null, databaseScope: "selected", allowedDatabases: ["old"], databasePolicies: [], allowSalesforceDml: false }],
+ });
+ h.onMcpExecutionModeChange("safe_write");
+ h.onMcpDatabaseAccessChange("c1", { databaseScope: "selected", allowedDatabases: ["old", "new"], databasePolicies: [] });
+ await h.applyMcpDatabaseAccess("c1");
+ expect(h.settingsStore.mcpGlobalPolicy.connectionPolicies[0]).toMatchObject({ executionModePolicyVersion: 1, readOnly: true, allowDangerousSql: false, allowedDatabases: ["new", "old"] });
+ expect(h.mcpPolicyDraft.value.connectionPolicies[0].readOnly).toBe(false);
+ });
+
+ it("keeps untouched legacy database ceilings at saved levels instead of applying a pending parent grant", async () => {
+ const h = createHarness({
+ configured: true,
+ readOnly: true,
+ connectionPolicies: [
+ {
+ connectionId: "c1",
+ readOnly: false,
+ allowDangerousSql: true,
+ executionModeConfigured: true,
+ executionModePolicyVersion: null,
+ databaseScope: "selected",
+ allowedDatabases: ["old"],
+ databasePolicies: [{ databaseName: "old", readOnly: false, allowDangerousSql: true }],
+ allowSalesforceDml: false,
+ },
+ ],
+ });
+ h.onMcpExecutionModeChange("safe_write");
+ const access = editableDatabaseAccess(h.mcpPolicyDraft.value, "c1", { groups: [], order: [] }, [{ id: "c1", name: "First", db_type: "mysql" }] as ConnectionConfig[]);
+ h.onMcpDatabaseAccessChange("c1", { ...access, allowedDatabases: ["old", "new"] });
+ await h.applyMcpDatabaseAccess("c1");
+ expect(h.settingsStore.mcpGlobalPolicy.connectionPolicies[0].databasePolicies).toEqual([{ databaseName: "old", readOnly: true, allowDangerousSql: false }]);
+ expect(h.mcpPolicyDraft.value.readOnly).toBe(false);
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(true);
+ });
+ it("applies an explicitly edited legacy database override independently of the pending parent", async () => {
+ const h = createHarness({
+ configured: true,
+ readOnly: true,
+ connectionPolicies: [
+ {
+ connectionId: "c1",
+ readOnly: false,
+ allowDangerousSql: true,
+ executionModeConfigured: true,
+ executionModePolicyVersion: null,
+ databaseScope: "selected",
+ allowedDatabases: ["old"],
+ databasePolicies: [{ databaseName: "old", readOnly: false, allowDangerousSql: true }],
+ allowSalesforceDml: false,
+ },
+ ],
+ });
+ h.onMcpExecutionModeChange("safe_write");
+ h.onMcpDatabaseAccessChange("c1", { databaseScope: "selected", allowedDatabases: ["old"], databasePolicies: [{ databaseName: "old", readOnly: false, allowDangerousSql: true }] });
+ await h.applyMcpDatabaseAccess("c1");
+ expect(h.settingsStore.mcpGlobalPolicy.connectionPolicies[0]).toMatchObject({ readOnly: true, databasePolicies: [{ databaseName: "old", readOnly: false, allowDangerousSql: true }] });
+ expect(h.settingsStore.mcpGlobalPolicy.readOnly).toBe(true);
+ });
+
+ it("applies only the current toolset, keeping other tool, permission and custom-entry drafts for a later Apply", async () => {
+ const harness = createHarness({ configured: true, readOnly: true, queryTimeoutSecs: 30, pluginToolsMode: "auto" });
+ harness.stageMcpPolicy({ pluginToolsMode: "flat" });
+ harness.onMcpToolAllowedChange("dbx_nacos_publish_config", false);
+ harness.onMcpToolAllowedChange("dbx_execute_query", false);
+ harness.onMcpExecutionModeChange("safe_write");
+ harness.onMcpConnectionExecutionModeChange("c1", "safe_write");
+ harness.mcpPolicyDraft.value.queryTimeoutSecs = 99;
+ harness.mcpCustomToolInput.value = "dbx_custom__inspect";
+ harness.onMcpCustomToolAdd();
+ const draft = normalizeMcpGlobalPolicy(harness.mcpPolicyDraft.value);
+
+ await harness.applyMcpToolset("nacos.config");
+ const saved = harness.settingsStore.mcpGlobalPolicy;
+ expect(harness.settingsStore.updateMcpGlobalPolicy).toHaveBeenCalledWith({ allowedToolNames: expect.any(Array) });
+ expect(saved.allowedToolNames).not.toContain("dbx_nacos_publish_config");
+ expect(saved.allowedToolNames).toContain("dbx_execute_query");
+ expect(saved.allowedToolNames).toContain(MCP_PLUGIN_TOOLS_WILDCARD);
+ expect(saved.allowedToolNames).not.toContain("dbx_custom__inspect");
+ expect(saved).toMatchObject({ readOnly: true, connectionPolicies: [], queryTimeoutSecs: 30, pluginToolsMode: "auto" });
+ expect(harness.mcpPolicyDraft.value).toEqual(draft);
+ expect(harness.mcpPolicyBaseline.value).toEqual(saved);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(true);
+ expect(harness.settingsStore.updateDesktopSettings).not.toHaveBeenCalled();
+ expect(harness.savePluginMcpGrant).not.toHaveBeenCalled();
+ expect(await harness.applySettingsForResult()).toBe(true);
+ expect(harness.settingsStore.mcpGlobalPolicy).toEqual(draft);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ });
+
+ it("discarding remaining drafts keeps the toolset already applied from its details", async () => {
+ const harness = createHarness({ readOnly: true, allowedToolNames: ["dbx_execute_query", "dbx_nacos_get_config", "dbx_helper__*", "custom-tool"] });
+ harness.onMcpToolAllowedChange("dbx_nacos_publish_config", true);
+ harness.onMcpToolAllowedChange("dbx_execute_query", false);
+ harness.onMcpExecutionModeChange("safe_write");
+ await harness.applyMcpToolset("nacos.config");
+ expect(harness.settingsStore.mcpGlobalPolicy.allowedToolNames).toEqual(["dbx_execute_query", "dbx_nacos_get_config", "dbx_helper__*", "custom-tool", "dbx_nacos_publish_config"]);
+ harness.discardUnsavedSettingsAndClose();
+ expect(harness.mcpPolicyDraft.value).toEqual(harness.settingsStore.mcpGlobalPolicy);
+ expect(harness.mcpPolicyDraft.value.readOnly).toBe(true);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).toHaveBeenCalledOnce();
+ });
+
+ it("clears the outer dirty state after applying toolsets in a different order from their edits", async () => {
+ const harness = createHarness({ allowedToolNames: [] });
+ harness.onMcpToolAllowedChange("dbx_nacos_get_config", true);
+ harness.onMcpToolAllowedChange("dbx_execute_query", true);
+ await harness.applyMcpToolset("sql.query");
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(true);
+ await harness.applyMcpToolset("nacos.config");
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ expect(harness.mcpPolicyDraft.value).toEqual(harness.settingsStore.mcpGlobalPolicy);
+ });
+
+ it("preserves the baseline and draft after failure and saves the same toolset on retry", async () => {
+ const harness = createHarness();
+ harness.onMcpToolAllowedChange("dbx_nacos_publish_config", false);
+ const baseline = normalizeMcpGlobalPolicy(harness.mcpPolicyBaseline.value);
+ const draft = normalizeMcpGlobalPolicy(harness.mcpPolicyDraft.value);
+ harness.settingsStore.updateMcpGlobalPolicy.mockRejectedValueOnce(new Error("disk full"));
+ await expect(harness.applyMcpToolset("nacos.config")).rejects.toThrow("disk full");
+ expect(harness.mcpPolicyBaseline.value).toEqual(baseline);
+ expect(harness.settingsStore.mcpGlobalPolicy).toEqual(baseline);
+ expect(harness.mcpPolicyDraft.value).toEqual(draft);
+ expect(harness.mcpPolicySaving.value).toBe(false);
+ await harness.applyMcpToolset("nacos.config");
+ expect(harness.settingsStore.updateMcpGlobalPolicy).toHaveBeenCalledTimes(2);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ });
+
+ it("blocks partial saves without a complete catalog or while another policy save is pending", async () => {
+ const harness = createHarness();
+ harness.mcpToolCatalogLoading.value = true;
+ await expect(harness.applyMcpToolset("sql.query")).rejects.toThrow();
+ harness.mcpToolCatalogLoading.value = false;
+ await expect(harness.applyMcpToolset("unknown")).rejects.toThrow();
+ const pending = deferred<void>();
+ harness.settingsStore.updateMcpGlobalPolicy.mockReturnValueOnce(pending.promise);
+ harness.onMcpToolAllowedChange("dbx_execute_query", false);
+ const saving = harness.applyMcpToolset("sql.query");
+ expect(harness.mcpPolicySaving.value).toBe(true);
+ await expect(harness.applyMcpToolset("nacos.config")).rejects.toThrow();
+ expect(harness.settingsStore.updateMcpGlobalPolicy).toHaveBeenCalledOnce();
+ pending.resolve();
+ await saving;
+ });
+
+ it("keeps a scope saved while permission context refresh is waiting for the plugin list", async () => {
+ const harness = createHarness();
+ const previous: McpAccessPolicy = { version: 2, defaultAccess: "read", rules: [] };
+ const saved: McpAccessPolicy = { ...previous, rules: [{ target: { kind: "connection", id: "nacos" }, subScope: "none", subScopeKind: "namespace" }] };
+ harness.mcpAccessPolicy.value = previous;
+ harness.loadMcpAccessPolicy.mockResolvedValueOnce(previous);
+ const plugins = deferred<Array<{ manifest: { id: string } }>>();
+ harness.listPlugins.mockReturnValueOnce(plugins.promise);
+ const loading = harness.loadMcpPluginScopeContext();
+ // The scope editor emits the policy returned by its immediate save.
+ harness.mcpAccessPolicy.value = saved;
+ plugins.resolve([{ manifest: { id: "io.dbx.scope" } }]);
+ await loading;
+ expect(harness.mcpAccessPolicy.value).toEqual(saved);
+ expect(harness.mcpInstalledPluginsForScopes.value).toEqual([{ manifest: { id: "io.dbx.scope" } }]);
+ });
+
+ it("ignores an older permission context refresh that finishes after a newer refresh", async () => {
+ const harness = createHarness();
+ const first = deferred<McpAccessPolicy>();
+ harness.loadMcpAccessPolicy.mockReturnValueOnce(first.promise);
+ harness.listPlugins.mockResolvedValueOnce([{ manifest: { id: "io.dbx.old" } }]);
+ const loading = harness.loadMcpPluginScopeContext();
+ const latest: McpAccessPolicy = { version: 2, defaultAccess: "write", rules: [{ target: { kind: "connection", id: "nacos" }, subScope: "selected" }] };
+ harness.loadMcpAccessPolicy.mockResolvedValueOnce(latest);
+ harness.listPlugins.mockResolvedValueOnce([{ manifest: { id: "io.dbx.new" } }]);
+ await harness.loadMcpPluginScopeContext();
+ first.resolve({ version: 2, defaultAccess: "read", rules: [] });
+ await loading;
+ expect(harness.mcpAccessPolicy.value).toEqual(latest);
+ expect(harness.mcpInstalledPluginsForScopes.value).toEqual([{ manifest: { id: "io.dbx.new" } }]);
+ });
+
+ it("opens MCP history after closing settings when there is no draft", () => {
+ const harness = createHarness();
+ harness.clickMcpCallHistory();
+ expect(harness.emit).toHaveBeenCalledWith("update:open", false);
+ expect(harness.openMcpCallHistory).toHaveBeenCalledOnce();
+ expect(harness.emit.mock.invocationCallOrder[0]).toBeLessThan(harness.openMcpCallHistory.mock.invocationCallOrder[0]);
+ });
+
+ it("keeps MCP history closed when the user cancels leaving an unsaved draft", async () => {
+ const harness = createHarness({ readOnly: true });
+ harness.onMcpExecutionModeChange("safe_write");
+ harness.clickMcpCallHistory();
+ expect(harness.showUnsavedSettingsCloseConfirm.value).toBe(true);
+ expect(harness.openMcpCallHistory).not.toHaveBeenCalled();
+ harness.cancelUnsavedSettingsClose();
+ expect(harness.emit).not.toHaveBeenCalled();
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(true);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ await harness.applySettingsAndClose();
+ expect(harness.emit).toHaveBeenCalledWith("update:open", false);
+ expect(harness.openMcpCallHistory).not.toHaveBeenCalled();
+ });
+
+ it("opens MCP history once after confirming draft discard, without persisting it", () => {
+ const harness = createHarness({ readOnly: true });
+ harness.onMcpExecutionModeChange("safe_write");
+ harness.clickMcpCallHistory();
+ expect(harness.openMcpCallHistory).not.toHaveBeenCalled();
+ harness.discardUnsavedSettingsAndClose();
+ expect(harness.mcpPolicyDraft.value.readOnly).toBe(true);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ expect(harness.emit).toHaveBeenCalledWith("update:open", false);
+ expect(harness.openMcpCallHistory).toHaveBeenCalledOnce();
+ expect(harness.emit.mock.invocationCallOrder[0]).toBeLessThan(harness.openMcpCallHistory.mock.invocationCallOrder[0]);
+ harness.requestCloseSettings(false);
+ expect(harness.openMcpCallHistory).toHaveBeenCalledOnce();
+ });
+
+ it("changes only global execution defaults, preserving tool switches and resource exceptions until Apply", async () => {
+ const harness = createHarness({
+ readOnly: true,
+ allowedToolNames: ["dbx_execute_query", "dbx_helper__inspect"],
+ allowedConnectionIds: ["c1", "c2", "inherited"],
+ groupPolicies: [{ groupId: "team", readOnly: true, allowDangerousSql: false }],
+ connectionPolicies: [
+ {
+ connectionId: "c1",
+ executionModeConfigured: true,
+ executionModePolicyVersion: 1,
+ readOnly: true,
+ allowDangerousSql: false,
+ databaseScope: "selected",
+ allowedDatabases: ["billing"],
+ databasePolicies: [{ databaseName: "billing", readOnly: false, allowDangerousSql: false }],
+ allowSalesforceDml: false,
+ },
+ ],
+ });
+ const original = structuredClone(harness.settingsStore.mcpGlobalPolicy);
+ const layout: SidebarLayout = {
+ groups: [{ id: "team", name: "Team", collapsed: false }],
+ order: [
+ { type: "group", id: "team", children: [{ type: "connection", id: "c2" }] },
+ { type: "connection", id: "c1" },
+ { type: "connection", id: "inherited" },
+ ],
+ };
+ const connections = ["c1", "c2", "inherited"].map((id) => ({ id, name: id, db_type: "mysql" }) as ConnectionConfig);
+ harness.mcpToolCatalog.value = null; // Permission changes do not depend on loading tools.
+ harness.onMcpExecutionModeChange("safe_write");
+ expect(harness.mcpPolicyDraft.value).toEqual({ ...original, readOnly: false });
+ expect(harness.settingsStore.mcpGlobalPolicy).toEqual(original);
+ const rows = buildMcpAccessTreeRows(harness.mcpPolicyDraft.value, layout, connections, { expandedGroupIds: new Set(["team"]), expandedConnectionIds: new Set(["c1"]) });
+ expect(rows.find((row) => row.key === "connection:inherited")).toMatchObject({ visible: true, effective: "safe_write", source: { kind: "global" } });
+ expect(rows.find((row) => row.key === "connection:c1")).toMatchObject({ effective: "read_only", source: { kind: "connection" } });
+ expect(rows.find((row) => row.key === "connection:c2")).toMatchObject({ effective: "read_only", source: { kind: "group" } });
+ expect(rows.find((row) => row.key === "database:c1:billing")).toMatchObject({ effective: "safe_write", source: { kind: "database" } });
+ expect(harness.savePluginMcpGrant).not.toHaveBeenCalled();
+ expect(await harness.applySettingsForResult()).toBe(true);
+ expect(harness.settingsStore.mcpGlobalPolicy).toEqual({ ...original, readOnly: false, configured: true });
+ });
+
+ it("preserves legacy semantics on unrelated saves and migrates only on deliberate selection", async () => {
+ const h = createHarness({ configured: true, promptHighRiskSql: true });
+ h.stageMcpPolicy({ queryTimeoutSecs: 90 });
+ expect(await h.applySettingsForResult()).toBe(true);
+ expect(h.settingsStore.mcpGlobalPolicy.promptHighRiskSql).toBe(true);
+ expect(h.settingsStore.mcpGlobalPolicy.callConfirmation).toBeUndefined();
+ h.onMcpHighRiskConfirmationChange(true);
+ expect(h.settingsStore.mcpGlobalPolicy.promptHighRiskSql).toBe(true);
+ expect(h.mcpPolicyDraft.value).toMatchObject({ promptHighRiskSql: false, callConfirmation: "high_risk" });
+ h.discardUnsavedSettingsAndClose();
+ expect(h.mcpPolicyDraft.value.promptHighRiskSql).toBe(true);
+ h.onMcpHighRiskConfirmationChange(true);
+ expect(await h.applySettingsForResult()).toBe(true);
+ expect(h.settingsStore.mcpGlobalPolicy).toMatchObject({ promptHighRiskSql: false, callConfirmation: "high_risk" });
+ h.onMcpHighRiskConfirmationChange(false);
+ expect(await h.applySettingsForResult()).toBe(true);
+ expect(h.settingsStore.mcpGlobalPolicy.promptHighRiskSql).toBe(false);
+ expect(h.settingsStore.mcpGlobalPolicy.callConfirmation).toBeUndefined();
+ });
+
+ it("keeps a pending safety migration when applying only a toolset", async () => {
+ const h = createHarness({ configured: true, promptHighRiskSql: true });
+ h.onMcpHighRiskConfirmationChange(true);
+ h.onMcpToolAllowedChange("dbx_execute_query", false);
+ await h.applyMcpToolset("sql.query");
+ expect(h.settingsStore.mcpGlobalPolicy.promptHighRiskSql).toBe(true);
+ expect(h.mcpPolicyDraft.value.callConfirmation).toBe("high_risk");
+ expect(h.mcpPolicyHasUnsavedChanges()).toBe(true);
+ });
+
+ it("discards default permission and confirmation edits without changing saved settings", () => {
+ const harness = createHarness({ readOnly: false, promptHighRiskSql: true, allowedToolNames: ["dbx_execute_query"] });
+ const original = structuredClone(harness.settingsStore.mcpGlobalPolicy);
+ harness.onMcpHighRiskConfirmationChange(false);
+ harness.onMcpExecutionModeChange("read_only");
+ harness.requestCloseSettings(false);
+ expect(harness.showUnsavedSettingsCloseConfirm.value).toBe(true);
+ harness.discardUnsavedSettingsAndClose();
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ expect(harness.settingsStore.mcpGlobalPolicy).toEqual(original);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ });
+
+ it("requires confirmation for full access and leaves the draft intact when cancelled", () => {
+ const harness = createHarness({ readOnly: false, promptHighRiskSql: true });
+ const original = structuredClone(harness.settingsStore.mcpGlobalPolicy);
+ harness.onMcpExecutionModeChange("high_risk_write");
+ expect(harness.mcpPolicyConfirmation.value?.message).toBe("settings.mcpExecutionModeHighRiskConfirm");
+ expect(harness.confirm).not.toHaveBeenCalled();
+ harness.mcpPolicyConfirmation.value = null;
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ harness.onMcpExecutionModeChange("high_risk_write");
+ harness.confirmMcpPolicyChange();
+ expect(harness.mcpPolicyConfirmation.value).toBeNull();
+ expect(harness.mcpPolicyDraft.value).toEqual({ ...original, allowDangerousSql: true });
+ harness.onMcpHighRiskConfirmationChange(true);
+ expect(harness.mcpPolicyDraft.value.callConfirmation).toBe("high_risk");
+ expect(harness.mcpPolicyDraft.value.promptHighRiskSql).toBe(false);
+ });
+
+ it("keeps default permission controls locked and preserves confirmation for resource overrides with any default", () => {
+ const harness = createHarness({ readOnly: true });
+ harness.onMcpHighRiskConfirmationChange(true);
+ expect(harness.mcpPolicyDraft.value.callConfirmation).toBe("high_risk");
+ expect(harness.mcpPolicyDraft.value.promptHighRiskSql).toBe(false);
+ harness.controlsDisabled.value = true;
+ harness.onMcpExecutionModeChange("high_risk_write");
+ expect(harness.confirm).not.toHaveBeenCalled();
+ expect(harness.mcpPolicyDraft.value.readOnly).toBe(true);
+ harness.controlsDisabled.value = false;
+ harness.onMcpExecutionModeChange("safe_write");
+ harness.onMcpHighRiskConfirmationChange(true);
+ expect(harness.mcpPolicyDraft.value.callConfirmation).toBe("high_risk");
+ expect(harness.mcpPolicyDraft.value.promptHighRiskSql).toBe(false);
+ harness.controlsDisabled.value = true;
+ harness.onMcpHighRiskConfirmationChange(false);
+ expect(harness.mcpPolicyDraft.value.callConfirmation).toBe("high_risk");
+ expect(harness.mcpPolicyDraft.value.promptHighRiskSql).toBe(false);
+ });
+
+ it.each(["group", "connection", "database"] as const)("confirms a %s full-access edit exactly once and preserves cancelled drafts", (kind) => {
+ const harness = createHarness({ readOnly: true });
+ if (kind === "database") {
+ harness.onMcpConnectionExecutionModeChange("c1", "safe_write");
+ const connection = harness.mcpPolicyDraft.value.connectionPolicies[0];
+ connection.databaseScope = "selected";
+ connection.allowedDatabases = ["billing"];
+ }
+ const original = JSON.parse(JSON.stringify(harness.mcpPolicyDraft.value));
+ const change = () => (kind === "group" ? harness.onMcpGroupExecutionModeChange("team", "high_risk_write") : kind === "connection" ? harness.onMcpConnectionExecutionModeChange("c1", "high_risk_write") : harness.onMcpDatabaseExecutionModeChange("c1", "billing", "high_risk_write"));
+ change();
+ expect(harness.mcpPolicyConfirmation.value).not.toBeNull();
+ expect(harness.confirm).not.toHaveBeenCalled();
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ harness.mcpPolicyConfirmation.value = null; // cancel / Escape / outside close
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ change();
+ harness.confirmMcpPolicyChange();
+ expect(harness.mcpPolicyConfirmation.value).toBeNull();
+ expect(harness.mcpPolicyDraft.value).not.toEqual(original);
+ });
+
+ it.each(["visibility", "databaseScope", "databaseRemoval"] as const)("requires an in-app decision before changing %s and discarding exceptions", (kind) => {
+ const harness = createHarness({
+ allowedConnectionIds: ["c1"],
+ connectionPolicies: [
+ {
+ connectionId: "c1",
+ readOnly: false,
+ allowDangerousSql: false,
+ executionModeConfigured: true,
+ executionModePolicyVersion: 1,
+ databaseScope: "selected",
+ allowedDatabases: ["main"],
+ databasePolicies: [{ databaseName: "main", readOnly: true, allowDangerousSql: false }],
+ allowSalesforceDml: false,
+ },
+ ],
+ });
+ const original = JSON.parse(JSON.stringify(harness.mcpPolicyDraft.value));
+ const change = () => (kind === "visibility" ? harness.onMcpTreeScopeMode("all") : kind === "databaseScope" ? harness.onMcpTreeDatabaseScope("c1", "all") : harness.onMcpTreeDatabaseAllowed("c1", "main", false));
+ change();
+ expect(harness.mcpPolicyConfirmation.value).not.toBeNull();
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ harness.mcpPolicyConfirmation.value = null;
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ change();
+ harness.confirmMcpPolicyChange();
+ expect(harness.mcpPolicyConfirmation.value).toBeNull();
+ expect(harness.mcpPolicyDraft.value).not.toEqual(original);
+ expect(harness.confirm).not.toHaveBeenCalled();
+ });
+
+ it("drops pending permission changes when closed or controls become unavailable", () => {
+ const harness = createHarness({ readOnly: true });
+ const original = structuredClone(harness.settingsStore.mcpGlobalPolicy);
+ harness.onMcpConnectionExecutionModeChange("c1", "high_risk_write");
+ harness.controlsDisabled.value = true;
+ harness.confirmMcpPolicyChange();
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ expect(harness.mcpPolicyConfirmation.value).toBeNull();
+ harness.controlsDisabled.value = false;
+ harness.onMcpGroupExecutionModeChange("team", "high_risk_write");
+ harness.requestCloseSettings(false);
+ harness.confirmMcpPolicyChange();
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ });
+
+ it("keeps confirmation when changing the default around resource-level write overrides", () => {
+ const harness = createHarness({ readOnly: false, promptHighRiskSql: true });
+ harness.onMcpConnectionExecutionModeChange("c1", "safe_write");
+ harness.onMcpExecutionModeChange("read_only");
+ expect(harness.mcpPolicyDraft.value.promptHighRiskSql).toBe(true);
+ expect(harness.mcpPolicyDraft.value.connectionPolicies[0].readOnly).toBe(false);
+ harness.onMcpExecutionModeChange("high_risk_write");
+ harness.confirmMcpPolicyChange();
+ expect(harness.mcpPolicyDraft.value.promptHighRiskSql).toBe(true);
+ });
+
+ it("restores inheritance at each resource level without rewriting the default or enabled tools", () => {
+ const harness = createHarness({ readOnly: true, allowedToolNames: ["dbx_execute_query"] });
+ harness.onMcpGroupExecutionModeChange("team", "safe_write");
+ harness.onMcpConnectionExecutionModeChange("c1", "safe_write");
+ const connection = harness.mcpPolicyDraft.value.connectionPolicies[0];
+ connection.databaseScope = "selected";
+ connection.allowedDatabases = ["billing"];
+ harness.onMcpDatabaseExecutionModeChange("c1", "billing", "read_only");
+ expect(harness.mcpPolicyDraft.value.connectionPolicies[0].databasePolicies).toHaveLength(1);
+ harness.onMcpDatabaseExecutionModeChange("c1", "billing", "inherit");
+ harness.onMcpConnectionExecutionModeChange("c1", "inherit");
+ harness.onMcpGroupExecutionModeChange("team", "inherit");
+ expect(harness.mcpPolicyDraft.value).toMatchObject({ readOnly: true, allowedToolNames: ["dbx_execute_query"], groupPolicies: [], connectionPolicies: [{ executionModeConfigured: false, databaseScope: "selected", allowedDatabases: ["billing"], databasePolicies: [] }] });
+ });
+
+ it("stages a whole category and discards it without writing either persistence boundary", () => {
+ const harness = createHarness({ readOnly: true, allowedConnectionIds: ["production"], allowedGroupIds: ["team"] });
+ const original = structuredClone(harness.settingsStore.mcpGlobalPolicy);
+ harness.onMcpCategoryAllowedChange("nacos", false);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(true);
+ expect(harness.mcpPolicyDraft.value.allowedToolNames).toEqual(["dbx_execute_query", "dbx_future_query", "dbx_add_connection", MCP_PLUGIN_TOOLS_WILDCARD]);
+ expect(harness.mcpPolicyDraft.value).toMatchObject({ readOnly: true, allowedConnectionIds: ["production"], allowedGroupIds: ["team"] });
+ expect(harness.settingsStore.mcpGlobalPolicy).toEqual(original);
+ harness.requestCloseSettings(false);
+ expect(harness.showUnsavedSettingsCloseConfirm.value).toBe(true);
+ expect(harness.emit).not.toHaveBeenCalled();
+ harness.discardUnsavedSettingsAndClose();
+ expect(harness.mcpPolicyDraft.value).toEqual(original);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ expect(harness.emit).toHaveBeenCalledExactlyOnceWith("update:open", false);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ expect(harness.savePluginMcpGrant).not.toHaveBeenCalled();
+ });
+
+ it("persists the category only through the actual Apply path and refreshes its baseline", async () => {
+ const harness = createHarness();
+ harness.onMcpCategoryAllowedChange("nacos", false);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ expect(await harness.applySettingsForResult()).toBe(true);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).toHaveBeenCalledTimes(1);
+ expect(harness.settingsStore.mcpGlobalPolicy.allowedToolNames).toEqual(["dbx_execute_query", "dbx_future_query", "dbx_add_connection", MCP_PLUGIN_TOOLS_WILDCARD]);
+ expect(harness.mcpPolicyDraft.value).toEqual(harness.settingsStore.mcpGlobalPolicy);
+ expect(harness.mcpPolicyBaseline.value).toEqual(harness.settingsStore.mcpGlobalPolicy);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ expect(harness.savePluginMcpGrant).not.toHaveBeenCalled();
+ await harness.applySettingsAndClose();
+ expect(harness.settingsStore.updateMcpGlobalPolicy).toHaveBeenCalledTimes(1);
+ expect(harness.emit).toHaveBeenCalledWith("update:open", false);
+ });
+
+ it("keeps a failed Apply draft retryable and does not close the settings dialog", async () => {
+ const harness = createHarness();
+ const original = structuredClone(harness.settingsStore.mcpGlobalPolicy);
+ harness.onMcpCategoryAllowedChange("nacos", false);
+ harness.settingsStore.updateMcpGlobalPolicy.mockRejectedValueOnce(new Error("disk unavailable"));
+ await harness.applySettingsAndClose();
+ expect(harness.emit).not.toHaveBeenCalled();
+ expect(harness.toast).toHaveBeenCalledWith("settings.applyFailed", 5000);
+ expect(harness.settingsStore.mcpGlobalPolicy).toEqual(original);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(true);
+ expect(harness.mcpPolicySaving.value).toBe(false);
+ expect(await harness.applySettingsForResult()).toBe(true);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ });
+
+ it("does not undo an immediately saved plugin grant when built-in changes are discarded", async () => {
+ const harness = createHarness();
+ harness.onMcpCategoryAllowedChange("nacos", false);
+ const grant = { ...plugin.grant, external: true };
+ const saved = await harness.persistMcpPluginGrant(plugin.pluginId, grant, true);
+ expect(harness.savePluginMcpGrant).toHaveBeenCalledExactlyOnceWith(plugin.pluginId, grant, true);
+ expect(harness.persistedPlugin.value.grant.external).toBe(true);
+ expect(harness.mcpPluginViews.value?.[0]).toEqual(saved);
+ harness.discardUnsavedSettingsAndClose();
+ expect(harness.mcpPolicyDraft.value.allowedToolNames).toBeNull();
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ expect(harness.persistedPlugin.value.grant.external).toBe(true);
+ expect(harness.mcpPluginViews.value?.[0].grant.external).toBe(true);
+ expect(harness.savePluginMcpGrant).toHaveBeenCalledTimes(1);
+ });
+
+ it("updates the cached plugin after a late save even without a child saved event", async () => {
+ const harness = createHarness();
+ let resolve!: (view: PluginMcpView) => void;
+ harness.savePluginMcpGrant.mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const grant = { ...plugin.grant, external: true };
+ const pending = harness.persistMcpPluginGrant(plugin.pluginId, grant, false);
+ harness.discardUnsavedSettingsAndClose();
+ const saved = { ...plugin, grant };
+ resolve(saved);
+ await expect(pending).resolves.toEqual(saved);
+ expect(harness.mcpPluginViews.value?.[0]).toEqual(saved);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ });
+
+ it("leaves plugin state unchanged after a failed immediate save", async () => {
+ const harness = createHarness();
+ harness.savePluginMcpGrant.mockRejectedValueOnce(new Error("plugin unavailable"));
+ await expect(harness.persistMcpPluginGrant(plugin.pluginId, { ...plugin.grant, external: true }, false)).rejects.toThrow("plugin unavailable");
+ expect(harness.mcpPluginViews.value?.[0]).toEqual(plugin);
+ expect(harness.persistedPlugin.value.grant.external).toBe(false);
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ });
+
+ it("keeps a grant saved during refresh while accepting refreshed and newly discovered plugins", async () => {
+ const harness = createHarness();
+ const other = { ...structuredClone(plugin), pluginId: "io.dbx.other", pluginName: "Other" };
+ const refreshedOther = { ...other, version: "2.0.0", grant: { ...other.grant, external: true } };
+ const discovered = { ...structuredClone(plugin), pluginId: "io.dbx.new", pluginName: "New" };
+ harness.mcpPluginViews.value = [structuredClone(plugin), other];
+ const discovery = deferred<PluginMcpView[]>();
+ harness.listPluginMcpViews.mockReturnValueOnce(discovery.promise);
+ const refreshing = harness.loadMcpPluginViews();
+ expect(harness.mcpPluginViewsLoading.value).toBe(true);
+ const saved = await harness.persistMcpPluginGrant(plugin.pluginId, { ...plugin.grant, external: true }, true);
+ discovery.resolve([structuredClone(plugin), refreshedOther, discovered]);
+ await refreshing;
+ expect(harness.mcpPluginViews.value).toEqual([saved, refreshedOther, discovered]);
+ expect(harness.mcpPluginViewsLoading.value).toBe(false);
+ expect(harness.mcpPluginViewsError.value).toBe("");
+ });
+
+ it("applies a save that finishes after refresh without reverting other refreshed plugins", async () => {
+ const harness = createHarness();
+ const refreshed = { ...structuredClone(plugin), version: "2.0.0" };
+ const other = { ...structuredClone(plugin), pluginId: "io.dbx.other", pluginName: "Other", version: "3.0.0" };
+ const discovery = deferred<PluginMcpView[]>();
+ const saving = deferred<PluginMcpView>();
+ harness.listPluginMcpViews.mockReturnValueOnce(discovery.promise);
+ harness.savePluginMcpGrant.mockReturnValueOnce(saving.promise);
+ const refreshing = harness.loadMcpPluginViews();
+ const grant = { ...plugin.grant, external: true };
+ const save = harness.persistMcpPluginGrant(plugin.pluginId, grant, true);
+ discovery.resolve([refreshed, other]);
+ await refreshing;
+ expect(harness.mcpPluginViews.value).toEqual([refreshed, other]);
+ const saved = { ...refreshed, grant };
+ saving.resolve(saved);
+ await save;
+ expect(harness.mcpPluginViews.value).toEqual([saved, other]);
+ });
+
+ it("accepts refreshed plugin data when a concurrent grant save fails", async () => {
+ const harness = createHarness();
+ const discovery = deferred<PluginMcpView[]>();
+ const saving = deferred<PluginMcpView>();
+ harness.listPluginMcpViews.mockReturnValueOnce(discovery.promise);
+ harness.savePluginMcpGrant.mockReturnValueOnce(saving.promise);
+ const refreshing = harness.loadMcpPluginViews();
+ const save = harness.persistMcpPluginGrant(plugin.pluginId, { ...plugin.grant, external: true }, true);
+ saving.reject(new Error("save unavailable"));
+ await expect(save).rejects.toThrow("save unavailable");
+ const refreshed = { ...structuredClone(plugin), version: "2.0.0", discoveryError: "probe unavailable" };
+ discovery.resolve([refreshed]);
+ await refreshing;
+ expect(harness.mcpPluginViews.value).toEqual([refreshed]);
+ expect(harness.mcpPluginViews.value?.[0].grant.external).toBe(false);
+ expect(harness.mcpPluginViewsLoading.value).toBe(false);
+ });
+
+ it("rejects duplicate saves for one plugin while allowing another plugin to save concurrently", async () => {
+ const harness = createHarness();
+ const other = { ...structuredClone(plugin), pluginId: "io.dbx.other", pluginName: "Other" };
+ const grant = { ...plugin.grant, external: true };
+ const saved = { ...structuredClone(plugin), grant };
+ const savedOther = { ...other, grant };
+ harness.mcpPluginViews.value = [structuredClone(plugin), other];
+ const saving = deferred<PluginMcpView>();
+ harness.savePluginMcpGrant.mockImplementation((id) => (id === plugin.pluginId ? saving.promise : Promise.resolve(savedOther)));
+ const first = harness.persistMcpPluginGrant(plugin.pluginId, grant, true);
+ await expect(harness.persistMcpPluginGrant(plugin.pluginId, grant, true)).rejects.toThrow("settings.mcpBrowser.pluginSaving");
+ expect(harness.savePluginMcpGrant).toHaveBeenCalledTimes(1);
+ await expect(harness.persistMcpPluginGrant(other.pluginId, grant, true)).resolves.toEqual(savedOther);
+ expect(harness.savePluginMcpGrant).toHaveBeenCalledTimes(2);
+ expect(harness.mcpPluginViews.value?.[1]).toEqual(savedOther);
+ saving.resolve(saved);
+ await expect(first).resolves.toEqual(saved);
+ await expect(harness.persistMcpPluginGrant(plugin.pluginId, grant, true)).resolves.toEqual(saved);
+ expect(harness.savePluginMcpGrant).toHaveBeenCalledTimes(3);
+ expect(harness.mcpPluginViews.value).toEqual([saved, savedOther]);
+ });
+
+ it("unlocks a plugin after a failed save so that a later retry can succeed", async () => {
+ const harness = createHarness();
+ const saving = deferred<PluginMcpView>();
+ harness.savePluginMcpGrant.mockReturnValueOnce(saving.promise);
+ const grant = { ...plugin.grant, external: true };
+ const first = harness.persistMcpPluginGrant(plugin.pluginId, grant, true);
+ saving.reject(new Error("save interrupted"));
+ await expect(first).rejects.toThrow("save interrupted");
+ const saved = { ...structuredClone(plugin), grant };
+ harness.savePluginMcpGrant.mockResolvedValueOnce(saved);
+ await expect(harness.persistMcpPluginGrant(plugin.pluginId, grant, true)).resolves.toEqual(saved);
+ expect(harness.savePluginMcpGrant).toHaveBeenCalledTimes(2);
+ expect(harness.mcpPluginViews.value).toEqual([saved]);
+ });
+
+ it("rejects category mutations while catalog loading, load failure or policy lock is active", () => {
+ const harness = createHarness();
+ harness.mcpToolCatalogLoading.value = true;
+ harness.onMcpCategoryAllowedChange("nacos", false);
+ harness.mcpToolCatalogLoading.value = false;
+ harness.mcpToolCatalogError.value = "catalog failed";
+ harness.onMcpCategoryAllowedChange("nacos", false);
+ harness.mcpToolCatalogError.value = "";
+ harness.controlsDisabled.value = true;
+ harness.onMcpCategoryAllowedChange("nacos", false);
+ expect(harness.mcpPolicyDraft.value.allowedToolNames).toBeNull();
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ });
+
+ it("adding a custom tool preserves the complete runtime catalog and plugin wildcard from an unrestricted policy", () => {
+ const harness = createHarness();
+ harness.mcpCustomToolInput.value = " dbx_custom__inspect ";
+ harness.onMcpCustomToolAdd();
+ expect(harness.mcpPolicyDraft.value.allowedToolNames).toEqual(["dbx_execute_query", "dbx_future_query", "dbx_nacos_get_config", "dbx_nacos_publish_config", "dbx_nacos_list_services", "dbx_add_connection", MCP_PLUGIN_TOOLS_WILDCARD, "dbx_custom__inspect"]);
+ expect(harness.mcpCustomToolInput.value).toBe("");
+ expect(harness.settingsStore.mcpGlobalPolicy.allowedToolNames).toBeNull();
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ });
+
+ it.each(["missing", "loading", "error", "policy"])("does not add a custom tool or clear its input while the catalog is locked: %s", (reason) => {
+ const harness = createHarness();
+ harness.mcpCustomToolInput.value = "dbx_custom__inspect";
+ if (reason === "missing") harness.mcpToolCatalog.value = null;
+ if (reason === "loading") harness.mcpToolCatalogLoading.value = true;
+ if (reason === "error") harness.mcpToolCatalogError.value = "catalog unavailable";
+ if (reason === "policy") harness.controlsDisabled.value = true;
+ harness.onMcpCustomToolAdd();
+ expect(harness.mcpPolicyDraft.value.allowedToolNames).toBeNull();
+ expect(harness.mcpCustomToolInput.value).toBe("dbx_custom__inspect");
+ expect(harness.mcpPolicyHasUnsavedChanges()).toBe(false);
+ expect(harness.settingsStore.updateMcpGlobalPolicy).not.toHaveBeenCalled();
+ });
+});
+
+describe("MCP policy corruption recovery", () => {
+ it("uses the in-app confirmation on desktop as well as web", () => {
+ expect(declaration("recoverMcpAccessPolicy")).not.toContain("window.confirm");
+ expect(dialogSource).toContain(':open="mcpPolicyConfirmationDialog.open"');
+ expect(declaration("mcpPolicyConfirmationDialog")).toContain("mcpPolicyRecoveryConfirmation.value");
+ expect(declaration("confirmMcpPolicyChange")).toContain("return recoverMcpAccessPolicy()");
+ });
+ it("shows access-policy errors and clears stale permission data", async () => {
+ const h = createHarness();
+ h.mcpAccessPolicy.value = { version: 2, defaultAccess: "full", rules: [] };
+ h.loadMcpAccessPolicy.mockRejectedValueOnce(new Error("MCP_POLICY_UNAVAILABLE: invalid MCP access policy"));
+ await h.loadMcpPluginScopeContext();
+ expect(h.mcpAccessPolicy.value).toBeNull();
+ expect(h.mcpAccessPolicyError.value).toContain("invalid MCP access policy");
+ expect(h.mcpAccessPolicyLoading.value).toBe(false);
+ await h.loadMcpPluginScopeContext();
+ expect(h.mcpAccessPolicyError.value).toBe("");
+ });
+
+ it("does not treat plugin discovery failure as policy corruption", async () => {
+ const h = createHarness();
+ h.listPlugins.mockRejectedValueOnce(new Error("plugin unavailable"));
+ await h.loadMcpPluginScopeContext();
+ expect(h.mcpAccessPolicy.value?.defaultAccess).toBe("read");
+ expect(h.mcpAccessPolicyError.value).toBe("");
+ });
+
+ it("requires explicit confirmation and reloads the saved policy after recovery", async () => {
+ const h = createHarness();
+ h.mcpPolicyRecoveryConfirmation.value = true;
+ h.onMcpPolicyConfirmationOpenChange(false);
+ await h.recoverMcpAccessPolicy();
+ expect(h.resetInvalidMcpAccessPolicy).not.toHaveBeenCalled();
+ h.mcpPolicyRecoveryConfirmation.value = true;
+ const pending = h.confirmMcpPolicyChange();
+ await h.recoverMcpAccessPolicy(); // A second confirm cannot start another reset.
+ await pending;
+ expect(h.resetInvalidMcpAccessPolicy).toHaveBeenCalledOnce();
+ expect(h.settingsStore.initMcpGlobalPolicy).toHaveBeenCalledWith(true);
+ expect(h.mcpPolicyRecovering.value).toBe(false);
+ h.resetInvalidMcpAccessPolicy.mockRejectedValueOnce(new Error("backup failed"));
+ h.mcpPolicyRecoveryConfirmation.value = true;
+ await h.recoverMcpAccessPolicy();
+ expect(h.mcpAccessPolicyError.value).toBe("backup failed");
+ expect(h.mcpPolicyRecovering.value).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpHistory.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpHistory.spec.ts
new file mode 100644
index 0000000000..5bb61d8f30
--- /dev/null
+++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpHistory.spec.ts
@@ -0,0 +1,58 @@
+// @vitest-environment happy-dom
+
+import { compile, createApp, nextTick, ref } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { History } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import en from "@/i18n/locales/en";
+import zhCN from "@/i18n/locales/zh-CN";
+import dialogSource from "../EditorSettingsDialog.vue?raw";
+
+// Mount the actual transport header with real tabs/buttons, without loading
+// the unrelated settings editors or calling backend services.
+const start = dialogSource.indexOf('<Tabs v-model="mcpTransportTab"');
+const end = dialogSource.indexOf('<TabsContent value="http"', start);
+if (start < 0 || end < 0) throw new Error("MCP transport header was not found");
+const template = `${dialogSource.slice(start, end)}<TabsContent value="stdio">stdio</TabsContent><TabsContent value="http">HTTP</TabsContent></Tabs>`;
+const cleanup: Array<() => void> = [];
+afterEach(() => cleanup.splice(0).forEach((unmount) => unmount()));
+
+describe("MCP transport header", () => {
+ it.each([
+ ["en", en.settings],
+ ["zh-CN", zhCN.settings],
+ ])("keeps the history action available in both transports with an accessible name in %s", async (_locale, messages) => {
+ const settings = messages as Record<string, string>;
+ const mcpTransportTab = ref("stdio");
+ const requestMcpCallHistory = vi.fn();
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp({
+ components: { Tabs, TabsContent, TabsList, TabsTrigger, Button, History },
+ setup: () => ({ mcpTransportTab, requestMcpCallHistory, t: (key: string) => settings[key.replace("settings.", "")] }),
+ render: compile(template),
+ });
+ app.mount(root);
+ cleanup.push(() => {
+ app.unmount();
+ root.remove();
+ });
+ await nextTick();
+ const history = root.querySelector<HTMLButtonElement>("[data-mcp-open-call-history]")!;
+ expect(root.querySelectorAll("[data-mcp-open-call-history]")).toHaveLength(1);
+ expect(history.getAttribute("aria-label")).toBe(settings.mcpOpenCallHistory);
+ expect(history.title).toBe(settings.mcpOpenCallHistory);
+ expect(history.closest('[role="tablist"]')).toBeNull();
+ history.click();
+ expect(requestMcpCallHistory).toHaveBeenCalledOnce();
+ expect(mcpTransportTab.value).toBe("stdio");
+ root.querySelector<HTMLButtonElement>('[role="tab"][id$="-http"]')!.dispatchEvent(new MouseEvent("mousedown", { button: 0, bubbles: true }));
+ await nextTick();
+ expect(mcpTransportTab.value).toBe("http");
+ await vi.waitFor(() => expect(root.querySelector('[role="tabpanel"][data-state="active"]')!.textContent).toBe("HTTP"));
+ history.click();
+ expect(requestMcpCallHistory).toHaveBeenCalledTimes(2);
+ expect(mcpTransportTab.value).toBe("http");
+ });
+});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.searchNavigation.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.searchNavigation.integration.spec.ts
index 5e92f4294b..e2ffbfef3a 100644
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.searchNavigation.integration.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.searchNavigation.integration.spec.ts
@@ -1,15 +1,87 @@
// @vitest-environment happy-dom
-import { createApp, h, nextTick, ref, watch, type App } from "vue";
+import * as Vue from "vue";
+import { createApp, defineComponent, h, nextTick, ref, shallowRef, watch, type App, type RenderFunction } from "vue";
+import { compileTemplate } from "vue/compiler-sfc";
import { afterEach, describe, expect, it, vi } from "vitest";
import ts from "typescript";
+import { AlertTriangle, X } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import McpCapabilityBrowser from "@/components/settings/McpCapabilityBrowser.vue";
+import McpPluginToolsModeSetting from "@/components/settings/McpPluginToolsModeSetting.vue";
+import { initialMcpCapabilityBrowserState, type McpCapabilityNavigator } from "@/lib/mcp/mcpCapabilitySearch";
+import type { McpToolCatalog } from "@/types/mcpCatalog";
import dialogSource from "../EditorSettingsDialog.vue?raw";
import formatterSource from "../SqlFormatterSettingsPanel.vue?raw";
-import McpAuthorizationTabs from "@/components/settings/McpAuthorizationTabs.vue";
import { findSettingsSearchHighlightTarget } from "@/lib/settings/settingsSearchHighlight";
-import type { SettingsSearchEntry } from "@/lib/settings/settingsSearch";
+import { SETTINGS_SEARCH_DEFINITIONS, resolveSettingsSearchEntries, searchSettings, type SettingsSearchEntry } from "@/lib/settings/settingsSearch";
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+// Only replace the portal/focus-trap boundary. The capability browser, tool
+// panel, expansion controls and advanced slot below are production components.
+vi.mock("@/components/ui/dialog", async () => {
+ const { defineComponent, h } = await import("vue");
+ const passthrough = (tag: string) =>
+ defineComponent({
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h(tag, attrs, slots.default?.()),
+ });
+ return {
+ Dialog: defineComponent({
+ props: { open: Boolean },
+ emits: ["update:open"],
+ setup:
+ (props, { slots, emit }) =>
+ () =>
+ props.open ? h("div", [...(slots.default?.() ?? []), h("button", { "data-dialog-dismiss": "", onClick: () => emit("update:open", false) })]) : null,
+ }),
+ DialogContent: passthrough("div"),
+ DialogDescription: passthrough("p"),
+ DialogHeader: passthrough("div"),
+ DialogTitle: passthrough("h2"),
+ };
+});
+
+const navigationTools = [
+ ["sql.query", "dbx_execute_query", "database"],
+ ["redis", "dbx_execute_redis_command", "database"],
+ ["nacos.config", "dbx_nacos_get_config", "nacos"],
+ ["consul.kv", "dbx_consul_kv_get", "consul"],
+ ["mq", "dbx_peek_messages", "mq"],
+ ["salesforce", "dbx_salesforce_current_user", "salesforce"],
+ ["core.discovery", "dbx_list_connections", "dbx"],
+] as const;
+
+const catalog: McpToolCatalog = {
+ toolsets: navigationTools.map(([id, name]) => ({
+ id,
+ provider: `builtin:${id.split(".")[0]}`,
+ resourceKinds: [],
+ scopeKinds: [],
+ tools: [{ name, access: "read", accessMode: "static", coverageKind: "none", databaseTypes: [], description: `Description for ${name}`, parameters: [] }],
+ })),
+};
+
+// Compile the real settings template fragment, including the component ref,
+// model binding and advanced input. This avoids a duplicate placeholder UI.
+const browserStart = dialogSource.indexOf("<McpCapabilityBrowser\n");
+const browserEnd = dialogSource.indexOf("</McpCapabilityBrowser>", browserStart);
+const compiledBrowser = compileTemplate({
+ source: dialogSource.slice(browserStart, browserEnd + "</McpCapabilityBrowser>".length),
+ filename: "EditorSettingsDialog.vue",
+ id: "settings-navigation",
+});
+if (browserStart < 0 || browserEnd < 0 || compiledBrowser.errors.length) throw new Error("Could not compile the settings capability browser");
+const browserExports = {} as { render: RenderFunction };
+new Function("require", "exports", ts.transpileModule(compiledBrowser.code, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText)((name: string) => {
+ if (name === "vue") return Vue;
+ throw new Error(`Unexpected template dependency: ${name}`);
+}, browserExports);
+
const apps: App[] = [];
afterEach(() => {
apps.splice(0).forEach((app) => app.unmount());
@@ -20,12 +92,15 @@ afterEach(() => {
// Compile the real navigation functions; rendering only the relevant views avoids booting
// database services. Unexpected saves or other business calls fail as unresolved bindings.
function navigationHarness(initialCategory = "appearance") {
+ const mutatePolicy = vi.fn();
+ const savePlugin = vi.fn();
const state = {
+ settingsVisible: ref(true),
activeSettingsTab: ref(initialCategory),
+ pendingSettingsSearchNavigation: shallowRef<{ result: SettingsSearchEntry; delivered: boolean } | null>(null),
syncMethodTab: ref("webdav"),
mcpManagementTab: ref("access"),
mcpTransportTab: ref("stdio"),
- mcpAuthorizationTab: ref("overrides"),
formatterMode: ref("form"),
shortcutSearchQuery: ref(""),
aiConfigListMode: ref("list"),
@@ -34,7 +109,46 @@ function navigationHarness(initialCategory = "appearance") {
settingsSearchActiveIndex: ref(0),
settingsContentScrollRef: ref<HTMLElement | null>(null),
highlightedSettingsSearchTargetId: ref(""),
+ mcpCapabilityBrowserState: ref(initialMcpCapabilityBrowserState()),
+ mcpCapabilityBrowserRef: ref<McpCapabilityNavigator>(),
+ mcpToolCatalog: ref<McpToolCatalog | null>(catalog),
+ mcpToolCatalogLoading: ref(false),
+ mcpToolCatalogError: ref(""),
};
+ const Browser = defineComponent({
+ components: { McpCapabilityBrowser, McpPluginToolsModeSetting, Button, Input, AlertTriangle, X },
+ setup: () => ({
+ ...state,
+ t: (key: string) => key,
+ mcpAllowedToolNames: [],
+ mcpPolicyBaseline: { allowedToolNames: [] },
+ mcpPolicyDraft: { pluginToolsMode: "flat" },
+ mcpCoverageConnections: [],
+ mcpPolicyControlsDisabled: false,
+ mcpCatalogControlsDisabled: false,
+ mcpPluginViews: [],
+ mcpPluginViewsLoading: false,
+ mcpPluginViewsError: "",
+ mcpPluginSavingIds: new Set<string>(),
+ isWeb: false,
+ mcpPluginToolsBlockedByAllowlist: false,
+ mcpPluginAllowlistPending: false,
+ mcpCustomToolEntries: [],
+ mcpCustomToolInput: ref(""),
+ applyMcpToolset: mutatePolicy,
+ persistMcpPluginGrant: savePlugin,
+ onMcpToolsetAllowedChange: mutatePolicy,
+ onMcpToolAllowedChange: mutatePolicy,
+ onMcpCategoryAllowedChange: mutatePolicy,
+ onMcpAllowPluginTools: mutatePolicy,
+ stageMcpPolicy: mutatePolicy,
+ onMcpCustomToolAdd: mutatePolicy,
+ onMcpCustomToolRemove: mutatePolicy,
+ ensureMcpToolCatalog: vi.fn(),
+ loadMcpPluginViews: vi.fn(),
+ }),
+ render: browserExports.render,
+ });
const start = dialogSource.indexOf("function applySettingsSearchRoute(");
const end = dialogSource.indexOf("function onSettingsSearchKeydown(", start);
const watcherStart = dialogSource.indexOf(" const result = pendingSettingsSearchResult;", dialogSource.indexOf("watch(activeSettingsTab,"));
@@ -52,41 +166,58 @@ function navigationHarness(initialCategory = "appearance") {
highlightedSettingsSearchElement?.classList.remove(...settingsSearchHighlightClasses);
}
${dialogSource.slice(start, end)}
+ watchSettingsSearchNavigation();
watch(activeSettingsTab, async () => { ${dialogSource.slice(watcherStart, watcherEnd)} });
return { selectSettingsSearchResult };
`,
{ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None } },
).outputText;
const factory = new Function(...Object.keys(state), "nextTick", "watch", "findSettingsSearchHighlightTarget", code);
- const api = factory(...Object.values(state), nextTick, watch, findSettingsSearchHighlightTarget) as {
+ let api!: {
selectSettingsSearchResult: (entry: SettingsSearchEntry) => Promise<void>;
};
const root = document.createElement("div");
document.body.append(root);
const app = createApp({
setup() {
+ // Register the production watchers in the app scope so unmount cleans up
+ // pending navigation and DOM observers as it does in the settings dialog.
+ api = factory(...Object.values(state), nextTick, watch, findSettingsSearchHighlightTarget);
return () =>
- h("div", { ref: state.settingsContentScrollRef }, [
- state.activeSettingsTab.value === "mcp"
- ? state.mcpManagementTab.value === "permissions"
- ? h(
- McpAuthorizationTabs,
- {
- modelValue: state.mcpAuthorizationTab.value as "overrides",
- "onUpdate:modelValue": (value: string) => {
- state.mcpAuthorizationTab.value = value;
+ state.settingsVisible.value
+ ? h("div", { ref: state.settingsContentScrollRef }, [
+ state.activeSettingsTab.value === "mcp"
+ ? h(
+ Tabs,
+ {
+ modelValue: state.mcpManagementTab.value,
+ "onUpdate:modelValue": (value) => {
+ state.mcpManagementTab.value = String(value);
+ },
},
- },
- Object.fromEntries(["overrides", "connections", "databases", "capabilities"].map((id) => [id, () => h("p", `Empty ${id}`)])),
- )
- : h("section", { "data-settings-search-id": `mcp-${state.mcpTransportTab.value}` }, "Transport")
- : h("section", { "data-settings-search-id": state.activeSettingsTab.value === "data" ? "redis-key-templates" : "appearance-settings" }, "Settings"),
- ]);
+ {
+ default: () => [
+ h(TabsList, {}, { default: () => ["access", "permissions", "capabilities"].map((value) => h(TabsTrigger, { value }, { default: () => value })) }),
+ h(TabsContent, { value: "access" }, { default: () => h("section", { "data-settings-search-id": `mcp-${state.mcpTransportTab.value}` }, "Transport") }),
+ h(
+ TabsContent,
+ { value: "permissions" },
+ {
+ default: () => ["overrides", "connections", "call-safety"].map((id) => h("section", { "data-settings-search-id": `mcp-${id}` }, `Empty ${id}`)),
+ },
+ ),
+ h(TabsContent, { value: "capabilities", "data-settings-search-id": "mcp-capabilities" }, { default: () => h(Browser) }),
+ ],
+ },
+ )
+ : h("section", { "data-settings-search-id": state.activeSettingsTab.value === "data" ? "redis-key-templates" : "appearance-settings" }, "Settings"),
+ ])
+ : null;
},
});
app.mount(root);
apps.push(app);
- return { ...state, ...api, root };
+ return { ...state, ...api, root, mutatePolicy, savePlugin };
}
function entry(category: SettingsSearchEntry["category"], targetId: string, route?: SettingsSearchEntry["route"]): SettingsSearchEntry {
@@ -97,9 +228,186 @@ async function flush() {
await nextTick();
await nextTick();
await nextTick();
+ await nextTick();
+ await nextTick();
+}
+
+function indexedMcpEntry(id: string) {
+ const definition = SETTINGS_SEARCH_DEFINITIONS.find((candidate) => candidate.id === id);
+ if (!definition) throw new Error(`Missing settings entry: ${id}`);
+ return resolveSettingsSearchEntries([definition], { isWeb: false, visibleCategories: new Set(["mcp"]) }, (key) => key, { mcp: "MCP" } as Record<SettingsSearchEntry["category"], string>)[0]!;
}
describe("settings search navigation", () => {
+ it.each(["access", "permissions"])("waits for real capability tab content when navigating from MCP %s", async (initialTab) => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness("mcp");
+ harness.mcpManagementTab.value = initialTab;
+ await flush();
+ expect(harness.mcpCapabilityBrowserRef.value).toBeFalsy();
+ expect(harness.root.querySelector("[data-mcp-global-search]")).toBeNull();
+
+ await harness.selectSettingsSearchResult(indexedMcpEntry("mcp-tool-dbx_nacos_get_config"));
+ await flush();
+
+ const panel = harness.root.querySelector('[role="tabpanel"][data-state="active"]');
+ expect(panel?.getAttribute("data-settings-search-id")).toBe("mcp-capabilities");
+ expect(panel?.hasAttribute("hidden")).toBe(false);
+ expect(panel?.querySelector('[data-mcp-tool="dbx_nacos_get_config"] [data-mcp-tool-toggle]')?.getAttribute("aria-expanded")).toBe("true");
+ expect(panel?.querySelector('[data-mcp-tool="dbx_nacos_get_config"] [data-mcp-tool-detail]')?.textContent).toContain("Description for dbx_nacos_get_config");
+ expect(harness.mutatePolicy).not.toHaveBeenCalled();
+ expect(harness.savePlugin).not.toHaveBeenCalled();
+ });
+
+ it.each(["mcp-custom-tool-entries", "mcp-tool-dbx_consul_kv_get"])("uses the newest request %s while the real capability tab is mounting", async (latestId) => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness("mcp");
+ await flush();
+ const first = harness.selectSettingsSearchResult(indexedMcpEntry("mcp-tool-dbx_nacos_get_config"));
+ await nextTick();
+ expect(harness.mcpCapabilityBrowserRef.value).toBeFalsy();
+ const second = harness.selectSettingsSearchResult(indexedMcpEntry(latestId));
+ await Promise.all([first, second]);
+ await flush();
+ if (latestId === "mcp-custom-tool-entries") {
+ expect(harness.root.querySelector("[data-mcp-advanced] [data-mcp-plugin-tool-entries] input")).not.toBeNull();
+ expect(harness.root.querySelector("[data-mcp-toolset-detail]")).toBeNull();
+ } else {
+ expect(harness.root.querySelector('[data-mcp-tool="dbx_consul_kv_get"] [data-mcp-tool-toggle]')?.getAttribute("aria-expanded")).toBe("true");
+ }
+ expect(harness.root.querySelector('[data-mcp-tool="dbx_nacos_get_config"] [data-mcp-tool-detail]')).toBeNull();
+ expect(harness.mutatePolicy).not.toHaveBeenCalled();
+ expect(harness.savePlugin).not.toHaveBeenCalled();
+ });
+
+ it.each(["management", "category", "close"])("cancels navigation before tab mount on %s and does not replay on return", async (leave) => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness("mcp");
+ await flush();
+ const selection = harness.selectSettingsSearchResult(indexedMcpEntry("mcp-tool-dbx_consul_kv_get"));
+ await nextTick();
+ expect(harness.mcpCapabilityBrowserRef.value).toBeFalsy();
+ if (leave === "management") harness.mcpManagementTab.value = "permissions";
+ if (leave === "category") harness.activeSettingsTab.value = "appearance";
+ if (leave === "close") harness.settingsVisible.value = false;
+ await selection;
+ await flush();
+ harness.settingsVisible.value = true;
+ harness.activeSettingsTab.value = "mcp";
+ harness.mcpManagementTab.value = "capabilities";
+ await flush();
+ expect(harness.root.querySelector("[data-mcp-global-search]")).not.toBeNull();
+ expect(harness.root.querySelector("[data-mcp-toolset-detail]")).toBeNull();
+ expect(harness.mcpCapabilityBrowserState.value.search).toBe("");
+ expect(harness.mutatePolicy).not.toHaveBeenCalled();
+ expect(harness.savePlugin).not.toHaveBeenCalled();
+ });
+
+ it("cancels a delivered request when leaving and returning before the catalog arrives", async () => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness("mcp");
+ harness.mcpToolCatalog.value = null;
+ harness.mcpToolCatalogLoading.value = true;
+ await harness.selectSettingsSearchResult(indexedMcpEntry("mcp-tool-dbx_nacos_get_config"));
+ await flush();
+ expect(harness.mcpCapabilityBrowserState.value.search).toBe("dbx_nacos_get_config");
+ // No render between leaving and returning: the browser is still mounted.
+ harness.mcpManagementTab.value = "permissions";
+ harness.mcpManagementTab.value = "capabilities";
+ harness.mcpToolCatalog.value = catalog;
+ harness.mcpToolCatalogLoading.value = false;
+ await flush();
+ expect(harness.root.querySelector("[data-mcp-toolset-detail]")).toBeNull();
+ expect(harness.mutatePolicy).not.toHaveBeenCalled();
+ });
+
+ it.each(navigationTools)("reveals %s tool details from the settings index despite old filters", async (_toolset, name, category) => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness();
+ harness.mcpCapabilityBrowserState.value = { selected: "advanced", search: "unrelated", onlyEnabled: true, viewMode: "overview" };
+ await harness.selectSettingsSearchResult(indexedMcpEntry(`mcp-tool-${name}`));
+ await flush();
+ expect(harness.root.querySelector(`[data-mcp-category="${category}"]`)?.getAttribute("aria-current")).toBe("page");
+ const tool = harness.root.querySelector(`[data-mcp-toolset-detail] [data-mcp-tool="${name}"]`);
+ expect(tool?.querySelector("[data-mcp-tool-toggle]")?.getAttribute("aria-expanded")).toBe("true");
+ expect(tool?.querySelector("[data-mcp-tool-detail]")?.textContent).toContain(`Description for ${name}`);
+ expect(harness.mutatePolicy).not.toHaveBeenCalled();
+ expect(harness.savePlugin).not.toHaveBeenCalled();
+ });
+
+ it("opens the real advanced whitelist input and can reopen the same tool within MCP", async () => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness("mcp");
+ harness.mcpManagementTab.value = "permissions";
+ await flush();
+ const custom = indexedMcpEntry("mcp-custom-tool-entries");
+ expect(searchSettings([custom], "settings.mcpToolCustomHint", "en")).toEqual([custom]);
+ harness.mcpCapabilityBrowserState.value = { selected: "nacos", search: "stale", onlyEnabled: true, viewMode: "overview" };
+ await harness.selectSettingsSearchResult(custom);
+ await flush();
+ const input = harness.root.querySelector<HTMLInputElement>("[data-mcp-advanced] [data-mcp-plugin-tool-entries] input");
+ expect(input?.placeholder).toBe("settings.mcpToolCustomPlaceholder");
+ expect(input?.disabled).toBe(false);
+ const result = indexedMcpEntry("mcp-tool-dbx_consul_kv_get");
+ for (let attempt = 0; attempt < 2; attempt++) {
+ await harness.selectSettingsSearchResult(result);
+ await flush();
+ expect(harness.root.querySelector('[data-mcp-tool="dbx_consul_kv_get"] [data-mcp-tool-detail]')).not.toBeNull();
+ harness.root.querySelector<HTMLButtonElement>("[data-dialog-dismiss]")!.click();
+ await flush();
+ expect(harness.root.querySelector("[data-mcp-toolset-detail]")).toBeNull();
+ }
+ expect(harness.mutatePolicy).not.toHaveBeenCalled();
+ expect(harness.savePlugin).not.toHaveBeenCalled();
+ });
+
+ it("waits through catalog loading and failure, then reveals the requested tool after recovery", async () => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness();
+ harness.mcpToolCatalog.value = null;
+ harness.mcpToolCatalogLoading.value = true;
+ await harness.selectSettingsSearchResult(indexedMcpEntry("mcp-tool-dbx_nacos_get_config"));
+ await flush();
+ expect(harness.root.querySelector("[data-mcp-toolset-detail]")).toBeNull();
+ harness.mcpToolCatalogLoading.value = false;
+ harness.mcpToolCatalogError.value = "offline";
+ await flush();
+ expect(harness.root.textContent).toContain("settings.mcpCapabilitiesLoadFailed");
+ expect(harness.root.querySelector("[data-mcp-toolset-detail]")).toBeNull();
+ harness.mcpToolCatalog.value = catalog;
+ harness.mcpToolCatalogError.value = "";
+ await flush();
+ expect(harness.root.querySelector('[data-mcp-tool="dbx_nacos_get_config"] [data-mcp-tool-detail]')).not.toBeNull();
+ expect(harness.mutatePolicy).not.toHaveBeenCalled();
+ });
+
+ it("cancels deferred navigation when the user chooses a different category", async () => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness();
+ harness.mcpToolCatalog.value = null;
+ harness.mcpToolCatalogLoading.value = true;
+ await harness.selectSettingsSearchResult(indexedMcpEntry("mcp-tool-dbx_nacos_get_config"));
+ await flush();
+ harness.root.querySelector<HTMLButtonElement>('[data-mcp-category="advanced"]')!.click();
+ await flush();
+ harness.mcpToolCatalog.value = catalog;
+ harness.mcpToolCatalogLoading.value = false;
+ await flush();
+ expect(harness.root.querySelector("[data-mcp-advanced] input")).not.toBeNull();
+ expect(harness.root.querySelector("[data-mcp-toolset-detail]")).toBeNull();
+ });
+
+ it("keeps an unavailable tool visible as an empty search instead of opening an unrelated detail", async () => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const harness = navigationHarness();
+ harness.mcpToolCatalog.value = { toolsets: [] };
+ await harness.selectSettingsSearchResult(indexedMcpEntry("mcp-tool-dbx_nacos_get_config"));
+ await flush();
+ expect(harness.root.querySelector<HTMLInputElement>("[data-mcp-global-search]")?.value).toBe("dbx_nacos_get_config");
+ expect(harness.root.textContent).toContain("settings.mcpCapabilitiesSearchEmpty");
+ expect(harness.root.querySelector("[data-mcp-toolset-detail]")).toBeNull();
+ });
+
it("scrolls keyboard selection into view past the former eight-result limit and wraps", async () => {
const settingsSearchResults = ref(Array.from({ length: 12 }, (_, index) => entry("editor", `entry-${index}`)));
const settingsSearchActiveIndex = ref(7);
@@ -142,14 +450,14 @@ describe("settings search navigation", () => {
expect(selectSettingsSearchResult).toHaveBeenCalledWith(settingsSearchResults.value[11]);
});
- it("reveals a cross-category MCP authorization tab, then another tab in the same category, even with no records", async () => {
+ it("reveals MCP permissions and capabilities across management tabs, even with no records", async () => {
const scroll = vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
const harness = navigationHarness();
- for (const tab of ["databases", "capabilities", "connections", "overrides"] as const) {
- await harness.selectSettingsSearchResult(entry("mcp", `mcp-${tab}`, { mcpManagementTab: "permissions", mcpAuthorizationTab: tab }));
+ for (const tab of ["connections", "capabilities", "call-safety", "overrides"] as const) {
+ await harness.selectSettingsSearchResult(entry("mcp", `mcp-${tab}`, { mcpManagementTab: tab === "capabilities" ? "capabilities" : "permissions" }));
await flush();
const panel = harness.root.querySelector(`[data-settings-search-id="mcp-${tab}"]`);
- expect(panel?.getAttribute("data-state")).toBe("active");
+ expect(panel).not.toBeNull();
expect(panel?.classList.contains("settings-search-highlight-breathe")).toBe(true);
expect(harness.settingsSearchQuery.value).toBe("");
expect(harness.settingsSearchOpen.value).toBe(false);
@@ -177,7 +485,6 @@ describe("settings search navigation", () => {
expect(harness.formatterMode.value).toBe("json");
expect(harness.syncMethodTab.value).toBe("snippet");
expect(dialogSource).toContain('v-model:mode="formatterMode"');
- expect(dialogSource).toContain('<McpAuthorizationTabs v-model="mcpAuthorizationTab">');
expect(formatterSource).toContain('data-settings-search-id="formatter-json"');
expect(dialogSource).toContain("searchSettings(settingsSearchEntries.value, settingsSearchQuery.value, currentLocale(), Infinity)");
});
diff --git a/apps/desktop/src/components/editor/__tests__/QueryHistory.mcpNavigation.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryHistory.mcpNavigation.spec.ts
new file mode 100644
index 0000000000..ef9ee6c5af
--- /dev/null
+++ b/apps/desktop/src/components/editor/__tests__/QueryHistory.mcpNavigation.spec.ts
@@ -0,0 +1,334 @@
+// @vitest-environment happy-dom
+import ts from "typescript";
+import { compile, createApp, defineAsyncComponent, nextTick, ref, watch, type App, type Ref } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import QueryHistory from "../QueryHistory.vue";
+import appSource from "../../../App.vue?raw";
+import type { McpCallHistoryRequest, McpCallHistoryResource } from "@/lib/mcp/mcpCallHistory";
+import { RIGHT_SIDEBAR_PANEL_IDS, transitionRightSidebarPanels } from "@/stores/settingsStore";
+
+const mocks = vi.hoisted(() => ({
+ search: vi.fn(),
+ loadConnectionOptions: vi.fn(),
+ getConfig: vi.fn(),
+ connectionOptions: [] as Array<{ connection_id: string; connection_name: string; databases: string[] }>,
+}));
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+vi.mock("@/stores/historyStore", () => ({
+ useHistoryStore: () => ({
+ entries: [],
+ get connectionOptions() {
+ return mocks.connectionOptions;
+ },
+ total: 0,
+ loading: false,
+ error: "",
+ nextCursor: null,
+ setHistoryPanelActive: vi.fn(),
+ loadConnectionOptions: mocks.loadConnectionOptions,
+ search: mocks.search,
+ }),
+}));
+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ getConfig: mocks.getConfig }) }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));
+vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: (text: string) => text }) }));
+vi.mock("@/lib/database/productionExecutionGuard", () => ({ executeWithProductionSqlGuard: vi.fn() }));
+vi.mock("@/lib/backend/api", () => ({}));
+
+// Exercise the real shell handler, component bindings and lazy history panel.
+// Delay the loader past nextTick to reproduce the first-open race from the UI.
+const script = appSource.match(/<script setup[^>]*>([\s\S]*?)<\/script>/)?.[1];
+if (!script) throw new Error("App script setup was not found");
+const source = ts.createSourceFile("App.ts", script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
+const names = [
+ "showHistory",
+ "mcpHistoryRequest",
+ "openMcpCallHistory",
+ "showAiPanel",
+ "isAiPanelMaximized",
+ "isHistoryPanelMaximized",
+ "showSqlLibraryPanel",
+ "showSqlFilePanel",
+ "rightSidebarPanelRefs",
+ "rightSidebarPanelStorageKeys",
+ "lastOpenedRightSidebarPanel",
+ "lastFocusedAuxiliarySurface",
+ "lastFocusedSidebarSurface",
+ "currentRightSidebarPanelState",
+ "applyRightSidebarPanelState",
+ "setRightSidebarPanelOpen",
+ "openRightSidebarPanel",
+ "closeRightSidebarPanel",
+];
+const declarations = names.map((name) => {
+ for (const statement of source.statements) {
+ if (ts.isFunctionDeclaration(statement) && statement.name?.text === name) return statement.getText(source);
+ if (ts.isVariableStatement(statement)) {
+ const target = statement.declarationList.declarations.find((item) => ts.isIdentifier(item.name) && item.name.text === name);
+ if (target) return `${statement.declarationList.flags & ts.NodeFlags.Const ? "const" : "let"} ${target.getText(source)};`;
+ }
+ }
+ throw new Error(`Missing App declaration: ${name}`);
+});
+const historyLifecycleWatches = source.statements.filter((statement) => ts.isExpressionStatement(statement) && ts.isCallExpression(statement.expression) && statement.expression.expression.getText(source) === "watch" && statement.expression.arguments[0]?.getText(source) === "showHistory");
+const compiled = ts.transpileModule([...declarations, ...historyLifecycleWatches.map((statement) => statement.getText(source))].join("\n"), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+const historyTemplate = appSource.match(/<QueryHistory\s[\s\S]*?\/>/)?.[0];
+if (!historyTemplate) throw new Error("App history panel was not found");
+
+let app: App | undefined;
+function mountShell() {
+ const isSpecialPageActive = ref(false);
+ const settingsStore = { isEditorSettingsLoaded: true, editorSettings: { toolbarItems: { exclusiveRightSidebarPanels: false } } };
+ const deps = {
+ ref,
+ watch,
+ RIGHT_SIDEBAR_PANEL_IDS,
+ transitionRightSidebarPanels,
+ settingsStore,
+ isSpecialPageActive,
+ activateQuerySurface: () => {
+ isSpecialPageActive.value = false;
+ },
+ safeLocalStorageGet: () => null,
+ safeLocalStorageSet: vi.fn(),
+ };
+ let state!: {
+ showHistory: Ref<boolean>;
+ showAiPanel: Ref<boolean>;
+ isAiPanelMaximized: Ref<boolean>;
+ isHistoryPanelMaximized: Ref<boolean>;
+ mcpHistoryRequest: Ref<McpCallHistoryRequest | null>;
+ openMcpCallHistory: (event: Event) => void;
+ openRightSidebarPanel: (id: string) => void;
+ closeRightSidebarPanel: (id: string) => void;
+ };
+ let resolve!: (component: typeof QueryHistory) => void;
+ const LazyHistory = defineAsyncComponent(
+ () =>
+ new Promise<typeof QueryHistory>((done) => {
+ resolve = done;
+ }),
+ );
+ const root = document.createElement("div");
+ document.body.append(root);
+ app = createApp({
+ components: { QueryHistory: LazyHistory },
+ setup: () => {
+ state = new Function(...Object.keys(deps), `${compiled}; return { ${names.join(", ")} };`)(...Object.values(deps));
+ return { ...state, activeTab: undefined, restoreHistorySql: vi.fn(), analyzeHistoryWithAi: vi.fn() };
+ },
+ render: compile(`<div v-if="showHistory">${historyTemplate}</div>`),
+ });
+ app.mount(root);
+ return {
+ ...state,
+ isSpecialPageActive,
+ settingsStore,
+ root,
+ open: (resource?: McpCallHistoryResource) => state.openMcpCallHistory(new CustomEvent("open", { detail: resource })),
+ resolve: async (expectedSource = "mcp") => {
+ resolve(QueryHistory);
+ await vi.waitFor(() => expect(mocks.search).toHaveBeenCalledWith(expect.objectContaining({ source: expectedSource })));
+ },
+ };
+}
+
+beforeEach(() => {
+ mocks.connectionOptions = [];
+ mocks.getConfig.mockReset().mockReturnValue({ name: "Test" });
+ mocks.search.mockReset().mockResolvedValue(undefined);
+ mocks.loadConnectionOptions.mockReset().mockResolvedValue(undefined);
+});
+afterEach(() => {
+ app?.unmount();
+ document.body.textContent = "";
+});
+
+describe("MCP history navigation", () => {
+ function clickButton(root: HTMLElement, text: string) {
+ const button = [...root.querySelectorAll("button")].find((item) => item.textContent?.trim() === text);
+ expect(button, `Missing button: ${text}`).toBeDefined();
+ button!.click();
+ }
+
+ it("opens MCP on the first lazy mount, even after the shell's next tick", async () => {
+ const shell = mountShell();
+ shell.open();
+ await nextTick();
+ await nextTick();
+ expect(mocks.search).not.toHaveBeenCalled();
+ await shell.resolve();
+ expect(mocks.search).toHaveBeenCalledWith(expect.objectContaining({ source: "mcp" }));
+ expect(shell.mcpHistoryRequest.value).toBeNull();
+ });
+
+ it("handles a new request while mounted and does not replay it on an ordinary reopen", async () => {
+ const shell = mountShell();
+ shell.open();
+ await nextTick();
+ await shell.resolve();
+ const sqlButton = [...shell.root.querySelectorAll("button")].find((button) => button.textContent?.trim() === "history.sources.sql")!;
+ expect(sqlButton).toBeDefined();
+ sqlButton.click();
+ await nextTick();
+ expect(shell.root.querySelector("[data-mcp-tool-search]")).toBeNull();
+ shell.open();
+ await nextTick();
+ expect(shell.root.querySelector("[data-mcp-tool-search]")).not.toBeNull();
+ expect(shell.mcpHistoryRequest.value).toBeNull();
+ shell.showHistory.value = false;
+ await nextTick();
+ mocks.search.mockClear();
+ shell.showHistory.value = true;
+ await nextTick();
+ expect(mocks.search).toHaveBeenCalledWith(expect.objectContaining({ source: "sql" }));
+ });
+
+ it("applies the requested scope on first mount without waiting for connection options", async () => {
+ let resolveOptions!: () => void;
+ mocks.loadConnectionOptions.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveOptions = resolve;
+ }),
+ );
+ const shell = mountShell();
+ shell.open({ connectionId: "c1", database: "analytics" });
+ await nextTick();
+ await shell.resolve();
+ expect(mocks.search).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ source: "mcp",
+ connections: [{ connection_id: "c1", connection_name: "Test" }],
+ databases: [{ connection_id: "c1", connection_name: "Test", database: "analytics" }],
+ }),
+ );
+ mocks.connectionOptions = [{ connection_id: "c1", connection_name: "Test", databases: ["analytics"] }];
+ resolveOptions();
+ await vi.waitFor(() =>
+ expect(mocks.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: "mcp",
+ connections: [{ connection_id: "c1", connection_name: "Test" }],
+ databases: [{ connection_id: "c1", connection_name: "Test", database: "analytics" }],
+ }),
+ ),
+ );
+ });
+
+ it.each([false, true])("cancels an unconsumed request before its first load (same tick reopen: %s)", async (sameTick) => {
+ const shell = mountShell();
+ shell.open({ connectionId: "c1", database: "analytics" });
+ await nextTick();
+ shell.closeRightSidebarPanel("history");
+ if (!sameTick) await nextTick();
+ shell.openRightSidebarPanel("history");
+ await shell.resolve("sql");
+ expect(mocks.search).toHaveBeenLastCalledWith(expect.objectContaining({ source: "sql", connections: [], databases: [] }));
+ });
+
+ it.each([false, true])("reveals history from settings and maximized AI (exclusive panels: %s)", async (exclusive) => {
+ const shell = mountShell();
+ shell.isSpecialPageActive.value = true;
+ shell.showAiPanel.value = true;
+ shell.isAiPanelMaximized.value = true;
+ shell.settingsStore.editorSettings.toolbarItems.exclusiveRightSidebarPanels = exclusive;
+ shell.open();
+ await nextTick();
+ await shell.resolve();
+ expect(shell.isSpecialPageActive.value).toBe(false);
+ expect(shell.isAiPanelMaximized.value).toBe(false);
+ expect(shell.showAiPanel.value).toBe(!exclusive);
+ });
+
+ it("does not carry an invisible SQL activity filter into MCP navigation", async () => {
+ const shell = mountShell();
+ shell.open();
+ await nextTick();
+ await shell.resolve();
+ clickButton(shell.root, "history.sources.sql");
+ await nextTick();
+ clickButton(shell.root, "history.filters.schema_change");
+ await nextTick();
+ mocks.search.mockClear();
+ shell.open();
+ await vi.waitFor(() => expect(mocks.search).toHaveBeenLastCalledWith(expect.objectContaining({ source: "mcp", activity_kind: undefined })));
+ });
+
+ it("does not undo a user's source selection when connection options arrive late", async () => {
+ let resolveOptions!: () => void;
+ mocks.loadConnectionOptions.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveOptions = resolve;
+ }),
+ );
+ const shell = mountShell();
+ shell.open({ connectionId: "c1", database: "analytics" });
+ await nextTick();
+ await shell.resolve();
+ clickButton(shell.root, "history.sources.sql");
+ await nextTick();
+ mocks.connectionOptions = [{ connection_id: "c1", connection_name: "Test", databases: ["analytics"] }];
+ resolveOptions();
+ await nextTick();
+ await nextTick();
+ expect(shell.root.querySelector("[data-mcp-tool-search]")).toBeNull();
+ });
+
+ it.each(["empty", "failed", "missing database"])("keeps exact resource filters when the connection options are %s", async (result) => {
+ if (result === "failed") mocks.loadConnectionOptions.mockRejectedValue(new Error("options unavailable"));
+ if (result === "missing database") mocks.connectionOptions = [{ connection_id: "c1", connection_name: "Test", databases: ["old_database"] }];
+ const shell = mountShell();
+ shell.open({ connectionId: "c1", database: "new_database" });
+ await nextTick();
+ await shell.resolve();
+ expect(mocks.search).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ connections: [{ connection_id: "c1", connection_name: "Test" }],
+ databases: [{ connection_id: "c1", connection_name: "Test", database: "new_database" }],
+ }),
+ );
+ });
+
+ it.each([false, true])("uses only the latest request while the panel is loading (global: %s)", async (global) => {
+ const shell = mountShell();
+ shell.open({ connectionId: "c1", database: "old_database" });
+ await nextTick();
+ shell.open(global ? undefined : { connectionId: "c2", database: "latest_database" });
+ await nextTick();
+ await shell.resolve();
+ expect(mocks.search).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ source: "mcp",
+ connections: global ? [] : [{ connection_id: "c2", connection_name: "Test" }],
+ databases: global ? [] : [{ connection_id: "c2", connection_name: "Test", database: "latest_database" }],
+ }),
+ );
+ });
+
+ it("clears a previous resource scope when the global MCP entry is opened", async () => {
+ const shell = mountShell();
+ shell.open({ connectionId: "c1", database: "analytics" });
+ await nextTick();
+ await shell.resolve();
+ mocks.search.mockClear();
+ shell.open();
+ await vi.waitFor(() => expect(mocks.search).toHaveBeenLastCalledWith(expect.objectContaining({ source: "mcp", connections: [], databases: [] })));
+ });
+
+ it("keeps an ID-only scope if neither history options nor saved connections know the name", async () => {
+ mocks.getConfig.mockReturnValue(undefined);
+ const shell = mountShell();
+ shell.open({ connectionId: "deleted-connection", database: "analytics" });
+ await nextTick();
+ await shell.resolve();
+ expect(mocks.search).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ connections: [{ connection_id: "deleted-connection", connection_name: "" }],
+ databases: [{ connection_id: "deleted-connection", connection_name: "", database: "analytics" }],
+ }),
+ );
+ });
+});
diff --git a/apps/desktop/src/components/mcp/McpSqlApprovalDialog.vue b/apps/desktop/src/components/mcp/McpSqlApprovalDialog.vue
index 1536ab9ece..6cec355218 100644
--- a/apps/desktop/src/components/mcp/McpSqlApprovalDialog.vue
+++ b/apps/desktop/src/components/mcp/McpSqlApprovalDialog.vue
@@ -7,36 +7,58 @@ import { getCurrentWindow } from "@tauri-apps/api/window";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
-interface Approval {
+/**
+ * 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).
+ */
+interface SqlApproval {
+ allow_timed?: boolean;
id: string;
connection_name: string;
database: string;
sql: string;
}
+interface ToolApproval {
+ id: string;
+ kind: "plugin_tool" | "redis_command" | string;
+ tool: string;
+ plugin: string | null;
+ connection_name: string | null;
+ database: string | null;
+ detail: string;
+}
+
+type Approval = ({ type: "sql" } & SqlApproval) | ({ type: "tool" } & ToolApproval);
+
const { t } = useI18n();
const pending = ref<Approval[]>([]);
const current = computed(() => pending.value[0]);
const expirationTimers = new Map<string, ReturnType<typeof setTimeout>>();
-let unlisten: UnlistenFn | undefined;
+const unlisteners: UnlistenFn[] = [];
+
+function enqueue(approval: Approval) {
+ if (pending.value.some((item) => item.id === approval.id)) return;
+ 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();
+}
onMounted(async () => {
- unlisten = await listen<Approval>("mcp-sql-approval", (event) => {
- if (pending.value.some((approval) => approval.id === event.payload.id)) return;
- pending.value.push(event.payload);
- expirationTimers.set(
- event.payload.id,
- setTimeout(() => {
- pending.value = pending.value.filter((approval) => approval.id !== event.payload.id);
- expirationTimers.delete(event.payload.id);
- }, 90_000),
- );
- void getCurrentWindow().setFocus();
- });
+ 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 })));
});
onUnmounted(() => {
- unlisten?.();
+ for (const unlisten of unlisteners) unlisten();
for (const timer of expirationTimers.values()) clearTimeout(timer);
expirationTimers.clear();
});
@@ -48,28 +70,50 @@ async function decide(decision: "once" | "hour" | "day" | "deny") {
clearTimeout(expirationTimers.get(approval.id));
expirationTimers.delete(approval.id);
try {
- await invoke("respond_mcp_sql_approval", { id: approval.id, decision });
+ // 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 });
} catch (error) {
- console.error("[DBX] MCP SQL approval expired:", error);
+ console.error("[DBX] MCP approval expired:", error);
}
}
+
+function toolTitle(approval: Extract<Approval, { type: "tool" }>): string {
+ if (approval.kind === "redis_command") return t("settings.mcpToolApprovalRedisTitle");
+ if (approval.kind === "plugin_tool") return t("settings.mcpToolApprovalPluginTitle", { plugin: approval.plugin ?? approval.tool });
+ return t("settings.mcpToolApprovalGenericTitle");
+}
</script>
<template>
<Dialog :open="!!current" @update:open="(open) => !open && decide('deny')">
- <DialogContent class="sm:max-w-[640px]">
- <DialogHeader
- ><DialogTitle>{{ t("settings.mcpSqlApprovalTitle") }}</DialogTitle></DialogHeader
- >
- <div v-if="current" class="min-w-0 space-y-3">
+ <DialogContent class="sm:max-w-[640px]" :data-mcp-approval="current?.type">
+ <DialogHeader>
+ <DialogTitle>{{ current?.type === "tool" ? toolTitle(current) : t("settings.mcpSqlApprovalTitle") }}</DialogTitle>
+ </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>
<pre class="max-h-64 overflow-auto rounded border bg-muted/40 p-3 text-xs whitespace-pre-wrap break-all">{{ current.sql }}</pre>
</div>
+ <div v-else-if="current?.type === 'tool'" class="min-w-0 space-y-3">
+ <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>
+ <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>
<DialogFooter class="flex-wrap gap-2">
<Button variant="outline" @click="decide('deny')">{{ t("settings.mcpSqlApprovalDeny") }}</Button>
- <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 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>
</DialogContent>
</Dialog>
diff --git a/apps/desktop/src/components/mcp/__tests__/McpSqlApprovalDialog.spec.ts b/apps/desktop/src/components/mcp/__tests__/McpSqlApprovalDialog.spec.ts
index af36e21931..fd22bdb323 100644
--- a/apps/desktop/src/components/mcp/__tests__/McpSqlApprovalDialog.spec.ts
+++ b/apps/desktop/src/components/mcp/__tests__/McpSqlApprovalDialog.spec.ts
@@ -4,7 +4,7 @@ import { createI18n } from "vue-i18n";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
const bridge = vi.hoisted(() => ({
- handler: null as null | ((event: { payload: { id: string; connection_name: string; database: string; sql: string } }) => void),
+ handlers: {} as Record<string, (event: { payload: Record<string, unknown> }) => void>,
invoke: vi.fn(async () => undefined),
focus: vi.fn(async () => undefined),
unlisten: vi.fn(),
@@ -12,8 +12,8 @@ const bridge = vi.hoisted(() => ({
vi.mock("@tauri-apps/api/core", () => ({ invoke: bridge.invoke }));
vi.mock("@tauri-apps/api/event", () => ({
- listen: vi.fn(async (_name: string, handler: typeof bridge.handler) => {
- bridge.handler = handler;
+ listen: vi.fn(async (name: string, handler: (event: { payload: Record<string, unknown> }) => void) => {
+ bridge.handlers[name] = handler;
return bridge.unlisten;
}),
}));
@@ -34,7 +34,7 @@ let app: ReturnType<typeof createApp>;
beforeEach(async () => {
vi.useFakeTimers();
- bridge.handler = null;
+ bridge.handlers = {};
bridge.invoke.mockClear();
bridge.focus.mockClear();
bridge.unlisten.mockClear();
@@ -54,6 +54,12 @@ beforeEach(async () => {
mcpSqlApprovalHour: "One hour",
mcpSqlApprovalDay: "One day",
mcpSqlApprovalDeny: "Deny",
+ mcpToolApprovalPluginTitle: "Confirm {plugin} tool",
+ mcpToolApprovalGenericTitle: "Confirm high-risk tool call",
+ mcpToolApprovalRedisTitle: "Confirm Redis command",
+ mcpToolApprovalDescription: "Review the call",
+ mcpToolApprovalTool: "Tool",
+ mcpToolApprovalTarget: "Target",
},
},
},
@@ -70,7 +76,13 @@ afterEach(() => {
});
function request(id: string) {
- bridge.handler?.({ payload: { id, connection_name: "Local", database: "app", sql: "DROP TABLE important;" } });
+ bridge.handlers["mcp-sql-approval"]?.({ payload: { id, connection_name: "Local", database: "app", sql: "DROP TABLE important;" } });
+}
+
+function toolRequest(id: string) {
+ bridge.handlers["mcp-tool-approval"]?.({
+ payload: { id, kind: "plugin_tool", tool: "dbx_ssh__exec", plugin: "Terminal", connection_name: null, database: null, detail: '{ "command": "rm -rf /tmp/x" }' },
+ });
}
it("shows the exact SQL and sends a one-time decision for its request ID", async () => {
@@ -94,3 +106,42 @@ it("removes an unanswered request when the desktop approval times out", async ()
expect(host.textContent).not.toContain("DROP TABLE important;");
expect(bridge.invoke).not.toHaveBeenCalled();
});
+
+it("confirms high-risk tool calls once only and queues them with SQL approvals", async () => {
+ toolRequest("tool-1");
+ request("approval-3");
+ await nextTick();
+ expect(host.textContent).toContain("Confirm Terminal tool");
+ expect(host.textContent).toContain("dbx_ssh__exec");
+ expect(host.textContent).toContain("rm -rf /tmp/x");
+ const labels = Array.from(host.querySelectorAll("button")).map((button) => button.textContent);
+ expect(labels).toEqual(["Deny", "Once"]);
+ Array.from(host.querySelectorAll("button"))
+ .find((button) => button.textContent === "Once")
+ ?.click();
+ await nextTick();
+ expect(bridge.invoke).toHaveBeenCalledWith("respond_mcp_sql_approval", { id: "tool-1", decision: "once" });
+ // The queued SQL approval comes next with its timed choices.
+ expect(host.textContent).toContain("DROP TABLE important;");
+ expect(Array.from(host.querySelectorAll("button")).map((button) => button.textContent)).toContain("One hour");
+});
+
+it("offers only a single-call decision under the new SQL confirmation policy", async () => {
+ bridge.handlers["mcp-sql-approval"]({ payload: { id: "new-policy", allow_timed: false, connection_name: "Local", database: "app", sql: "DROP TABLE items" } });
+ await nextTick();
+ expect(Array.from(host.querySelectorAll("button")).map((button) => button.textContent)).toEqual(["Deny", "Once"]);
+ host.querySelector<HTMLButtonElement>("[data-mcp-approval-allow-once]")!.click();
+ await nextTick();
+ expect(bridge.invoke).toHaveBeenCalledWith("respond_mcp_sql_approval", { id: "new-policy", decision: "once" });
+});
+
+it.each(["product_tool", "mongo_command", "connection_management"])("uses a generic title and supports denial for %s", async (kind) => {
+ bridge.handlers["mcp-tool-approval"]({ payload: { id: kind, kind, tool: "dbx_example", connection_name: "Local", detail: "Destructive operation" } });
+ await nextTick();
+ expect(host.textContent).toContain("Confirm high-risk tool call");
+ expect(host.textContent).not.toContain("plugin");
+ const deny = Array.from(host.querySelectorAll("button")).find((button) => button.textContent === "Deny")!;
+ deny.click();
+ await nextTick();
+ expect(bridge.invoke).toHaveBeenCalledWith("respond_mcp_sql_approval", { id: kind, decision: "deny" });
+});
diff --git a/apps/desktop/src/components/plugins/PluginAiAccessSection.vue b/apps/desktop/src/components/plugins/PluginAiAccessSection.vue
index aac289ba06..7a9ab216f8 100644
--- a/apps/desktop/src/components/plugins/PluginAiAccessSection.vue
+++ b/apps/desktop/src/components/plugins/PluginAiAccessSection.vue
@@ -1,13 +1,14 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
-import { Bot, Database, Loader2, ShieldCheck, TriangleAlert, X } from "@lucide/vue";
+import { Bot, Database, Loader2, Plug, ShieldCheck, TriangleAlert, X } from "@lucide/vue";
import * as api from "@/lib/backend/api";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useToast } from "@/composables/useToast";
import type { InstalledPlugin } from "@/types/database";
+import { installedPluginOffersExternalMcp, installedPluginProvidesMcpTools } from "@/lib/plugins/pluginMcpMark";
import type { PluginDataGrant } from "@/types/pluginData";
import { PLUGIN_DATA_READ_PERMISSION } from "@/types/pluginData";
import type { PluginToolPreview } from "@/types/pluginAiTools";
@@ -26,6 +27,10 @@ const { toast } = useToast();
const pluginId = computed(() => props.plugin.manifest.id);
const hasBackend = computed(() => !!props.plugin.manifest.entrypoints?.backend);
+// External MCP is governed in Settings → MCP → Capabilities; this card only
+// mirrors the author opt-in so users know where the switch lives.
+const providesMcpTools = computed(() => installedPluginProvidesMcpTools(props.plugin));
+const externalMcpOffered = computed(() => installedPluginOffersExternalMcp(props.plugin));
const declaresDataRead = computed(() => (props.plugin.manifest.permissions || []).includes(PLUGIN_DATA_READ_PERMISSION));
const aiEnabled = ref(false);
@@ -138,6 +143,14 @@ watch(pluginId, () => void load(), { immediate: true });
</div>
</section>
+ <section v-if="providesMcpTools" class="flex items-start gap-2 rounded-lg border p-4" data-plugin-external-mcp>
+ <Plug class="mt-0.5 size-4 shrink-0 text-primary" />
+ <div class="min-w-0">
+ <div class="text-sm font-medium">{{ t("pluginPlatform.externalMcp.title") }}</div>
+ <p class="mt-1 text-xs leading-5 text-muted-foreground">{{ externalMcpOffered ? t("pluginPlatform.externalMcp.offered") : t("pluginPlatform.externalMcp.notOffered") }}</p>
+ </div>
+ </section>
+
<section v-if="declaresDataRead" class="space-y-3 rounded-lg border p-4" data-plugin-data-access>
<div class="flex min-w-0 items-start gap-2">
<Database class="mt-0.5 size-4 shrink-0 text-primary" />
diff --git a/apps/desktop/src/components/plugins/PluginContributionsPanel.vue b/apps/desktop/src/components/plugins/PluginContributionsPanel.vue
index d05ad34b25..fda2353948 100644
--- a/apps/desktop/src/components/plugins/PluginContributionsPanel.vue
+++ b/apps/desktop/src/components/plugins/PluginContributionsPanel.vue
@@ -45,6 +45,7 @@ import { useToast } from "@/composables/useToast";
import PluginShortcutSettings from "./PluginShortcutSettings.vue";
import PluginIcon from "@/components/plugins/PluginIcon.vue";
import PluginAiAccessSection from "@/components/plugins/PluginAiAccessSection.vue";
+import { installedPluginProvidesMcpTools, marketplacePluginProvidesMcpTools } from "@/lib/plugins/pluginMcpMark";
import PluginGraphicsEngineSection from "@/components/plugins/PluginGraphicsEngineSection.vue";
import * as api from "@/lib/backend/api";
import { clearPluginIconCache } from "@/lib/plugins/pluginIconResolver";
@@ -209,7 +210,11 @@ const mutationRunning = computed(() => batchRunning.value || !!marketplaceInstal
const registry = computed(() => createFrontendPluginRegistry(installedPlugins.value, appLocale.value));
const pinnedPluginIds = ref<string[]>(loadPinnedPluginIds());
-const definitions = computed(() => sortPluginsPinnedFirst(registry.value.listPlugins(), pinnedPluginIds.value));
+// "MCP tools" filter: plugins carrying the provides-MCP-tools mark.
+const installedMcpOnly = ref(false);
+const allDefinitions = computed(() => sortPluginsPinnedFirst(registry.value.listPlugins(), pinnedPluginIds.value));
+const installedMcpCount = computed(() => allDefinitions.value.filter((definition) => installedPluginProvidesMcpTools(definition.plugin)).length);
+const definitions = computed(() => (installedMcpOnly.value ? allDefinitions.value.filter((definition) => installedPluginProvidesMcpTools(definition.plugin)) : allDefinitions.value));
const isPluginPinned = (pluginId: string) => pinnedPluginIds.value.includes(pluginId);
const togglePluginPinned = (pluginId: string) => {
pinnedPluginIds.value = isPluginPinned(pluginId) ? pinnedPluginIds.value.filter((id) => id !== pluginId) : [...pinnedPluginIds.value, pluginId];
@@ -1541,7 +1546,12 @@ onBeforeUnmount(() => {
<div class="flex min-w-0 items-start gap-3">
<PluginIcon :plugin-id="listing.plugin.id" :icon="listing.plugin.icon" class="size-10 shrink-0 rounded-lg border bg-background p-1.5" />
<div class="min-w-0 flex-1">
- <div class="truncate text-sm font-semibold" :title="listing.name">{{ listing.name }}</div>
+ <div class="flex min-w-0 items-center gap-1.5">
+ <div class="truncate text-sm font-semibold" :title="listing.name">{{ listing.name }}</div>
+ <span v-if="marketplacePluginProvidesMcpTools(listing.plugin)" class="shrink-0 rounded border border-primary/40 px-1 text-[10px] font-medium leading-4 text-primary" :title="t('pluginPlatform.mcpToolsBadgeHint')" data-marketplace-mcp-badge>{{
+ t("pluginPlatform.mcpToolsBadge")
+ }}</span>
+ </div>
<div class="mt-1 flex min-w-0 items-center gap-1 text-xs text-muted-foreground">
<BadgeCheck v-if="listing.verified" class="size-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" :title="t('pluginPlatform.verified')" :aria-label="t('pluginPlatform.verified')" />
<span class="min-w-0 truncate"
@@ -1674,6 +1684,9 @@ onBeforeUnmount(() => {
<div class="flex min-w-0 items-center gap-1">
<span class="truncate text-sm font-semibold" :title="listing.name">{{ listing.name }}</span>
<BadgeCheck v-if="listing.verified" class="size-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" :title="t('pluginPlatform.verified')" :aria-label="t('pluginPlatform.verified')" />
+ <span v-if="marketplacePluginProvidesMcpTools(listing.plugin)" class="shrink-0 rounded border border-primary/40 px-1 text-[10px] font-medium leading-4 text-primary" :title="t('pluginPlatform.mcpToolsBadgeHint')" data-marketplace-mcp-badge>{{
+ t("pluginPlatform.mcpToolsBadge")
+ }}</span>
</div>
<div class="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs text-muted-foreground">
<span class="min-w-0 truncate"
@@ -1806,6 +1819,10 @@ onBeforeUnmount(() => {
</div>
<div class="grid min-h-0 flex-1 gap-4 lg:grid-cols-[260px_minmax(0,1fr)]">
<div class="space-y-1 rounded-lg border bg-muted/10 p-2">
+ <label v-if="installedMcpCount || installedMcpOnly" class="flex items-center gap-1.5 px-2 py-1 text-[11px] text-muted-foreground" data-plugin-mcp-filter>
+ <input v-model="installedMcpOnly" type="checkbox" />
+ {{ t("pluginPlatform.mcpToolsFilter", { count: installedMcpCount }) }}
+ </label>
<div
v-for="definition in definitions"
:key="definition.plugin.manifest.id"
@@ -1834,6 +1851,7 @@ onBeforeUnmount(() => {
<ArrowUp class="size-2.5" />v{{ installedUpdateEntryFor(definition.plugin.manifest.id)?.listing.plugin.latestVersion }}
</span>
<Badge :variant="definition.plugin.compatibility.compatible ? 'secondary' : 'destructive'" class="h-4 px-1.5 text-[10px]">{{ definition.plugin.compatibility.compatible ? t("pluginPlatform.compatible") : t("pluginPlatform.blocked") }}</Badge>
+ <Badge v-if="installedPluginProvidesMcpTools(definition.plugin)" variant="outline" class="h-4 border-primary/40 px-1.5 text-[10px] text-primary" :title="t('pluginPlatform.mcpToolsBadgeHint')" data-plugin-mcp-badge>{{ t("pluginPlatform.mcpToolsBadge") }}</Badge>
<Badge v-if="catalogChecked && !catalogPartialFailure && !pluginInCatalog(definition.plugin.manifest.id)" variant="outline" class="h-4 border-dashed px-1.5 text-[10px] text-muted-foreground" :title="t('pluginPlatform.notInRepositoriesHint')">{{
t("pluginPlatform.notInRepositories")
}}</Badge>
@@ -2108,6 +2126,7 @@ onBeforeUnmount(() => {
</DialogTitle>
<DialogDescription class="mt-1 flex flex-wrap items-center gap-1.5 text-xs">
<BadgeCheck v-if="selectedMarketplaceListing.verified" class="size-3.5 text-emerald-600 dark:text-emerald-400" :title="t('pluginPlatform.verified')" />
+ <span v-if="marketplacePluginProvidesMcpTools(selectedMarketplaceListing.plugin)" class="rounded border border-primary/40 px-1 text-[10px] font-medium leading-4 text-primary" :title="t('pluginPlatform.mcpToolsBadgeHint')">{{ t("pluginPlatform.mcpToolsBadge") }}</span>
<button type="button" class="rounded-sm font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" @click.stop="filterByPublisher(selectedMarketplaceListing.plugin.publisher)">
{{ selectedMarketplaceListing.plugin.publisher }}
</button>
diff --git a/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts b/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts
index 292deb0155..cd6660e85d 100644
--- a/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts
+++ b/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
openPluginConnection: vi.fn(),
openPluginWorkbench: vi.fn(),
listPlugins: vi.fn(),
+ getAiPluginToolPlugins: vi.fn(async () => []),
listPluginTrustedKeys: vi.fn(),
listPluginRepositories: vi.fn(),
fetchPluginMarketplaceCatalogs: vi.fn(),
@@ -279,6 +280,26 @@ afterEach(() => {
});
describe("PluginContributionsPanel batch source validation", () => {
+ it("keeps the MCP filter available after the last matching plugin is removed", async () => {
+ const marked = installed("mcp");
+ marked.manifest.entrypoints = { backend: { executable: "sidecar" } };
+ marked.manifest.contributions = [{ type: "mcp", id: "mcp.tools" }];
+ state.installedPlugins = [marked, installed("ordinary")];
+ state.activeSection = "installed";
+ await flushUi();
+ host.querySelector<HTMLInputElement>("[data-plugin-mcp-filter] input")!.click();
+ await nextTick();
+ state.installedPlugins = [installed("ordinary")];
+ await flushUi();
+ const filter = host.querySelector<HTMLInputElement>("[data-plugin-mcp-filter] input");
+ expect(filter).not.toBeNull();
+ expect(filter!.checked).toBe(true);
+ filter!.click();
+ await nextTick();
+ expect(host.textContent).toContain("ordinary");
+ expect(host.querySelector("[data-plugin-mcp-filter]")).toBeNull();
+ });
+
it.each(["first", "second"])("does not silently resolve selected source conflicts by filtering to %s", async (repositoryId) => {
state.catalogResults = [catalog("first", ["a"]), catalog("second", ["a"], "2.0.0")];
state.selectAllUpdatable();
diff --git a/apps/desktop/src/components/settings/McpAccessTree.vue b/apps/desktop/src/components/settings/McpAccessTree.vue
new file mode 100644
index 0000000000..e10724be99
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpAccessTree.vue
@@ -0,0 +1,384 @@
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { ChevronDown, ChevronRight, Database, Folder, History, Search, Server } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import type { McpConnectionPolicy, McpGlobalPolicy } from "@/lib/backend/tauri";
+import { buildMcpAccessTreeRows, countMcpTreeExceptions, type McpTreeConnectionRow, type McpTreeLevel, type McpTreeRow, type McpTreeSetting } from "@/lib/mcp/mcpAccessTree";
+import type { ConnectionConfig, SidebarLayout } from "@/types/database";
+import type { McpAccessPolicy, McpAccessRule, McpSubScopeMode } from "@/types/mcpCatalog";
+import McpPluginScopeEditor from "@/components/settings/McpPluginScopeEditor.vue";
+import McpDatabaseAccessDialog from "./McpDatabaseAccessDialog.vue";
+import { databaseConnectionRow, editableDatabaseAccess, type McpDatabaseAccess, type McpDatabaseAccessPolicy } from "@/lib/mcp/mcpDatabaseAccess";
+import { openMcpCallHistory } from "@/lib/mcp/mcpCallHistory";
+
+/**
+ * Access-control tree: one table over groups, connections and databases that
+ * replaces the four-step wizard's scope / database / permission steps. Each row
+ * edits its own setting; the effective level and its source are always shown.
+ * All edits are emitted to the settings dialog, which stages them in the MCP
+ * policy draft (the existing v1 policy fields).
+ */
+const props = withDefaults(
+ defineProps<{
+ policy: Pick<McpGlobalPolicy, "readOnly" | "allowDangerousSql" | "allowedConnectionIds" | "allowedGroupIds" | "connectionPolicies" | "groupPolicies">;
+ layout: SidebarLayout;
+ connections: readonly ConnectionConfig[];
+ disabled?: boolean;
+ /** Loads the databases of one connection (session cache lives here). */
+ loadDatabases?: (connection: ConnectionConfig) => Promise<string[]>;
+ /** Declared plugin sub-scope (`mcp.scope`) by plugin id. */
+ pluginScopes?: Record<string, { kind: string; title: string }>;
+ savedPolicy?: McpDatabaseAccessPolicy;
+ saveDatabaseAccess?: (connectionId: string) => Promise<void>;
+ accessPolicy?: McpAccessPolicy | null;
+ savePluginScope?: (connectionId: string, kind: string, value: string | null, rule: McpAccessRule | null, subScope: McpSubScopeMode | null) => Promise<McpAccessPolicy>;
+ listPluginScopes?: (pluginId: string, connectionId: string) => Promise<{ values: string[] }>;
+ }>(),
+ { disabled: false, loadDatabases: undefined, pluginScopes: () => ({}), accessPolicy: null, savePluginScope: undefined, listPluginScopes: undefined },
+);
+
+const emit = defineEmits<{
+ "set:scope-mode": [mode: "all" | "custom"];
+ "set:group-visible": [groupId: string, visible: boolean];
+ "set:connection-visible": [connectionId: string, visible: boolean];
+ "set:group-level": [groupId: string, setting: McpTreeSetting];
+ "set:connection-level": [connectionId: string, setting: McpTreeSetting];
+ "set:database-access": [connectionId: string, value: McpDatabaseAccess];
+ "set:database-scope": [connectionId: string, scope: McpConnectionPolicy["databaseScope"]];
+ "set:database-allowed": [connectionId: string, database: string, allowed: boolean];
+ "set:database-level": [connectionId: string, database: string, setting: McpTreeSetting];
+ "set:salesforce-dml": [connectionId: string, allowed: boolean];
+ "plugin-scope-saved": [policy: McpAccessPolicy];
+}>();
+
+// Built-in product providers with a sub-scope the server enforces per call.
+// Consul's datacenter is the connection's own setting, so it has none here.
+const PRODUCT_SCOPES: Partial<Record<string, { kind: string; titleKey: string }>> = {
+ nacos: { kind: "namespace", titleKey: "settings.mcpAccessTreeNacosNamespace" },
+};
+
+function pluginScopeFor(row: Pick<McpTreeConnectionRow, "connection">): { kind: string; title: string } | null {
+ const product = PRODUCT_SCOPES[row.connection.db_type];
+ if (product) return { kind: product.kind, title: t(product.titleKey) };
+ const pluginId = row.connection.plugin_id;
+ return pluginId ? (props.pluginScopes[pluginId] ?? null) : null;
+}
+
+/** Database scope only applies to connections whose MCP tools take a database. */
+function showsDatabaseScope(row: McpTreeConnectionRow): boolean {
+ return !PRODUCT_SCOPES[row.connection.db_type] && row.connection.db_type !== "consul" && !row.connection.plugin_id;
+}
+
+const { t } = useI18n();
+const query = ref("");
+const exceptionsOnly = ref(false);
+const expandedGroupIds = ref(new Set<string>());
+const expandedConnectionIds = ref(new Set<string>());
+const pickerConnectionId = ref<string | null>(null);
+let pickerTrigger: HTMLElement | null = null;
+const pickerRow = computed(() => (pickerConnectionId.value ? databaseConnectionRow(props.policy, pickerConnectionId.value, props.layout, props.connections) : undefined));
+const pickerSavedRow = computed(() => (pickerConnectionId.value ? databaseConnectionRow(props.savedPolicy ?? props.policy, pickerConnectionId.value, props.layout, props.connections) : undefined));
+const pickerValue = computed(() => editableDatabaseAccess(props.policy, pickerConnectionId.value ?? "", props.layout, props.connections));
+const pickerSavedValue = computed(() => editableDatabaseAccess(props.savedPolicy ?? props.policy, pickerConnectionId.value ?? "", props.layout, props.connections));
+
+// v2-only scopes are persisted separately from the staged SQL policy. Keep
+// them visible in the exceptions filter even under collapsed ancestors.
+const scopeExceptionIds = computed(
+ () =>
+ new Set(
+ props.connections
+ .filter((connection) => {
+ const scope = pluginScopeFor({ connection });
+ return (
+ scope &&
+ props.accessPolicy?.rules.some((rule) => (rule.target.kind === "connection" && rule.target.id === connection.id && rule.subScope !== undefined && rule.subScope !== "all") || (rule.target.kind === "scope" && rule.target.connectionId === connection.id && rule.target.scope === scope.kind))
+ );
+ })
+ .map((connection) => connection.id),
+ ),
+);
+
+const customScope = computed(() => props.policy.allowedConnectionIds !== null);
+const rows = computed(() =>
+ buildMcpAccessTreeRows(props.policy, props.layout, props.connections, {
+ expandedGroupIds: expandedGroupIds.value,
+ expandedConnectionIds: expandedConnectionIds.value,
+ query: query.value,
+ exceptionsOnly: exceptionsOnly.value,
+ scopeExceptionIds: scopeExceptionIds.value,
+ }),
+);
+const exceptionCounts = computed(() => countMcpTreeExceptions(props.policy, scopeExceptionIds.value));
+const visibleConnectionCount = computed(() => {
+ const all = buildMcpAccessTreeRows(props.policy, props.layout, props.connections, { expandedGroupIds: new Set(props.layout.groups.map((group) => group.id)), expandedConnectionIds: new Set() });
+ return all.filter((row) => row.type === "connection" && row.visible).length;
+});
+
+const LEVELS: McpTreeLevel[] = ["read_only", "safe_write", "high_risk_write"];
+
+function toggle(set: Set<string>, id: string): Set<string> {
+ const next = new Set(set);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+}
+
+function levelLabel(level: McpTreeLevel): string {
+ return t(level === "read_only" ? "settings.mcpExecutionModeReadOnly" : level === "safe_write" ? "settings.mcpExecutionModeSafeWrite" : "settings.mcpExecutionModeHighRiskWrite");
+}
+
+function sourceLabel(row: McpTreeRow): string {
+ switch (row.source.kind) {
+ case "global":
+ return t("settings.mcpAccessTreeSourceGlobal");
+ case "group":
+ return t("settings.mcpAccessTreeSourceGroup", { group: row.source.groupName });
+ case "connection":
+ return t("settings.mcpAccessTreeSourceConnection");
+ case "database":
+ return t("settings.mcpAccessTreeSourceDatabase");
+ }
+}
+
+const levelClass: Record<McpTreeLevel, string> = {
+ read_only: "text-foreground",
+ safe_write: "text-amber-700 dark:text-amber-300",
+ high_risk_write: "text-red-600 dark:text-red-400",
+};
+
+function onSettingChange(row: McpTreeRow, value: string) {
+ const setting = value as McpTreeSetting;
+ // The settings owner confirms once before changing its draft.
+ if (row.type === "group") emit("set:group-level", row.id, setting);
+ else if (row.type === "connection") emit("set:connection-level", row.id, setting);
+ else emit("set:database-level", row.connectionId, row.database, setting);
+}
+
+function onVisibleChange(row: McpTreeRow, visible: boolean) {
+ if (row.type === "group") emit("set:group-visible", row.id, visible);
+ else if (row.type === "connection") emit("set:connection-visible", row.id, visible);
+}
+
+function visibilityLocked(row: McpTreeRow): boolean {
+ return !customScope.value || row.type === "database" || row.coveredBy !== null;
+}
+
+function visibilityChecked(row: McpTreeRow): boolean {
+ if (!customScope.value) return true;
+ return row.type === "database" ? row.visible : row.selected || row.coveredBy !== null;
+}
+
+function visibilityIndeterminate(row: McpTreeRow): boolean {
+ return row.type === "group" && !row.visible && row.visibleConnectionCount > 0;
+}
+
+function hasVisibleResources(row: McpTreeRow): boolean {
+ return row.visible || visibilityIndeterminate(row);
+}
+
+function groupVisibilityLabel(row: McpTreeRow): string {
+ if (row.type !== "group") return "";
+ return t(row.visibleConnectionCount === row.connectionCount ? "settings.mcpAccessTreeGroupCurrentVisible" : "settings.mcpAccessTreeGroupPartiallyVisible", { visible: row.visibleConnectionCount, total: row.connectionCount });
+}
+
+function openDatabasePicker(row: McpTreeConnectionRow, event: MouseEvent) {
+ pickerTrigger = event.currentTarget as HTMLElement;
+ pickerConnectionId.value = row.id;
+}
+function restorePickerFocus() {
+ if (pickerTrigger?.isConnected) pickerTrigger.focus();
+}
+
+function openResourceHistory(row: McpTreeRow) {
+ if (row.type === "group") return;
+ openMcpCallHistory({ connectionId: row.type === "connection" ? row.id : row.connectionId, database: row.type === "database" ? row.database : undefined });
+}
+</script>
+
+<template>
+ <section class="space-y-3" data-mcp-access-tree>
+ <header class="flex flex-wrap items-start justify-between gap-3">
+ <div class="min-w-0">
+ <p class="text-sm font-semibold">{{ t("settings.mcpAccessTreeTitle") }}</p>
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpAccessTreeDescription") }}</p>
+ <p class="mt-1 text-[11px] text-muted-foreground" data-mcp-access-tree-summary>
+ {{ t("settings.mcpAccessTreeSummary", { visible: visibleConnectionCount, total: connections.length, groups: exceptionCounts.groups, connections: exceptionCounts.connections, databases: exceptionCounts.databases }) }}
+ </p>
+ </div>
+ <div class="flex rounded-md border p-0.5 text-xs" role="radiogroup" :aria-label="t('settings.mcpAccessTreeScopeLabel')">
+ <button
+ v-for="mode in ['all', 'custom'] as const"
+ :key="mode"
+ type="button"
+ role="radio"
+ class="rounded px-2.5 py-1"
+ :class="(mode === 'custom') === customScope ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground'"
+ :aria-checked="(mode === 'custom') === customScope"
+ :disabled="disabled"
+ :data-mcp-access-scope-mode="mode"
+ @click="emit('set:scope-mode', mode)"
+ >
+ {{ t(mode === "all" ? "settings.mcpAccessTreeScopeAll" : "settings.mcpAccessTreeScopeCustom") }}
+ </button>
+ </div>
+ </header>
+
+ <div class="flex flex-wrap items-center gap-2">
+ <div class="relative min-w-48 flex-1">
+ <Search class="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input v-model="query" class="h-8 pl-8 text-xs" :placeholder="t('settings.mcpAccessTreeSearchPlaceholder')" />
+ </div>
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <input v-model="exceptionsOnly" type="checkbox" data-mcp-access-exceptions-only />
+ {{ t("settings.mcpAccessTreeExceptionsOnly") }}
+ </label>
+ </div>
+
+ <div class="overflow-x-auto rounded-md border">
+ <table class="w-full min-w-[46rem] table-fixed text-xs">
+ <thead class="bg-muted/50 text-muted-foreground">
+ <tr>
+ <th class="w-[42%] px-3 py-2 text-left font-medium">{{ t("settings.mcpAccessTreeColumnResource") }}</th>
+ <th class="w-[10%] px-2 py-2 text-center font-medium">{{ t("settings.mcpAccessTreeColumnVisible") }}</th>
+ <th class="w-[20%] px-2 py-2 text-left font-medium">{{ t("settings.mcpAccessTreeColumnSetting") }}</th>
+ <th class="w-[28%] px-2 py-2 text-left font-medium">{{ t("settings.mcpAccessTreeColumnEffective") }}</th>
+ </tr>
+ </thead>
+ <tbody class="divide-y">
+ <template v-for="row in rows" :key="row.key">
+ <tr :class="hasVisibleResources(row) ? '' : 'text-muted-foreground'" :data-mcp-access-row="row.key">
+ <td class="px-3 py-1.5">
+ <div class="flex min-w-0 items-center gap-1.5" :style="{ paddingLeft: `${row.depth * 16}px` }">
+ <button
+ v-if="row.type === 'group' || (row.type === 'connection' && row.databaseCount > 0)"
+ type="button"
+ class="shrink-0 text-muted-foreground hover:text-foreground"
+ :aria-expanded="row.type === 'group' ? expandedGroupIds.has(row.id) : expandedConnectionIds.has(row.id)"
+ :data-mcp-access-toggle="row.key"
+ @click="row.type === 'group' ? (expandedGroupIds = toggle(expandedGroupIds, row.id)) : (expandedConnectionIds = toggle(expandedConnectionIds, row.id))"
+ >
+ <ChevronDown v-if="row.type === 'group' ? expandedGroupIds.has(row.id) : expandedConnectionIds.has(row.id)" class="size-3.5" />
+ <ChevronRight v-else class="size-3.5" />
+ </button>
+ <span v-else class="w-3.5 shrink-0" />
+ <Folder v-if="row.type === 'group'" class="size-3.5 shrink-0 text-muted-foreground" />
+ <Server v-else-if="row.type === 'connection'" class="size-3.5 shrink-0 text-muted-foreground" />
+ <Database v-else class="size-3.5 shrink-0 text-muted-foreground" />
+ <button
+ v-if="row.type === 'group' && row.childCount > 0"
+ type="button"
+ class="min-w-0 truncate rounded text-left font-medium hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ :aria-expanded="expandedGroupIds.has(row.id)"
+ :data-mcp-access-group-name="row.id"
+ @click="expandedGroupIds = toggle(expandedGroupIds, row.id)"
+ >
+ {{ row.name }}
+ </button>
+ <span v-else class="min-w-0 truncate" :class="row.type === 'database' ? 'font-mono' : 'font-medium'">
+ {{ row.type === "group" ? row.name : row.type === "connection" ? row.connection.name : row.database }}
+ </span>
+ <span v-if="row.type === 'group'" class="shrink-0 text-[11px] text-muted-foreground">{{ t("settings.mcpAccessTreeGroupCount", { count: row.connectionCount }) }}</span>
+ <span v-if="row.type === 'connection'" class="shrink-0 font-mono text-[10px] text-muted-foreground">{{ row.connection.db_type }}</span>
+ <span v-if="row.type === 'connection' && row.legacy" class="shrink-0 rounded border px-1 text-[10px] text-muted-foreground" :title="t('settings.mcpAccessTreeLegacyHint')">{{ t("settings.mcpAccessTreeLegacy") }}</span>
+ <Button v-if="row.type === 'connection' || row.type === 'database'" variant="ghost" size="icon" class="ml-auto size-6 shrink-0" :title="t('history.title')" :aria-label="t('history.title')" :data-mcp-access-history="row.key" @click.stop="openResourceHistory(row)">
+ <History class="size-3.5" />
+ </Button>
+ </div>
+ </td>
+ <td class="px-2 py-1.5 text-center">
+ <input
+ v-if="row.type !== 'database'"
+ type="checkbox"
+ :checked="visibilityChecked(row)"
+ :indeterminate="visibilityIndeterminate(row)"
+ :aria-checked="visibilityIndeterminate(row) ? 'mixed' : visibilityChecked(row)"
+ :disabled="disabled || visibilityLocked(row)"
+ :title="visibilityIndeterminate(row) ? t('settings.mcpAccessTreeGroupChildrenOnlyHint') : row.coveredBy ? t('settings.mcpAccessTreeCoveredByGroup') : undefined"
+ :aria-description="visibilityIndeterminate(row) ? `${groupVisibilityLabel(row)}. ${t('settings.mcpAccessTreeGroupChildrenOnlyHint')}` : undefined"
+ :aria-label="t('settings.mcpAccessTreeColumnVisible')"
+ :data-mcp-access-visible="row.key"
+ @change="onVisibleChange(row, ($event.target as HTMLInputElement).checked)"
+ />
+ </td>
+ <td class="px-2 py-1.5">
+ <span v-if="row.type === 'database'">{{ row.setting === "inherit" ? t("settings.mcpAccessTreeInherit") : levelLabel(row.setting) }}</span>
+ <Select v-else :model-value="row.setting" :disabled="disabled || !hasVisibleResources(row)" @update:model-value="(value) => onSettingChange(row, String(value))">
+ <SelectTrigger size="sm" class="h-7 w-full text-xs" :aria-label="t('settings.mcpAccessTreeColumnSetting')" :title="row.type === 'group' ? t('settings.mcpAccessTreeGroupDefaultHint') : undefined" :data-mcp-access-setting="row.key">
+ <SelectValue>{{ row.setting === "inherit" ? t("settings.mcpAccessTreeInherit") : levelLabel(row.setting) }}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="inherit">{{ t("settings.mcpAccessTreeInherit") }}</SelectItem>
+ <SelectItem v-for="level in LEVELS" :key="level" :value="level">{{ levelLabel(level) }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </td>
+ <td class="px-2 py-1.5" :data-mcp-access-effective="row.key">
+ <span v-if="visibilityIndeterminate(row)" class="font-medium">{{ groupVisibilityLabel(row) }}</span>
+ <span v-else-if="!row.visible" class="text-muted-foreground">{{ t("settings.mcpAccessTreeHidden") }}</span>
+ <span v-else class="flex min-w-0 flex-wrap items-baseline gap-x-1.5 gap-y-0.5">
+ <span class="font-medium" :class="levelClass[row.effective]">{{ levelLabel(row.effective) }}</span>
+ <span class="break-words text-[11px] text-muted-foreground [overflow-wrap:anywhere]">{{ sourceLabel(row) }}</span>
+ </span>
+ </td>
+ </tr>
+ <!-- Connection extras: database scope and Salesforce writes. -->
+ <tr v-if="row.type === 'connection' && row.visible" class="bg-muted/20" :data-mcp-access-connection-extras="row.id">
+ <td colspan="4" class="px-3 py-1">
+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground" :style="{ paddingLeft: `${row.depth * 16 + 22}px` }">
+ <template v-if="showsDatabaseScope(row)">
+ <span>{{ t("settings.mcpAccessTreeDatabases") }}</span>
+ <span :data-mcp-access-database-scope="row.id">{{
+ t(row.databaseScope === "all" ? "settings.mcpAccessTreeDatabaseScopeAll" : row.databaseScope === "none" ? "settings.mcpAccessTreeDatabaseScopeNone" : "settings.mcpAccessTreeDatabaseScopeSelected", { count: row.databaseCount })
+ }}</span>
+ <span v-if="policy.connectionPolicies.find((entry) => entry.connectionId === row.id)?.databasePolicies.length">{{ t("settings.mcpDatabaseOverrideCount", { count: policy.connectionPolicies.find((entry) => entry.connectionId === row.id)?.databasePolicies.length }) }}</span>
+ <Button variant="outline" size="sm" class="h-7 text-xs" :disabled="disabled" :data-mcp-access-pick-databases="row.id" @click="openDatabasePicker(row, $event)">{{ t("settings.mcpDatabaseConfigure") }}</Button>
+ </template>
+ <label v-if="row.connection.db_type === 'salesforce'" class="flex items-center gap-1">
+ <input type="checkbox" :checked="row.salesforceDml" :disabled="disabled || row.effective === 'read_only'" :data-mcp-access-salesforce="row.id" @change="emit('set:salesforce-dml', row.id, ($event.target as HTMLInputElement).checked)" />
+ {{ t("settings.mcpConnectionPolicyAllowSalesforceDml") }}
+ </label>
+ </div>
+ <div v-if="pluginScopeFor(row) && savePluginScope" class="mt-1" :style="{ paddingLeft: `${row.depth * 16 + 22}px` }">
+ <McpPluginScopeEditor
+ :connection-id="row.id"
+ :plugin-id="row.connection.plugin_id ?? ''"
+ :kind="pluginScopeFor(row)!.kind"
+ :title="pluginScopeFor(row)!.title"
+ :policy="accessPolicy"
+ :disabled="disabled"
+ :save="savePluginScope"
+ :list-values="row.connection.plugin_id ? listPluginScopes : undefined"
+ @saved="emit('plugin-scope-saved', $event)"
+ />
+ </div>
+ </td>
+ </tr>
+ </template>
+ <tr v-if="rows.length === 0">
+ <td colspan="4" class="px-3 py-6 text-center text-muted-foreground">{{ t(query || exceptionsOnly ? "settings.mcpAccessTreeNoMatch" : "settings.mcpAccessTreeEmpty") }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <p class="text-[11px] leading-relaxed text-muted-foreground">{{ t("settings.mcpAccessTreeFootnote") }}</p>
+ <McpDatabaseAccessDialog
+ v-if="pickerRow"
+ :open="pickerConnectionId !== null"
+ :connection="pickerRow.connection"
+ :value="pickerValue"
+ :saved-value="pickerSavedValue"
+ :inherited-label="`${levelLabel(pickerRow.effective)} · ${sourceLabel(pickerRow)}`"
+ :saved-inherited-label="pickerSavedRow ? `${levelLabel(pickerSavedRow.effective)} · ${sourceLabel(pickerSavedRow)}` : ''"
+ :saved-visible="pickerSavedRow?.visible ?? false"
+ :disabled="disabled"
+ :load-databases="loadDatabases"
+ :save="saveDatabaseAccess"
+ @change="emit('set:database-access', pickerRow.id, $event)"
+ @update:open="!$event && (pickerConnectionId = null)"
+ @return-focus="restorePickerFocus"
+ />
+ </section>
+</template>
diff --git a/apps/desktop/src/components/settings/McpCallSafetyPanel.vue b/apps/desktop/src/components/settings/McpCallSafetyPanel.vue
new file mode 100644
index 0000000000..b2716a9430
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpCallSafetyPanel.vue
@@ -0,0 +1,45 @@
+<script setup lang="ts">
+import { nextTick, ref, useId } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+
+const props = defineProps<{ mode: "off" | "full" | "high_risk"; disabled?: boolean }>();
+const emit = defineEmits<{ "set:confirmation": [enabled: boolean] }>();
+const { t } = useI18n();
+const hintId = useId();
+const expanded = ref(props.mode === "full");
+const confirmationInput = ref<HTMLInputElement | null>(null);
+async function setConfirmation(enabled: boolean) {
+ if (props.disabled) return;
+ const leavingLegacy = props.mode === "full";
+ emit("set:confirmation", enabled);
+ if (leavingLegacy) {
+ await nextTick();
+ confirmationInput.value?.focus();
+ }
+}
+</script>
+
+<template>
+ <details class="min-w-0 space-y-3 rounded-md border bg-background p-3 sm:p-4" :open="expanded" data-mcp-call-safety @toggle="expanded = ($event.target as HTMLDetailsElement).open">
+ <summary class="cursor-pointer rounded-sm text-sm font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {{ t("settings.mcpCallSafety") }}
+ <span class="ml-2 text-xs font-normal text-muted-foreground" data-mcp-safety-status>{{ t(mode === "full" ? "settings.mcpCallSafetyLegacy" : mode === "high_risk" ? "settings.mcpCallSafetyEnabled" : "settings.mcpCallSafetyDisabled") }}</span>
+ </summary>
+ <template v-if="mode === 'full'">
+ <p class="text-xs leading-relaxed text-muted-foreground" data-mcp-safety-legacy>{{ t("settings.mcpCallSafetyLegacyHint") }}</p>
+ <div class="flex flex-wrap gap-2">
+ <Button type="button" size="sm" variant="outline" :disabled="disabled" data-mcp-safety-migrate @click="setConfirmation(true)">{{ t("settings.mcpCallSafetyMigrate") }}</Button>
+ <Button type="button" size="sm" variant="ghost" :disabled="disabled" data-mcp-safety-disable-legacy @click="setConfirmation(false)">{{ t("settings.mcpCallSafetyDisableLegacy") }}</Button>
+ </div>
+ </template>
+ <template v-else>
+ <label class="flex items-center gap-2 text-xs">
+ <input ref="confirmationInput" type="checkbox" class="shrink-0 accent-primary" :checked="mode === 'high_risk'" :disabled="disabled" :aria-describedby="hintId" data-mcp-high-risk-confirmation @change="setConfirmation(($event.target as HTMLInputElement).checked)" />
+ {{ t("settings.mcpCallSafetyConfirm") }}
+ </label>
+ <p :id="hintId" class="text-xs leading-relaxed text-muted-foreground">{{ t("settings.mcpCallSafetyHint") }}</p>
+ <p class="text-xs leading-relaxed text-muted-foreground">{{ t("settings.mcpCallSafetyDesktopHint") }}</p>
+ </template>
+ </details>
+</template>
diff --git a/apps/desktop/src/components/settings/McpCapabilitiesPanel.vue b/apps/desktop/src/components/settings/McpCapabilitiesPanel.vue
new file mode 100644
index 0000000000..f9689f9afb
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpCapabilitiesPanel.vue
@@ -0,0 +1,429 @@
+<script setup lang="ts">
+import { computed, nextTick, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { ChevronDown, ChevronRight, Loader2, Minus, Search } from "@lucide/vue";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import type { McpAccessLevel, McpToolCatalog, McpToolCatalogTool, McpToolCatalogToolset } from "@/types/mcpCatalog";
+import { mcpToolsetTitle } from "@/lib/mcp/mcpCapabilitySearch";
+import {
+ groupMcpDatabaseTypesByCategory,
+ mcpCoverageByCategory,
+ mcpDatabaseTypeLabel,
+ mcpToolAllowed,
+ mcpToolLabelKey,
+ mcpToolsetAccessLevels,
+ mcpToolsetHasCoverage,
+ mcpToolsetMessageKey,
+ mcpToolsetScopeKinds,
+ mcpToolsetState,
+ summarizeMcpToolsetCoverage,
+ type McpCoverageConnection,
+} from "@/lib/mcp/mcpToolCatalog";
+
+/**
+ * MCP capability tab: built-in toolsets as cards, each with its applicable
+ * database coverage. Toolset and tool switches only edit the flat
+ * `allowedToolNames` allowlist owned by the settings dialog.
+ */
+const props = withDefaults(
+ defineProps<{
+ catalog: McpToolCatalog | null;
+ loading?: boolean;
+ loadError?: string;
+ allowedToolNames: readonly string[] | null;
+ savedToolNames?: readonly string[] | null;
+ saveToolset?: (toolsetId: string) => Promise<void>;
+ connections: readonly McpCoverageConnection[];
+ disabled?: boolean;
+ filterKind?: "all" | "builtin" | "plugin";
+ onlyEnabled?: boolean;
+ visibleToolsetIds?: readonly string[];
+ titlePath?: string;
+ listHidden?: boolean;
+ focusFallback?: () => void;
+ }>(),
+ { loading: false, loadError: "", disabled: false, filterKind: "all", onlyEnabled: false },
+);
+
+const emit = defineEmits<{
+ "set:toolset": [toolset: McpToolCatalogToolset, enabled: boolean];
+ "set:tool": [toolName: string, enabled: boolean];
+ retry: [];
+}>();
+
+const { t } = useI18n();
+const detailToolsetId = ref<string | null>(null);
+const detailTitlePath = ref("");
+const detailView = ref<"tools" | "coverage">("tools");
+const coverageSearch = ref("");
+const expandedToolNames = ref(new Set<string>());
+const detailSaving = ref(false);
+const detailSaveError = ref("");
+let detailTrigger: HTMLElement | null = null;
+
+const userConnectionTypes = computed(() => new Set(props.connections.map((connection) => connection.dbType)));
+
+function toolLabel(tool: McpToolCatalogTool): string {
+ const key = mcpToolLabelKey(tool.name);
+ return key ? t(key) : tool.name;
+}
+
+// Keep the complete view model separate from navigation filters. An open detail
+// must survive category changes and switching off its final enabled tool.
+const allCards = computed(() =>
+ (props.catalog?.toolsets ?? []).map((toolset) => ({
+ toolset,
+ title: mcpToolsetTitle(toolset.id, t),
+ description: toolsetDescription(toolset.id),
+ scopeKinds: mcpToolsetScopeKinds(toolset),
+ state: mcpToolsetState(props.allowedToolNames, toolset),
+ enabledCount: toolset.tools.filter((tool) => mcpToolAllowed(props.allowedToolNames, tool.name)).length,
+ levels: mcpToolsetAccessLevels(toolset),
+ hasCoverage: mcpToolsetHasCoverage(toolset),
+ coverage: summarizeMcpToolsetCoverage(toolset, props.connections),
+ })),
+);
+
+const cards = computed(() =>
+ allCards.value
+ .filter(({ toolset }) => props.visibleToolsetIds === undefined || props.visibleToolsetIds.includes(toolset.id))
+ .filter(() => props.filterKind !== "plugin")
+ .filter(({ state }) => !props.onlyEnabled || state !== "off"),
+);
+
+function toolsetDescription(id: string) {
+ const key = mcpToolsetMessageKey(id, "description");
+ const text = t(key);
+ return text === key ? "" : text;
+}
+
+const detail = computed(() => allCards.value.find((card) => card.toolset.id === detailToolsetId.value) ?? null);
+const detailChangedCount = computed(() => detail.value?.toolset.tools.filter((tool) => mcpToolAllowed(props.allowedToolNames, tool.name) !== mcpToolAllowed(props.savedToolNames ?? null, tool.name)).length ?? 0);
+
+async function applyDetail() {
+ if (!detail.value || !props.saveToolset || props.disabled || detailSaving.value || !detailChangedCount.value) return;
+ detailSaving.value = true;
+ detailSaveError.value = "";
+ try {
+ await props.saveToolset(detail.value.toolset.id);
+ } catch (error) {
+ detailSaveError.value = error instanceof Error ? error.message : String(error);
+ } finally {
+ detailSaving.value = false;
+ }
+}
+const detailCoverageRows = computed(() => {
+ if (!detail.value) return [];
+ const rows = mcpCoverageByCategory(detail.value.toolset);
+ const needle = coverageSearch.value.trim().toLowerCase();
+ if (!needle) return rows;
+ return rows
+ .map((row) => {
+ const types = row.types.filter((type) => mcpDatabaseTypeLabel(type).toLowerCase().includes(needle) || type.includes(needle));
+ return { ...row, types, tools: row.tools.map((entry) => ({ ...entry, supported: new Set(types.filter((type) => entry.supported.has(type))) })) };
+ })
+ .filter((row) => row.types.length > 0);
+});
+
+function openDetail(toolsetId: string, view: "tools" | "coverage" = "tools", toolName?: string, trigger?: EventTarget | null) {
+ if (detailSaving.value) return;
+ const card = allCards.value.find((entry) => entry.toolset.id === toolsetId);
+ if (!card) return;
+ const source = trigger ?? (typeof document === "undefined" ? null : document.activeElement);
+ detailTrigger = source && "focus" in source && typeof source.focus === "function" ? (source as HTMLElement) : null;
+ detailTitlePath.value = props.titlePath ?? "";
+ detailToolsetId.value = toolsetId;
+ detailSaveError.value = "";
+ detailView.value = view === "coverage" && !card.hasCoverage ? "tools" : view;
+ coverageSearch.value = "";
+ expandedToolNames.value = new Set(card.toolset.tools.some((tool) => tool.name === toolName) ? [toolName!] : []);
+ if (toolName)
+ void nextTick(() => {
+ if (typeof document === "undefined") return;
+ const rows = document.querySelectorAll<HTMLElement>("[data-mcp-toolset-detail] [data-mcp-tool]");
+ const row = [...rows].find((element) => element.dataset.mcpTool === toolName);
+ row?.scrollIntoView?.({ block: "nearest" });
+ row?.querySelector<HTMLButtonElement>("[data-mcp-tool-toggle]")?.focus();
+ });
+}
+
+defineExpose({ openDetail });
+
+function toggleToolExpanded(name: string) {
+ const next = new Set(expandedToolNames.value);
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+ expandedToolNames.value = next;
+}
+
+/** Your connections this tool cannot run on, although its toolset reaches them. */
+function toolSkippedConnections(tool: McpToolCatalogTool) {
+ return detail.value?.coverage.partialConnections.filter((entry) => entry.unsupportedTools.some((unsupported) => unsupported.name === tool.name)).map((entry) => entry.connection) ?? [];
+}
+
+function toolCoverageGroups(tool: McpToolCatalogTool) {
+ return groupMcpDatabaseTypesByCategory(tool.databaseTypes);
+}
+
+function parameterDefault(value: unknown): string {
+ return typeof value === "string" ? value : JSON.stringify(value);
+}
+
+function closeDetail(open: boolean) {
+ if (open || detailSaving.value) return;
+ detailToolsetId.value = null;
+ void nextTick(restoreDetailFocus);
+}
+
+function restoreDetailFocus(event?: Event) {
+ // Search results may be DOM elements outside this panel. A vanished trigger
+ // cannot receive focus, so leave the enclosing dialog's focus handling intact.
+ if (detailTrigger && detailTrigger.isConnected !== false) {
+ event?.preventDefault();
+ detailTrigger.focus({ preventScroll: true });
+ } else if (props.focusFallback) {
+ event?.preventDefault();
+ props.focusFallback();
+ }
+}
+
+function scopeLabel(kind: string): string {
+ const knownKinds = ["database", "dbIndex", "topic", "queue", "org", "namespace"];
+ return knownKinds.includes(kind) ? t(`settings.mcpBrowser.resourceKind.${kind}`) : kind;
+}
+
+const levelClass: Record<McpAccessLevel, string> = {
+ read: "border-border text-muted-foreground",
+ write: "border-amber-500/40 text-amber-700 dark:text-amber-300",
+ full: "border-red-500/40 text-red-600 dark:text-red-400",
+};
+
+function coverageSummaryText(card: (typeof cards.value)[number]): string {
+ const { coverage } = card;
+ if (!card.hasCoverage) return t("settings.mcpCoverageNotBound");
+ if (!coverage.usableConnections.length) return t("settings.mcpBrowser.noMatchingConnections");
+ const parts = [t("settings.mcpBrowser.coverageConnections", { count: coverage.usableConnections.length })];
+ if (coverage.partialConnections.length) parts.push(t("settings.mcpBrowser.coveragePartialConnections", { count: coverage.partialConnections.length }));
+ return parts.join(" · ");
+}
+
+function toolCoverageText(tool: McpToolCatalogTool): string {
+ if (tool.coverageKind === "none") return t("settings.mcpCoverageNotBound");
+ return t("settings.mcpCoverageTypes", { count: tool.databaseTypes.length });
+}
+
+/** Tools that reach only some of a row's types; tools that reach none are omitted. */
+function partialTools(row: (typeof detailCoverageRows.value)[number]) {
+ return row.tools.filter((entry) => entry.supported.size > 0 && entry.supported.size < row.types.length);
+}
+</script>
+
+<template>
+ <div class="space-y-4" data-mcp-capabilities>
+ <div v-if="!listHidden" data-mcp-capability-list>
+ <div v-if="loadError" class="flex items-center justify-between gap-3 rounded-md border border-red-500/30 bg-red-500/5 px-3 py-2 text-xs text-red-600 dark:text-red-400" role="alert">
+ <p>{{ t("settings.mcpCapabilitiesLoadFailed", { error: loadError }) }}</p>
+ <Button variant="outline" size="sm" :disabled="loading" data-mcp-catalog-retry @click="emit('retry')">{{ t("settings.mcpBrowser.retry") }}</Button>
+ </div>
+ <div v-else-if="loading && !catalog" class="flex items-center gap-2 py-6 text-xs text-muted-foreground"><Loader2 class="size-3.5 animate-spin" />{{ t("settings.mcpCapabilitiesLoading") }}</div>
+
+ <template v-else-if="catalog">
+ <ul class="divide-y rounded-md border">
+ <li v-for="card in cards" :key="card.toolset.id" class="flex items-start gap-3 px-3 py-3" :data-mcp-toolset="card.toolset.id">
+ <div class="min-w-0 flex-1">
+ <button type="button" class="w-full rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [overflow-wrap:anywhere]" data-mcp-toolset-open @click="openDetail(card.toolset.id, 'tools', undefined, $event.currentTarget)">
+ <div class="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span class="text-sm font-medium">{{ card.title }}</span>
+ <span class="text-xs text-muted-foreground">{{ t("settings.mcpBrowser.enabledToolCount", { enabled: card.enabledCount, total: card.toolset.tools.length }) }}</span>
+ <span v-if="card.state === 'partial'" class="rounded border border-amber-500/40 px-1.5 text-[11px] text-amber-700 dark:text-amber-300" data-mcp-toolset-partial>{{ t("settings.mcpBrowser.partialEnabled") }}</span>
+ <span v-for="level in card.levels" :key="level" class="rounded border px-1.5 text-[10px] leading-4" :class="levelClass[level]">{{ t(`settings.mcpAccessLevel.${level}`) }}</span>
+ </div>
+ <p class="mt-0.5 text-xs text-muted-foreground">{{ card.description }}</p>
+ </button>
+ <button
+ v-if="card.hasCoverage"
+ type="button"
+ class="mt-1 inline-flex items-center gap-0.5 rounded-sm text-left text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ data-mcp-coverage-link
+ @click="openDetail(card.toolset.id, 'coverage', undefined, $event.currentTarget)"
+ >
+ {{ coverageSummaryText(card) }}<ChevronRight class="size-3" />
+ </button>
+ <p v-else class="mt-1 text-xs text-muted-foreground">{{ coverageSummaryText(card) }}</p>
+ </div>
+ <Switch class="mt-0.5 shrink-0" :model-value="card.state !== 'off'" :disabled="disabled" :aria-label="card.title" @update:model-value="emit('set:toolset', card.toolset, $event === true)" />
+ </li>
+ <li v-if="cards.length === 0" class="px-3 py-6 text-center text-xs text-muted-foreground">{{ t(onlyEnabled ? "settings.mcpBrowser.emptyEnabled" : "settings.mcpCapabilitiesSearchEmpty") }}</li>
+ </ul>
+ </template>
+ </div>
+
+ <Dialog :open="!!detail" @update:open="closeDetail">
+ <DialogContent
+ v-if="detail"
+ class="flex max-h-[85vh] flex-col overflow-hidden sm:max-w-3xl"
+ :show-close-button="!detailSaving"
+ data-mcp-toolset-detail
+ @close-auto-focus="restoreDetailFocus"
+ @escape-key-down="detailSaving && $event.preventDefault()"
+ @interact-outside="detailSaving && $event.preventDefault()"
+ >
+ <DialogHeader class="shrink-0">
+ <DialogTitle>{{ detailTitlePath ? `${detailTitlePath} / ${detail.title}` : detail.title }}</DialogTitle>
+ <DialogDescription>{{ detail.description }}</DialogDescription>
+ </DialogHeader>
+ <p v-if="detail.scopeKinds.length" class="shrink-0 text-xs text-muted-foreground" data-mcp-scope-kinds>{{ t("settings.mcpBrowser.resourceScopes") }}:{{ detail.scopeKinds.map(scopeLabel).join(" / ") }}</p>
+
+ <div class="flex shrink-0 gap-1 border-b">
+ <button type="button" class="-mb-px border-b-2 px-3 py-1.5 text-xs font-medium" :class="detailView === 'tools' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground'" @click="detailView = 'tools'">{{ t("settings.mcpToolsetDetailTools") }}</button>
+ <button v-if="detail.hasCoverage" type="button" class="-mb-px border-b-2 px-3 py-1.5 text-xs font-medium" :class="detailView === 'coverage' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground'" @click="detailView = 'coverage'">
+ {{ t("settings.mcpToolsetDetailCoverage") }}
+ </button>
+ </div>
+
+ <div class="min-h-0 flex-1 overflow-y-auto" data-mcp-toolset-scroll>
+ <ul v-if="detailView === 'tools'" class="divide-y rounded-md border">
+ <li v-for="tool in detail.toolset.tools" :key="tool.name" :data-mcp-tool="tool.name">
+ <div class="flex items-center gap-3 px-3 py-2">
+ <button type="button" class="flex min-w-0 flex-1 items-start gap-1.5 text-left" :aria-expanded="expandedToolNames.has(tool.name)" data-mcp-tool-toggle @click="toggleToolExpanded(tool.name)">
+ <ChevronDown v-if="expandedToolNames.has(tool.name)" class="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ <ChevronRight v-else class="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ <span class="min-w-0 flex-1">
+ <span class="flex flex-wrap items-center gap-2">
+ <span class="text-xs font-medium">{{ toolLabel(tool) }}</span>
+ <span class="rounded border px-1.5 text-[10px] leading-4" :class="levelClass[tool.accessMode === 'classified' ? 'full' : tool.access]">{{ tool.accessMode === "classified" ? t("settings.mcpAccessLevelClassified") : t(`settings.mcpAccessLevel.${tool.access}`) }}</span>
+ </span>
+ <span class="mt-0.5 flex flex-wrap gap-x-3 text-[11px] text-muted-foreground">
+ <span class="font-mono">{{ tool.name }}</span>
+ <span>{{ toolCoverageText(tool) }}</span>
+ <span v-if="toolSkippedConnections(tool).length" class="text-amber-700 dark:text-amber-300">{{ t("settings.mcpToolSkippedConnections", { count: toolSkippedConnections(tool).length }) }}</span>
+ </span>
+ </span>
+ </button>
+ <Switch size="sm" class="shrink-0" :model-value="mcpToolAllowed(allowedToolNames, tool.name)" :disabled="disabled || detailSaving" :aria-label="toolLabel(tool)" @update:model-value="emit('set:tool', tool.name, $event === true)" />
+ </div>
+
+ <div v-if="expandedToolNames.has(tool.name)" class="space-y-3 border-t bg-muted/30 px-3 py-3 pl-8 text-xs" data-mcp-tool-detail>
+ <dl class="grid gap-x-4 gap-y-1.5 sm:grid-cols-[6rem_minmax(0,1fr)]">
+ <dt class="text-muted-foreground">{{ t("settings.mcpToolDetailId") }}</dt>
+ <dd class="font-mono">{{ tool.name }}</dd>
+ <dt class="text-muted-foreground">{{ t("settings.mcpToolDetailSummary") }}</dt>
+ <dd>{{ toolLabel(tool) }}</dd>
+ <dt class="text-muted-foreground">{{ t("settings.mcpToolDetailAccess") }}</dt>
+ <dd>{{ tool.accessMode === "classified" ? t("settings.mcpToolDetailAccessClassified") : t(`settings.mcpAccessLevel.${tool.access}`) }}</dd>
+ <template v-if="tool.description">
+ <dt class="text-muted-foreground">{{ t("settings.mcpToolDetailDescription") }}</dt>
+ <dd class="whitespace-pre-wrap break-words text-muted-foreground">{{ tool.description }}</dd>
+ </template>
+ </dl>
+
+ <section class="space-y-1.5">
+ <p class="font-medium">{{ t("settings.mcpToolDetailParameters") }}</p>
+ <p v-if="tool.parameters.length === 0" class="text-muted-foreground">{{ t("settings.mcpToolDetailNoParameters") }}</p>
+ <div v-else class="overflow-x-auto rounded border bg-background">
+ <table class="w-full text-left text-[11px]">
+ <thead class="bg-muted/50 text-muted-foreground">
+ <tr>
+ <th class="px-2 py-1 font-medium">{{ t("settings.mcpToolDetailParameterName") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("settings.mcpToolDetailParameterType") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("settings.mcpToolDetailParameterRequired") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("settings.mcpToolDetailParameterDescription") }}</th>
+ </tr>
+ </thead>
+ <tbody class="divide-y">
+ <tr v-for="parameter in tool.parameters" :key="parameter.name" class="align-top">
+ <td class="whitespace-nowrap px-2 py-1 font-mono">{{ parameter.name }}</td>
+ <td class="px-2 py-1 font-mono text-muted-foreground">{{ parameter.valueType }}</td>
+ <td class="whitespace-nowrap px-2 py-1">
+ <span v-if="parameter.required" class="text-foreground">{{ t("settings.mcpToolDetailParameterRequiredYes") }}</span>
+ <span v-else class="text-muted-foreground">{{ t("settings.mcpToolDetailParameterRequiredNo") }}</span>
+ </td>
+ <td class="px-2 py-1 text-muted-foreground">
+ {{ parameter.description }}
+ <span v-if="parameter.default !== undefined" class="whitespace-nowrap">({{ t("settings.mcpToolDetailParameterDefault", { value: parameterDefault(parameter.default) }) }})</span>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+
+ <section v-if="tool.coverageKind !== 'none'" class="space-y-1.5" data-mcp-tool-coverage>
+ <p class="font-medium">{{ t("settings.mcpToolDetailCoverage", { count: tool.databaseTypes.length }) }}</p>
+ <div v-for="group in toolCoverageGroups(tool)" :key="group.category" class="flex flex-wrap items-baseline gap-1.5">
+ <span class="w-full text-[11px] text-muted-foreground sm:w-24 sm:shrink-0">{{ t(group.titleKey) }}</span>
+ <span v-for="type in group.types" :key="type" class="rounded border px-1.5 text-[11px] leading-5" :class="userConnectionTypes.has(type) ? 'border-primary/50 bg-primary/5' : 'bg-background'">{{ mcpDatabaseTypeLabel(type) }}</span>
+ </div>
+ <p v-if="toolSkippedConnections(tool).length" class="text-[11px] text-amber-700 dark:text-amber-300">
+ {{
+ t("settings.mcpToolDetailSkippedConnections", {
+ names: toolSkippedConnections(tool)
+ .map((connection) => connection.name)
+ .join("、"),
+ })
+ }}
+ </p>
+ </section>
+ <p v-else class="text-muted-foreground">{{ t("settings.mcpCoverageNotBound") }}</p>
+ </div>
+ </li>
+ </ul>
+
+ <div v-else class="space-y-3" data-mcp-coverage-detail>
+ <div class="relative">
+ <Search class="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input v-model="coverageSearch" class="h-8 pl-8 text-xs" :placeholder="t('settings.mcpCoverageSearchPlaceholder')" />
+ </div>
+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpCoverageLegend") }}</p>
+ <section v-for="row in detailCoverageRows" :key="row.category" class="space-y-2 rounded-md border p-3">
+ <p class="text-xs font-semibold">
+ {{ t(row.titleKey) }} <span class="font-normal text-muted-foreground">({{ row.types.length }})</span>
+ </p>
+ <div class="flex flex-wrap gap-1.5">
+ <Badge
+ v-for="type in row.types"
+ :key="type"
+ variant="outline"
+ class="gap-1 text-[11px] font-normal"
+ :class="userConnectionTypes.has(type) ? 'border-primary/50 bg-primary/5' : ''"
+ :title="
+ row.tools
+ .filter((entry) => !entry.supported.has(type))
+ .map((entry) => t('settings.mcpCoverageTypeUnsupportedTool', { tool: toolLabel(entry.tool) }))
+ .join('\n') || undefined
+ "
+ >
+ {{ mcpDatabaseTypeLabel(type) }}
+ <span v-if="row.tools.some((entry) => !entry.supported.has(type))" class="text-amber-600">*</span>
+ </Badge>
+ </div>
+ <p v-for="entry in partialTools(row)" :key="entry.tool.name" class="flex items-center gap-1 text-[11px] text-muted-foreground">
+ <Minus class="size-3 text-amber-600" />
+ {{ t("settings.mcpCoveragePartialTool", { tool: toolLabel(entry.tool), count: entry.supported.size, total: row.types.length }) }}
+ </p>
+ </section>
+ <p v-if="detailCoverageRows.length === 0" class="py-6 text-center text-xs text-muted-foreground">{{ t("settings.mcpCoverageSearchEmpty") }}</p>
+ </div>
+ </div>
+ <div class="flex shrink-0 flex-wrap items-center justify-end gap-3 border-t pt-3" data-mcp-toolset-footer :aria-busy="detailSaving">
+ <div v-if="saveToolset" class="min-w-0 flex-1 basis-52 space-y-1 text-xs text-muted-foreground">
+ <p role="status" aria-live="polite" data-mcp-toolset-save-status>{{ detailSaving ? t("settings.mcpToolsetApplying") : detailChangedCount ? t("settings.mcpToolsetPending", { count: detailChangedCount }) : t("settings.mcpToolsetApplied") }}</p>
+ <p v-if="detailChangedCount">{{ t("settings.mcpToolsetCloseKeepsDraft") }}</p>
+ <p v-if="detailSaveError" role="alert" class="break-words text-destructive" data-mcp-toolset-save-error>{{ t("settings.mcpToolsetApplyFailed", { error: detailSaveError }) }}</p>
+ </div>
+ <div class="flex shrink-0 gap-2">
+ <Button variant="outline" size="sm" :disabled="detailSaving" data-mcp-toolset-close @click="closeDetail(false)">{{ t("settings.mcpToolsetDetailClose") }}</Button>
+ <Button v-if="saveToolset" size="sm" :disabled="disabled || detailSaving || !detailChangedCount" data-mcp-toolset-apply @click="applyDetail">
+ <Loader2 v-if="detailSaving" class="mr-1 size-3.5 animate-spin" />
+ {{ t(detailSaving ? "settings.mcpToolsetApplying" : "settings.mcpToolsetApply") }}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/settings/McpCapabilityBrowser.vue b/apps/desktop/src/components/settings/McpCapabilityBrowser.vue
new file mode 100644
index 0000000000..21ce9b0108
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpCapabilityBrowser.vue
@@ -0,0 +1,768 @@
+<script setup lang="ts">
+import { computed, nextTick, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Search, X, RefreshCw, Loader2 } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
+import McpCapabilitiesPanel from "./McpCapabilitiesPanel.vue";
+import McpPluginCapabilities from "./McpPluginCapabilities.vue";
+import type { McpToolCatalog, McpToolCatalogToolset, PluginMcpGrant, PluginMcpView } from "@/types/mcpCatalog";
+import { mcpCapabilityCategories, mcpCapabilityCategoryId, mcpToolAllowed, mcpToolsetAccessLevels, mcpToolsetHasCoverage, mcpToolsetState, summarizeMcpToolsetCoverage, type McpCoverageConnection, type McpCapabilityCategoryId } from "@/lib/mcp/mcpToolCatalog";
+import { initialMcpCapabilityBrowserState, mcpCategoryTitle, mcpToolsetTitle, searchMcpCapabilities, type McpCapabilityBrowserState, type McpCapabilityNavigationTarget, type McpCapabilityNavigator, type McpCapabilitySearchItem } from "@/lib/mcp/mcpCapabilitySearch";
+import { pluginMcpEnabled, pluginMcpExposedCount, pluginMcpPendingTools } from "@/lib/mcp/pluginMcpGrant";
+
+const props = withDefaults(
+ defineProps<{
+ catalog: McpToolCatalog | null;
+ loading?: boolean;
+ loadError?: string;
+ allowedToolNames: string[] | null;
+ savedToolNames?: readonly string[] | null;
+ saveToolset?: (toolsetId: string) => Promise<void>;
+ connections: McpCoverageConnection[];
+ disabled?: boolean;
+ plugins: PluginMcpView[] | null;
+ pluginsLoading?: boolean;
+ pluginsError?: string;
+ pendingPluginIds?: readonly string[];
+ showPlugins?: boolean;
+ savePlugin: (pluginId: string, grant: PluginMcpGrant, approveCurrent: boolean) => Promise<PluginMcpView>;
+ }>(),
+ { showPlugins: true },
+);
+
+const emit = defineEmits<{
+ "set:toolset": [toolset: McpToolCatalogToolset, enabled: boolean];
+ "set:tool": [name: string, enabled: boolean];
+ "set:category": [category: McpCapabilityCategoryId, enabled: boolean];
+ retry: [];
+ "refresh:plugins": [];
+ "saved:plugin": [view: PluginMcpView];
+}>();
+const state = defineModel<McpCapabilityBrowserState>({ default: initialMcpCapabilityBrowserState });
+const { t } = useI18n();
+const rootElement = ref<HTMLElement>();
+const builtinPanel = ref<InstanceType<typeof McpCapabilitiesPanel>>();
+const pluginPanel = ref<InstanceType<typeof McpPluginCapabilities>>();
+const batchChanged = ref(false);
+const detailPath = ref("");
+const categories = computed(() => mcpCapabilityCategories(props.catalog));
+const searching = computed(() => !!state.value.search.trim());
+const selectedCategory = computed(() => categories.value.find((category) => category.id === state.value.selected));
+const selectedPluginId = computed(() => (state.value.selected.startsWith("plugin:") ? state.value.selected.slice(7) : undefined));
+const viewMode = computed(() => state.value.viewMode ?? "manage");
+const showBuiltin = computed(() => viewMode.value === "manage" && !searching.value && !!selectedCategory.value);
+const title = computed(() => (selectedCategory.value ? mcpCategoryTitle(selectedCategory.value.id, t) : ""));
+const categoryTools = computed(() => selectedCategory.value?.toolsets.flatMap((toolset) => toolset.tools) ?? []);
+const enabledCount = computed(() => categoryTools.value.filter((tool) => mcpToolAllowed(props.allowedToolNames, tool.name)).length);
+const editable = computed(() => !!props.catalog && !props.loading && !props.loadError && !props.disabled);
+const overviewCategories = computed(() =>
+ categories.value.map((category) => {
+ const tools = category.toolsets.flatMap((toolset) => toolset.tools);
+ const visibleToolsets = state.value.onlyEnabled ? category.toolsets.filter((toolset) => mcpToolsetState(props.allowedToolNames, toolset) !== "off") : category.toolsets;
+ return {
+ ...category,
+ visibleToolsets,
+ tools,
+ enabled: tools.filter((tool) => mcpToolAllowed(props.allowedToolNames, tool.name)).length,
+ };
+ }),
+);
+const overviewPlugins = computed(() => (props.plugins ?? []).filter((plugin) => !state.value.onlyEnabled || pluginMcpEnabled(plugin)));
+const overviewHasContent = computed(() => overviewCategories.value.some((category) => category.visibleToolsets.length > 0) || (props.showPlugins && overviewPlugins.value.length > 0));
+const collapsedOverviewCategories = ref(new Set<McpCapabilityCategoryId>());
+const builtinFilter = ref("");
+const pluginFilter = ref("");
+const pendingToolNavigation = ref<{ toolName: string } | null>(null);
+const filteredCategories = computed(() => {
+ const query = builtinFilter.value.trim().toLocaleLowerCase();
+ if (!query) return categories.value;
+ return categories.value.filter((category) => {
+ const title = mcpCategoryTitle(category.id, t).toLocaleLowerCase();
+ return title.includes(query) || category.id.toLocaleLowerCase().includes(query);
+ });
+});
+const filteredPlugins = computed(() => {
+ const query = pluginFilter.value.trim().toLocaleLowerCase();
+ if (!query) return props.plugins ?? [];
+ return (props.plugins ?? []).filter((plugin) => plugin.pluginName.toLocaleLowerCase().includes(query) || plugin.pluginId.toLocaleLowerCase().includes(query));
+});
+const results = computed(() =>
+ searchMcpCapabilities({
+ query: state.value.search,
+ catalog: props.loadError ? null : props.catalog,
+ plugins: props.showPlugins ? props.plugins : null,
+ allowedToolNames: props.allowedToolNames,
+ onlyEnabled: state.value.onlyEnabled,
+ t,
+ }),
+);
+
+function focusSearch() {
+ rootElement.value?.querySelector?.<HTMLInputElement>("[data-mcp-global-search]")?.focus();
+}
+
+function revealSearchTarget(target?: McpCapabilityNavigationTarget) {
+ pendingToolNavigation.value = null;
+ if (!target) return;
+ builtinFilter.value = "";
+ pluginFilter.value = "";
+ batchChanged.value = false;
+ state.value = {
+ ...initialMcpCapabilityBrowserState(),
+ ...(target.kind === "advanced" ? { selected: "advanced" as const } : { search: target.toolName }),
+ };
+ pendingToolNavigation.value = target.kind === "tool" ? { toolName: target.toolName } : null;
+}
+
+// A settings result can arrive before the catalog. Keep the exact-name search
+// visible during loading/errors, then reveal the tool without changing grants.
+watch(
+ [pendingToolNavigation, () => props.catalog, () => props.loading, () => props.loadError],
+ async ([target, catalog, loading, loadError], _previous, onCleanup) => {
+ if (!target || !catalog || loading || loadError) return;
+ const toolset = catalog.toolsets.find((entry) => entry.tools.some((tool) => tool.name === target.toolName));
+ if (!toolset) return;
+ let cancelled = false;
+ onCleanup(() => {
+ cancelled = true;
+ });
+ state.value = { ...state.value, selected: mcpCapabilityCategoryId(toolset.id), search: "", onlyEnabled: false, viewMode: "manage" };
+ await nextTick();
+ if (cancelled || pendingToolNavigation.value !== target) return;
+ builtinPanel.value?.openDetail(toolset.id, "tools", target.toolName);
+ pendingToolNavigation.value = null;
+ },
+ { flush: "post" },
+);
+
+defineExpose<McpCapabilityNavigator>({ revealSearchTarget });
+
+function focusNavigationFilter(event: MouseEvent) {
+ const target = event.currentTarget as HTMLElement | null;
+ const eventTarget = event.target as HTMLElement | null;
+ if (!target || (eventTarget && typeof eventTarget.closest === "function" && eventTarget.closest("input,button"))) return;
+ if (typeof target.querySelector !== "function") return;
+ target.querySelector<HTMLInputElement>("input")?.focus();
+}
+
+function select(value: unknown) {
+ if (typeof value !== "string") return;
+ pendingToolNavigation.value = null;
+ state.value = {
+ ...state.value,
+ selected: value as McpCapabilityBrowserState["selected"],
+ search: "",
+ ...(searching.value ? { viewMode: "manage" as const } : {}),
+ };
+ batchChanged.value = false;
+}
+
+function setViewMode(mode: "manage" | "overview") {
+ pendingToolNavigation.value = null;
+ if (viewMode.value === mode) return;
+ state.value = { ...state.value, viewMode: mode };
+ batchChanged.value = false;
+}
+
+function toggleOverviewCategory(categoryId: McpCapabilityCategoryId) {
+ const next = new Set(collapsedOverviewCategories.value);
+ if (next.has(categoryId)) next.delete(categoryId);
+ else next.add(categoryId);
+ collapsedOverviewCategories.value = next;
+}
+
+function overviewCategoryExpanded(categoryId: McpCapabilityCategoryId) {
+ return !collapsedOverviewCategories.value.has(categoryId);
+}
+
+function updateSearch(value: string | number) {
+ pendingToolNavigation.value = null;
+ const clearing = state.value.search.length > 0 && String(value).length === 0;
+ state.value = { ...state.value, search: String(value) };
+ batchChanged.value = false;
+ if (clearing) void nextTick(focusSearch);
+}
+
+function batch(enabled: boolean) {
+ if (!editable.value || !selectedCategory.value || searching.value || !categoryTools.value.length) return;
+ if (enabled ? enabledCount.value === categoryTools.value.length : enabledCount.value === 0) return;
+ emit("set:category", selectedCategory.value.id, enabled);
+ batchChanged.value = true;
+}
+
+function batchCategory(categoryId: McpCapabilityCategoryId, enabled: boolean) {
+ const category = categories.value.find((entry) => entry.id === categoryId);
+ if (!editable.value || !category || !category.toolsets.flatMap((toolset) => toolset.tools).length) return;
+ const tools = category.toolsets.flatMap((toolset) => toolset.tools);
+ const enabledTools = tools.filter((tool) => mcpToolAllowed(props.allowedToolNames, tool.name)).length;
+ if (enabled ? enabledTools === tools.length : enabledTools === 0) return;
+ emit("set:category", categoryId, enabled);
+ batchChanged.value = true;
+}
+
+async function openOverviewToolset(categoryId: McpCapabilityCategoryId, toolset: McpToolCatalogToolset, event: Event) {
+ const trigger = event.currentTarget;
+ detailPath.value = mcpCategoryTitle(categoryId, t);
+ await nextTick();
+ builtinPanel.value?.openDetail(toolset.id, "tools", undefined, trigger);
+}
+
+function openOverviewPlugin(plugin: PluginMcpView, event: Event) {
+ pluginPanel.value?.openDetail(plugin.pluginId, event.currentTarget as HTMLElement);
+}
+
+function overviewToolsetDescription(toolset: McpToolCatalogToolset) {
+ const key = `settings.mcpToolset.${toolset.id.replace(/\.(\w)/g, (_, letter: string) => letter.toUpperCase())}.description`;
+ const text = t(key);
+ return text === key ? "" : text;
+}
+
+function overviewToolsetCoverage(toolset: McpToolCatalogToolset) {
+ if (!mcpToolsetHasCoverage(toolset)) return t("settings.mcpCoverageNotBound");
+ const coverage = summarizeMcpToolsetCoverage(toolset, props.connections);
+ if (!coverage.usableConnections.length) return t("settings.mcpBrowser.noMatchingConnections");
+ const parts = [t("settings.mcpBrowser.coverageConnections", { count: coverage.usableConnections.length })];
+ if (coverage.partialConnections.length) parts.push(t("settings.mcpBrowser.coveragePartialConnections", { count: coverage.partialConnections.length }));
+ return parts.join(" · ");
+}
+
+function overviewPluginSummary(plugin: PluginMcpView) {
+ if (!plugin.authorAllowsExternal) return t("settings.mcpPluginAuthorClosed");
+ if (plugin.discoveryError) return t("settings.mcpPluginDiscoveryError", { error: plugin.discoveryError });
+ if (!pluginMcpEnabled(plugin)) return t("settings.mcpPluginToolCountOff", { total: plugin.tools.length });
+ return [t("settings.mcpPluginToolCount", { exposed: pluginMcpExposedCount(plugin), total: plugin.tools.length }), t("settings.mcpPluginCeilingSummary", { level: t(`settings.mcpAccessLevel.${plugin.grant.ceiling}`) })].join(" · ");
+}
+
+async function openResult(item: McpCapabilitySearchItem, event: Event) {
+ const trigger = event.currentTarget as HTMLElement;
+ if (item.pluginId) {
+ if (item.toolName) pluginPanel.value?.openTool(item.pluginId, item.toolName, trigger);
+ else pluginPanel.value?.openDetail(item.pluginId, trigger);
+ } else if (item.toolsetId) {
+ detailPath.value = mcpCategoryTitle(mcpCapabilityCategoryId(item.toolsetId), t);
+ await nextTick();
+ builtinPanel.value?.openDetail(item.toolsetId, "tools", item.toolName, trigger);
+ }
+}
+</script>
+
+<template>
+ <section ref="rootElement" class="mcp-capability-browser min-w-0 space-y-3" data-mcp-capability-browser>
+ <div class="flex flex-wrap items-center gap-3">
+ <div class="relative min-w-48 flex-1">
+ <Search class="pointer-events-none absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
+ <Input :model-value="state.search" class="h-9 pl-8 pr-9 text-sm" :placeholder="t('settings.mcpBrowser.searchPlaceholder')" :aria-label="t('settings.mcpBrowser.searchPlaceholder')" data-mcp-global-search @update:model-value="updateSearch" />
+ <Button v-if="state.search" variant="ghost" size="icon-sm" class="absolute right-1 top-1" :aria-label="t('settings.mcpBrowser.clearSearch')" data-mcp-clear-search @click="updateSearch('')"><X class="size-3.5" /></Button>
+ </div>
+ <div class="flex shrink-0 rounded-md border p-0.5" role="group" :aria-label="t('settings.mcpBrowser.viewMode')" data-mcp-view-toggle>
+ <button type="button" class="rounded px-2.5 py-1 text-xs" :class="viewMode === 'manage' ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground'" :aria-pressed="viewMode === 'manage'" data-mcp-view-mode="manage" @click="setViewMode('manage')">
+ {{ t("settings.mcpBrowser.viewManage") }}
+ </button>
+ <button type="button" class="rounded px-2.5 py-1 text-xs" :class="viewMode === 'overview' ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground'" :aria-pressed="viewMode === 'overview'" data-mcp-view-mode="overview" @click="setViewMode('overview')">
+ {{ t("settings.mcpBrowser.viewOverview") }}
+ </button>
+ </div>
+ <label class="flex shrink-0 items-center gap-2 text-xs">
+ <input type="checkbox" :checked="state.onlyEnabled" class="accent-primary" data-mcp-only-enabled @change="state = { ...state, onlyEnabled: ($event.target as HTMLInputElement).checked }" />
+ {{ t("settings.mcpCapabilitiesOnlyEnabled") }}
+ </label>
+ </div>
+
+ <div v-if="viewMode === 'manage' || searching" class="mcp-category-select flex items-center gap-2">
+ <Select :model-value="state.selected" @update:model-value="select">
+ <SelectTrigger class="min-w-0 flex-1" :aria-label="t('settings.mcpBrowser.navigation')"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <!-- Sidebar filters are hidden in compact layouts, so keep every destination available here. -->
+ <SelectGroup>
+ <SelectLabel>{{ t("settings.mcpBrowser.builtin") }}</SelectLabel>
+ <SelectItem v-for="category in categories" :key="category.id" :value="category.id">{{ mcpCategoryTitle(category.id, t) }} · {{ t("settings.mcpBrowser.categoryCount", { count: category.toolsets.length }) }}</SelectItem>
+ </SelectGroup>
+ <SelectGroup v-if="showPlugins">
+ <SelectLabel>{{ t("settings.mcpBrowser.plugins") }}</SelectLabel>
+ <SelectItem v-for="plugin in plugins ?? []" :key="plugin.pluginId" :value="`plugin:${plugin.pluginId}`">
+ {{ plugin.pluginName }} · {{ t("settings.mcpCapabilitiesFilterPlugin") }}
+ <span v-if="pluginMcpPendingTools(plugin).length"> · {{ t("settings.mcpPluginPendingTools", { count: pluginMcpPendingTools(plugin).length }) }}</span>
+ </SelectItem>
+ </SelectGroup>
+ <SelectItem value="advanced">{{ t("settings.mcpBrowser.advanced") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <Button v-if="showPlugins" variant="ghost" size="icon-sm" :disabled="pluginsLoading" :aria-label="`${t('settings.mcpBrowser.plugins')} · ${t('settings.mcpPluginsRefresh')}`" :title="`${t('settings.mcpBrowser.plugins')} · ${t('settings.mcpPluginsRefresh')}`" @click="emit('refresh:plugins')"
+ ><RefreshCw class="size-3.5" :class="{ 'animate-spin': pluginsLoading }"
+ /></Button>
+ </div>
+
+ <section v-if="viewMode === 'overview' && !searching" class="space-y-4" data-mcp-overview>
+ <div v-if="loading && !catalog" role="status" class="py-6 text-xs text-muted-foreground">{{ t("settings.mcpCapabilitiesLoading") }}</div>
+ <div v-else-if="loadError" role="alert" class="space-y-2 rounded-md border border-red-500/30 bg-red-500/5 px-3 py-2 text-xs text-red-600 dark:text-red-400">
+ <p>{{ t("settings.mcpCapabilitiesLoadFailed", { error: loadError }) }}</p>
+ <Button variant="outline" size="sm" :disabled="loading" data-mcp-overview-retry @click="emit('retry')">{{ t("settings.mcpBrowser.retry") }}</Button>
+ </div>
+ <p v-else-if="!catalog" class="rounded-md border border-dashed px-4 py-8 text-center text-xs text-muted-foreground">{{ t("settings.mcpCapabilitiesLoading") }}</p>
+ <template v-else>
+ <p v-if="!overviewHasContent" class="rounded-md border border-dashed px-4 py-8 text-center text-xs text-muted-foreground" data-mcp-overview-empty>{{ t(state.onlyEnabled ? "settings.mcpBrowser.emptyEnabled" : "settings.mcpCapabilitiesSearchEmpty") }}</p>
+ <section v-for="category in overviewCategories" :key="category.id" class="overflow-hidden rounded-md border" :data-mcp-overview-category="category.id">
+ <header class="flex flex-wrap items-start gap-3 bg-muted/20 px-3 py-3">
+ <button
+ type="button"
+ class="min-w-0 flex-1 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ :aria-expanded="overviewCategoryExpanded(category.id)"
+ :aria-label="`${overviewCategoryExpanded(category.id) ? t('settings.mcpBrowser.collapseCategory') : t('settings.mcpBrowser.expandCategory')}: ${mcpCategoryTitle(category.id, t)}`"
+ data-mcp-overview-category-toggle
+ @click="toggleOverviewCategory(category.id)"
+ >
+ <span class="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span aria-hidden="true" class="text-muted-foreground">{{ overviewCategoryExpanded(category.id) ? "▾" : "▸" }}</span>
+ <span class="text-sm font-semibold">{{ mcpCategoryTitle(category.id, t) }}</span>
+ <span class="text-xs text-muted-foreground">{{ t("settings.mcpBrowser.overviewSummary", { toolsets: category.toolsets.length, total: category.tools.length, enabled: category.enabled }) }}</span>
+ </span>
+ <span class="mt-1 block text-xs text-muted-foreground">{{ t(`settings.mcpBrowser.category.${category.id}.description`) }}</span>
+ </button>
+ <div class="flex shrink-0 flex-wrap gap-1.5">
+ <Button variant="outline" size="sm" class="h-7 text-[11px]" :disabled="!editable || !category.tools.length || category.enabled === category.tools.length" :data-mcp-overview-category-enable="category.id" @click="batchCategory(category.id, true)">{{
+ t("settings.mcpBrowser.enableCategory")
+ }}</Button>
+ <Button variant="outline" size="sm" class="h-7 text-[11px]" :disabled="!editable || !category.tools.length || category.enabled === 0" :data-mcp-overview-category-disable="category.id" @click="batchCategory(category.id, false)">{{ t("settings.mcpBrowser.disableCategory") }}</Button>
+ </div>
+ </header>
+ <ul v-if="overviewCategoryExpanded(category.id)" class="divide-y">
+ <li v-for="toolset in category.visibleToolsets" :key="toolset.id" class="flex items-start gap-3 px-3 py-3" :data-mcp-overview-toolset="toolset.id">
+ <button type="button" class="min-w-0 flex-1 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" data-mcp-overview-toolset-open @click="openOverviewToolset(category.id, toolset, $event)">
+ <span class="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span class="break-words text-sm font-medium">{{ mcpToolsetTitle(toolset.id, t) }}</span>
+ <span class="text-xs text-muted-foreground">{{ t("settings.mcpBrowser.enabledToolCount", { enabled: toolset.tools.filter((tool) => mcpToolAllowed(allowedToolNames, tool.name)).length, total: toolset.tools.length }) }}</span>
+ <span v-if="mcpToolsetState(allowedToolNames, toolset) === 'partial'" class="rounded border border-amber-500/40 px-1.5 text-[11px] text-amber-700 dark:text-amber-300" data-mcp-overview-partial>{{ t("settings.mcpBrowser.partialEnabled") }}</span>
+ <span v-for="level in mcpToolsetAccessLevels(toolset)" :key="level" class="rounded border px-1.5 text-[10px] leading-4">{{ t(`settings.mcpAccessLevel.${level}`) }}</span>
+ </span>
+ <span v-if="overviewToolsetDescription(toolset)" class="mt-0.5 block break-words text-xs text-muted-foreground">{{ overviewToolsetDescription(toolset) }}</span>
+ <span class="mt-1 block text-xs text-muted-foreground">{{ overviewToolsetCoverage(toolset) }}</span>
+ </button>
+ <input
+ type="checkbox"
+ class="mt-1 size-4 shrink-0 accent-primary"
+ :checked="mcpToolsetState(allowedToolNames, toolset) !== 'off'"
+ :disabled="!editable"
+ :aria-label="mcpToolsetTitle(toolset.id, t)"
+ :data-mcp-overview-toolset-switch="toolset.id"
+ @change="emit('set:toolset', toolset, ($event.target as HTMLInputElement).checked)"
+ />
+ </li>
+ <li v-if="category.visibleToolsets.length === 0" class="px-3 py-5 text-center text-xs text-muted-foreground" data-mcp-overview-category-empty>{{ t("settings.mcpBrowser.emptyEnabled") }}</li>
+ </ul>
+ </section>
+
+ <slot v-if="showPlugins" name="plugin-warning" />
+ <section v-if="showPlugins" class="overflow-hidden rounded-md border" data-mcp-overview-plugins>
+ <header class="flex items-center justify-between gap-3 bg-muted/20 px-3 py-3">
+ <div>
+ <h3 class="text-sm font-semibold">{{ t("settings.mcpBrowser.plugins") }}</h3>
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpBrowser.overviewPluginsHint") }}</p>
+ </div>
+ <Button variant="ghost" size="sm" class="h-7 text-[11px]" :disabled="pluginsLoading" data-mcp-overview-plugins-refresh @click="emit('refresh:plugins')">{{ t("settings.mcpPluginsRefresh") }}</Button>
+ </header>
+ <ul v-if="overviewPlugins.length" class="divide-y">
+ <li v-for="plugin in overviewPlugins" :key="plugin.pluginId" class="flex items-start gap-3 px-3 py-3" :data-mcp-overview-plugin="plugin.pluginId">
+ <button type="button" class="min-w-0 flex-1 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" data-mcp-overview-plugin-open @click="openOverviewPlugin(plugin, $event)">
+ <span class="flex flex-wrap items-center gap-x-2 gap-y-1"
+ ><span class="break-words text-sm font-medium">{{ plugin.pluginName }}</span
+ ><span class="rounded border px-1.5 text-[10px] text-muted-foreground">{{ t("settings.mcpCapabilitiesFilterPlugin") }}</span></span
+ >
+ <span class="mt-0.5 block break-words text-xs text-muted-foreground">{{ overviewPluginSummary(plugin) }}</span>
+ <span v-if="pluginMcpPendingTools(plugin).length" class="mt-1 block text-[11px] text-amber-700 dark:text-amber-300">{{ t("settings.mcpPluginPendingTools", { count: pluginMcpPendingTools(plugin).length }) }}</span>
+ </button>
+ <span class="mt-1 text-xs text-muted-foreground">{{ t("settings.mcpBrowser.overviewOpenDetails") }}</span>
+ </li>
+ </ul>
+ <p v-else class="px-3 py-5 text-center text-xs text-muted-foreground">
+ {{ pluginsLoading ? t("settings.mcpPluginsLoading") : pluginsError ? t("settings.mcpPluginsLoadFailed", { error: pluginsError }) : state.onlyEnabled && plugins?.length ? t("settings.mcpBrowser.emptyEnabled") : t("settings.mcpPluginsEmpty") }}
+ </p>
+ </section>
+ <p v-if="batchChanged" role="status" class="text-xs" data-mcp-batch-feedback>{{ t("settings.mcpBrowser.batchChanged") }}</p>
+ </template>
+ </section>
+
+ <div class="mcp-capability-layout" :class="{ hidden: viewMode === 'overview' && !searching }">
+ <aside v-if="viewMode === 'manage' || searching" class="mcp-category-sidebar min-w-0">
+ <nav :aria-label="t('settings.mcpBrowser.navigation')" class="mcp-navigation-rail" data-mcp-navigation>
+ <div class="mcp-nav-section" data-mcp-nav-section="builtin">
+ <div class="mcp-nav-section-header">
+ <p class="mcp-nav-section-title">
+ <span>{{ t("settings.mcpBrowser.builtin") }}</span>
+ <span class="mcp-nav-section-count">{{ categories.length }}</span>
+ </p>
+ <div class="mcp-nav-filter-control" :class="{ active: builtinFilter }" :title="`${t('settings.mcpCapabilitiesFilterLabel')}: ${t('settings.mcpBrowser.builtin')}`" @click="focusNavigationFilter">
+ <Search class="mcp-nav-filter-icon" aria-hidden="true" />
+ <Input v-model="builtinFilter" class="mcp-nav-filter-input h-6 border-0 bg-transparent px-0 text-[11px] shadow-none focus-visible:ring-0" :placeholder="''" :aria-label="`${t('settings.mcpCapabilitiesFilterLabel')}: ${t('settings.mcpBrowser.builtin')}`" data-mcp-builtin-filter />
+ <Button v-if="builtinFilter" variant="ghost" size="icon-sm" class="mcp-nav-filter-action size-6 shrink-0" :aria-label="t('settings.mcpBrowser.clearSearch')" data-mcp-clear-builtin-filter @click="builtinFilter = ''"><X class="size-3" /></Button>
+ </div>
+ </div>
+ <button
+ v-for="category in filteredCategories"
+ :key="category.id"
+ type="button"
+ class="mcp-category-button"
+ :class="state.selected === category.id && !searching ? 'mcp-category-button-selected font-semibold text-foreground' : 'text-muted-foreground'"
+ :aria-current="state.selected === category.id && !searching ? 'page' : undefined"
+ :data-mcp-category="category.id"
+ @click="select(category.id)"
+ >
+ <span class="min-w-0 break-words [overflow-wrap:anywhere]">{{ mcpCategoryTitle(category.id, t) }}</span
+ ><span class="shrink-0 text-xs tabular-nums" :aria-label="t('settings.mcpBrowser.categoryCount', { count: category.toolsets.length })">{{ category.toolsets.length }}</span>
+ </button>
+ <p v-if="filteredCategories.length === 0" class="px-2 py-2 text-[11px] text-muted-foreground">{{ t("settings.mcpCapabilitiesSearchEmpty") }}</p>
+ </div>
+ <div v-if="showPlugins" class="mcp-nav-section" data-mcp-nav-section="plugins">
+ <div class="mcp-nav-section-header">
+ <p class="mcp-nav-section-title">
+ <span>{{ t("settings.mcpBrowser.plugins") }}</span>
+ <span class="mcp-nav-section-count">{{ props.plugins?.length ?? 0 }}</span>
+ </p>
+ <div class="mcp-nav-filter-control mcp-nav-filter-control-with-refresh" :class="{ active: pluginFilter }" :title="`${t('settings.mcpCapabilitiesFilterLabel')}: ${t('settings.mcpBrowser.plugins')}`" @click="focusNavigationFilter">
+ <Search class="mcp-nav-filter-icon" aria-hidden="true" />
+ <Input v-model="pluginFilter" class="mcp-nav-filter-input h-6 border-0 bg-transparent px-0 text-[11px] shadow-none focus-visible:ring-0" :placeholder="''" :aria-label="`${t('settings.mcpCapabilitiesFilterLabel')}: ${t('settings.mcpBrowser.plugins')}`" data-mcp-plugin-filter />
+ <Button v-if="pluginFilter" variant="ghost" size="icon-sm" class="mcp-nav-filter-action size-6 shrink-0" :aria-label="t('settings.mcpBrowser.clearSearch')" data-mcp-clear-plugin-filter @click="pluginFilter = ''"><X class="size-3" /></Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ class="mcp-nav-filter-action mcp-nav-refresh-action size-6 shrink-0"
+ :disabled="pluginsLoading"
+ :aria-label="`${t('settings.mcpBrowser.plugins')} · ${t('settings.mcpPluginsRefresh')}`"
+ :title="t('settings.mcpPluginsRefresh')"
+ data-mcp-plugins-refresh-nav
+ @click="emit('refresh:plugins')"
+ ><RefreshCw class="size-3" :class="{ 'animate-spin': pluginsLoading }"
+ /></Button>
+ </div>
+ </div>
+ <button
+ v-for="plugin in filteredPlugins"
+ :key="plugin.pluginId"
+ type="button"
+ class="mcp-category-button flex-wrap"
+ :class="selectedPluginId === plugin.pluginId && !searching ? 'mcp-category-button-selected font-semibold text-foreground' : 'text-muted-foreground'"
+ :aria-current="selectedPluginId === plugin.pluginId && !searching ? 'page' : undefined"
+ :data-mcp-category="`plugin:${plugin.pluginId}`"
+ @click="select(`plugin:${plugin.pluginId}`)"
+ >
+ <span class="min-w-0 break-words [overflow-wrap:anywhere]">{{ plugin.pluginName }}</span>
+ <span class="rounded border px-1 text-[10px] font-normal">{{ t("settings.mcpCapabilitiesFilterPlugin") }}</span>
+ <span v-if="pluginMcpPendingTools(plugin).length" class="max-w-full truncate text-[11px] font-normal text-amber-700 dark:text-amber-300">{{ t("settings.mcpPluginPendingTools", { count: pluginMcpPendingTools(plugin).length }) }}</span>
+ </button>
+ <p v-if="filteredPlugins.length === 0" class="px-2 py-2 text-[11px] text-muted-foreground">{{ t(plugins?.length ? "settings.mcpCapabilitiesSearchEmpty" : "settings.mcpPluginsEmpty") }}</p>
+ </div>
+ <button
+ type="button"
+ class="mcp-category-button mcp-advanced-category-button"
+ :class="state.selected === 'advanced' && !searching ? 'mcp-category-button-selected font-semibold text-foreground' : 'text-muted-foreground'"
+ :aria-current="state.selected === 'advanced' && !searching ? 'page' : undefined"
+ data-mcp-category="advanced"
+ @click="select('advanced')"
+ >
+ {{ t("settings.mcpBrowser.advanced") }}
+ </button>
+ </nav>
+ </aside>
+
+ <div class="min-w-0 space-y-4" data-mcp-category-content>
+ <div v-if="(viewMode === 'manage' || searching) && showPlugins && (!selectedPluginId || searching) && (pluginsLoading || pluginsError || !plugins?.length)" class="space-y-2 text-xs text-muted-foreground" data-mcp-plugin-source-status>
+ <p v-if="pluginsLoading" role="status" class="flex items-center gap-2"><Loader2 class="size-3.5 shrink-0 animate-spin" />{{ t("settings.mcpPluginsLoading") }}</p>
+ <p v-else-if="pluginsError" role="alert" class="break-words text-destructive">{{ t("settings.mcpPluginsLoadFailed", { error: pluginsError }) }}</p>
+ <p v-else-if="plugins">{{ t("settings.mcpPluginsEmpty") }}</p>
+ <Button v-if="!pluginsLoading" variant="outline" size="sm" class="h-7 gap-1.5 text-xs" data-mcp-plugin-source-retry @click="emit('refresh:plugins')"><RefreshCw class="size-3.5" />{{ t("settings.mcpPluginsRefresh") }}</Button>
+ </div>
+
+ <template v-if="searching">
+ <h3 class="text-base font-semibold">{{ t("settings.mcpBrowser.searchResults") }}</h3>
+ <p v-if="loading" role="status" class="text-xs text-muted-foreground">{{ t("settings.mcpCapabilitiesLoading") }}</p>
+ <div v-if="loadError" role="alert" class="space-y-2 text-xs">
+ <p class="text-destructive">{{ t("settings.mcpCapabilitiesLoadFailed", { error: loadError }) }}</p>
+ <Button variant="outline" size="sm" :disabled="loading" @click="emit('retry')">{{ t("settings.mcpBrowser.retry") }}</Button>
+ </div>
+ <section v-for="group in results" :key="group.id" class="space-y-2" :data-mcp-search-group="group.id">
+ <h4 class="flex flex-wrap items-center gap-2 text-sm font-medium">
+ {{ group.title }}<span class="rounded border px-1.5 text-[10px] font-normal text-muted-foreground">{{ t(group.source === "plugin" ? "settings.mcpBrowser.plugins" : "settings.mcpBrowser.builtin") }}</span>
+ </h4>
+ <ul class="divide-y rounded-md border">
+ <li v-for="item in group.items" :key="item.key">
+ <button type="button" class="w-full space-y-1 px-3 py-2.5 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" :data-mcp-search-result="item.key" @click="openResult(item, $event)">
+ <span class="block break-words text-sm font-medium">{{ item.title }}</span>
+ <span class="block break-words text-xs text-muted-foreground">{{ item.path }}</span>
+ <span v-if="item.toolName && item.toolName !== item.title" class="block break-all font-mono text-xs text-muted-foreground">{{ item.toolName }}</span>
+ </button>
+ </li>
+ </ul>
+ </section>
+ <p v-if="!results.length && !loading && !pluginsLoading" class="rounded-md border border-dashed px-4 py-8 text-center text-xs text-muted-foreground">{{ t("settings.mcpCapabilitiesSearchEmpty") }}</p>
+ </template>
+
+ <div v-if="showBuiltin && selectedCategory" class="space-y-3">
+ <header class="space-y-1">
+ <h3 class="text-base font-semibold">{{ title }}</h3>
+ <p class="text-xs leading-relaxed text-muted-foreground">{{ t(`settings.mcpBrowser.category.${selectedCategory.id}.description`) }}</p>
+ <p v-if="catalog && !loading && !loadError" class="text-xs text-muted-foreground" data-mcp-category-summary>{{ t("settings.mcpBrowser.summary", { toolsets: selectedCategory.toolsets.length, total: categoryTools.length, enabled: enabledCount }) }}</p>
+ </header>
+ <div class="flex flex-wrap gap-2" data-mcp-category-batch>
+ <Button variant="outline" size="sm" class="h-auto min-h-7 whitespace-normal py-1 text-xs" :disabled="!editable || enabledCount === categoryTools.length" data-mcp-category-enable @click="batch(true)">{{ t("settings.mcpBrowser.enableCategory") }}</Button>
+ <Button variant="outline" size="sm" class="h-auto min-h-7 whitespace-normal py-1 text-xs" :disabled="!editable || enabledCount === 0" data-mcp-category-disable @click="batch(false)">{{ t("settings.mcpBrowser.disableCategory") }}</Button>
+ </div>
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpBrowser.coverageHint") }}</p>
+ <p v-if="batchChanged" role="status" class="text-xs" data-mcp-batch-feedback>{{ t("settings.mcpBrowser.batchChanged") }}</p>
+ </div>
+
+ <!-- Keep these instances mounted so a detail stays open as filters change. -->
+ <McpCapabilitiesPanel
+ ref="builtinPanel"
+ :focus-fallback="focusSearch"
+ :catalog="catalog"
+ :loading="loading"
+ :load-error="loadError"
+ :allowed-tool-names="allowedToolNames"
+ :saved-tool-names="savedToolNames"
+ :save-toolset="saveToolset"
+ :connections="connections"
+ :disabled="!editable"
+ :visible-toolset-ids="viewMode === 'overview' || searching ? undefined : (selectedCategory?.toolsets.map((toolset) => toolset.id) ?? [])"
+ :title-path="searching || viewMode === 'overview' ? detailPath : title"
+ :list-hidden="viewMode !== 'manage' || !showBuiltin"
+ :only-enabled="state.onlyEnabled"
+ @set:toolset="(toolset, enabled) => emit('set:toolset', toolset, enabled)"
+ @set:tool="(name, enabled) => emit('set:tool', name, enabled)"
+ @retry="emit('retry')"
+ />
+ <p v-if="showBuiltin" class="text-xs text-muted-foreground">{{ t("settings.mcpBrowser.draftHint") }}</p>
+
+ <slot v-if="(viewMode === 'manage' || searching) && showPlugins && ((!searching && selectedPluginId) || (searching && results.some((group) => group.source === 'plugin')))" name="plugin-warning" />
+ <McpPluginCapabilities
+ v-if="showPlugins"
+ ref="pluginPanel"
+ :focus-fallback="focusSearch"
+ :plugins="plugins"
+ :loading="pluginsLoading"
+ :load-error="pluginsError"
+ :selected-plugin-id="viewMode === 'manage' && !searching ? selectedPluginId : undefined"
+ :pending-plugin-ids="pendingPluginIds"
+ :list-hidden="viewMode !== 'manage' || searching || !selectedPluginId"
+ :only-enabled="state.onlyEnabled"
+ :save="savePlugin"
+ @refresh="emit('refresh:plugins')"
+ @saved="(view) => emit('saved:plugin', view)"
+ />
+
+ <section v-if="viewMode === 'manage' && state.selected === 'advanced' && !searching" class="space-y-3" data-mcp-advanced>
+ <h3 class="text-base font-semibold">{{ t("settings.mcpBrowser.advanced") }}</h3>
+ <p v-if="loading" role="status" class="text-xs text-muted-foreground">{{ t("settings.mcpCapabilitiesLoading") }}</p>
+ <div v-if="loadError" role="alert" class="space-y-2 text-xs">
+ <p class="text-destructive">{{ t("settings.mcpCapabilitiesLoadFailed", { error: loadError }) }}</p>
+ <Button variant="outline" size="sm" :disabled="loading" @click="emit('retry')">{{ t("settings.mcpBrowser.retry") }}</Button>
+ </div>
+ <slot name="advanced" />
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpBrowser.draftHint") }}</p>
+ </section>
+ </div>
+ </div>
+ </section>
+</template>
+
+<style scoped>
+.mcp-capability-browser {
+ container-type: inline-size;
+}
+.mcp-category-sidebar {
+ display: none;
+ align-self: start;
+}
+.mcp-navigation-rail {
+ border: 1px solid color-mix(in srgb, var(--border) 78%, transparent);
+ border-radius: calc(var(--radius-md) + 2px);
+ padding: 7px;
+ background: color-mix(in srgb, var(--background) 94%, var(--muted));
+ box-shadow: 0 1px 2px color-mix(in srgb, var(--foreground) 5%, transparent);
+}
+.mcp-nav-section {
+ padding: 0 1px;
+}
+.mcp-nav-section + .mcp-nav-section {
+ margin-top: 9px;
+ padding-top: 9px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 72%, transparent);
+}
+.mcp-nav-section-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 4px;
+ min-height: 26px;
+ padding: 0 4px 5px;
+}
+.mcp-nav-section-title {
+ display: flex;
+ min-width: 0;
+ align-items: center;
+ gap: 5px;
+ margin: 0;
+ line-height: 1.2;
+ letter-spacing: 0.015em;
+ color: var(--foreground);
+ font-size: 11px;
+ font-weight: 650;
+}
+.mcp-nav-section-count {
+ color: var(--muted-foreground);
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ font-weight: 500;
+}
+.mcp-nav-filter-control {
+ display: flex;
+ min-width: 0;
+ width: 32px;
+ height: 26px;
+ align-items: center;
+ overflow: hidden;
+ border: 1px solid color-mix(in srgb, var(--border) 84%, transparent);
+ border-radius: var(--radius-sm);
+ background: var(--background);
+ cursor: text;
+ transition:
+ width 150ms ease,
+ border-color 140ms ease,
+ box-shadow 140ms ease;
+}
+.mcp-nav-filter-control.active,
+.mcp-nav-filter-control:focus-within {
+ width: 128px;
+}
+.mcp-nav-filter-icon {
+ width: 13px;
+ height: 13px;
+ flex: 0 0 13px;
+ margin: 0 8px;
+ pointer-events: none;
+ color: var(--muted-foreground);
+}
+.mcp-nav-filter-input {
+ min-width: 0;
+ flex: 1 1 auto;
+ opacity: 1;
+}
+.mcp-nav-filter-action {
+ margin-right: 2px;
+}
+.mcp-nav-refresh-action {
+ margin: 0;
+ border-left: 1px solid color-mix(in srgb, var(--border) 84%, transparent);
+ border-radius: 0;
+ padding-right: 5px;
+ padding-left: 5px;
+}
+.mcp-nav-filter-control-with-refresh {
+ width: 62px;
+}
+.mcp-nav-filter-control-with-refresh.active,
+.mcp-nav-filter-control-with-refresh:focus-within {
+ width: 132px;
+}
+.mcp-nav-filter-control-with-refresh .mcp-nav-filter-input {
+ width: auto;
+}
+.mcp-capability-layout {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ gap: 12px;
+}
+.mcp-category-button {
+ position: relative;
+ display: flex;
+ width: 100%;
+ min-height: 30px;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ border-radius: var(--radius-sm);
+ padding: 6px 8px;
+ text-align: left;
+ font-size: 12px;
+ line-height: 1.25;
+ transition:
+ background-color 140ms ease,
+ color 140ms ease,
+ box-shadow 140ms ease;
+}
+.mcp-category-button-selected {
+ background: color-mix(in srgb, var(--primary) 8%, var(--background));
+ box-shadow: inset 2px 0 var(--primary);
+}
+.mcp-category-button:hover {
+ background: color-mix(in srgb, var(--muted) 70%, var(--background));
+}
+.mcp-category-button-selected:hover {
+ background: color-mix(in srgb, var(--primary) 12%, var(--background));
+}
+.mcp-category-button:focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 2px;
+}
+.mcp-advanced-category-button {
+ margin-top: 8px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 72%, transparent);
+ border-radius: 0;
+ padding-top: 11px;
+}
+.mcp-nav-filter-control:focus-within {
+ border-color: var(--ring);
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--ring) 25%, transparent);
+}
+@container (min-width: 600px) {
+ .mcp-category-select {
+ display: none;
+ }
+ .mcp-category-sidebar {
+ display: block;
+ }
+ .mcp-capability-layout {
+ grid-template-columns: 144px minmax(0, 1fr);
+ }
+ .mcp-nav-section-header {
+ flex-wrap: wrap;
+ }
+ .mcp-nav-filter-control {
+ width: 32px;
+ }
+ .mcp-nav-filter-control-with-refresh {
+ width: 62px;
+ }
+ .mcp-nav-filter-control.active,
+ .mcp-nav-filter-control:focus-within {
+ width: 104px;
+ }
+ .mcp-nav-filter-control-with-refresh.active,
+ .mcp-nav-filter-control-with-refresh:focus-within {
+ width: 116px;
+ }
+}
+@container (min-width: 760px) {
+ .mcp-capability-layout {
+ grid-template-columns: 184px minmax(0, 1fr);
+ gap: 16px;
+ }
+ .mcp-nav-section-header {
+ flex-wrap: nowrap;
+ }
+ .mcp-nav-filter-control {
+ width: 32px;
+ }
+ .mcp-nav-filter-control-with-refresh {
+ width: 62px;
+ }
+ .mcp-nav-filter-control.active,
+ .mcp-nav-filter-control:focus-within {
+ width: 116px;
+ }
+ .mcp-nav-filter-control-with-refresh.active,
+ .mcp-nav-filter-control-with-refresh:focus-within {
+ width: 124px;
+ }
+}
+</style>
diff --git a/apps/desktop/src/components/settings/McpDatabaseAccessDialog.vue b/apps/desktop/src/components/settings/McpDatabaseAccessDialog.vue
new file mode 100644
index 0000000000..3ab4d89d19
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpDatabaseAccessDialog.vue
@@ -0,0 +1,337 @@
+<script setup lang="ts">
+import { computed, ref, watch, onBeforeUnmount } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { HelpTooltip } from "@/components/ui/tooltip";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import type { ConnectionConfig } from "@/types/database";
+import type { McpTreeSetting } from "@/lib/mcp/mcpAccessTree";
+import { databaseAccess, databaseAccessEqual, type McpDatabaseAccess } from "@/lib/mcp/mcpDatabaseAccess";
+
+const props = defineProps<{
+ open: boolean;
+ connection: ConnectionConfig;
+ value: McpDatabaseAccess;
+ savedValue: McpDatabaseAccess;
+ inheritedLabel: string;
+ savedInheritedLabel: string;
+ savedVisible: boolean;
+ disabled?: boolean;
+ loadDatabases?: (connection: ConnectionConfig) => Promise<string[]>;
+ save?: (connectionId: string) => Promise<void>;
+}>();
+const emit = defineEmits<{ "update:open": [open: boolean]; change: [value: McpDatabaseAccess]; "return-focus": [] }>();
+const { t } = useI18n();
+const names = ref<string[]>([]);
+const knownNames = ref<string[]>([...props.value.allowedDatabases]);
+const loaded = ref(false);
+const loading = ref(false);
+const loadError = ref("");
+const saveError = ref("");
+const saving = ref(false);
+const applied = ref(false);
+const leftSearch = ref("");
+const rightSearch = ref("");
+const leftChecked = ref<string[]>([]);
+const rightChecked = ref<string[]>([]);
+const leftLimit = ref(100);
+const rightLimit = ref(100);
+const manualName = ref("");
+const selectedDraft = ref<McpDatabaseAccess | null>(null);
+const confirmation = ref<{ message: string; value: McpDatabaseAccess } | null>(null);
+let loadRevision = 0;
+const dirty = computed(() => !databaseAccessEqual(props.value, props.savedValue));
+const locked = computed(() => props.disabled || saving.value || !!confirmation.value);
+const selected = computed(() => new Set(props.value.allowedDatabases));
+const available = computed(() => [...new Set([...names.value, ...knownNames.value])].sort((a, b) => a.localeCompare(b)).filter((name) => !selected.value.has(name) && name.toLocaleLowerCase().includes(leftSearch.value.trim().toLocaleLowerCase())));
+const chosen = computed(() => props.value.allowedDatabases.filter((name) => name.toLocaleLowerCase().includes(rightSearch.value.trim().toLocaleLowerCase())));
+const checkedDatabases = computed(() => {
+ const checked = new Set(rightChecked.value);
+ return chosen.value.filter((name) => checked.has(name));
+});
+const candidates = computed(
+ () =>
+ [
+ { side: "left", names: available.value, checked: leftChecked.value, limit: leftLimit.value, search: leftSearch.value },
+ { side: "right", names: chosen.value, checked: rightChecked.value, limit: rightLimit.value, search: rightSearch.value },
+ ] as const,
+);
+watch(leftSearch, () => {
+ leftChecked.value = [];
+ leftLimit.value = 100;
+});
+watch(rightSearch, () => {
+ rightChecked.value = [];
+ rightLimit.value = 100;
+});
+watch(
+ () => props.value,
+ () => {
+ knownNames.value = [...new Set([...knownNames.value, ...props.value.allowedDatabases])];
+ applied.value = false;
+ saveError.value = "";
+ },
+);
+watch(
+ [() => props.open, () => props.connection.id],
+ ([open, id], previous) => {
+ ++loadRevision;
+ if (!open) {
+ selectedDraft.value = null;
+ return;
+ }
+ if (previous?.[1] !== id) {
+ names.value = [];
+ selectedDraft.value = null;
+ knownNames.value = [...props.value.allowedDatabases];
+ loaded.value = false;
+ }
+ leftSearch.value = rightSearch.value = manualName.value = saveError.value = "";
+ leftChecked.value = [];
+ rightChecked.value = [];
+ confirmation.value = null;
+ applied.value = false;
+ leftLimit.value = rightLimit.value = 100;
+ void refresh();
+ },
+ { immediate: true },
+);
+onBeforeUnmount(() => {
+ ++loadRevision;
+});
+
+async function refresh() {
+ const revision = ++loadRevision;
+ loadError.value = "";
+ if (!props.loadDatabases) {
+ loading.value = false;
+ return;
+ }
+ loading.value = true;
+ try {
+ // These metadata APIs return every database visible to the account. Local
+ // rendering limits never truncate discovery, search, or the saved selection.
+ const result = await props.loadDatabases(props.connection);
+ if (revision !== loadRevision) return;
+ names.value = [...new Set(result.filter((name) => name.trim().length > 0))].sort((a, b) => a.localeCompare(b));
+ loaded.value = true;
+ } catch (error) {
+ if (revision === loadRevision) loadError.value = String(error instanceof Error ? error.message : error);
+ } finally {
+ if (revision === loadRevision) loading.value = false;
+ }
+}
+function levelLabel(setting: McpTreeSetting) {
+ return t(setting === "inherit" ? "settings.mcpAccessTreeInherit" : setting === "read_only" ? "settings.mcpExecutionModeReadOnly" : setting === "safe_write" ? "settings.mcpExecutionModeSafeWrite" : "settings.mcpExecutionModeHighRiskWrite");
+}
+function settingFor(name: string): McpTreeSetting {
+ const rule = props.value.databasePolicies.find((entry) => entry.databaseName === name);
+ return !rule ? "inherit" : rule.readOnly ? "read_only" : rule.allowDangerousSql ? "high_risk_write" : "safe_write";
+}
+function permissionDescription(name: string) {
+ const permission = settingFor(name) === "inherit" ? t("settings.mcpDatabaseInherited", { level: props.inheritedLabel }) : t("settings.mcpAccessTreeSourceDatabase");
+ return loaded.value && !loading.value && !loadError.value && !names.value.includes(name) ? `${permission} · ${t("settings.mcpDatabaseNotDiscovered")}` : permission;
+}
+function change(value: McpDatabaseAccess, message?: string) {
+ if (locked.value) return;
+ if (message) confirmation.value = { message, value: databaseAccess(value) };
+ else emit("change", databaseAccess(value));
+}
+function confirmChange() {
+ if (!confirmation.value || props.disabled || saving.value) return;
+ const value = confirmation.value.value;
+ confirmation.value = null;
+ emit("change", value);
+}
+function changeScope(scope: McpDatabaseAccess["databaseScope"]) {
+ if (scope === props.value.databaseScope) return;
+ if (props.value.databaseScope === "selected") selectedDraft.value = databaseAccess(props.value);
+ const value = scope === "selected" && selectedDraft.value ? selectedDraft.value : { ...props.value, databaseScope: scope };
+ change(value, scope !== "selected" && props.value.databasePolicies.length ? t("settings.mcpDatabaseScopeClearsPermissionExceptions") : undefined);
+}
+function check(side: string, name: string, checked: boolean) {
+ if (locked.value) return;
+ const target = side === "left" ? leftChecked : rightChecked;
+ target.value = checked ? [...new Set([...target.value, name])] : target.value.filter((item) => item !== name);
+}
+function checkResults(side: string, checked: boolean) {
+ if (locked.value) return;
+ if (side === "left") leftChecked.value = checked ? [...available.value] : [];
+ else rightChecked.value = checked ? [...chosen.value] : [];
+}
+function add(namesToAdd: string[]) {
+ if (locked.value || !namesToAdd.length) return;
+ change({ ...props.value, databaseScope: "selected", allowedDatabases: [...props.value.allowedDatabases, ...namesToAdd] });
+ leftChecked.value = [];
+ manualName.value = "";
+}
+function remove() {
+ const removed = new Set(rightChecked.value);
+ if (!removed.size) return;
+ change({ ...props.value, allowedDatabases: props.value.allowedDatabases.filter((name) => !removed.has(name)) }, props.value.databasePolicies.some((entry) => removed.has(entry.databaseName)) ? t("settings.mcpDatabaseRemoveConfirm") : undefined);
+ rightChecked.value = [];
+}
+function setLevels(namesToChange: string[], setting: McpTreeSetting, batch = false) {
+ if (locked.value || props.value.databaseScope !== "selected") return;
+ const targets = new Set(namesToChange.filter((name) => selected.value.has(name) && settingFor(name) !== setting));
+ if (!targets.size) return;
+ const databasePolicies = props.value.databasePolicies.filter((entry) => !targets.has(entry.databaseName));
+ if (setting !== "inherit") {
+ for (const name of targets) databasePolicies.push({ databaseName: name, readOnly: setting === "read_only", allowDangerousSql: setting === "high_risk_write" });
+ }
+ change({ ...props.value, databasePolicies }, setting === "high_risk_write" ? (batch ? t("settings.mcpDatabaseBatchHighRiskConfirm", { count: targets.size }) : t("settings.mcpDatabasePolicyHighRiskConfirm")) : undefined);
+}
+function close() {
+ if (!saving.value) emit("update:open", false);
+}
+async function apply() {
+ if (locked.value || !dirty.value || !props.save) return;
+ saving.value = true;
+ saveError.value = "";
+ try {
+ await props.save(props.connection.id);
+ selectedDraft.value = null;
+ applied.value = true;
+ } catch (error) {
+ saveError.value = t("settings.mcpToolsetApplyFailed", { error: error instanceof Error ? error.message : String(error) });
+ } finally {
+ saving.value = false;
+ }
+}
+</script>
+
+<template>
+ <Dialog :open="open" @update:open="!$event && close()">
+ <DialogContent
+ class="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-5xl"
+ :show-close-button="!saving"
+ data-mcp-database-dialog
+ @close-auto-focus="
+ $event.preventDefault();
+ emit('return-focus');
+ "
+ @escape-key-down="saving && $event.preventDefault()"
+ @interact-outside="$event.preventDefault()"
+ >
+ <DialogHeader class="shrink-0">
+ <DialogTitle class="break-all">{{ t("settings.mcpDatabaseDialogTitle", { name: connection.name }) }}</DialogTitle>
+ <DialogDescription>{{ t("settings.mcpDatabaseDialogDescription") }}</DialogDescription>
+ </DialogHeader>
+ <div class="min-h-0 flex-1 space-y-3 overflow-y-auto">
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpDatabaseInherited", { level: inheritedLabel }) }}</p>
+ <p v-if="inheritedLabel !== savedInheritedLabel" class="text-xs text-amber-700 dark:text-amber-300" data-mcp-database-parent-draft>{{ t("settings.mcpDatabaseSavedInherited", { level: savedInheritedLabel }) }}</p>
+ <p v-if="!savedVisible" class="text-xs text-amber-700 dark:text-amber-300">{{ t("settings.mcpDatabaseHiddenConnection") }}</p>
+ <Select :model-value="value.databaseScope" :disabled="locked" @update:model-value="changeScope($event as McpDatabaseAccess['databaseScope'])">
+ <SelectTrigger class="w-full sm:w-64" :aria-label="t('settings.mcpAccessTreeDatabases')" data-mcp-database-mode
+ ><SelectValue>{{
+ t(value.databaseScope === "all" ? "settings.mcpAccessTreeDatabaseScopeAll" : value.databaseScope === "none" ? "settings.mcpAccessTreeDatabaseScopeNone" : "settings.mcpAccessTreeDatabaseScopeSelected", { count: value.allowedDatabases.length })
+ }}</SelectValue></SelectTrigger
+ >
+ <SelectContent
+ ><SelectItem value="all">{{ t("settings.mcpAccessTreeDatabaseScopeAll") }}</SelectItem
+ ><SelectItem value="selected">{{ t("settings.mcpAccessTreeDatabaseScopeSelected", { count: value.allowedDatabases.length }) }}</SelectItem
+ ><SelectItem value="none">{{ t("settings.mcpAccessTreeDatabaseScopeNone") }}</SelectItem></SelectContent
+ >
+ </Select>
+ <p v-if="value.databaseScope === 'all'" class="text-xs text-muted-foreground">{{ t("settings.mcpDatabaseAllHint") }}</p>
+ <p v-else-if="value.databaseScope === 'none' || !value.allowedDatabases.length" class="text-xs text-muted-foreground">{{ t("settings.mcpDatabaseNoneHint") }}</p>
+ <template v-if="value.databaseScope === 'selected'">
+ <div class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <span role="status">{{ loading ? t("settings.mcpAccessTreeLoadingDatabases") : t("settings.mcpDatabaseLoaded", { count: names.length }) }}</span>
+ <Button variant="outline" size="sm" :disabled="loading || locked" data-mcp-database-refresh @click="refresh">{{ t("settings.mcpDatabaseRefresh") }}</Button>
+ </div>
+ <p v-if="loadError" role="alert" class="text-xs text-destructive">{{ t("settings.mcpAccessTreeLoadDatabasesFailed", { error: loadError }) }}</p>
+ <div class="grid min-w-0 gap-3 md:grid-cols-[minmax(0,1fr)_auto_minmax(0,1.5fr)]">
+ <template v-for="pane in candidates" :key="pane.side">
+ <div v-if="pane.side === 'right'" class="flex items-center justify-center gap-2 md:flex-col">
+ <Button variant="outline" size="sm" :disabled="locked || !leftChecked.length" data-mcp-database-add @click="add(leftChecked)">{{ t("settings.mcpDatabaseAddSelected") }}</Button>
+ <Button variant="outline" size="sm" :disabled="locked || !rightChecked.length" data-mcp-database-remove @click="remove">{{ t("settings.mcpDatabaseRemoveSelected") }}</Button>
+ </div>
+ <section class="flex min-w-0 flex-col rounded-md border" :data-mcp-database-pane="pane.side" :aria-label="t(pane.side === 'left' ? 'settings.mcpDatabaseAvailable' : 'settings.mcpDatabaseSelected', { count: pane.names.length })">
+ <div class="space-y-2 border-b bg-muted/30 p-3">
+ <p class="text-sm font-medium">{{ t(pane.side === "left" ? "settings.mcpDatabaseAvailable" : "settings.mcpDatabaseSelected", { count: pane.side === "left" ? new Set([...names, ...knownNames].filter((name) => !selected.has(name))).size : value.allowedDatabases.length }) }}</p>
+ <Input :model-value="pane.search" :placeholder="t('settings.mcpDatabaseSearch')" :aria-label="t('settings.mcpDatabaseSearch')" :data-mcp-database-search="pane.side" @update:model-value="pane.side === 'left' ? (leftSearch = String($event)) : (rightSearch = String($event))" />
+ <div class="flex min-h-7 flex-wrap items-center justify-between gap-2">
+ <label class="flex items-center gap-2 text-xs"
+ ><input
+ type="checkbox"
+ class="m-0 size-3.5 shrink-0"
+ :disabled="locked || !pane.names.length"
+ :checked="!!pane.names.length && pane.names.every((name) => pane.checked.includes(name))"
+ :data-mcp-database-check-results="pane.side"
+ @change="checkResults(pane.side, ($event.target as HTMLInputElement).checked)"
+ />{{ t("settings.mcpDatabaseSelectResults", { count: pane.names.length }) }}</label
+ >
+ <Select v-if="pane.side === 'right'" model-value="" :disabled="locked || !checkedDatabases.length" @update:model-value="setLevels(checkedDatabases, $event as McpTreeSetting, true)">
+ <SelectTrigger size="sm" class="max-w-full text-xs" :aria-label="t('settings.mcpDatabaseBatchLevel', { count: checkedDatabases.length })" data-mcp-database-batch-level>
+ <SelectValue :placeholder="t('settings.mcpDatabaseBatchLevel', { count: checkedDatabases.length })" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="level in ['inherit', 'read_only', 'safe_write', 'high_risk_write'] as const" :key="level" :value="level">{{ levelLabel(level) }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ <div class="h-64 overflow-y-auto p-1 md:h-[min(40vh,24rem)]">
+ <div v-for="name in pane.names.slice(0, pane.limit)" :key="name" class="grid min-h-8 min-w-0 items-center gap-x-2 rounded px-2 py-0.5 hover:bg-muted/50" :class="pane.side === 'right' ? 'grid-cols-[minmax(0,1fr)_9rem]' : 'grid-cols-1'" :data-mcp-database-name="name">
+ <label class="flex min-h-6 min-w-0 items-center gap-2 text-sm leading-5"
+ ><input class="m-0 size-3.5 shrink-0" type="checkbox" :checked="pane.checked.includes(name)" :disabled="locked" :data-mcp-database-check="`${pane.side}:${name}`" @change="check(pane.side, name, ($event.target as HTMLInputElement).checked)" /><span
+ class="min-w-0 truncate"
+ :title="name"
+ >{{ name }}</span
+ ></label
+ >
+ <div v-if="pane.side === 'right'" class="flex min-w-0 items-center gap-1.5">
+ <Select :model-value="settingFor(name)" :disabled="locked" @update:model-value="setLevels([name], $event as McpTreeSetting)">
+ <SelectTrigger size="sm" class="min-w-0 flex-1 text-xs" :aria-label="`${name} / ${t('settings.mcpAccessTreeColumnSetting')}`" :aria-description="permissionDescription(name)" :data-mcp-database-level="name"
+ ><SelectValue>{{ levelLabel(settingFor(name)) }}</SelectValue></SelectTrigger
+ >
+ <SelectContent
+ ><SelectItem v-for="level in ['inherit', 'read_only', 'safe_write', 'high_risk_write'] as const" :key="level" :value="level">{{ levelLabel(level) }}</SelectItem></SelectContent
+ >
+ </Select>
+ <HelpTooltip :label="`${name} / ${permissionDescription(name)}`" />
+ </div>
+ </div>
+ <p v-if="!pane.names.length" class="p-4 text-center text-xs text-muted-foreground">{{ t("settings.mcpAccessTreeNoMatch") }}</p>
+ <Button v-if="pane.names.length > pane.limit" variant="outline" size="sm" class="w-full" :data-mcp-database-more="pane.side" @click="pane.side === 'left' ? (leftLimit += 100) : (rightLimit += 100)">{{
+ t("settings.mcpDatabaseShowMore", { shown: Math.min(pane.limit, pane.names.length), total: pane.names.length })
+ }}</Button>
+ </div>
+ </section>
+ </template>
+ </div>
+ <div class="flex gap-2">
+ <Input v-model="manualName" :disabled="locked" :placeholder="t('settings.mcpAccessTreeManualDatabase')" :aria-label="t('settings.mcpAccessTreeManualDatabase')" data-mcp-database-manual @keydown.enter.prevent="manualName.trim() && add([manualName.trim()])" /><Button
+ variant="outline"
+ :disabled="locked || !manualName.trim()"
+ data-mcp-database-manual-add
+ @click="add([manualName.trim()])"
+ >{{ t("settings.mcpToolCustomAdd") }}</Button
+ >
+ </div>
+ </template>
+ </div>
+ <div class="shrink-0 space-y-3 border-t pt-3">
+ <div v-if="confirmation" role="alert" class="space-y-2 rounded border p-3 text-sm">
+ <p>{{ confirmation.message }}</p>
+ <div class="flex justify-end gap-2">
+ <Button variant="outline" data-mcp-database-confirm-cancel @click="confirmation = null">{{ t("common.cancel") }}</Button
+ ><Button :disabled="disabled" data-mcp-database-confirm @click="confirmChange">{{ t("common.confirm") }}</Button>
+ </div>
+ </div>
+ <p v-if="saveError" role="alert" class="text-xs text-destructive">{{ saveError }}</p>
+ <div class="flex flex-wrap items-center justify-end gap-2">
+ <div class="min-w-0 flex-1 basis-64 space-y-1 text-xs text-muted-foreground">
+ <p>{{ t("settings.mcpDatabaseSaveHint") }}</p>
+ <p role="status" aria-live="polite">{{ saving ? t("settings.mcpToolsetApplying") : dirty ? t("settings.mcpToolsetCloseKeepsDraft") : applied ? t("settings.mcpToolsetApplied") : "" }}</p>
+ </div>
+ <Button variant="outline" :disabled="saving" data-mcp-database-close @click="close">{{ t("settings.mcpToolsetDetailClose") }}</Button>
+ <Button :disabled="locked || !dirty || !save" data-mcp-database-apply @click="apply">{{ t("settings.mcpDatabaseApply") }}</Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+</template>
diff --git a/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue b/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue
deleted file mode 100644
index 4dca8c7dc7..0000000000
--- a/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue
+++ /dev/null
@@ -1,364 +0,0 @@
-<script setup lang="ts">
-import { computed, ref, watch } from "vue";
-import { Check, ChevronLeft, ChevronRight, Loader2, Plus, RefreshCw, Search } from "@lucide/vue";
-import { useI18n } from "vue-i18n";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Badge } from "@/components/ui/badge";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { listDatabases, mongoListDatabases, redisListDatabases } from "@/lib/backend/api";
-import { useConnectionStore } from "@/stores/connectionStore";
-import type { McpConnectionPolicy } from "@/stores/settingsStore";
-import type { ConnectionConfig } from "@/types/database";
-
-type DatabaseScope = McpConnectionPolicy["databaseScope"];
-type ExecutionMode = "read_only" | "safe_write" | "high_risk_write";
-const { t } = useI18n();
-const connectionStore = useConnectionStore();
-
-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[];
- disabled?: boolean;
- busy?: boolean;
- }>(),
- { disabled: false, busy: false },
-);
-
-const emit = defineEmits<{
- "update:connectionPolicies": [value: McpConnectionPolicy[]];
- "set:database-policy": [connectionId: string, databaseName: string, mode: ExecutionMode | "inherit"];
-}>();
-
-const selectedConnectionId = ref("");
-const databasesByConnection = ref<Record<string, string[]>>({});
-const loadingConnectionId = ref("");
-const loadError = ref("");
-const search = ref("");
-const manualDatabase = ref("");
-const pageSize = ref<number>(PAGE_SIZE_OPTIONS[0]);
-const connectionPage = ref(1);
-const databasePage = ref(1);
-
-const scopedConnections = computed(() => (props.allowedConnectionIds === null ? [...props.connections] : props.connections.filter((connection) => props.allowedConnectionIds?.includes(connection.id))));
-const selectedConnection = computed(() => scopedConnections.value.find((connection) => connection.id === selectedConnectionId.value));
-const selectedPolicy = computed(() => props.connectionPolicies.find((policy) => policy.connectionId === selectedConnectionId.value));
-const selectedScope = computed<DatabaseScope>(() => selectedPolicy.value?.databaseScope ?? "all");
-const selectedDatabases = computed(() => selectedPolicy.value?.allowedDatabases ?? []);
-const selectedDatabasePolicies = computed(() => selectedPolicy.value?.databasePolicies ?? []);
-const displayedDatabases = computed(() => {
- const query = search.value.trim().toLocaleLowerCase();
- // 加载缓存是会话级的:把已持久化的库名并入列表,重开对话框后授权项仍完整可见。
- const loaded = databasesByConnection.value[selectedConnectionId.value] ?? [];
- return [...new Set([...selectedDatabases.value, ...loaded])].sort((left, right) => left.localeCompare(right)).filter((database) => !query || database.toLocaleLowerCase().includes(query));
-});
-const connectionPageCount = computed(() => Math.max(1, Math.ceil(scopedConnections.value.length / pageSize.value)));
-const databasePageCount = computed(() => Math.max(1, Math.ceil(displayedDatabases.value.length / pageSize.value)));
-const pagedScopedConnections = computed(() => {
- const start = (connectionPage.value - 1) * pageSize.value;
- return scopedConnections.value.slice(start, start + pageSize.value);
-});
-const pagedDatabases = computed(() => {
- const start = (databasePage.value - 1) * pageSize.value;
- return displayedDatabases.value.slice(start, start + pageSize.value);
-});
-
-watch(
- scopedConnections,
- (connections) => {
- if (!connections.some((connection) => connection.id === selectedConnectionId.value)) {
- selectedConnectionId.value = connections[0]?.id ?? "";
- }
- },
- { immediate: true },
-);
-
-function policyFor(connectionId: string): McpConnectionPolicy {
- return (
- props.connectionPolicies.find((policy) => policy.connectionId === connectionId) ?? {
- connectionId,
- readOnly: false,
- allowDangerousSql: false,
- executionModeConfigured: false,
- executionModePolicyVersion: null,
- databaseScope: "all",
- allowedDatabases: [],
- databasePolicies: [],
- allowSalesforceDml: false,
- }
- );
-}
-
-function updateSelectedPolicy(patch: Partial<McpConnectionPolicy>) {
- if (props.disabled || !selectedConnectionId.value) return;
- const existing = policyFor(selectedConnectionId.value);
- 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 : [],
- databasePolicies: scope === "selected" ? selectedDatabasePolicies.value.filter((policy) => selectedDatabases.value.includes(policy.databaseName)) : [],
- });
-}
-
-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);
-}
-
-function setDatabasePage(page: number) {
- databasePage.value = Math.min(Math.max(1, page), databasePageCount.value);
-}
-
-function selectConnection(connectionId: string) {
- selectedConnectionId.value = connectionId;
- loadError.value = "";
- search.value = "";
- databasePage.value = 1;
-}
-
-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",
- allowedDatabases: databases,
- databasePolicies: selectedDatabasePolicies.value.filter((policy) => databases.includes(policy.databaseName)),
- });
-}
-
-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 addManualDatabase() {
- // busy 期间 updateSelectedPolicy 会被丢弃;提前拦截,避免库名进了本地列表却没进策略。
- if (props.disabled || props.busy) return;
- const database = manualDatabase.value.trim();
- if (!database) return;
- const loaded = databasesByConnection.value[selectedConnectionId.value] ?? [];
- databasesByConnection.value = {
- ...databasesByConnection.value,
- [selectedConnectionId.value]: [...new Set([...loaded, database])].sort((left, right) => left.localeCompare(right)),
- };
- toggleDatabase(database, true);
- manualDatabase.value = "";
- databasePage.value = 1;
-}
-
-async function loadConnectionDatabases() {
- const connection = selectedConnection.value;
- if (!connection || loadingConnectionId.value) return;
- loadingConnectionId.value = connection.id;
- loadError.value = "";
- try {
- // SQL 连接的 list_databases 只读后端现有连接池,从未在侧边栏连接过的连接
- // 会报 "Connection not found";与侧边栏流程一致,先确保连接建立。
- await connectionStore.ensureConnected(connection.id, { activate: false });
- const databases = connection.db_type === "mongodb" ? await mongoListDatabases(connection.id) : connection.db_type === "redis" ? (await redisListDatabases(connection.id)).map((database) => String(database.db)) : (await listDatabases(connection.id)).map((database) => database.name);
- databasesByConnection.value = {
- ...databasesByConnection.value,
- [connection.id]: [...new Set(databases.map((database) => database.trim()).filter(Boolean))].sort((left, right) => left.localeCompare(right)),
- };
- } catch (error: unknown) {
- loadError.value = error instanceof Error ? error.message : String(error);
- } finally {
- loadingConnectionId.value = "";
- }
-}
-
-function scopeSummary(connection: ConnectionConfig): string {
- const policy = props.connectionPolicies.find((item) => item.connectionId === connection.id);
- if (!policy || policy.databaseScope === "all") return t("settings.mcpDatabaseScopeSummaryAll");
- if (policy.databaseScope === "none") return t("settings.mcpDatabaseScopeSummaryNone");
- return t("settings.mcpDatabaseScopeSummarySelected", { count: policy.allowedDatabases.length });
-}
-
-watch(search, () => {
- databasePage.value = 1;
-});
-
-watch(pageSize, () => {
- connectionPage.value = 1;
- databasePage.value = 1;
-});
-
-watch(connectionPageCount, () => setConnectionPage(connectionPage.value));
-watch(databasePageCount, () => setDatabasePage(databasePage.value));
-</script>
-
-<template>
- <section class="space-y-3">
- <div>
- <p class="text-sm font-medium">{{ t("settings.mcpDatabaseScopeTitle") }}</p>
- <p class="text-xs text-muted-foreground">{{ t("settings.mcpDatabaseScopeDescription") }}</p>
- </div>
-
- <div v-if="!scopedConnections.length" class="rounded border border-dashed bg-background px-3 py-4 text-center text-xs text-muted-foreground">{{ t("settings.mcpDatabaseScopeEmptyHint") }}</div>
- <div v-else class="grid min-h-72 overflow-hidden rounded-md border bg-background md:grid-cols-[minmax(14rem,0.42fr)_minmax(0,1fr)]">
- <div class="border-b p-2 md:border-b-0 md:border-r">
- <div class="flex items-center justify-between gap-2 px-2 pb-2">
- <p class="text-xs font-medium text-muted-foreground">{{ t("settings.mcpDatabaseScopeAllowedConnections") }}</p>
- <div class="flex items-center gap-1 text-[11px] text-muted-foreground">
- <span>{{ t("settings.mcpPerPage") }}</span>
- <Select :model-value="String(pageSize)" :disabled="disabled" @update:model-value="(value) => (pageSize = Number(value))">
- <SelectTrigger size="sm" class="h-7 w-14 px-1.5 text-[11px]"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem v-for="size in PAGE_SIZE_OPTIONS" :key="size" :value="String(size)">{{ size }}</SelectItem>
- </SelectContent>
- </Select>
- </div>
- </div>
- <div class="space-y-1">
- <button
- v-for="connection in pagedScopedConnections"
- :key="connection.id"
- type="button"
- class="w-full cursor-pointer rounded-md px-2 py-2 text-left transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
- :class="selectedConnectionId === connection.id ? 'bg-muted' : ''"
- :aria-current="selectedConnectionId === connection.id ? 'true' : undefined"
- @pointerdown="selectConnection(connection.id)"
- @click="selectConnection(connection.id)"
- >
- <div class="pointer-events-none flex items-center justify-between gap-2">
- <span class="min-w-0 truncate text-sm font-medium">{{ connection.name }}</span>
- <Badge variant="outline" class="shrink-0 text-[10px] font-normal">{{ scopeSummary(connection) }}</Badge>
- </div>
- <p class="pointer-events-none mt-0.5 truncate font-mono text-[10px] text-muted-foreground">{{ connection.db_type }} · {{ connection.host || connection.database || connection.id }}</p>
- </button>
- </div>
- <div v-if="connectionPageCount > 1" class="mt-2 flex items-center justify-center gap-2 border-t pt-2 text-xs text-muted-foreground">
- <Button type="button" size="icon-sm" variant="ghost" :disabled="connectionPage === 1" :title="t('settings.mcpPreviousPage')" :aria-label="t('settings.mcpPreviousPage')" @click="setConnectionPage(connectionPage - 1)"><ChevronLeft /></Button>
- <span class="min-w-12 text-center tabular-nums">{{ connectionPage }} / {{ connectionPageCount }}</span>
- <Button type="button" size="icon-sm" variant="ghost" :disabled="connectionPage === connectionPageCount" :title="t('settings.mcpNextPage')" :aria-label="t('settings.mcpNextPage')" @click="setConnectionPage(connectionPage + 1)"><ChevronRight /></Button>
- </div>
- </div>
-
- <div v-if="selectedConnection" class="space-y-3 p-3">
- <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.mcpDatabaseScopeDescription") }}</p>
- </div>
- <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") }}
- </Button>
- </div>
-
- <div class="grid gap-2 sm:grid-cols-3" role="radiogroup" :aria-label="t('settings.mcpDatabaseScopeAriaLabel')">
- <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"
- 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"
- 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
- >
- </Button>
- </div>
-
- <template v-if="selectedScope === 'selected'">
- <p class="text-xs text-muted-foreground">{{ t("settings.mcpDatabaseScopeSelectedSummary", { count: selectedDatabases.length }) }}</p>
- <div class="flex gap-2">
- <div class="relative min-w-0 flex-1"><Search class="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" /><Input v-model="search" class="h-8 pl-8 text-xs" :placeholder="t('settings.mcpDatabaseSearchPlaceholder')" /></div>
- <Input v-model="manualDatabase" class="h-8 w-40 text-xs" :placeholder="t('settings.mcpDatabaseManualPlaceholder')" :disabled="disabled || busy" @keydown.enter.prevent="addManualDatabase" />
- <Button type="button" variant="outline" size="sm" :disabled="disabled || busy || !manualDatabase.trim()" @click="addManualDatabase"><Plus class="h-3.5 w-3.5" /></Button>
- </div>
- <p v-if="loadError" class="rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-xs text-destructive">{{ t("settings.mcpDatabaseLoadFailed", { error: loadError }) }}</p>
- <div v-if="displayedDatabases.length" class="rounded border">
- <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>
- <Check v-if="selectedDatabases.includes(database)" class="h-3.5 w-3.5 text-green-600" />
- <Select v-if="selectedDatabases.includes(database)" :model-value="databasePolicyMode(database)" :disabled="disabled || busy" @update:model-value="(value) => $emit('set:database-policy', selectedConnectionId, database, value as ExecutionMode | 'inherit')">
- <SelectTrigger size="sm" class="h-7 w-44 shrink-0 text-[11px]" @click.stop><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="inherit">{{ t("settings.mcpConnectionPolicyInherit") }}</SelectItem>
- <SelectItem value="read_only">{{ t("settings.mcpConnectionPolicyReadOnly") }}</SelectItem>
- <SelectItem value="safe_write">{{ t("settings.mcpConnectionPolicySafeWrite") }}</SelectItem>
- <SelectItem value="high_risk_write">{{ t("settings.mcpConnectionPolicyHighRiskWrite") }}</SelectItem>
- </SelectContent>
- </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>
- <span class="min-w-12 text-center tabular-nums">{{ databasePage }} / {{ databasePageCount }}</span>
- <Button type="button" size="icon-sm" variant="ghost" :disabled="databasePage === databasePageCount" :title="t('settings.mcpNextPage')" :aria-label="t('settings.mcpNextPage')" @click="setDatabasePage(databasePage + 1)"><ChevronRight /></Button>
- </div>
- </div>
- <p v-else class="rounded border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">{{ t("settings.mcpDatabaseEmptyHint") }}</p>
- </template>
- </div>
- </div>
- </section>
-</template>
diff --git a/apps/desktop/src/components/settings/McpDefaultAccessPanel.vue b/apps/desktop/src/components/settings/McpDefaultAccessPanel.vue
new file mode 100644
index 0000000000..9b8dbac9ce
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpDefaultAccessPanel.vue
@@ -0,0 +1,92 @@
+<script setup lang="ts">
+import { computed, nextTick, useId } from "vue";
+import { useI18n } from "vue-i18n";
+import { Check, X } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { MCP_CAPABILITY_ROWS, MCP_EXECUTION_MODE_COLUMNS, type McpExecutionMode } from "@/lib/mcp/mcpPolicySelection";
+
+const props = defineProps<{ mode: McpExecutionMode; disabled?: boolean }>();
+const emit = defineEmits<{ "set:mode": [mode: McpExecutionMode] }>();
+const { t } = useI18n();
+const labelId = useId();
+const descriptionId = useId();
+const descriptionKey = computed(() => `${MCP_EXECUTION_MODE_COLUMNS.find((column) => column.mode === props.mode)!.labelKey}Description`);
+
+function selectMode(mode: McpExecutionMode) {
+ if (!props.disabled && mode !== props.mode) emit("set:mode", mode);
+}
+
+async function onModeKeydown(event: KeyboardEvent, mode: McpExecutionMode) {
+ if (props.disabled) return;
+ const modes = MCP_EXECUTION_MODE_COLUMNS.map((column) => column.mode);
+ const current = modes.indexOf(mode);
+ let next: number;
+ if (event.key === "Home") next = 0;
+ else if (event.key === "End") next = modes.length - 1;
+ else if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (current + 1) % modes.length;
+ else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (current - 1 + modes.length) % modes.length;
+ else return;
+ event.preventDefault();
+ event.stopPropagation();
+ const group = (event.currentTarget as HTMLElement).closest('[role="radiogroup"]');
+ selectMode(modes[next]);
+ await nextTick();
+ // The parent can reject full access in its confirmation dialog.
+ group?.querySelector<HTMLElement>(`[data-mcp-execution-mode="${props.mode}"]`)?.focus();
+}
+</script>
+
+<template>
+ <section class="min-w-0 space-y-3 rounded-md border bg-background p-3 sm:p-4" data-mcp-default-access>
+ <header class="space-y-1">
+ <h3 :id="labelId" class="text-sm font-semibold">{{ t("settings.mcpExecutionMode") }}</h3>
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpExecutionModeDescription") }}</p>
+ </header>
+ <div class="grid grid-cols-1 gap-2 sm:grid-cols-3" role="radiogroup" :aria-labelledby="labelId" :aria-describedby="descriptionId">
+ <Button
+ v-for="column in MCP_EXECUTION_MODE_COLUMNS"
+ :key="column.mode"
+ type="button"
+ role="radio"
+ variant="outline"
+ class="settings-choice-card h-auto min-h-10 whitespace-normal px-3 py-2 text-center"
+ :class="mode === column.mode ? 'dbx-choice-selected' : ''"
+ :disabled="disabled"
+ :data-mcp-execution-mode="column.mode"
+ :aria-checked="mode === column.mode"
+ :tabindex="mode === column.mode ? 0 : -1"
+ @click="selectMode(column.mode)"
+ @keydown="onModeKeydown($event, column.mode)"
+ >{{ t(column.labelKey) }}</Button
+ >
+ </div>
+ <p :id="descriptionId" class="text-xs leading-relaxed text-muted-foreground" data-mcp-mode-description>{{ t(descriptionKey) }}</p>
+ <details class="space-y-2 border-t border-border/60 pt-3" data-mcp-permission-help>
+ <summary class="cursor-pointer rounded-sm text-xs font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">{{ t("settings.mcpCapabilityTitle") }}</summary>
+ <p class="text-[11px] leading-relaxed text-muted-foreground">{{ t("settings.mcpCapabilityDescription") }}</p>
+ <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>
+ </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>
+ <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" />
+ <X v-else class="h-4 w-4" aria-hidden="true" />
+ <span class="sr-only">{{ t(row[column.mode] ? "settings.mcpCapabilityAllowed" : "settings.mcpCapabilityBlocked") }}</span>
+ </span>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <p class="text-[11px] leading-relaxed text-muted-foreground">{{ t("settings.mcpCapabilityAlwaysEnforced") }}</p>
+ </details>
+ </section>
+</template>
diff --git a/apps/desktop/src/components/settings/McpPluginCapabilities.vue b/apps/desktop/src/components/settings/McpPluginCapabilities.vue
new file mode 100644
index 0000000000..efcb2d752e
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpPluginCapabilities.vue
@@ -0,0 +1,472 @@
+<script setup lang="ts">
+import { computed, nextTick, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { AlertTriangle, ChevronDown, ChevronRight, Loader2, Puzzle, RefreshCw } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Switch } from "@/components/ui/switch";
+import type { PluginMcpAccessLevel, PluginMcpGrant, PluginMcpToolView, PluginMcpView } from "@/types/mcpCatalog";
+import {
+ PLUGIN_MCP_ACCESS_LEVELS,
+ pluginMcpAccessLevels,
+ pluginMcpAuthorizedGrant,
+ pluginMcpBaseGrant,
+ pluginMcpDeclaredTools,
+ pluginMcpDefaultCeiling,
+ pluginMcpEnabled,
+ pluginMcpExposedCount,
+ pluginMcpLevelAtMost,
+ pluginMcpNeedsAuthorization,
+ pluginMcpPendingTools,
+ pluginMcpSetCeiling,
+ pluginMcpSetEnabled,
+ pluginMcpSetToolEnabled,
+ pluginMcpToolsByToolset,
+ pluginMcpUndeclaredTools,
+} from "@/lib/mcp/pluginMcpGrant";
+
+/**
+ * Plugin cards of the MCP capability tab: one card per MCP-capable plugin,
+ * managed per plugin (switch, access ceiling, per-tool opt-outs, confirming
+ * new tools). Grants save immediately through `save`, independent of the
+ * settings dialog's Apply button, because they live outside the MCP policy.
+ */
+const props = withDefaults(
+ defineProps<{
+ plugins: readonly PluginMcpView[] | null;
+ loading?: boolean;
+ loadError?: string;
+ search?: string;
+ disabled?: boolean;
+ filterKind?: "all" | "builtin" | "plugin";
+ onlyEnabled?: boolean;
+ selectedPluginId?: string;
+ listHidden?: boolean;
+ focusFallback?: () => void;
+ pendingPluginIds?: readonly string[];
+ save: (pluginId: string, grant: PluginMcpGrant, approveCurrent: boolean) => Promise<PluginMcpView>;
+ }>(),
+ { loading: false, loadError: "", search: "", disabled: false, filterKind: "all", onlyEnabled: false, listHidden: false },
+);
+
+const emit = defineEmits<{ refresh: []; saved: [view: PluginMcpView] }>();
+
+const { t } = useI18n();
+const rootElement = ref<HTMLElement | null>(null);
+const inline = computed(() => props.selectedPluginId !== undefined && !props.listHidden);
+let detailTrigger: HTMLElement | null = null;
+let authorizeTrigger: HTMLElement | null = null;
+const detailPluginId = ref<string | null>(null);
+const expandedToolNames = ref(new Set<string>());
+const authorizePluginId = ref<string | null>(null);
+const authorizeCeiling = ref<PluginMcpAccessLevel>("write");
+const localSavingPluginIds = ref(new Set<string>());
+const savingPluginIds = computed(() => new Set([...localSavingPluginIds.value, ...(props.pendingPluginIds ?? [])]));
+const savedPluginIds = ref(new Set<string>());
+const saveErrors = ref(new Map<string, string>());
+const saveError = computed(() => (inline.value ? (saveErrors.value.get(props.selectedPluginId!) ?? "") : [...saveErrors.value.values()].join(" ")));
+
+const cards = computed(() => {
+ const needle = props.search.trim().toLowerCase();
+ return (props.plugins ?? []).filter((view) => {
+ if (props.filterKind === "builtin" || (props.onlyEnabled && !pluginMcpEnabled(view))) return false;
+ if (!needle) return true;
+ return [view.pluginName, view.pluginId, ...view.tools.flatMap((tool) => [tool.name, tool.description])].some((text) => text.toLowerCase().includes(needle));
+ });
+});
+
+const detail = computed(() => props.plugins?.find((view) => view.pluginId === (inline.value ? props.selectedPluginId : detailPluginId.value)) ?? null);
+const authorizing = computed(() => props.plugins?.find((view) => view.pluginId === authorizePluginId.value) ?? null);
+const detailGroups = computed(() => {
+ if (!detail.value) return [];
+ const view = detail.value;
+ return pluginMcpToolsByToolset(view)
+ .map((group) => ({ ...group, tools: group.tools.filter((tool) => !props.onlyEnabled || expandedToolNames.value.has(tool.name) || (pluginMcpEnabled(view) && tool.access !== null && !view.grant.disabledTools.includes(tool.name))) }))
+ .filter((group) => group.tools.length > 0);
+});
+
+watch(
+ () => props.selectedPluginId,
+ () => {
+ expandedToolNames.value = new Set();
+ },
+);
+
+const levelClass: Record<PluginMcpAccessLevel, string> = {
+ read: "border-border text-muted-foreground",
+ write: "border-amber-500/40 text-amber-700 dark:text-amber-300",
+ full: "border-red-500/40 text-red-600 dark:text-red-400",
+};
+
+async function persist(view: PluginMcpView, grant: PluginMcpGrant, approveCurrent = false) {
+ if (props.disabled || !view.authorAllowsExternal || savingPluginIds.value.has(view.pluginId)) return false;
+ localSavingPluginIds.value.add(view.pluginId);
+ savedPluginIds.value.delete(view.pluginId);
+ saveErrors.value.delete(view.pluginId);
+ try {
+ emit("saved", await props.save(view.pluginId, grant, approveCurrent));
+ savedPluginIds.value.add(view.pluginId);
+ return true;
+ } catch (error) {
+ saveErrors.value.set(view.pluginId, t("settings.mcpPluginSaveFailed", { name: view.pluginName, message: error instanceof Error ? error.message : String(error) }));
+ return false;
+ } finally {
+ localSavingPluginIds.value.delete(view.pluginId);
+ }
+}
+
+function onPluginSwitch(view: PluginMcpView, enabled: boolean) {
+ if (props.disabled || !view.authorAllowsExternal || savingPluginIds.value.has(view.pluginId)) return;
+ if (enabled && pluginMcpNeedsAuthorization(view)) {
+ openAuthorize(view);
+ return;
+ }
+ void persist(view, pluginMcpSetEnabled(pluginMcpBaseGrant(view), enabled));
+}
+
+function openAuthorize(view: PluginMcpView, trigger?: HTMLElement | null) {
+ if (props.disabled || !view.authorAllowsExternal || savingPluginIds.value.has(view.pluginId)) return;
+ authorizeTrigger = trigger ?? activeFocusTarget();
+ authorizePluginId.value = view.pluginId;
+ authorizeCeiling.value = view.hasSavedGrant && view.grant.external ? view.grant.ceiling : pluginMcpDefaultCeiling(view);
+}
+
+async function confirmAuthorize() {
+ const view = authorizing.value;
+ if (!view) return;
+ if (await persist(view, pluginMcpAuthorizedGrant(view, authorizeCeiling.value), true)) authorizePluginId.value = null;
+}
+
+function closeAuthorize(open: boolean) {
+ if (!open && (!authorizing.value || !savingPluginIds.value.has(authorizing.value.pluginId))) authorizePluginId.value = null;
+}
+
+function onCeilingChange(view: PluginMcpView, ceiling: PluginMcpAccessLevel) {
+ if (!pluginMcpEnabled(view)) return;
+ void persist(view, pluginMcpSetCeiling(pluginMcpBaseGrant(view), ceiling));
+}
+
+function onToolSwitch(view: PluginMcpView, tool: PluginMcpToolView, enabled: boolean) {
+ if (!pluginMcpEnabled(view) || tool.access === null) return;
+ void persist(view, pluginMcpSetToolEnabled(pluginMcpBaseGrant(view), tool.name, enabled));
+}
+
+function openDetail(plugin: PluginMcpView | string, trigger?: HTMLElement | null) {
+ const pluginId = typeof plugin === "string" ? plugin : plugin.pluginId;
+ if (!props.plugins?.some((view) => view.pluginId === pluginId)) return;
+ detailTrigger = trigger ?? activeFocusTarget();
+ detailPluginId.value = pluginId;
+ expandedToolNames.value = new Set();
+}
+
+async function openTool(pluginId: string, toolName: string, trigger?: HTMLElement | null) {
+ const view = props.plugins?.find((plugin) => plugin.pluginId === pluginId);
+ if (!view?.tools.some((tool) => tool.name === toolName)) return;
+ openDetail(pluginId, trigger);
+ await nextTick();
+ if (detail.value?.pluginId !== pluginId) return;
+ expandedToolNames.value = new Set([toolName]);
+ await nextTick();
+ const rows = rootElement.value?.querySelectorAll?.<HTMLElement>("[data-mcp-plugin-tool]") ?? [];
+ const dialogRows = typeof document === "undefined" ? [] : document.querySelectorAll<HTMLElement>("[data-mcp-plugin-detail] [data-mcp-plugin-tool]");
+ const row = [...rows, ...dialogRows].find((element) => element.dataset.mcpPluginTool === toolName);
+ row?.scrollIntoView?.({ block: "nearest" });
+ row?.querySelector<HTMLButtonElement>("[data-mcp-plugin-tool-toggle]")?.focus();
+}
+
+function activeFocusTarget(): HTMLElement | null {
+ if (typeof document === "undefined" || document.activeElement === document.body || document.activeElement === document.documentElement) return null;
+ return document.activeElement as HTMLElement | null;
+}
+
+function restoreFocus(event: Event, trigger: HTMLElement | null) {
+ if (trigger?.isConnected) {
+ event.preventDefault();
+ trigger.focus();
+ } else if (props.focusFallback) {
+ event.preventDefault();
+ props.focusFallback();
+ }
+}
+
+function restoreDetailFocus(event: Event) {
+ restoreFocus(event, detailTrigger);
+}
+
+function restoreAuthorizeFocus(event: Event) {
+ restoreFocus(event, authorizeTrigger);
+}
+
+defineExpose({ openDetail, openTool });
+
+function toggleTool(name: string) {
+ const next = new Set(expandedToolNames.value);
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+ expandedToolNames.value = next;
+}
+
+function toolsetTitle(title: string | null): string {
+ return title ?? t("settings.mcpPluginDefaultToolset");
+}
+
+function exposureText(tool: PluginMcpToolView): string {
+ return t(`settings.mcpPluginExposure.${tool.exposure}`);
+}
+
+function parameterDefault(value: unknown): string {
+ return typeof value === "string" ? value : JSON.stringify(value);
+}
+
+function cardSummary(view: PluginMcpView): string {
+ if (!view.authorAllowsExternal) return t("settings.mcpPluginAuthorClosed");
+ if (view.discoveryError) return t("settings.mcpPluginDiscoveryFailed");
+ if (!pluginMcpEnabled(view)) return t("settings.mcpPluginToolCountOff", { total: view.tools.length });
+ return t("settings.mcpPluginToolCount", { exposed: pluginMcpExposedCount(view), total: view.tools.length });
+}
+</script>
+
+<template>
+ <section ref="rootElement" class="min-w-0 space-y-2" data-mcp-plugins>
+ <div v-if="!inline && !listHidden" class="flex items-center justify-between gap-2">
+ <div>
+ <p class="text-sm font-semibold">{{ t("settings.mcpPluginsTitle") }}</p>
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpPluginsDescription") }}</p>
+ </div>
+ <Button variant="outline" size="sm" class="h-7 shrink-0 gap-1.5 text-xs" :disabled="loading" data-mcp-plugins-refresh @click="emit('refresh')">
+ <Loader2 v-if="loading" class="size-3.5 animate-spin" />
+ <RefreshCw v-else class="size-3.5" />
+ {{ t("settings.mcpPluginsRefresh") }}
+ </Button>
+ </div>
+
+ <p v-if="loadError && !listHidden" 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.mcpPluginsLoadFailed", { error: loadError }) }}</p>
+ <p v-if="saveError && !listHidden && !inline" role="alert" 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" data-mcp-plugin-save-error>{{ saveError }}</p>
+
+ <div v-if="loading && !plugins && !listHidden" class="flex items-center gap-2 py-4 text-xs text-muted-foreground"><Loader2 class="size-3.5 animate-spin" />{{ t("settings.mcpPluginsLoading") }}</div>
+ <div v-else-if="inline && plugins && !detail" class="space-y-3 rounded-md border border-dashed px-3 py-4 text-center text-xs text-muted-foreground" data-mcp-plugin-unavailable>
+ <p>{{ t("settings.mcpBrowser.pluginUnavailable") }}</p>
+ <Button variant="outline" size="sm" :disabled="loading" data-mcp-plugins-refresh @click="emit('refresh')">
+ <Loader2 v-if="loading" class="size-3.5 animate-spin" />
+ <RefreshCw v-else class="size-3.5" />
+ {{ t("settings.mcpPluginsRefresh") }}
+ </Button>
+ </div>
+ <p v-else-if="!listHidden && !inline && plugins && plugins.length === 0" class="rounded-md border border-dashed px-3 py-4 text-center text-xs text-muted-foreground" data-mcp-plugins-empty>{{ t("settings.mcpPluginsEmpty") }}</p>
+
+ <ul v-else-if="!inline && !listHidden && cards.length" class="divide-y rounded-md border">
+ <li v-for="view in cards" :key="view.pluginId" class="flex items-start gap-3 px-3 py-2.5" :class="{ 'opacity-60': !view.authorAllowsExternal }" :data-mcp-plugin="view.pluginId">
+ <Puzzle class="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <button type="button" class="min-w-0 flex-1 rounded-sm text-left focus-visible:ring-3 focus-visible:ring-ring/50" data-mcp-plugin-open @click="openDetail(view)">
+ <span class="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span class="break-words text-sm font-medium [overflow-wrap:anywhere]">{{ view.pluginName }}</span>
+ <span class="text-[11px] text-muted-foreground">v{{ view.version }}</span>
+ <span v-for="level in pluginMcpAccessLevels(view.tools)" :key="level" class="rounded border px-1.5 text-[10px] leading-4" :class="levelClass[level]">{{ t(`settings.mcpAccessLevel.${level}`) }}</span>
+ </span>
+ <span class="mt-0.5 flex flex-wrap gap-x-3 text-[11px] text-muted-foreground">
+ <span class="font-mono">{{ view.pluginId }}</span>
+ <span>{{ cardSummary(view) }}</span>
+ <span v-if="pluginMcpEnabled(view)">{{ t("settings.mcpPluginCeilingSummary", { level: t(`settings.mcpAccessLevel.${view.grant.ceiling}`) }) }}</span>
+ </span>
+ <span v-if="view.authorAllowsExternal && pluginMcpUndeclaredTools(view.tools).length" class="mt-1 block text-[11px] text-muted-foreground" data-mcp-plugin-undeclared>{{ t("settings.mcpPluginUndeclaredCount", { count: pluginMcpUndeclaredTools(view.tools).length }) }}</span>
+ <span v-if="pluginMcpEnabled(view) && pluginMcpPendingTools(view).length" class="mt-1 inline-flex items-center gap-1 text-[11px] text-amber-700 dark:text-amber-300" data-mcp-plugin-pending>
+ <AlertTriangle class="size-3" />{{ t("settings.mcpPluginPendingTools", { count: pluginMcpPendingTools(view).length }) }}
+ </span>
+ </button>
+ <Button v-if="pluginMcpEnabled(view) && pluginMcpPendingTools(view).length" variant="outline" size="sm" class="h-7 shrink-0 text-xs" :disabled="disabled || savingPluginIds.has(view.pluginId)" data-mcp-plugin-review @click="openAuthorize(view, $event.currentTarget as HTMLElement)">
+ {{ t("settings.mcpPluginReview") }}
+ </Button>
+ <Switch class="mt-0.5 shrink-0" :model-value="pluginMcpEnabled(view)" :disabled="disabled || !view.authorAllowsExternal || savingPluginIds.has(view.pluginId)" :aria-label="view.pluginName" @update:model-value="onPluginSwitch(view, $event === true)" />
+ </li>
+ </ul>
+ <p v-else-if="!inline && !listHidden && plugins && plugins.length" class="px-3 py-4 text-center text-xs text-muted-foreground">{{ t("settings.mcpCapabilitiesSearchEmpty") }}</p>
+
+ <!-- One shared detail view supports category navigation and search dialogs. -->
+ <component :is="inline ? 'div' : Dialog" v-bind="inline ? {} : { open: !!detail }" @update:open="(open: boolean) => !open && (detailPluginId = null)">
+ <component :is="inline ? 'div' : DialogContent" v-if="detail" :class="inline ? 'min-w-0 space-y-3' : 'max-h-[85vh] overflow-hidden sm:max-w-3xl'" :data-mcp-plugin-inline="inline ? detail.pluginId : undefined" data-mcp-plugin-detail @close-auto-focus="restoreDetailFocus">
+ <component :is="inline ? 'header' : DialogHeader" class="min-w-0 space-y-2">
+ <div class="flex items-start gap-3">
+ <div class="min-w-0 flex-1">
+ <span class="mb-1 inline-flex items-center gap-1 text-[11px] text-muted-foreground"><Puzzle class="size-3.5" />{{ t("settings.mcpCapabilitiesFilterPlugin") }}</span>
+ <component :is="inline ? 'h2' : DialogTitle" class="break-words text-base font-semibold [overflow-wrap:anywhere]">{{ detail.pluginName }}</component>
+ <component :is="inline ? 'p' : DialogDescription" class="break-words text-[11px] text-muted-foreground [overflow-wrap:anywhere]">{{ t("settings.mcpPluginDetailDescription", { id: detail.pluginId, version: detail.version }) }}</component>
+ </div>
+ <Switch class="mt-1 shrink-0" :model-value="pluginMcpEnabled(detail)" :disabled="disabled || !detail.authorAllowsExternal || savingPluginIds.has(detail.pluginId)" :aria-label="detail.pluginName" data-mcp-plugin-master @update:model-value="onPluginSwitch(detail, $event === true)" />
+ </div>
+ <p class="text-xs text-muted-foreground" data-mcp-plugin-summary>{{ cardSummary(detail) }}</p>
+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpBrowser.pluginImmediate") }}</p>
+ <p v-if="savingPluginIds.has(detail.pluginId)" role="status" class="flex items-center gap-1.5 text-xs text-muted-foreground" data-mcp-plugin-saving><Loader2 class="size-3.5 animate-spin" />{{ t("settings.mcpBrowser.pluginSaving") }}</p>
+ <p v-else-if="savedPluginIds.has(detail.pluginId)" role="status" class="text-xs text-muted-foreground" data-mcp-plugin-saved>{{ t("settings.mcpBrowser.pluginSaved") }}</p>
+ <div v-if="pluginMcpEnabled(detail) && pluginMcpPendingTools(detail).length" class="flex flex-wrap items-center justify-between gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2" data-mcp-plugin-pending>
+ <p class="text-xs text-amber-700 dark:text-amber-300">{{ t("settings.mcpPluginPendingTools", { count: pluginMcpPendingTools(detail).length }) }}</p>
+ <Button variant="outline" size="sm" :disabled="disabled || savingPluginIds.has(detail.pluginId)" data-mcp-plugin-review @click="openAuthorize(detail, $event.currentTarget as HTMLElement)">{{ t("settings.mcpPluginReview") }}</Button>
+ </div>
+ </component>
+
+ <div :class="inline ? 'min-w-0 space-y-3' : 'max-h-[62vh] space-y-3 overflow-y-auto'">
+ <p v-if="saveErrors.get(detail.pluginId)" role="alert" 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" data-mcp-plugin-save-error>{{ saveErrors.get(detail.pluginId) }}</p>
+ <p v-if="detail.discoveryError" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-800 dark:text-amber-200">{{ t("settings.mcpPluginDiscoveryError", { error: detail.discoveryError }) }}</p>
+
+ <section class="space-y-1.5 rounded-md border p-3" data-mcp-plugin-ceiling>
+ <p class="text-xs font-medium">{{ t("settings.mcpPluginCeilingTitle") }}</p>
+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpPluginCeilingDescription") }}</p>
+ <div class="flex flex-wrap gap-1.5">
+ <button
+ v-for="level in PLUGIN_MCP_ACCESS_LEVELS"
+ :key="level"
+ type="button"
+ class="rounded border px-2.5 py-1 text-xs focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50"
+ :class="detail.grant.ceiling === level ? 'border-primary bg-primary/10 font-medium text-foreground' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="detail.grant.ceiling === level"
+ :disabled="disabled || !pluginMcpEnabled(detail) || savingPluginIds.has(detail.pluginId)"
+ :data-mcp-plugin-ceiling-level="level"
+ @click="onCeilingChange(detail, level)"
+ >
+ {{ t(`settings.mcpPluginCeilingLevel.${level}`) }}
+ </button>
+ </div>
+ <p v-if="!pluginMcpEnabled(detail)" class="text-[11px] text-muted-foreground">{{ t("settings.mcpPluginEnableFirst") }}</p>
+ </section>
+
+ <section v-for="group in detailGroups" :key="group.id" class="min-w-0 space-y-1.5">
+ <div>
+ <p class="break-words text-xs font-semibold [overflow-wrap:anywhere]">{{ toolsetTitle(group.title) }}</p>
+ <p v-if="group.description" class="text-[11px] text-muted-foreground">{{ group.description }}</p>
+ </div>
+ <ul class="divide-y rounded-md border">
+ <li v-for="tool in group.tools" :key="tool.name" :data-mcp-plugin-tool="tool.name">
+ <div class="flex items-center gap-3 px-3 py-2">
+ <button type="button" class="flex min-w-0 flex-1 items-start gap-1.5 rounded-sm text-left focus-visible:ring-3 focus-visible:ring-ring/50" :aria-expanded="expandedToolNames.has(tool.name)" data-mcp-plugin-tool-toggle @click="toggleTool(tool.name)">
+ <ChevronDown v-if="expandedToolNames.has(tool.name)" class="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ <ChevronRight v-else class="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ <span class="min-w-0 flex-1">
+ <span class="flex flex-wrap items-center gap-2">
+ <span class="break-words font-mono text-xs font-medium [overflow-wrap:anywhere]">{{ tool.name }}</span>
+ <span v-if="tool.access" class="rounded border px-1.5 text-[10px] leading-4" :class="levelClass[tool.access]">{{ t(`settings.mcpAccessLevel.${tool.access}`) }}</span>
+ <span v-if="tool.exposure !== 'exposed'" class="text-[11px]" :class="tool.exposure === 'pendingApproval' ? 'text-amber-700 dark:text-amber-300' : 'text-muted-foreground'">{{ exposureText(tool) }}</span>
+ </span>
+ <span v-if="tool.description" class="mt-0.5 line-clamp-2 block text-[11px] text-muted-foreground">{{ tool.description }}</span>
+ </span>
+ </button>
+ <Switch
+ size="sm"
+ class="shrink-0"
+ :model-value="tool.access !== null && !detail.grant.disabledTools.includes(tool.name)"
+ :disabled="disabled || tool.access === null || !pluginMcpEnabled(detail) || savingPluginIds.has(detail.pluginId)"
+ :aria-label="tool.name"
+ @update:model-value="onToolSwitch(detail, tool, $event === true)"
+ />
+ </div>
+ <div v-if="expandedToolNames.has(tool.name)" class="space-y-2 border-t bg-muted/30 px-3 py-3 pl-8 text-xs" data-mcp-plugin-tool-detail>
+ <dl class="grid gap-x-4 gap-y-1.5 sm:grid-cols-[6rem_minmax(0,1fr)]">
+ <dt class="text-muted-foreground">{{ t("settings.mcpToolDetailId") }}</dt>
+ <dd class="break-words font-mono [overflow-wrap:anywhere]">{{ tool.name }}</dd>
+ <dt class="text-muted-foreground">{{ t("settings.mcpToolDetailAccess") }}</dt>
+ <dd>{{ tool.access ? t(`settings.mcpAccessLevel.${tool.access}`) : t("settings.mcpPluginAccessUndeclared") }}</dd>
+ <template v-if="tool.description">
+ <dt class="text-muted-foreground">{{ t("settings.mcpToolDetailDescription") }}</dt>
+ <dd class="whitespace-pre-wrap break-words text-muted-foreground">{{ tool.description }}</dd>
+ </template>
+ </dl>
+ <p class="font-medium">{{ t("settings.mcpToolDetailParameters") }}</p>
+ <p v-if="tool.parameters.length === 0" class="text-muted-foreground">{{ t("settings.mcpToolDetailNoParameters") }}</p>
+ <div v-else class="max-w-full overflow-x-auto rounded border bg-background">
+ <table class="w-full text-left text-[11px]">
+ <thead class="bg-muted/50 text-muted-foreground">
+ <tr>
+ <th class="px-2 py-1 font-medium">{{ t("settings.mcpToolDetailParameterName") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("settings.mcpToolDetailParameterType") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("settings.mcpToolDetailParameterRequired") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("settings.mcpToolDetailParameterDescription") }}</th>
+ </tr>
+ </thead>
+ <tbody class="divide-y">
+ <tr v-for="parameter in tool.parameters" :key="parameter.name" class="align-top">
+ <td class="whitespace-nowrap px-2 py-1 font-mono">{{ parameter.name }}</td>
+ <td class="px-2 py-1 font-mono text-muted-foreground">{{ parameter.valueType }}</td>
+ <td class="whitespace-nowrap px-2 py-1">{{ parameter.required ? t("settings.mcpToolDetailParameterRequiredYes") : t("settings.mcpToolDetailParameterRequiredNo") }}</td>
+ <td class="px-2 py-1 text-muted-foreground">
+ {{ parameter.description }}
+ <span v-if="parameter.default !== undefined" class="whitespace-nowrap">({{ t("settings.mcpToolDetailParameterDefault", { value: parameterDefault(parameter.default) }) }})</span>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </li>
+ </ul>
+ </section>
+ <p v-if="detail.tools.length === 0 && !detail.discoveryError" class="py-6 text-center text-xs text-muted-foreground">{{ t("settings.mcpPluginNoTools") }}</p>
+ <p v-else-if="onlyEnabled && detail.tools.length && detailGroups.length === 0" class="py-6 text-center text-xs text-muted-foreground" data-mcp-plugin-filter-empty>{{ t("settings.mcpBrowser.pluginOnlyEnabledEmpty") }}</p>
+ </div>
+ <div v-if="!inline" class="flex justify-end">
+ <Button variant="outline" size="sm" @click="detailPluginId = null">{{ t("settings.mcpToolsetDetailClose") }}</Button>
+ </div>
+ </component>
+ </component>
+
+ <!-- Authorization: first enable, re-enable, or confirming new tools. -->
+ <Dialog :open="!!authorizing" @update:open="closeAuthorize">
+ <DialogContent v-if="authorizing" class="max-h-[85vh] overflow-hidden sm:max-w-xl" data-mcp-plugin-authorize @close-auto-focus="restoreAuthorizeFocus">
+ <DialogHeader>
+ <DialogTitle>{{ t("settings.mcpPluginAuthorizeTitle", { name: authorizing.pluginName }) }}</DialogTitle>
+ <DialogDescription>{{ t("settings.mcpPluginAuthorizeDescription") }}</DialogDescription>
+ </DialogHeader>
+ <div class="max-h-[55vh] space-y-3 overflow-y-auto text-xs">
+ <p v-if="saveErrors.get(authorizing.pluginId)" role="alert" 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" data-mcp-plugin-authorize-error>{{ saveErrors.get(authorizing.pluginId) }}</p>
+ <p v-if="authorizing.discoveryError" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-amber-800 dark:text-amber-200">{{ t("settings.mcpPluginDiscoveryError", { error: authorizing.discoveryError }) }}</p>
+ <section class="space-y-1.5">
+ <p class="font-medium">{{ t("settings.mcpPluginCeilingTitle") }}</p>
+ <div class="flex flex-wrap gap-1.5">
+ <button
+ v-for="level in PLUGIN_MCP_ACCESS_LEVELS"
+ :key="level"
+ type="button"
+ class="rounded border px-2.5 py-1 focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50"
+ :class="authorizeCeiling === level ? 'border-primary bg-primary/10 font-medium text-foreground' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="authorizeCeiling === level"
+ :disabled="disabled || savingPluginIds.has(authorizing.pluginId)"
+ :data-mcp-plugin-authorize-level="level"
+ @click="authorizeCeiling = level"
+ >
+ {{ t(`settings.mcpPluginCeilingLevel.${level}`) }}
+ </button>
+ </div>
+ </section>
+ <section class="space-y-1.5">
+ <p class="font-medium">{{ t("settings.mcpPluginAuthorizeTools", { count: pluginMcpDeclaredTools(authorizing.tools).length }) }}</p>
+ <ul class="divide-y rounded-md border">
+ <li v-for="tool in pluginMcpDeclaredTools(authorizing.tools)" :key="tool.name" class="flex items-center gap-2 px-3 py-1.5" :data-mcp-plugin-authorize-tool="tool.name">
+ <span class="min-w-0 flex-1 truncate font-mono">{{ tool.name }}</span>
+ <span v-if="tool.exposure === 'pendingApproval'" class="text-[11px] text-amber-700 dark:text-amber-300">{{ t("settings.mcpPluginExposure.pendingApproval") }}</span>
+ <span class="rounded border px-1.5 text-[10px] leading-4" :class="levelClass[tool.access]">{{ t(`settings.mcpAccessLevel.${tool.access}`) }}</span>
+ <span class="w-16 text-right text-[11px]" :class="pluginMcpLevelAtMost(tool.access, authorizeCeiling) ? 'text-emerald-700 dark:text-emerald-400' : 'text-muted-foreground'">
+ {{ pluginMcpLevelAtMost(tool.access, authorizeCeiling) ? t("settings.mcpPluginAuthorizeIncluded") : t("settings.mcpPluginAuthorizeExcluded") }}
+ </span>
+ </li>
+ </ul>
+ </section>
+ <p v-if="pluginMcpUndeclaredTools(authorizing.tools).length" class="rounded-md border border-dashed px-3 py-2 text-[11px] text-muted-foreground" data-mcp-plugin-authorize-undeclared>
+ {{
+ t("settings.mcpPluginUndeclaredTools", {
+ count: pluginMcpUndeclaredTools(authorizing.tools).length,
+ names: pluginMcpUndeclaredTools(authorizing.tools)
+ .map((tool) => tool.name)
+ .join(", "),
+ })
+ }}
+ </p>
+ <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpPluginAuthorizeFootnote") }}</p>
+ </div>
+ <div class="flex justify-end gap-2">
+ <Button variant="outline" size="sm" :disabled="savingPluginIds.has(authorizing.pluginId)" @click="closeAuthorize(false)">{{ t("settings.mcpPluginAuthorizeCancel") }}</Button>
+ <Button size="sm" :disabled="disabled || !authorizing.authorAllowsExternal || savingPluginIds.has(authorizing.pluginId)" data-mcp-plugin-authorize-confirm @click="confirmAuthorize">
+ <Loader2 v-if="savingPluginIds.has(authorizing.pluginId)" class="mr-1.5 size-3.5 animate-spin" />
+ {{ t("settings.mcpPluginAuthorizeConfirm") }}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </section>
+</template>
diff --git a/apps/desktop/src/components/settings/McpPluginScopeEditor.vue b/apps/desktop/src/components/settings/McpPluginScopeEditor.vue
new file mode 100644
index 0000000000..89e37b579f
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpPluginScopeEditor.vue
@@ -0,0 +1,174 @@
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { Loader2, Plus, X } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import type { McpAccessLevelV2, McpAccessPolicy, McpAccessRule, McpSubScopeMode } from "@/types/mcpCatalog";
+
+/**
+ * Sub-scope rules for one plugin connection (e.g. Kubernetes namespaces),
+ * declared by the plugin's `mcp.scope`. These rules live only in the v2
+ * policy, so edits save immediately through `save` instead of the settings
+ * dialog's staged v1 draft (same as plugin authorizations).
+ */
+const props = withDefaults(
+ defineProps<{
+ connectionId: string;
+ pluginId?: string;
+ kind: string;
+ title: string;
+ policy: McpAccessPolicy | null;
+ disabled?: boolean;
+ save: (connectionId: string, kind: string, value: string | null, rule: McpAccessRule | null, subScope: McpSubScopeMode | null) => Promise<McpAccessPolicy>;
+ listValues?: (pluginId: string, connectionId: string) => Promise<{ values: string[] }>;
+ }>(),
+ { disabled: false, pluginId: "", listValues: undefined },
+);
+
+const emit = defineEmits<{ saved: [policy: McpAccessPolicy] }>();
+
+const { t } = useI18n();
+const newValue = ref("");
+const saving = ref(false);
+const error = ref("");
+const listedValues = ref<string[]>([]);
+const loadingValues = ref(false);
+const mutationBlocked = computed(() => props.disabled || saving.value || !props.policy);
+
+const mode = computed<McpSubScopeMode>(() => props.policy?.rules.find((rule) => rule.target.kind === "connection" && rule.target.id === props.connectionId)?.subScope ?? "all");
+
+const values = computed(() =>
+ (props.policy?.rules ?? [])
+ .filter((rule) => rule.target.kind === "scope" && rule.target.connectionId === props.connectionId && rule.target.scope === props.kind)
+ .map((rule) => ({ value: rule.target.kind === "scope" ? rule.target.value : "", visible: rule.visible === true, access: rule.access ?? "inherit" }))
+ .sort((left, right) => left.value.localeCompare(right.value)),
+);
+
+async function run(value: string | null, rule: McpAccessRule | null, subScope: McpSubScopeMode | null): Promise<boolean> {
+ if (mutationBlocked.value) return false;
+ saving.value = true;
+ error.value = "";
+ try {
+ emit("saved", await props.save(props.connectionId, props.kind, value, rule, subScope));
+ return true;
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ return false;
+ } finally {
+ saving.value = false;
+ }
+}
+
+function setMode(next: McpSubScopeMode) {
+ if (next !== mode.value) void run(null, null, next);
+}
+
+function savedRule(value: string): McpAccessRule | undefined {
+ const entry = props.policy?.rules.find((rule) => rule.target.kind === "scope" && rule.target.connectionId === props.connectionId && rule.target.scope === props.kind && rule.target.value === value);
+ if (!entry) return undefined;
+ const { target: _target, ...rule } = entry;
+ return rule;
+}
+
+const canAdd = computed(() => !mutationBlocked.value && !!newValue.value.trim() && !savedRule(newValue.value.trim()));
+
+async function addValue() {
+ if (!canAdd.value) return;
+ const value = newValue.value.trim();
+ if (await run(value, { visible: true }, mode.value === "all" ? "selected" : null)) {
+ if (newValue.value.trim() === value) newValue.value = "";
+ }
+}
+
+function setAccess(value: string, access: string) {
+ const rule: McpAccessRule = { ...savedRule(value) };
+ if (access === "inherit") delete rule.access;
+ else rule.access = access as McpAccessLevelV2;
+ void run(value, rule, null);
+}
+
+function removeValue(value: string) {
+ void run(value, null, null);
+}
+
+async function loadValues() {
+ if (!props.listValues) return;
+ loadingValues.value = true;
+ error.value = "";
+ try {
+ listedValues.value = [...new Set((await props.listValues(props.pluginId, props.connectionId)).values)].sort();
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ loadingValues.value = false;
+ }
+}
+
+function isSelected(value: string) {
+ return values.value.some((entry) => entry.value === value && entry.visible);
+}
+
+function toggleListedValue(value: string) {
+ if (isSelected(value)) removeValue(value);
+ else void run(value, { ...savedRule(value), visible: true }, mode.value === "all" ? "selected" : null);
+}
+
+const LEVELS: Array<{ value: McpAccessLevelV2 | "inherit"; key: string }> = [
+ { value: "inherit", key: "settings.mcpAccessTreeInherit" },
+ { value: "read", key: "settings.mcpExecutionModeReadOnly" },
+ { value: "write", key: "settings.mcpExecutionModeSafeWrite" },
+ { value: "full", key: "settings.mcpExecutionModeHighRiskWrite" },
+];
+
+function accessLabel(access: string): string {
+ const level = LEVELS.find((entry) => entry.value === access);
+ return level ? t(level.key) : access;
+}
+</script>
+
+<template>
+ <div class="space-y-1.5" :data-mcp-plugin-scope="connectionId">
+ <div class="flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] text-muted-foreground">
+ <span>{{ title }}</span>
+ <Select :model-value="mode" :disabled="mutationBlocked" @update:model-value="(value) => setMode(value as McpSubScopeMode)">
+ <SelectTrigger size="sm" class="h-6 text-[11px]" :data-mcp-plugin-scope-mode="connectionId">
+ <SelectValue>{{ t(mode === "all" ? "settings.mcpPluginScopeAll" : mode === "none" ? "settings.mcpPluginScopeNone" : "settings.mcpPluginScopeSelected", { title, count: values.length }) }}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{{ t("settings.mcpPluginScopeAll", { title }) }}</SelectItem>
+ <SelectItem value="selected">{{ t("settings.mcpPluginScopeSelected", { count: values.length }) }}</SelectItem>
+ <SelectItem value="none">{{ t("settings.mcpPluginScopeNone", { title }) }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <Loader2 v-if="saving" class="size-3 animate-spin" />
+ </div>
+ <p class="text-[11px] leading-relaxed text-muted-foreground">{{ t("settings.mcpBrowser.pluginImmediate") }}</p>
+ <div v-if="mode !== 'none'" class="flex flex-wrap items-center gap-1.5">
+ <span v-for="entry in values" :key="entry.value" class="inline-flex items-center gap-1 rounded border bg-background px-1.5 py-0.5 text-[11px]" :data-mcp-plugin-scope-value="entry.value">
+ <span class="font-mono">{{ entry.value }}</span>
+ <Select :model-value="entry.access" :disabled="mutationBlocked" @update:model-value="(value) => setAccess(entry.value, String(value))">
+ <SelectTrigger size="sm" class="h-5 border-0 px-1 text-[10px]">
+ <SelectValue>{{ accessLabel(entry.access) }}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="level in LEVELS" :key="level.value" :value="level.value">{{ t(level.key) }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <button type="button" class="text-muted-foreground hover:text-destructive" :disabled="mutationBlocked" :aria-label="t('settings.mcpToolCustomRemove')" @click="removeValue(entry.value)"><X class="size-3" /></button>
+ </span>
+ <span class="inline-flex items-center gap-1">
+ <Input v-model="newValue" class="h-6 w-36 font-mono text-[11px]" :placeholder="t('settings.mcpPluginScopeAdd', { title })" :disabled="mutationBlocked" @keydown.enter.prevent="addValue" />
+ <Button variant="ghost" size="sm" class="h-6 px-1.5" :disabled="!canAdd" :data-mcp-plugin-scope-add="connectionId" @click="addValue"><Plus class="size-3" /></Button>
+ </span>
+ </div>
+ <div v-if="listValues && pluginId" class="space-y-1.5">
+ <Button variant="outline" size="sm" class="h-6 text-[11px]" :disabled="disabled || saving || loadingValues" data-mcp-plugin-scope-list @click="loadValues"> <Loader2 v-if="loadingValues" class="mr-1 size-3 animate-spin" />{{ t("settings.mcpPluginScopeLoad") }} </Button>
+ <div v-if="listedValues.length" class="grid max-h-36 gap-1 overflow-y-auto rounded border p-1.5 sm:grid-cols-2">
+ <label v-for="value in listedValues" :key="value" class="flex items-center gap-1.5 text-[11px]"><input type="checkbox" :checked="isSelected(value)" :disabled="mutationBlocked" @change="toggleListedValue(value)" />{{ value }}</label>
+ </div>
+ </div>
+ <p v-if="error" class="text-[11px] text-red-600 dark:text-red-400">{{ error }}</p>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/settings/McpPluginToolsModeSetting.vue b/apps/desktop/src/components/settings/McpPluginToolsModeSetting.vue
new file mode 100644
index 0000000000..b2fd603f8c
--- /dev/null
+++ b/apps/desktop/src/components/settings/McpPluginToolsModeSetting.vue
@@ -0,0 +1,37 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import type { McpGlobalPolicy } from "@/stores/settingsStore";
+
+const props = defineProps<{ disabled?: boolean }>();
+const mode = defineModel<McpGlobalPolicy["pluginToolsMode"]>({ required: true });
+const { t } = useI18n();
+const labels = { flat: "settings.mcpPluginToolsModeFlat", lazy: "settings.mcpPluginToolsModeLazy", auto: "settings.mcpPluginToolsModeAuto" };
+const description = computed(() => `${labels[mode.value]}Description`);
+
+function updateMode(value: unknown) {
+ if (!props.disabled && (value === "flat" || value === "lazy" || value === "auto")) mode.value = value;
+}
+</script>
+
+<template>
+ <details class="rounded-md border p-3" data-mcp-plugin-tools-mode-setting>
+ <summary class="cursor-pointer rounded-sm text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <span id="mcp-plugin-tools-mode-label">{{ t("settings.mcpPluginToolsMode") }}</span>
+ <span class="ml-2 text-xs font-normal text-muted-foreground" data-mcp-plugin-tools-mode-summary>{{ t(labels[mode]) }}</span>
+ </summary>
+ <div class="mt-3 space-y-2">
+ <p class="text-xs text-muted-foreground">{{ t("settings.mcpPluginToolsModeDescription") }}</p>
+ <Select :model-value="mode" :disabled="disabled" @update:model-value="updateMode">
+ <SelectTrigger class="h-8 w-full sm:w-56" aria-labelledby="mcp-plugin-tools-mode-label" aria-describedby="mcp-plugin-tools-mode-description" data-mcp-plugin-tools-mode-trigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="flat">{{ t(labels.flat) }}</SelectItem>
+ <SelectItem value="lazy">{{ t(labels.lazy) }}</SelectItem>
+ <SelectItem value="auto">{{ t(labels.auto) }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <p id="mcp-plugin-tools-mode-description" class="text-xs text-muted-foreground">{{ t(description) }}</p>
+ </div>
+ </details>
+</template>
diff --git a/apps/desktop/src/components/settings/McpResourceScopePicker.vue b/apps/desktop/src/components/settings/McpResourceScopePicker.vue
deleted file mode 100644
index 02fc046316..0000000000
--- a/apps/desktop/src/components/settings/McpResourceScopePicker.vue
+++ /dev/null
@@ -1,444 +0,0 @@
-<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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-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; allowSalesforceDml?: 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"];
- "set:connection-salesforce-dml": [connectionId: string, allowed: boolean];
-}>();
-
-const { t } = useI18n();
-const search = ref("");
-const expandedGroupIds = ref(new Set<string>());
-const initializedExpansion = ref(false);
-const lastCustomScope = ref<{ allowedGroupIds: string[]; allowedConnectionIds: string[] } | null>(null);
-
-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;
-});
-
-// Exceptions survive visibility-scope changes. Keep an editor for every saved
-// exception, even when its resource is unselected, collapsed, or filtered out.
-const hiddenPolicyExceptions = computed(() => {
- const inlineEditors = new Set(scopeMode.value === "custom" ? visibleRows.value.filter((node) => (node.type === "group" ? selectedGroupIds.value.has(node.id) : explicitConnectionIds.value.has(node.id) || Boolean(selectedAncestor(node)))).map((node) => `${node.type}:${node.id}`) : []);
- const result: ResourceNode[] = [];
- const visit = (nodes: ResourceNode[]) => {
- for (const node of nodes) {
- const configured = node.type === "group" ? groupPolicyMode(node.id) !== "inherit" : connectionPolicyMode(node.id) !== "inherit" || (isSalesforceConnection(node) && props.connectionPolicies?.some((policy) => policy.connectionId === node.id && policy.allowSalesforceDml));
- if (configured && !inlineEditors.has(`${node.type}:${node.id}`)) result.push(node);
- if (node.type === "group") visit(node.children);
- }
- };
- visit(resourceTree.value);
- return result;
-});
-
-function exceptionInScope(node: ResourceNode): boolean {
- if (scopeMode.value === "all") return true;
- if (node.type === "connection") return effectiveConnectionIds.value.has(node.id);
- return selectedGroupIds.value.has(node.id) || descendants(node).connectionIds.some((id) => effectiveConnectionIds.value.has(id));
-}
-
-function copyCustomScope(groupIds: readonly string[], connectionIds: readonly string[] | null): { allowedGroupIds: string[]; allowedConnectionIds: string[] } {
- return { allowedGroupIds: [...groupIds], allowedConnectionIds: [...(connectionIds ?? [])] };
-}
-
-function setScopeMode(mode: ScopeMode) {
- if (props.disabled || props.busy || mode === scopeMode.value) return;
- if (mode === "all") {
- if ((props.allowedGroupIds.length > 0 || (props.allowedConnectionIds?.length ?? 0) > 0) && !window.confirm(t("settings.mcpResourceScopeAllConfirm"))) return;
- lastCustomScope.value = copyCustomScope(props.allowedGroupIds, props.allowedConnectionIds);
- emit("update:scope", { allowedGroupIds: [], allowedConnectionIds: null });
- return;
- }
- emit("update:scope", copyCustomScope(lastCustomScope.value?.allowedGroupIds ?? [], lastCustomScope.value?.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));
-}
-
-// Salesforce writes are the one permission that cannot be expressed as an execution
-// mode: SOQL has no write verb, so a DML toggle is the only gate an agent can be given.
-// It is per-connection because it is per-org, and it stays hidden for every other driver.
-function isSalesforceConnection(node: ResourceNode): boolean {
- return node.type === "connection" && node.connection.db_type === "salesforce";
-}
-
-function connectionAllowsSalesforceDml(connectionId: string): boolean {
- const policy = props.connectionPolicies?.find((item) => item.connectionId === connectionId);
- return policy?.allowSalesforceDml === true && policy.readOnly !== true;
-}
-</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" data-scope-mode="all" :class="scopeMode === 'all' ? 'bg-background shadow-sm' : 'text-muted-foreground'" :aria-checked="scopeMode === 'all'" :disabled="disabled || busy" @click="setScopeMode('all')">
- {{ t("settings.mcpScopeModeAll") }}
- </Button>
- <Button type="button" role="radio" variant="ghost" class="h-9" data-scope-mode="custom" :class="scopeMode === 'custom' ? 'bg-background shadow-sm' : 'text-muted-foreground'" :aria-checked="scopeMode === 'custom'" :disabled="disabled || busy" @click="setScopeMode('custom')">
- {{ t("settings.mcpResourceScopeModeCustom") }}
- </Button>
- </div>
-
- <section v-if="hiddenPolicyExceptions.length" class="space-y-2 border-t p-3" :aria-label="t('settings.mcpPolicyExceptionsTitle')">
- <p class="text-xs font-medium">{{ t("settings.mcpPolicyExceptionsTitle") }}</p>
- <p class="text-[11px] text-muted-foreground">{{ t("settings.mcpPolicyExceptionsDescription") }}</p>
- <div class="max-h-80 space-y-2 overflow-auto">
- <div v-for="node in hiddenPolicyExceptions" :key="`${node.type}:${node.id}`" class="flex flex-wrap items-center gap-2 rounded-md border p-2 text-xs">
- <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" />
- <span class="min-w-0 flex-1 break-words font-medium">{{ node.type === "group" ? node.pathNames.join(" / ") : node.connection.name }}</span>
- <Badge variant="secondary" class="rounded font-normal">{{ t(exceptionInScope(node) ? "settings.mcpPolicyExceptionInScope" : "settings.mcpPolicyExceptionOutsideScope") }}</Badge>
- <Select
- :model-value="node.type === 'group' ? groupPolicyMode(node.id) : connectionPolicyMode(node.id)"
- :disabled="disabled || busy"
- @update:model-value="(value) => (node.type === 'group' ? emit('set:group-policy', node.id, value as ExecutionMode | 'inherit') : emit('set:connection-policy', node.id, value as ExecutionMode | 'inherit'))"
- >
- <SelectTrigger size="sm" class="h-7 w-44 text-[11px]" :aria-label="node.type === 'group' ? node.pathNames.join(' / ') : node.connection.name"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="inherit">{{ t("settings.mcpPolicyExceptionInherit") }}</SelectItem>
- <SelectItem value="read_only">{{ t("settings.mcpConnectionPolicyReadOnly") }}</SelectItem>
- <SelectItem value="safe_write">{{ t("settings.mcpConnectionPolicySafeWrite") }}</SelectItem>
- <SelectItem value="high_risk_write">{{ t("settings.mcpConnectionPolicyHighRiskWrite") }}</SelectItem>
- </SelectContent>
- </Select>
- <label v-if="isSalesforceConnection(node)" class="flex h-7 items-center gap-1 rounded border px-1.5 text-[11px]" :title="t('settings.mcpConnectionPolicyAllowSalesforceDmlHint')">
- <input type="checkbox" class="size-3" :checked="connectionAllowsSalesforceDml(node.id)" :disabled="disabled || busy" :aria-label="t('settings.mcpConnectionPolicyAllowSalesforceDml')" @change="emit('set:connection-salesforce-dml', node.id, ($event.target as HTMLInputElement).checked)" />
- {{ t("settings.mcpConnectionPolicyAllowSalesforceDml") }}
- </label>
- </div>
- </div>
- </section>
-
- <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)" :model-value="groupPolicyMode(node.id)" :disabled="disabled || busy" @update:model-value="(value) => emit('set:group-policy', node.id, value as ExecutionMode | 'inherit')">
- <SelectTrigger size="sm" class="h-7 w-44 shrink-0 text-[11px]" @click.stop><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="inherit">{{ t("settings.mcpConnectionPolicyInherit") }}</SelectItem>
- <SelectItem value="read_only">{{ t("settings.mcpConnectionPolicyReadOnly") }}</SelectItem>
- <SelectItem value="safe_write">{{ t("settings.mcpConnectionPolicySafeWrite") }}</SelectItem>
- <SelectItem value="high_risk_write">{{ t("settings.mcpConnectionPolicyHighRiskWrite") }}</SelectItem>
- </SelectContent>
- </Select>
- <Select
- v-if="node.type === 'connection' && (explicitConnectionIds.has(node.id) || Boolean(selectedAncestor(node)))"
- :model-value="connectionPolicyMode(node.id)"
- :disabled="disabled || busy"
- @update:model-value="(value) => emit('set:connection-policy', node.id, value as ExecutionMode | 'inherit')"
- >
- <SelectTrigger size="sm" class="h-7 w-44 shrink-0 text-[11px]" @click.stop><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="inherit">{{ selectedAncestor(node) ? t("settings.mcpGroupPolicyInherit") : t("settings.mcpConnectionPolicyInherit") }}</SelectItem>
- <SelectItem value="read_only">{{ t("settings.mcpConnectionPolicyReadOnly") }}</SelectItem>
- <SelectItem value="safe_write">{{ t("settings.mcpConnectionPolicySafeWrite") }}</SelectItem>
- <SelectItem value="high_risk_write">{{ t("settings.mcpConnectionPolicyHighRiskWrite") }}</SelectItem>
- </SelectContent>
- </Select>
- <label
- v-if="isSalesforceConnection(node) && (explicitConnectionIds.has(node.id) || Boolean(selectedAncestor(node)))"
- class="flex h-7 shrink-0 cursor-pointer items-center gap-1 rounded border bg-background px-1.5 text-[11px]"
- :class="connectionAllowsSalesforceDml(node.id) ? 'border-primary/50 text-foreground' : 'text-muted-foreground'"
- :title="t('settings.mcpConnectionPolicyAllowSalesforceDmlHint')"
- >
- <input
- type="checkbox"
- class="size-3"
- :checked="connectionAllowsSalesforceDml(node.id)"
- :disabled="disabled || busy"
- :aria-label="t('settings.mcpConnectionPolicyAllowSalesforceDml')"
- @click.stop
- @change="emit('set:connection-salesforce-dml', node.id, ($event.target as HTMLInputElement).checked)"
- />
- {{ t("settings.mcpConnectionPolicyAllowSalesforceDml") }}
- </label>
- <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/components/settings/__tests__/McpAccessTree.locale.spec.ts b/apps/desktop/src/components/settings/__tests__/McpAccessTree.locale.spec.ts
new file mode 100644
index 0000000000..944eee9a6b
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpAccessTree.locale.spec.ts
@@ -0,0 +1,165 @@
+// @vitest-environment happy-dom
+
+import { createApp, h, nextTick, ref } from "vue";
+import { createI18n } from "vue-i18n";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import McpAccessTree from "../McpAccessTree.vue";
+import en from "@/i18n/locales/en";
+import zhCN from "@/i18n/locales/zh-CN";
+import type { ConnectionConfig } from "@/types/database";
+import type { McpAccessPolicy } from "@/types/mcpCatalog";
+
+const cleanup: Array<() => void> = [];
+afterEach(() => cleanup.splice(0).forEach((unmount) => unmount()));
+
+describe("McpAccessTree translated selections", () => {
+ it("renders native mixed checkboxes, reacts to descendant changes, and selects the whole group on click", async () => {
+ const i18n = createI18n({ legacy: false, locale: "zh-CN", messages: { en, "zh-CN": zhCN } as Record<string, Record<string, unknown>> });
+ const policy = ref({ readOnly: true, allowDangerousSql: false, allowedConnectionIds: ["c1"] as string[] | null, allowedGroupIds: [] as string[], connectionPolicies: [], groupPolicies: [] });
+ const groupChange = vi.fn((id: string, visible: boolean) => {
+ policy.value = { ...policy.value, allowedConnectionIds: [], allowedGroupIds: visible ? [id] : [] };
+ });
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp({
+ render: () =>
+ h(McpAccessTree, {
+ policy: policy.value,
+ connections: ["c1", "c2"].map((id) => ({ id, name: id, db_type: "mysql" }) as ConnectionConfig),
+ layout: {
+ groups: [
+ { id: "parent", name: "Parent", collapsed: true },
+ { id: "child", name: "Child", collapsed: true },
+ ],
+ order: [
+ {
+ type: "group",
+ id: "parent",
+ children: [
+ { type: "group", id: "child", children: [{ type: "connection", id: "c1" }] },
+ { type: "connection", id: "c2" },
+ ],
+ },
+ ],
+ },
+ "onSet:group-visible": groupChange,
+ }),
+ }).use(i18n);
+ app.mount(root);
+ cleanup.push(() => {
+ app.unmount();
+ root.remove();
+ });
+ await nextTick();
+ const checkbox = () => root.querySelector<HTMLInputElement>('[data-mcp-access-visible="group:parent"]')!;
+ const effective = () => root.querySelector('[data-mcp-access-effective="group:parent"]')!.textContent;
+ expect(checkbox().indeterminate).toBe(true);
+ expect(checkbox().getAttribute("aria-checked")).toBe("mixed");
+ expect(effective()).toContain("部分连接可见(1/2)");
+ policy.value = { ...policy.value, allowedConnectionIds: ["c1", "c2"] };
+ await nextTick();
+ expect(checkbox().indeterminate).toBe(true);
+ expect(effective()).toContain("当前连接均可见(2/2)");
+ i18n.global.locale.value = "en";
+ await nextTick();
+ expect(effective()).toContain("All current connections visible (2/2)");
+ expect(checkbox().title).toBe(en.settings.mcpAccessTreeGroupChildrenOnlyHint);
+ checkbox().click();
+ await nextTick();
+ expect(groupChange).toHaveBeenCalledExactlyOnceWith("parent", true);
+ expect(checkbox().checked).toBe(true);
+ expect(checkbox().indeterminate).toBe(false);
+ root.querySelector<HTMLButtonElement>('[data-mcp-access-group-name="parent"]')!.click();
+ await nextTick();
+ const child = root.querySelector<HTMLInputElement>('[data-mcp-access-visible="group:child"]')!;
+ expect(child.checked).toBe(true);
+ expect(child.indeterminate).toBe(false);
+ expect(child.disabled).toBe(true);
+ checkbox().click();
+ await nextTick();
+ expect(checkbox().checked).toBe(false);
+ expect(checkbox().indeterminate).toBe(false);
+ expect(effective()).toContain(en.settings.mcpAccessTreeHidden);
+ policy.value = { ...policy.value, allowedConnectionIds: null };
+ await nextTick();
+ expect(checkbox().checked).toBe(true);
+ expect(checkbox().indeterminate).toBe(false);
+ expect(checkbox().disabled).toBe(true);
+ });
+
+ it.each(["nacos", "plugin"])("updates %s sub-scope counts and selected labels without reopening the controls", async (provider) => {
+ const i18n = createI18n({ legacy: false, locale: "zh-CN", messages: { en, "zh-CN": zhCN } as Record<string, Record<string, unknown>> });
+ const access = ref<McpAccessPolicy>({
+ version: 2,
+ defaultAccess: "write",
+ rules: [
+ { target: { kind: "connection", id: "scoped" }, subScope: "selected" },
+ { target: { kind: "scope", connectionId: "scoped", scope: "namespace", value: "team" }, visible: true, access: "read" },
+ ],
+ });
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp({
+ render: () =>
+ h(McpAccessTree, {
+ policy: { readOnly: true, allowDangerousSql: false, allowedConnectionIds: null, allowedGroupIds: [], connectionPolicies: [], groupPolicies: [] },
+ layout: { groups: [], order: [{ type: "connection", id: "scoped" }] },
+ connections: [{ id: "scoped", name: "Scoped", db_type: provider === "nacos" ? "nacos" : "mysql", ...(provider === "plugin" ? { plugin_id: "demo" } : {}) } as ConnectionConfig],
+ pluginScopes: { demo: { kind: "namespace", title: "Namespace" } },
+ accessPolicy: access.value,
+ savePluginScope: vi.fn(async () => access.value),
+ }),
+ }).use(i18n);
+ app.mount(root);
+ cleanup.push(() => {
+ app.unmount();
+ root.remove();
+ });
+ await nextTick();
+ await nextTick();
+ const mode = root.querySelector('[data-mcp-plugin-scope-mode="scoped"]')!;
+ const level = root.querySelector('[data-mcp-plugin-scope-value="team"] [role="combobox"]')!;
+ expect(mode.textContent).toContain("指定(1)");
+ access.value = { ...access.value, rules: [...access.value.rules, { target: { kind: "scope", connectionId: "scoped", scope: "namespace", value: "ops" }, visible: true }] };
+ await nextTick();
+ await nextTick();
+ expect(mode.textContent).toContain("指定(2)");
+ i18n.global.locale.value = "en";
+ await nextTick();
+ await nextTick();
+ expect(mode.textContent).toContain("Selected (2)");
+ expect(level.textContent).toContain(en.settings.mcpExecutionModeReadOnly);
+ expect(level.textContent).not.toContain(zhCN.settings.mcpExecutionModeReadOnly);
+ });
+
+ it("updates selected permission and database scope labels when the language changes", async () => {
+ const i18n = createI18n({ legacy: false, locale: "zh-CN", messages: { en, "zh-CN": zhCN } as Record<string, Record<string, unknown>> });
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp({
+ render: () =>
+ h(McpAccessTree, {
+ policy: { readOnly: true, allowDangerousSql: false, allowedConnectionIds: null, allowedGroupIds: [], connectionPolicies: [], groupPolicies: [] },
+ layout: { groups: [], order: [{ type: "connection", id: "dev" }] },
+ connections: [{ id: "dev", name: "Development", db_type: "mysql" } as ConnectionConfig],
+ }),
+ }).use(i18n);
+ app.mount(root);
+ cleanup.push(() => {
+ app.unmount();
+ root.remove();
+ });
+ await nextTick();
+ await nextTick();
+ const permission = root.querySelector('[data-mcp-access-setting="connection:dev"]')!;
+ const scope = root.querySelector('[data-mcp-access-database-scope="dev"]')!;
+ expect(permission.textContent).toContain(zhCN.settings.mcpAccessTreeInherit);
+ expect(scope.textContent).toContain(zhCN.settings.mcpAccessTreeDatabaseScopeAll);
+ i18n.global.locale.value = "en";
+ await nextTick();
+ await nextTick();
+ expect(permission.textContent).toContain(en.settings.mcpAccessTreeInherit);
+ expect(scope.textContent).toContain(en.settings.mcpAccessTreeDatabaseScopeAll);
+ expect(permission.textContent).not.toContain(zhCN.settings.mcpAccessTreeInherit);
+ });
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpAccessTree.spec.ts b/apps/desktop/src/components/settings/__tests__/McpAccessTree.spec.ts
new file mode 100644
index 0000000000..5cb73fa958
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpAccessTree.spec.ts
@@ -0,0 +1,319 @@
+// @vitest-environment happy-dom
+
+import { nextTick } from "vue";
+import { describe, expect, it, vi } from "vitest";
+import { dispatch, findAll, findOne, hostText, mountComponent } from "@/components/grid/__tests__/vueHostHarness";
+import type { McpConnectionPolicy } from "@/lib/backend/tauri";
+import type { ConnectionConfig, SidebarLayout } from "@/types/database";
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({
+ t: (key: string, values?: Record<string, unknown>) => `${key}${values ? ` ${JSON.stringify(values)}` : ""}`,
+ }),
+}));
+
+vi.mock("@lucide/vue", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const icon = createPassthroughStub("Icon", "i");
+ return { ChevronDown: icon, ChevronRight: icon, Database: icon, Folder: icon, History: icon, Loader2: icon, Plus: icon, Search: icon, Server: icon, X: icon };
+});
+vi.mock("@/components/ui/button", async () => ({ Button: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Button", "button") }));
+vi.mock("@/components/ui/input", async () => ({ Input: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Input", "input") }));
+vi.mock("@/components/ui/select", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ return {
+ Select: createPassthroughStub("Select", "div"),
+ SelectContent: createPassthroughStub("SelectContent", "div"),
+ SelectItem: createPassthroughStub("SelectItem", "div"),
+ SelectTrigger: createPassthroughStub("SelectTrigger", "button"),
+ SelectValue: createPassthroughStub("SelectValue", "span"),
+ };
+});
+
+vi.mock("@/components/settings/McpDatabaseAccessDialog.vue", async () => ({ default: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("McpDatabaseAccessDialog", "div") }));
+
+import McpAccessTree from "@/components/settings/McpAccessTree.vue";
+
+function connection(id: string, dbType = "mysql"): ConnectionConfig {
+ return { id, name: `${id}-name`, db_type: dbType, host: "h", port: 1, username: "u", password: "" } as ConnectionConfig;
+}
+
+const layout: SidebarLayout = {
+ groups: [{ id: "prod", name: "Production", collapsed: false }] as SidebarLayout["groups"],
+ order: [
+ { type: "group", id: "prod", children: [{ type: "connection", id: "c1" }] },
+ { type: "connection", id: "sf" },
+ ],
+};
+
+function rule(patch: Partial<McpConnectionPolicy> & { connectionId: string }): McpConnectionPolicy {
+ return { readOnly: false, allowDangerousSql: false, executionModeConfigured: false, executionModePolicyVersion: 1, databaseScope: "all", allowedDatabases: [], databasePolicies: [], allowSalesforceDml: false, ...patch };
+}
+
+function mountTree(policyPatch: Record<string, unknown> = {}, extra: Record<string, unknown> = {}) {
+ const listeners = {
+ "onSet:scope-mode": vi.fn(),
+ "onSet:group-visible": vi.fn(),
+ "onSet:connection-visible": vi.fn(),
+ "onSet:group-level": vi.fn(),
+ "onSet:connection-level": vi.fn(),
+ "onSet:database-access": vi.fn(),
+ "onSet:database-scope": vi.fn(),
+ "onSet:database-allowed": vi.fn(),
+ "onSet:database-level": vi.fn(),
+ "onSet:salesforce-dml": vi.fn(),
+ };
+ const mounted = mountComponent(McpAccessTree, {
+ policy: { readOnly: true, allowDangerousSql: false, allowedConnectionIds: null, allowedGroupIds: [], connectionPolicies: [], groupPolicies: [], ...policyPatch },
+ layout,
+ connections: [connection("c1"), connection("sf", "salesforce")],
+ ...listeners,
+ ...extra,
+ });
+ return { mounted, listeners };
+}
+
+const row = (root: ReturnType<typeof mountComponent>["root"], key: string) => findOne(root, (node) => node.props["data-mcp-access-row"] === key);
+const control = (root: ReturnType<typeof mountComponent>["root"], attr: string, value: string) => findOne(root, (node) => node.props[attr] === value);
+
+/** Picks a value in the shared Select whose trigger carries `attr=value`. */
+function choose(root: ReturnType<typeof mountComponent>["root"], attr: string, value: string, picked: string) {
+ const select = findAll(root, (node) => node.props["data-stub"] === "Select").find((node) => findAll(node, (child) => child.props[attr] === value).length > 0);
+ if (!select) throw new Error(`no Select for ${attr}=${value}`);
+ (select.props["onUpdate:modelValue"] as (value: string) => void)(picked);
+}
+
+describe("McpAccessTree", () => {
+ it("opens groups by name and updates inherited permissions while keeping group and database overrides", async () => {
+ const policy = {
+ readOnly: true,
+ allowDangerousSql: false,
+ allowedConnectionIds: null,
+ allowedGroupIds: [],
+ groupPolicies: [{ groupId: "prod", readOnly: true, allowDangerousSql: false }],
+ connectionPolicies: [rule({ connectionId: "sf", databaseScope: "selected", allowedDatabases: ["billing"], databasePolicies: [{ databaseName: "billing", readOnly: true, allowDangerousSql: false }] })],
+ };
+ const { mounted, listeners } = mountTree(policy);
+ const groupName = () => control(mounted.root, "data-mcp-access-group-name", "prod");
+ expect(groupName().type).toBe("button");
+ expect(groupName().props["aria-expanded"]).toBe(false);
+ dispatch(groupName(), "click");
+ dispatch(control(mounted.root, "data-mcp-access-toggle", "connection:sf"), "click");
+ await nextTick();
+ await mounted.setProps({ policy: { ...policy, readOnly: false } });
+ const effective = (key: string) => hostText(control(mounted.root, "data-mcp-access-effective", key));
+ expect(effective("connection:sf")).toContain("settings.mcpExecutionModeSafeWrite");
+ expect(effective("connection:sf")).toContain("settings.mcpAccessTreeSourceGlobal");
+ expect(effective("connection:c1")).toContain("settings.mcpExecutionModeReadOnly");
+ expect(effective("connection:c1")).toContain("settings.mcpAccessTreeSourceGroup");
+ expect(effective("database:sf:billing")).toContain("settings.mcpExecutionModeReadOnly");
+ expect(effective("database:sf:billing")).toContain("settings.mcpAccessTreeSourceDatabase");
+ expect(groupName().props["aria-expanded"]).toBe(true);
+ dispatch(groupName(), "click");
+ await nextTick();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-access-row"] === "connection:c1")).toHaveLength(0);
+ dispatch(control(mounted.root, "data-mcp-access-toggle", "group:prod"), "click");
+ await nextTick();
+ expect(row(mounted.root, "connection:c1")).toBeDefined();
+ expect(groupName().props["aria-expanded"]).toBe(true);
+ expect(listeners["onSet:group-visible"]).not.toHaveBeenCalled();
+ expect(listeners["onSet:group-level"]).not.toHaveBeenCalled();
+ mounted.unmount();
+ });
+
+ it.each(["selected", "none", "all"] as const)("keeps immediately saved %s scopes visible in the exceptions filter under collapsed groups", async (mode) => {
+ const { mounted } = mountTree(
+ {},
+ {
+ connections: [connection("c1", "nacos"), { ...connection("sf"), plugin_id: "test-plugin" }],
+ pluginScopes: { "test-plugin": { kind: "workspace", title: "Workspace" } },
+ accessPolicy: {
+ version: 2,
+ defaultAccess: "read",
+ confirm: "never",
+ visibility: "all",
+ rules: [
+ { target: { kind: "connection", id: "c1" }, subScope: mode, subScopeKind: "namespace" },
+ ...(mode === "all" ? [{ target: { kind: "scope", connectionId: "c1", scope: "namespace", value: "public" }, visible: true, access: "read" }] : []),
+ { target: { kind: "connection", id: "sf" }, subScope: "none", subScopeKind: "workspace" },
+ ],
+ },
+ savePluginScope: vi.fn(),
+ },
+ );
+ const toggle = findOne(mounted.root, (node) => node.props["data-mcp-access-exceptions-only"] !== undefined);
+ dispatch(toggle, "update:modelValue", true);
+ await nextTick();
+ expect(hostText(mounted.root)).toContain('"connections":2');
+ expect(row(mounted.root, "group:prod")).toBeDefined();
+ expect(row(mounted.root, "connection:c1")).toBeDefined();
+ expect(row(mounted.root, "connection:sf")).toBeDefined();
+ mounted.unmount();
+ });
+
+ it("shows an inaccessible state instead of full access for a hidden connection", () => {
+ const { mounted } = mountTree({ readOnly: false, allowDangerousSql: true, allowedConnectionIds: [] });
+ const effective = hostText(control(mounted.root, "data-mcp-access-effective", "connection:sf"));
+ expect(effective).toContain("settings.mcpAccessTreeHidden");
+ expect(effective).not.toContain("settings.mcpExecutionModeHighRiskWrite");
+ mounted.unmount();
+ });
+
+ it("shows a mixed group and a descendant count instead of hidden when only children are granted", async () => {
+ const { mounted, listeners } = mountTree(
+ { allowedConnectionIds: ["c1"] },
+ {
+ layout: {
+ groups: layout.groups,
+ order: [
+ {
+ type: "group",
+ id: "prod",
+ children: [
+ { type: "connection", id: "c1" },
+ { type: "connection", id: "sf" },
+ ],
+ },
+ ],
+ },
+ },
+ );
+ const visibility = control(mounted.root, "data-mcp-access-visible", "group:prod");
+ expect(visibility.props).toMatchObject({ checked: false, indeterminate: true, "aria-checked": "mixed", disabled: false });
+ expect(hostText(control(mounted.root, "data-mcp-access-effective", "group:prod"))).toBe('settings.mcpAccessTreeGroupPartiallyVisible {"visible":1,"total":2}');
+ expect(row(mounted.root, "group:prod").props.class).not.toContain("text-muted-foreground");
+ const permission = findAll(mounted.root, (node) => node.props["data-stub"] === "Select").find((node) => findAll(node, (child) => child.props["data-mcp-access-setting"] === "group:prod").length)!;
+ expect(permission.props.disabled).toBe(false);
+ choose(mounted.root, "data-mcp-access-setting", "group:prod", "read_only");
+ expect(listeners["onSet:group-level"]).toHaveBeenCalledExactlyOnceWith("prod", "read_only");
+ expect(listeners["onSet:group-visible"]).not.toHaveBeenCalled();
+ dispatch(visibility, "change", { target: { checked: true } });
+ expect(listeners["onSet:group-visible"]).toHaveBeenCalledExactlyOnceWith("prod", true);
+ expect(listeners["onSet:connection-visible"]).not.toHaveBeenCalled();
+ mounted.unmount();
+ });
+
+ it("keeps a group mixed when all current children are individually selected", () => {
+ const { mounted } = mountTree({ allowedConnectionIds: ["c1"] });
+ expect(control(mounted.root, "data-mcp-access-visible", "group:prod").props).toMatchObject({ checked: false, indeterminate: true, "aria-checked": "mixed" });
+ expect(hostText(control(mounted.root, "data-mcp-access-effective", "group:prod"))).toBe('settings.mcpAccessTreeGroupCurrentVisible {"visible":1,"total":1}');
+ mounted.unmount();
+ });
+
+ it("updates saved scope exceptions reactively and counts an overlapping connection rule once", async () => {
+ const { mounted } = mountTree(
+ { connectionPolicies: [rule({ connectionId: "c1", executionModeConfigured: true })] },
+ {
+ connections: [connection("c1", "nacos"), { ...connection("sf"), plugin_id: "test-plugin" }, connection("sql")],
+ pluginScopes: { "test-plugin": { kind: "workspace", title: "Workspace" } },
+ accessPolicy: { version: 2, defaultAccess: "read", rules: [] },
+ },
+ );
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-access-exceptions-only"] !== undefined),
+ "update:modelValue",
+ true,
+ );
+ await nextTick();
+ expect(hostText(mounted.root)).toContain('"connections":1');
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-access-row"] === "connection:sf")).toHaveLength(0);
+ await mounted.setProps({
+ accessPolicy: {
+ version: 2,
+ defaultAccess: "read",
+ rules: [
+ { target: { kind: "connection", id: "c1" }, subScope: "none", subScopeKind: "namespace" },
+ { target: { kind: "connection", id: "sf" }, subScope: "selected", subScopeKind: "workspace" },
+ // SQL changes use the staged v1 policy, not an older v2 snapshot.
+ { target: { kind: "connection", id: "sql" }, subScope: "none" },
+ ],
+ },
+ });
+ expect(hostText(mounted.root)).toContain('"connections":2');
+ expect(row(mounted.root, "connection:c1")).toBeDefined();
+ expect(row(mounted.root, "connection:sf")).toBeDefined();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-access-row"] === "connection:sql")).toHaveLength(0);
+ await mounted.setProps({ accessPolicy: { version: 2, defaultAccess: "read", rules: [] } });
+ expect(hostText(mounted.root)).toContain('"connections":1');
+ expect(row(mounted.root, "connection:c1")).toBeDefined();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-access-row"] === "connection:sf")).toHaveLength(0);
+ mounted.unmount();
+ });
+
+ it("shows the effective level and its source per row", async () => {
+ const { mounted } = mountTree({ groupPolicies: [{ groupId: "prod", readOnly: false, allowDangerousSql: false }] });
+ expect(hostText(row(mounted.root, "group:prod"))).toContain("settings.mcpExecutionModeSafeWrite");
+ dispatch(control(mounted.root, "data-mcp-access-toggle", "group:prod"), "click");
+ await nextTick();
+ const c1 = hostText(row(mounted.root, "connection:c1"));
+ expect(c1).toContain("settings.mcpExecutionModeSafeWrite");
+ expect(c1).toContain('settings.mcpAccessTreeSourceGroup {"group":"Production"}');
+ expect(hostText(row(mounted.root, "connection:sf"))).toContain("settings.mcpAccessTreeSourceGlobal");
+ });
+
+ it("delegates level edits to the settings owner without a duplicate confirmation", async () => {
+ const { mounted, listeners } = mountTree();
+ choose(mounted.root, "data-mcp-access-setting", "connection:sf", "safe_write");
+ expect(listeners["onSet:connection-level"]).toHaveBeenCalledWith("sf", "safe_write");
+ const confirm = vi.fn().mockReturnValue(false);
+ vi.stubGlobal("confirm", confirm);
+ choose(mounted.root, "data-mcp-access-setting", "group:prod", "high_risk_write");
+ expect(confirm).not.toHaveBeenCalled();
+ expect(listeners["onSet:group-level"]).toHaveBeenCalledExactlyOnceWith("prod", "high_risk_write");
+ vi.unstubAllGlobals();
+ });
+
+ it("locks visibility under all-connections and emits it under a custom scope", () => {
+ const all = mountTree();
+ expect(control(all.mounted.root, "data-mcp-access-visible", "connection:sf").props.disabled).toBe(true);
+ const custom = mountTree({ allowedConnectionIds: [], allowedGroupIds: [] });
+ expect(hostText(row(custom.mounted.root, "connection:sf"))).toContain("settings.mcpAccessTreeHidden");
+ dispatch(control(custom.mounted.root, "data-mcp-access-visible", "connection:sf"), "change", { target: { checked: true } });
+ expect(custom.listeners["onSet:connection-visible"]).toHaveBeenCalledWith("sf", true);
+ dispatch(control(custom.mounted.root, "data-mcp-access-scope-mode", "all"), "click");
+ expect(custom.listeners["onSet:scope-mode"]).toHaveBeenCalledWith("all");
+ });
+
+ it("shows a database summary and read-only child rows, opening the transfer editor with the saved baseline", async () => {
+ const savedPolicy = { readOnly: true, allowDangerousSql: false, allowedConnectionIds: null, allowedGroupIds: [], connectionPolicies: [], groupPolicies: [] };
+ const saveDatabaseAccess = vi.fn();
+ const { mounted, listeners } = mountTree({ connectionPolicies: [rule({ connectionId: "sf", databaseScope: "selected", allowedDatabases: ["billing"], databasePolicies: [{ databaseName: "billing", readOnly: false, allowDangerousSql: false }] })] }, { savedPolicy, saveDatabaseAccess });
+ dispatch(control(mounted.root, "data-mcp-access-toggle", "connection:sf"), "click");
+ await nextTick();
+ expect(hostText(row(mounted.root, "database:sf:billing"))).toContain("settings.mcpAccessTreeSourceDatabase");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-access-setting"] === "database:sf:billing")).toHaveLength(0);
+ dispatch(control(mounted.root, "data-mcp-access-pick-databases", "sf"), "click", { currentTarget: null });
+ await nextTick();
+ const dialog = findOne(mounted.root, (node) => node.props["data-stub"] === "McpDatabaseAccessDialog");
+ expect(dialog.props.value.allowedDatabases).toEqual(["billing"]);
+ expect(dialog.props["saved-value"].databaseScope).toBe("all");
+ expect(dialog.props.save).toBe(saveDatabaseAccess);
+ dialog.props.onChange({ databaseScope: "none", allowedDatabases: [], databasePolicies: [] });
+ expect(listeners["onSet:database-access"]).toHaveBeenCalledWith("sf", { databaseScope: "none", allowedDatabases: [], databasePolicies: [] });
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-access-exceptions-only"] !== undefined),
+ "update:modelValue",
+ true,
+ );
+ await nextTick();
+ expect(findOne(mounted.root, (node) => node.props["data-stub"] === "McpDatabaseAccessDialog")).toBeDefined();
+ mounted.unmount();
+ });
+
+ it("offers the Salesforce write switch only on Salesforce connections", () => {
+ const { mounted, listeners } = mountTree({ readOnly: false });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-access-salesforce"] === "c1")).toEqual([]);
+ dispatch(control(mounted.root, "data-mcp-access-salesforce", "sf"), "change", { target: { checked: true } });
+ expect(listeners["onSet:salesforce-dml"]).toHaveBeenCalledWith("sf", true);
+ });
+
+ it("offers a direct MCP history link for connection resources", () => {
+ const listener = vi.fn();
+ window.addEventListener("dbx:open-mcp-call-history", listener);
+ const { mounted } = mountTree();
+ dispatch(control(mounted.root, "data-mcp-access-history", "connection:sf"), "click");
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect((listener.mock.calls[0][0] as CustomEvent).detail).toEqual({ connectionId: "sf", database: undefined });
+ window.removeEventListener("dbx:open-mcp-call-history", listener);
+ });
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpCallSafetyPanel.spec.ts b/apps/desktop/src/components/settings/__tests__/McpCallSafetyPanel.spec.ts
new file mode 100644
index 0000000000..50b80f575c
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpCallSafetyPanel.spec.ts
@@ -0,0 +1,69 @@
+// @vitest-environment happy-dom
+import { createApp, h, nextTick, reactive } from "vue";
+import { afterEach, expect, it, vi } from "vitest";
+import McpCallSafetyPanel from "../McpCallSafetyPanel.vue";
+
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+const cleanup: Array<() => void> = [];
+afterEach(() => cleanup.splice(0).forEach((fn) => fn()));
+function mount(mode: "off" | "full" | "high_risk", disabled = false) {
+ const props = reactive({ mode, disabled });
+ const change = vi.fn((enabled: boolean) => {
+ props.mode = enabled ? "high_risk" : "off";
+ });
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp({ render: () => h(McpCallSafetyPanel, { ...props, "onSet:confirmation": change }) });
+ app.mount(root);
+ cleanup.push(() => {
+ app.unmount();
+ root.remove();
+ });
+ return { root, change, props };
+}
+
+it("shows a separate collapsed policy and allows enabling and disabling confirmation", async () => {
+ const { root, change } = mount("off");
+ expect(root.querySelector("details")!.open).toBe(false);
+ root.querySelector("details")!.open = true;
+ const input = root.querySelector<HTMLInputElement>("input")!;
+ expect(input.checked).toBe(false);
+ expect(document.getElementById(input.getAttribute("aria-describedby")!)!.textContent).toContain("mcpCallSafetyHint");
+ input.click();
+ await nextTick();
+ expect(change).toHaveBeenLastCalledWith(true);
+ expect(root.textContent).toContain("mcpCallSafetyEnabled");
+ input.click();
+ await nextTick();
+ expect(change).toHaveBeenLastCalledWith(false);
+});
+
+it.each([true, false])("explains legacy behavior and changes it only on an explicit choice: %s", async (enable) => {
+ const { root, change } = mount("full");
+ expect(root.querySelector("details")!.open).toBe(true);
+ expect(root.querySelector("input")).toBeNull();
+ expect(root.textContent).toContain("mcpCallSafetyLegacyHint");
+ expect(root.textContent).not.toContain("settings.mcpCallSafetyHint");
+ expect(root.textContent).not.toContain("settings.mcpCallSafetyDesktopHint");
+ expect(change).not.toHaveBeenCalled();
+ root.querySelector<HTMLButtonElement>(enable ? "[data-mcp-safety-migrate]" : "[data-mcp-safety-disable-legacy]")!.click();
+ await nextTick();
+ expect(change).toHaveBeenCalledExactlyOnceWith(enable);
+ expect(root.querySelector<HTMLInputElement>("input")!.checked).toBe(enable);
+ expect(root.querySelector("[data-mcp-safety-legacy]")).toBeNull();
+ expect(root.textContent).toContain("settings.mcpCallSafetyHint");
+ expect(root.textContent).toContain("settings.mcpCallSafetyDesktopHint");
+ expect(root.querySelector("details")!.open).toBe(true);
+ expect(document.activeElement).toBe(root.querySelector("input"));
+});
+
+it.each(["off", "full", "high_risk"] as const)("locks safety controls while saving or loading: %s", async (mode) => {
+ const { root, change } = mount(mode, true);
+ for (const control of root.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button")) {
+ expect(control.disabled).toBe(true);
+ control.click();
+ control.dispatchEvent(new Event("change", { bubbles: true }));
+ }
+ await nextTick();
+ expect(change).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpCapabilitiesPanel.spec.ts b/apps/desktop/src/components/settings/__tests__/McpCapabilitiesPanel.spec.ts
new file mode 100644
index 0000000000..61bbba3f01
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpCapabilitiesPanel.spec.ts
@@ -0,0 +1,547 @@
+// @vitest-environment happy-dom
+
+import { createApp, nextTick } from "vue";
+import { describe, expect, it, vi } from "vitest";
+import { dispatch, findAll, findOne, hostText, mountComponent } from "@/components/grid/__tests__/vueHostHarness";
+import type { McpToolCatalog } from "@/types/mcpCatalog";
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ const known: Record<string, string> = { "settings.mcpToolset.sqlSchema.title": "对象结构", "settings.mcpToolset.sqlSchema.description": "浏览表、字段和存储过程源码。" };
+ return `${known[key] ?? key}${values ? ` ${JSON.stringify(values)}` : ""}`;
+ },
+ }),
+}));
+
+vi.mock("@lucide/vue", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const icon = createPassthroughStub("Icon", "i");
+ return { AlertTriangle: icon, ChevronDown: icon, ChevronRight: icon, Loader2: icon, Minus: icon, Search: icon };
+});
+
+vi.mock("@/components/ui/badge", async () => ({ Badge: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Badge", "span") }));
+vi.mock("@/components/ui/button", async () => ({ Button: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Button", "button") }));
+vi.mock("@/components/ui/input", async () => ({ Input: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Input", "input") }));
+vi.mock("@/components/ui/switch", async () => ({ Switch: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Switch", "button") }));
+vi.mock("@/components/ui/dialog", async () => {
+ const { defineComponent, h } = await import("vue");
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ return {
+ // Render the dialog body only while open, like the real portal.
+ Dialog: defineComponent({
+ name: "Dialog",
+ props: { open: Boolean },
+ emits: ["update:open"],
+ setup(props, { slots, emit }) {
+ return () => (props.open ? h("div", { "data-stub": "Dialog" }, [...(slots.default?.() ?? []), h("button", { "data-dialog-dismiss": "", onClick: () => emit("update:open", false) })]) : null);
+ },
+ }),
+ DialogContent: createPassthroughStub("DialogContent", "div"),
+ DialogDescription: createPassthroughStub("DialogDescription", "p"),
+ DialogHeader: createPassthroughStub("DialogHeader", "div"),
+ DialogTitle: createPassthroughStub("DialogTitle", "h2"),
+ };
+});
+
+import McpCapabilitiesPanel from "@/components/settings/McpCapabilitiesPanel.vue";
+
+const catalog: McpToolCatalog = {
+ toolsets: [
+ {
+ id: "sql.schema",
+ provider: "builtin:sql",
+ resourceKinds: ["database"],
+ scopeKind: "database",
+ scopeKinds: ["database"],
+ tools: [
+ {
+ name: "dbx_list_tables",
+ access: "read",
+ accessMode: "static",
+ coverageKind: "capability",
+ databaseTypes: ["mysql", "sqlite"],
+ description: "List tables and views for a database connection",
+ parameters: [
+ { name: "connection_id", valueType: "string", required: true, description: "Unique ID of the DBX connection" },
+ { name: "limit", valueType: "integer", required: false, default: 100, description: "Maximum rows" },
+ ],
+ },
+ { name: "dbx_get_routine_source", access: "read", accessMode: "static", coverageKind: "capability", databaseTypes: ["mysql"], description: "", parameters: [] },
+ ],
+ },
+ {
+ id: "salesforce",
+ provider: "builtin:salesforce",
+ resourceKinds: ["org"],
+ scopeKind: "org",
+ scopeKinds: ["org"],
+ tools: [{ name: "dbx_salesforce_current_user", access: "read", accessMode: "static", coverageKind: "types", databaseTypes: ["salesforce"], description: "", parameters: [] }],
+ },
+ {
+ id: "admin.connections",
+ provider: "builtin:admin",
+ resourceKinds: [],
+ scopeKinds: [],
+ tools: [{ name: "dbx_add_connection", access: "write", accessMode: "static", coverageKind: "none", databaseTypes: [], description: "", parameters: [] }],
+ },
+ ],
+};
+
+const connections = [
+ { id: "c1", name: "local-mysql", dbType: "mysql" },
+ { id: "c2", name: "notes", dbType: "sqlite" },
+ { id: "c3", name: "dev-nacos", dbType: "nacos" },
+];
+
+function mountPanel(props: Record<string, unknown> = {}) {
+ const setToolset = vi.fn();
+ const setTool = vi.fn();
+ const mounted = mountComponent(McpCapabilitiesPanel, {
+ catalog,
+ allowedToolNames: null,
+ connections,
+ "onSet:toolset": setToolset,
+ "onSet:tool": setTool,
+ ...props,
+ });
+ return { mounted, setToolset, setTool };
+}
+
+function card(root: ReturnType<typeof mountComponent>["root"], id: string) {
+ return findOne(root, (node) => node.props["data-mcp-toolset"] === id);
+}
+
+describe("McpCapabilitiesPanel", () => {
+ it("applies in place, locks edits while saving, and retains the expanded tool", async () => {
+ let complete!: () => void;
+ const saving = new Promise<void>((resolve) => {
+ complete = resolve;
+ });
+ const saveToolset = vi.fn(async () => {
+ await saving;
+ await mounted.setProps({ savedToolNames: ["dbx_list_tables"] });
+ });
+ const { mounted } = mountPanel({ allowedToolNames: ["dbx_list_tables"], savedToolNames: null, saveToolset });
+ mounted.exposed.value.openDetail("sql.schema");
+ await nextTick();
+ const detail = () => findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined);
+ const apply = () => findOne(detail(), (node) => node.props["data-mcp-toolset-apply"] !== undefined);
+ expect(hostText(detail())).toContain('settings.mcpToolsetPending {"count":1}');
+ dispatch(
+ findOne(detail(), (node) => node.props["data-mcp-tool-toggle"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ const request = apply().props.onClick();
+ await nextTick();
+ expect(saveToolset).toHaveBeenCalledWith("sql.schema");
+ expect(apply().props.disabled).toBe(true);
+ expect(findAll(detail(), (node) => node.props["data-stub"] === "Switch").every((node) => node.props.disabled)).toBe(true);
+ const escape = new Event("keydown", { cancelable: true });
+ detail().props.onEscapeKeyDown(escape);
+ expect(escape.defaultPrevented).toBe(true);
+ expect(detail().props["show-close-button"]).toBe(false);
+ await apply().props.onClick();
+ expect(saveToolset).toHaveBeenCalledOnce();
+ dispatch(
+ findOne(detail(), (node) => node.props["data-mcp-toolset-close"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ expect(detail()).toBeDefined();
+ complete();
+ await request;
+ await nextTick();
+ expect(hostText(detail())).toContain("settings.mcpToolsetApplied");
+ expect(findAll(detail(), (node) => node.props["data-mcp-tool-detail"] !== undefined)).toHaveLength(1);
+ expect(apply().props.disabled).toBe(true);
+ mounted.unmount();
+ });
+
+ it("shows a failed save inside the dialog and retries without losing the switches", async () => {
+ const saveToolset = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("disk full"))
+ .mockImplementationOnce(async () => {
+ await mounted.setProps({ savedToolNames: ["dbx_list_tables"] });
+ });
+ const { mounted } = mountPanel({ allowedToolNames: ["dbx_list_tables"], savedToolNames: null, saveToolset });
+ mounted.exposed.value.openDetail("sql.schema");
+ await nextTick();
+ const apply = () => findOne(mounted.root, (node) => node.props["data-mcp-toolset-apply"] !== undefined);
+ await apply().props.onClick();
+ await nextTick();
+ expect(hostText(findOne(mounted.root, (node) => node.props["data-mcp-toolset-save-error"] !== undefined))).toContain("disk full");
+ expect(apply().props.disabled).toBe(false);
+ const switches = findAll(
+ findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined),
+ (node) => node.props["data-stub"] === "Switch",
+ );
+ expect(switches.map((node) => node.props["model-value"] ?? node.props.modelValue)).toEqual([true, false]);
+ await apply().props.onClick();
+ await nextTick();
+ expect(saveToolset).toHaveBeenCalledTimes(2);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-toolset-save-error"] !== undefined)).toEqual([]);
+ expect(hostText(mounted.root)).toContain("settings.mcpToolsetApplied");
+ mounted.unmount();
+ });
+
+ it.each(["footer", "dismiss"])("keeps changed switches as drafts after %s closing and reopening, without saving", async (method) => {
+ const saveToolset = vi.fn();
+ const { mounted, setTool } = mountPanel({ savedToolNames: null, saveToolset });
+ mounted.exposed.value.openDetail("sql.schema");
+ await nextTick();
+ const detail = () => findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined);
+ const toggle = findAll(detail(), (node) => node.props["data-stub"] === "Switch")[1];
+ toggle.props["onUpdate:modelValue"](false);
+ expect(setTool).toHaveBeenCalledWith("dbx_get_routine_source", false);
+ // The parent owns the shared draft and feeds the edited list back to the dialog.
+ await mounted.setProps({ allowedToolNames: ["dbx_list_tables"] });
+ expect(hostText(detail())).toContain("settings.mcpToolsetCloseKeepsDraft");
+ if (method === "footer")
+ dispatch(
+ findOne(detail(), (node) => node.props["data-mcp-toolset-close"] !== undefined),
+ "click",
+ );
+ else
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-dialog-dismiss"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined)).toEqual([]);
+ expect(saveToolset).not.toHaveBeenCalled();
+ mounted.exposed.value.openDetail("sql.schema");
+ await nextTick();
+ expect(hostText(detail())).toContain('settings.mcpToolsetPending {"count":1}');
+ const switches = findAll(detail(), (node) => node.props["data-stub"] === "Switch");
+ expect(switches.map((node) => node.props["model-value"] ?? node.props.modelValue)).toEqual([true, false]);
+ await mounted.setProps({ allowedToolNames: null });
+ expect(findOne(detail(), (node) => node.props["data-mcp-toolset-apply"] !== undefined).props.disabled).toBe(true);
+ expect(hostText(detail())).not.toContain("settings.mcpToolsetPending");
+ mounted.unmount();
+ });
+
+ it("renders compact coverage without resource ids or per-tool type summaries", () => {
+ const { mounted } = mountPanel();
+ const schema = hostText(card(mounted.root, "sql.schema"));
+ expect(schema).toContain("对象结构");
+ expect(schema).toContain('settings.mcpBrowser.coverageConnections {"count":2}');
+ // SQLite is reached by list_tables but not by routine source.
+ expect(schema).toContain('settings.mcpBrowser.coveragePartialConnections {"count":1}');
+ expect(schema).not.toContain("settings.mcpCoverageToolTypes");
+ expect(findAll(card(mounted.root, "sql.schema"), (node) => node.props["data-mcp-scope-kinds"] !== undefined)).toEqual([]);
+
+ expect(hostText(card(mounted.root, "salesforce"))).toContain("settings.mcpBrowser.noMatchingConnections");
+ expect(hostText(card(mounted.root, "admin.connections"))).toContain("settings.mcpCoverageNotBound");
+ });
+
+ it("leaves page search and headings to the browser", () => {
+ const { mounted } = mountPanel();
+ expect(findAll(mounted.root, (node) => node.type === "input" || node.type === "header")).toEqual([]);
+ });
+
+ it("scopes the list to requested toolsets and applies the enabled filter", () => {
+ const { mounted } = mountPanel({ visibleToolsetIds: ["sql.schema", "salesforce"], onlyEnabled: true, allowedToolNames: ["dbx_list_tables"] });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-toolset"] !== undefined).map((node) => node.props["data-mcp-toolset"])).toEqual(["sql.schema"]);
+ expect(hostText(card(mounted.root, "sql.schema"))).toContain('settings.mcpBrowser.enabledToolCount {"enabled":1,"total":2}');
+ expect(hostText(card(mounted.root, "sql.schema"))).toContain("settings.mcpBrowser.partialEnabled");
+ });
+
+ it("keeps toolsets configurable when there are no matching connections", () => {
+ const { mounted, setToolset } = mountPanel({ connections: [], allowedToolNames: [] });
+ const row = card(mounted.root, "salesforce");
+ expect(row.props.class).not.toContain("opacity");
+ const toggle = findOne(row, (node) => node.props["data-stub"] === "Switch");
+ expect(toggle.props.disabled).toBe(false);
+ (toggle.props["onUpdate:modelValue"] as (value: boolean) => void)(true);
+ expect(setToolset).toHaveBeenCalledWith(catalog.toolsets[1], true);
+ });
+
+ it("emits toolset switches from the allowlist state", () => {
+ const { mounted, setToolset } = mountPanel({ allowedToolNames: ["dbx_list_tables"] });
+ const toggle = findOne(card(mounted.root, "sql.schema"), (node) => node.props["data-stub"] === "Switch");
+ expect(toggle.props["model-value"] ?? toggle.props.modelValue).toBe(true);
+ const handler = toggle.props["onUpdate:modelValue"] as (value: boolean) => void;
+ handler(false);
+ expect(setToolset).toHaveBeenCalledWith(catalog.toolsets[0], false);
+
+ const salesforceToggle = findOne(card(mounted.root, "salesforce"), (node) => node.props["data-stub"] === "Switch");
+ expect(salesforceToggle.props["model-value"] ?? salesforceToggle.props.modelValue).toBe(false);
+ });
+
+ it("opens the coverage detail with only supported types, grouped by category", async () => {
+ const { mounted } = mountPanel();
+ dispatch(
+ findOne(card(mounted.root, "sql.schema"), (node) => node.props["data-mcp-coverage-link"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-coverage-detail"] !== undefined);
+ const text = hostText(detail);
+ expect(text).toContain("connection.databaseCategorySql");
+ expect(text).toContain("connection.databaseCategoryLightweight");
+ expect(text).toContain("MySQL");
+ expect(text).toContain("SQLite");
+ // No unsupported type is listed (catalog-wide types such as Salesforce stay out).
+ expect(text).not.toContain("Salesforce");
+ // SQLite is reached by list_tables only: it carries the partial marker, and a
+ // tool supporting none of a row is not spelled out as "0 of N".
+ expect(text).toContain("SQLite *");
+ expect(text).not.toContain("settings.mcpCoveragePartialTool");
+ });
+
+ it("recomputes partial coverage counts for the types matching the search", async () => {
+ const toolset = catalog.toolsets[0];
+ const { mounted } = mountPanel({
+ catalog: {
+ toolsets: [
+ {
+ ...toolset,
+ tools: [
+ { ...toolset.tools[0], databaseTypes: ["mysql", "postgres", "tidb"] },
+ { ...toolset.tools[1], databaseTypes: ["mysql", "tidb"] },
+ ],
+ },
+ ],
+ },
+ });
+ mounted.exposed.value.openDetail("sql.schema", "coverage");
+ await nextTick();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-coverage-detail"] !== undefined);
+ const input = findOne(detail, (node) => node.props["data-stub"] === "Input");
+ input.props["onUpdate:modelValue"]("sql");
+ await nextTick();
+ const text = hostText(detail);
+ expect(text).toContain("MySQL");
+ expect(text).toContain("PostgreSQL");
+ expect(text).not.toContain("TiDB");
+ expect(text).toContain('settings.mcpCoveragePartialTool {"tool":"settings.mcpToolGetRoutineSource","count":1,"total":2}');
+ mounted.unmount();
+ });
+
+ it("lists every tool with its own switch and an expandable detail", async () => {
+ const { mounted, setTool } = mountPanel({ allowedToolNames: ["dbx_list_tables"] });
+ const opener = findAll(card(mounted.root, "sql.schema"), (node) => node.type === "button")[0];
+ dispatch(opener, "click");
+ await nextTick();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined);
+ // Unsupported connections collapse into a count until the tool is expanded.
+ expect(hostText(detail)).toContain('settings.mcpToolSkippedConnections {"count":1}');
+ expect(findAll(detail, (node) => node.props["data-mcp-tool-detail"] !== undefined)).toEqual([]);
+
+ const switches = findAll(detail, (node) => node.props["data-stub"] === "Switch");
+ expect(switches.map((node) => node.props["model-value"] ?? node.props.modelValue)).toEqual([true, false]);
+ (switches[1].props["onUpdate:modelValue"] as (value: boolean) => void)(true);
+ expect(setTool).toHaveBeenCalledWith("dbx_get_routine_source", true);
+
+ const listTables = findOne(detail, (node) => node.props["data-mcp-tool"] === "dbx_list_tables");
+ dispatch(
+ findOne(listTables, (node) => node.props["data-mcp-tool-toggle"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ const expanded = hostText(findOne(mounted.root, (node) => node.props["data-mcp-tool-detail"] !== undefined));
+ expect(expanded).toContain("List tables and views for a database connection");
+ expect(expanded).toContain("connection_id");
+ expect(expanded).toContain("settings.mcpToolDetailParameterRequiredYes");
+ expect(expanded).toContain('settings.mcpToolDetailParameterDefault {"value":"100"}');
+ expect(expanded).toContain('settings.mcpToolDetailCoverage {"count":2}');
+ expect(expanded).toContain("MySQL");
+ expect(expanded).toContain("SQLite");
+ });
+
+ it("names the connections a tool skips inside its expanded detail", async () => {
+ const { mounted } = mountPanel();
+ dispatch(findAll(card(mounted.root, "sql.schema"), (node) => node.type === "button")[0], "click");
+ await nextTick();
+ const routine = findOne(mounted.root, (node) => node.props["data-mcp-tool"] === "dbx_get_routine_source");
+ dispatch(
+ findOne(routine, (node) => node.props["data-mcp-tool-toggle"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ const coverage = hostText(findOne(routine, (node) => node.props["data-mcp-tool-coverage"] !== undefined));
+ expect(coverage).toContain('settings.mcpToolDetailSkippedConnections {"names":"notes"}');
+ expect(coverage).toContain("MySQL");
+ expect(coverage).not.toContain("SQLite");
+ });
+
+ it("shows the load error instead of cards", () => {
+ const { mounted } = mountPanel({ catalog: null, loadError: "boom" });
+ expect(hostText(mounted.root)).toContain('settings.mcpCapabilitiesLoadFailed {"error":"boom"}');
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-toolset"] !== undefined)).toEqual([]);
+ });
+
+ it("emits retry and disables retry while loading", async () => {
+ const retry = vi.fn();
+ const { mounted } = mountPanel({ catalog: null, loadError: "boom", onRetry: retry });
+ const button = () => findOne(mounted.root, (node) => node.props["data-mcp-catalog-retry"] !== undefined);
+ dispatch(button(), "click");
+ expect(retry).toHaveBeenCalledTimes(1);
+ await mounted.setProps({ loading: true });
+ dispatch(button(), "click");
+ expect(retry).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps details open when the row is filtered away or its last tool is disabled", async () => {
+ const { mounted } = mountPanel({ visibleToolsetIds: ["sql.schema"], onlyEnabled: true, titlePath: "数据库" });
+ dispatch(
+ findOne(card(mounted.root, "sql.schema"), (node) => node.props["data-mcp-toolset-open"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ await mounted.setProps({ allowedToolNames: [] });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-toolset"] !== undefined)).toEqual([]);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-tool"] !== undefined)).toHaveLength(2);
+ await mounted.setProps({ visibleToolsetIds: ["salesforce"], filterKind: "plugin", titlePath: "Salesforce" });
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined);
+ expect(hostText(detail)).toContain("数据库 / 对象结构");
+ expect(hostText(detail)).not.toContain("Salesforce / 对象结构");
+ });
+
+ it("exposes detail opening for a hidden result and expands the requested tool", async () => {
+ const { mounted } = mountPanel({ visibleToolsetIds: [], listHidden: true });
+ mounted.exposed.value.openDetail("sql.schema", "tools", "dbx_list_tables");
+ await nextTick();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-capability-list"] !== undefined)).toEqual([]);
+ const tool = findOne(mounted.root, (node) => node.props["data-mcp-tool"] === "dbx_list_tables");
+ expect(findOne(tool, (node) => node.props["data-mcp-tool-toggle"] !== undefined).props["aria-expanded"]).toBe(true);
+ expect(hostText(tool)).toContain("List tables and views for a database connection");
+ const other = findOne(mounted.root, (node) => node.props["data-mcp-tool"] === "dbx_get_routine_source");
+ expect(findOne(other, (node) => node.props["data-mcp-tool-toggle"] !== undefined).props["aria-expanded"]).toBe(false);
+ });
+
+ it("translates resource kinds in details only", async () => {
+ const resourceKinds = ["database", "dbIndex", "topic", "queue", "org", "namespace"];
+ const { mounted } = mountPanel({ catalog: { toolsets: [{ ...catalog.toolsets[0], resourceKinds }] } });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-scope-kinds"] !== undefined)).toEqual([]);
+ mounted.exposed.value.openDetail("sql.schema");
+ await nextTick();
+ const scopes = hostText(findOne(mounted.root, (node) => node.props["data-mcp-scope-kinds"] !== undefined));
+ expect(scopes).toContain("settings.mcpBrowser.resourceScopes");
+ for (const kind of resourceKinds) expect(scopes).toContain(`settings.mcpBrowser.resourceKind.${kind}`);
+ });
+
+ it("restores focus to the row that opened the detail", async () => {
+ const { mounted } = mountPanel();
+ const opener = findOne(card(mounted.root, "sql.schema"), (node) => node.props["data-mcp-toolset-open"] !== undefined);
+ dispatch(opener, "click");
+ await nextTick();
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-toolset-close"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ expect(opener.focused).toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined)).toEqual([]);
+ });
+
+ it("restores focus to an external search trigger through dialog close autofocus", async () => {
+ const { mounted } = mountPanel({ listHidden: true });
+ const searchTrigger = document.createElement("button");
+ document.body.append(searchTrigger);
+ searchTrigger.focus();
+ try {
+ mounted.exposed.value.openDetail("sql.schema", "tools", "dbx_list_tables");
+ await nextTick();
+ searchTrigger.blur();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined);
+ const event = new Event("close-auto-focus", { cancelable: true });
+ detail.props.onCloseAutoFocus(event);
+ expect(event.defaultPrevented).toBe(true);
+ expect(document.activeElement).toBe(searchTrigger);
+ } finally {
+ searchTrigger.remove();
+ mounted.unmount();
+ }
+ });
+
+ it("preserves default focus recovery when the search trigger was removed", async () => {
+ const { mounted } = mountPanel({ listHidden: true });
+ const searchTrigger = document.createElement("button");
+ document.body.append(searchTrigger);
+ mounted.exposed.value.openDetail("sql.schema", "tools", undefined, searchTrigger);
+ await nextTick();
+ searchTrigger.remove();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined);
+ const event = new Event("close-auto-focus", { cancelable: true });
+ detail.props.onCloseAutoFocus(event);
+ expect(event.defaultPrevented).toBe(false);
+ mounted.unmount();
+ });
+
+ it("uses the supplied focus fallback when filtering removed the detail trigger", async () => {
+ const trigger = document.createElement("button");
+ const fallbackTarget = document.createElement("input");
+ document.body.append(trigger, fallbackTarget);
+ const focusFallback = vi.fn(() => fallbackTarget.focus());
+ const { mounted } = mountPanel({ listHidden: true, focusFallback });
+ try {
+ mounted.exposed.value.openDetail("sql.schema", "tools", undefined, trigger);
+ await nextTick();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined);
+ const closeAutoFocus = detail.props.onCloseAutoFocus;
+ trigger.remove();
+ dispatch(
+ findOne(detail, (node) => node.props["data-mcp-toolset-close"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ expect(focusFallback).toHaveBeenCalled();
+ expect(document.activeElement).toBe(fallbackTarget);
+ const event = new Event("close-auto-focus", { cancelable: true });
+ closeAutoFocus(event);
+ expect(event.defaultPrevented).toBe(true);
+ } finally {
+ mounted.unmount();
+ trigger.remove();
+ fallbackTarget.remove();
+ }
+ });
+
+ it("keeps unknown toolsets usable without displaying missing translation keys", async () => {
+ const { mounted, setToolset } = mountPanel({ catalog: { toolsets: [{ ...catalog.toolsets[0], id: "future.inspect" }] }, titlePath: "其他能力" });
+ const row = card(mounted.root, "future.inspect");
+ expect(hostText(row)).toContain("future.inspect");
+ expect(hostText(row)).not.toContain("settings.mcpToolset.futureInspect");
+ const toggle = findOne(row, (node) => node.props["data-stub"] === "Switch");
+ (toggle.props["onUpdate:modelValue"] as (value: boolean) => void)(false);
+ expect(setToolset).toHaveBeenCalledWith(expect.objectContaining({ id: "future.inspect" }), false);
+ mounted.exposed.value.openDetail("future.inspect");
+ await nextTick();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-toolset-detail"] !== undefined);
+ expect(hostText(detail)).toContain("其他能力 / future.inspect");
+ expect(findAll(detail, (node) => node.props["data-mcp-tool"] !== undefined)).toHaveLength(2);
+ mounted.unmount();
+ });
+
+ it("scrolls to and focuses a direct tool after the real DOM detail is rendered", async () => {
+ const container = document.createElement("div");
+ const trigger = document.createElement("button");
+ document.body.append(trigger, container);
+ const scroll = vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ const app = createApp(McpCapabilitiesPanel, { catalog, allowedToolNames: null, connections, listHidden: true });
+ const panel = app.mount(container) as unknown as { openDetail: (id: string, view: string, toolName: string, trigger: HTMLElement) => void };
+ try {
+ panel.openDetail("sql.schema", "tools", "dbx_get_routine_source", trigger);
+ await nextTick();
+ const row = container.querySelector('[data-mcp-tool="dbx_get_routine_source"]');
+ const opener = row?.querySelector("[data-mcp-tool-toggle]");
+ expect(row).not.toBeNull();
+ expect(opener?.getAttribute("aria-expanded")).toBe("true");
+ expect(document.activeElement).toBe(opener);
+ expect(scroll).toHaveBeenCalledWith({ block: "nearest" });
+ expect(scroll.mock.contexts).toContain(row);
+ (container.querySelector("[data-mcp-toolset-close]") as HTMLButtonElement).click();
+ await nextTick();
+ expect(document.activeElement).toBe(trigger);
+ } finally {
+ app.unmount();
+ scroll.mockRestore();
+ trigger.remove();
+ container.remove();
+ }
+ });
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpCapabilityBrowser.spec.ts b/apps/desktop/src/components/settings/__tests__/McpCapabilityBrowser.spec.ts
new file mode 100644
index 0000000000..4390a83f71
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpCapabilityBrowser.spec.ts
@@ -0,0 +1,609 @@
+// @vitest-environment happy-dom
+
+import { defineComponent, h, nextTick } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { dispatch, findAll, findOne, hostText, mountComponent, type HostNode } from "@/components/grid/__tests__/vueHostHarness";
+import type { McpToolCatalog, McpToolCatalogToolset, PluginMcpView } from "@/types/mcpCatalog";
+import type { McpCapabilityBrowserState } from "@/lib/mcp/mcpCapabilitySearch";
+
+const detailCalls = vi.hoisted(() => ({ builtin: vi.fn(), plugin: vi.fn(), pluginTool: vi.fn() }));
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ const messages: Record<string, string> = {
+ "settings.mcpBrowser.category.database.title": "数据库",
+ "settings.mcpBrowser.category.nacos.title": "Nacos",
+ "settings.mcpBrowser.category.consul.title": "Consul",
+ "settings.mcpBrowser.category.mq.title": "消息队列",
+ "settings.mcpBrowser.category.salesforce.title": "Salesforce",
+ "settings.mcpBrowser.category.dbx.title": "DBX 通用",
+ "settings.mcpBrowser.category.other.title": "其他能力",
+ "settings.mcpToolset.sqlQuery.title": "查询与脚本",
+ "settings.mcpToolset.sqlSchema.title": "对象结构",
+ "settings.mcpToolset.nacosConfig.title": "配置管理",
+ "settings.mcpToolset.nacosService.title": "服务管理",
+ };
+ return `${messages[key] ?? key}${values ? ` ${JSON.stringify(values)}` : ""}`;
+ },
+ }),
+}));
+
+vi.mock("@lucide/vue", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const icon = createPassthroughStub("Icon", "i");
+ return { Search: icon, X: icon, RefreshCw: icon, Loader2: icon };
+});
+
+vi.mock("@/components/ui/button", async () => ({ Button: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Button", "button") }));
+vi.mock("@/components/ui/input", async () => ({ Input: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Input", "input") }));
+vi.mock("@/components/ui/select", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ return Object.fromEntries(["Select", "SelectContent", "SelectGroup", "SelectItem", "SelectLabel", "SelectTrigger", "SelectValue"].map((name) => [name, createPassthroughStub(name)]));
+});
+
+vi.mock("@/components/settings/McpCapabilitiesPanel.vue", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ default: defineComponent({
+ name: "McpCapabilitiesPanel",
+ inheritAttrs: false,
+ setup(_props, { attrs, expose }) {
+ expose({ openDetail: detailCalls.builtin });
+ return () => h("div", { ...attrs, "data-stub": "BuiltinPanel" });
+ },
+ }),
+ };
+});
+
+vi.mock("@/components/settings/McpPluginCapabilities.vue", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ default: defineComponent({
+ name: "McpPluginCapabilities",
+ inheritAttrs: false,
+ setup(_props, { attrs, expose }) {
+ expose({ openDetail: detailCalls.plugin, openTool: detailCalls.pluginTool });
+ return () => h("div", { ...attrs, "data-stub": "PluginPanel" });
+ },
+ }),
+ };
+});
+
+import McpCapabilityBrowser from "@/components/settings/McpCapabilityBrowser.vue";
+
+function toolset(id: string, names: string[], type = "mysql"): McpToolCatalogToolset {
+ return {
+ id,
+ provider: `builtin:${id.split(".")[0]}`,
+ resourceKinds: [],
+ scopeKinds: [],
+ tools: names.map((name) => ({ name, access: "read", accessMode: "static", coverageKind: "types", databaseTypes: [type], description: `${name} description`, parameters: [] })),
+ };
+}
+
+// Deliberately shuffled: navigation order comes from the product taxonomy.
+const catalog: McpToolCatalog = {
+ toolsets: [
+ toolset("nacos.service", ["dbx_nacos_list_services"], "nacos"),
+ toolset("future.inspect", ["dbx_future_inspect"]),
+ toolset("sql.schema", ["dbx_list_tables"]),
+ toolset("core.discovery", ["dbx_list_connections"]),
+ toolset("nacos.config", ["dbx_nacos_get_config", "dbx_nacos_publish_config"], "nacos"),
+ toolset("sql.query", ["dbx_execute_query"]),
+ ],
+};
+
+const plugin: PluginMcpView = {
+ pluginId: "io.dbx.nacos-helper",
+ pluginName: "Nacos",
+ version: "1.0.0",
+ authorAllowsExternal: true,
+ hasSavedGrant: true,
+ grant: { external: true, ceiling: "write", approvedTools: { dbx_helper__inspect: "read" }, disabledTools: [] },
+ discoveryError: null,
+ toolsets: [{ id: "helpers", title: "辅助工具", description: "Nacos helpers" }],
+ tools: [
+ { name: "dbx_helper__inspect", description: "Inspect deployment", access: "read", exposure: "exposed", toolset: "helpers", parameters: [] },
+ { name: "dbx_helper__update", description: "Update deployment", access: "write", exposure: "pendingApproval", toolset: "helpers", parameters: [] },
+ ],
+};
+
+type Mounted = ReturnType<typeof mountComponent>;
+const mounts: Mounted[] = [];
+
+const BrowserWithSlots = defineComponent({
+ inheritAttrs: false,
+ setup(_props, { attrs }) {
+ return () =>
+ h(McpCapabilityBrowser, attrs as never, {
+ advanced: () => h("button", { "data-test-advanced-editor": "" }, "工具白名单"),
+ "plugin-warning": () => h("p", { "data-test-plugin-warning": "" }, "插件白名单提示"),
+ });
+ },
+});
+
+function mountBrowser(props: Record<string, unknown> = {}) {
+ let mounted: Mounted;
+ const modelUpdates = vi.fn((value: McpCapabilityBrowserState) => void mounted.setProps({ modelValue: value }));
+ const setTool = vi.fn();
+ const setToolset = vi.fn();
+ const setCategory = vi.fn();
+ const retry = vi.fn();
+ const refreshPlugins = vi.fn();
+ const savedPlugin = vi.fn();
+ const savePlugin = vi.fn(async () => plugin);
+ mounted = mountComponent(BrowserWithSlots, {
+ catalog,
+ allowedToolNames: null,
+ connections: [],
+ plugins: [plugin],
+ savePlugin,
+ "onUpdate:modelValue": modelUpdates,
+ "onSet:tool": setTool,
+ "onSet:toolset": setToolset,
+ "onSet:category": setCategory,
+ onRetry: retry,
+ "onRefresh:plugins": refreshPlugins,
+ "onSaved:plugin": savedPlugin,
+ ...props,
+ });
+ mounts.push(mounted);
+ return { mounted, modelUpdates, setTool, setToolset, setCategory, retry, refreshPlugins, savedPlugin, savePlugin };
+}
+
+function byData(root: HostNode, name: string, value?: string) {
+ return findOne(root, (node) => (value === undefined ? node.props[name] !== undefined : node.props[name] === value));
+}
+
+function builtin(root: HostNode) {
+ return byData(root, "data-stub", "BuiltinPanel");
+}
+
+function plugins(root: HostNode) {
+ return byData(root, "data-stub", "PluginPanel");
+}
+
+async function select(root: HostNode, category: string) {
+ dispatch(byData(root, "data-mcp-category", category), "click");
+ await nextTick();
+}
+
+async function search(root: HostNode, value: string) {
+ byData(root, "data-mcp-global-search").props["onUpdate:modelValue"](value);
+ await nextTick();
+}
+
+beforeEach(() => vi.clearAllMocks());
+afterEach(() => {
+ for (const mounted of mounts.splice(0)) mounted.unmount();
+});
+
+describe("McpCapabilityBrowser", () => {
+ it("keeps toolset saving and the saved baseline connected in category, overview and search views", async () => {
+ const saveToolset = vi.fn(async () => {});
+ const savedToolNames = ["dbx_nacos_get_config"];
+ const { mounted } = mountBrowser({ savedToolNames, saveToolset });
+ for (const mode of ["manage", "overview"] as const) {
+ dispatch(byData(mounted.root, "data-mcp-view-mode", mode), "click");
+ await nextTick();
+ expect(builtin(mounted.root).props["saved-tool-names"]).toEqual(savedToolNames);
+ await builtin(mounted.root).props["save-toolset"]("nacos.config");
+ }
+ await search(mounted.root, "nacos");
+ await builtin(mounted.root).props["save-toolset"]("nacos.config");
+ expect(saveToolset).toHaveBeenCalledTimes(3);
+ expect(saveToolset).toHaveBeenLastCalledWith("nacos.config");
+ expect(plugins(mounted.root).props["save-toolset"]).toBeUndefined();
+ });
+
+ it("starts at databases and retains the fixed business order independently of catalog order", () => {
+ const { mounted } = mountBrowser();
+ const navigation = findAll(mounted.root, (node) => node.props["data-mcp-category"] !== undefined);
+ expect(navigation.map((node) => node.props["data-mcp-category"])).toEqual(["database", "nacos", "consul", "mq", "salesforce", "dbx", "other", `plugin:${plugin.pluginId}`, "advanced"]);
+ expect(byData(mounted.root, "data-mcp-category", "database").props["aria-current"]).toBe("page");
+ expect(byData(mounted.root, "data-mcp-category", "database").props.class).toContain("mcp-category-button-selected");
+ expect(builtin(mounted.root).props["visible-toolset-ids"]).toEqual(["sql.query", "sql.schema"]);
+ expect(builtin(mounted.root).props["list-hidden"]).toBe(false);
+ expect(plugins(mounted.root).props["list-hidden"]).toBe(true);
+ expect(byData(mounted.root, "data-mcp-view-mode", "manage").props["aria-pressed"]).toBe(true);
+ });
+
+ it("filters built-in navigation without changing the selected category or its content", async () => {
+ const { mounted } = mountBrowser();
+ const filter = byData(mounted.root, "data-mcp-builtin-filter");
+ filter.props["onUpdate:modelValue"]("nacos");
+ await nextTick();
+
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category"] !== undefined).map((node) => node.props["data-mcp-category"])).toEqual(["nacos", `plugin:${plugin.pluginId}`, "advanced"]);
+ expect(builtin(mounted.root).props["visible-toolset-ids"]).toEqual(["sql.query", "sql.schema"]);
+
+ dispatch(byData(mounted.root, "data-mcp-clear-builtin-filter"), "click");
+ await nextTick();
+ expect(byData(mounted.root, "data-mcp-category", "database").props["aria-current"]).toBe("page");
+ });
+
+ it("filters plugins by display name and plugin id while keeping the refresh action available", async () => {
+ const secondPlugin: PluginMcpView = { ...plugin, pluginId: "com.example.timestamp-converter", pluginName: "Timestamp Converter" };
+ const { mounted } = mountBrowser({ plugins: [plugin, secondPlugin] });
+ const filter = byData(mounted.root, "data-mcp-plugin-filter");
+ filter.props["onUpdate:modelValue"]("timestamp");
+ await nextTick();
+
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category"]?.startsWith("plugin:")).map((node) => node.props["data-mcp-category"])).toEqual([`plugin:${secondPlugin.pluginId}`]);
+ expect(byData(mounted.root, "data-mcp-plugins-refresh-nav")).toBeDefined();
+
+ dispatch(byData(mounted.root, "data-mcp-clear-plugin-filter"), "click");
+ await nextTick();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category"]?.startsWith("plugin:")).map((node) => node.props["data-mcp-category"])).toEqual([`plugin:${plugin.pluginId}`, `plugin:${secondPlugin.pluginId}`]);
+ });
+
+ it("keeps navigation filters icon-only and combines plugin refresh with the filter control", async () => {
+ const { mounted } = mountBrowser();
+ const builtinFilter = byData(mounted.root, "data-mcp-builtin-filter");
+ const pluginFilter = byData(mounted.root, "data-mcp-plugin-filter");
+ const refresh = byData(mounted.root, "data-mcp-plugins-refresh-nav");
+
+ expect(builtinFilter.props.placeholder).toBe("");
+ expect(pluginFilter.props.placeholder).toBe("");
+ expect(builtinFilter.props["aria-label"]).toBeTruthy();
+ expect(pluginFilter.props["aria-label"]).toBeTruthy();
+ expect(builtinFilter.props["modelValue"]).toBe("");
+ expect(pluginFilter.props["modelValue"]).toBe("");
+ expect(refresh.parent).toBeDefined();
+ expect(refresh.props.class).toContain("mcp-nav-refresh-action");
+
+ pluginFilter.props["onUpdate:modelValue"]("sql");
+ await nextTick();
+ expect(byData(mounted.root, "data-mcp-plugin-filter").parent?.props.class).toContain("active");
+
+ dispatch(byData(mounted.root, "data-mcp-clear-plugin-filter"), "click");
+ await nextTick();
+ await select(mounted.root, `plugin:${plugin.pluginId}`);
+ expect(byData(mounted.root, "data-mcp-category", `plugin:${plugin.pluginId}`).props.class).toContain("mcp-category-button-selected");
+ });
+
+ it("switches to a grouped global overview without losing the selected category", async () => {
+ const { mounted, modelUpdates, setCategory, setToolset } = mountBrowser({ allowedToolNames: ["dbx_list_tables"] });
+ await select(mounted.root, "nacos");
+ dispatch(byData(mounted.root, "data-mcp-view-mode", "overview"), "click");
+ await nextTick();
+ expect(modelUpdates).toHaveBeenLastCalledWith({ selected: "nacos", search: "", onlyEnabled: false, viewMode: "overview" });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category"] !== undefined)).toEqual([]);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-overview-category"] !== undefined).map((node) => node.props["data-mcp-overview-category"])).toEqual(["database", "nacos", "consul", "mq", "salesforce", "dbx", "other"]);
+ expect(hostText(byData(mounted.root, "data-mcp-overview-category", "database"))).toContain('"enabled":1');
+ expect(findAll(mounted.root, (node) => node.props["data-test-plugin-warning"] !== undefined)).toHaveLength(1);
+
+ dispatch(byData(mounted.root, "data-mcp-overview-category-enable", "database"), "click");
+ expect(setCategory).toHaveBeenCalledExactlyOnceWith("database", true);
+ dispatch(byData(mounted.root, "data-mcp-overview-toolset-switch", "sql.query"), "change", { target: { checked: false } });
+ expect(setToolset).toHaveBeenCalledExactlyOnceWith(
+ catalog.toolsets.find((item) => item.id === "sql.query"),
+ false,
+ );
+ dispatch(byData(mounted.root, "data-mcp-view-mode", "manage"), "click");
+ await nextTick();
+ expect(byData(mounted.root, "data-mcp-category", "nacos").props["aria-current"]).toBe("page");
+ expect(builtin(mounted.root).props["visible-toolset-ids"]).toEqual(["nacos.config", "nacos.service"]);
+ });
+
+ it("collapses overview categories and opens existing toolset details with a category path", async () => {
+ const { mounted } = mountBrowser();
+ dispatch(byData(mounted.root, "data-mcp-view-mode", "overview"), "click");
+ await nextTick();
+ const category = byData(mounted.root, "data-mcp-overview-category", "database");
+ const toggle = byData(category, "data-mcp-overview-category-toggle");
+ expect(toggle.props["aria-expanded"]).toBe(true);
+ dispatch(toggle, "click");
+ await nextTick();
+ expect(toggle.props["aria-expanded"]).toBe(false);
+ expect(findAll(category, (node) => node.props["data-mcp-overview-toolset"] !== undefined)).toEqual([]);
+
+ dispatch(toggle, "click");
+ await nextTick();
+ const toolsetRow = byData(category, "data-mcp-overview-toolset", "sql.query");
+ const trigger = byData(toolsetRow, "data-mcp-overview-toolset-open");
+ // Native events clear currentTarget immediately after synchronous dispatch.
+ const event = { currentTarget: trigger as HostNode | null };
+ (trigger.props.onClick as (event: unknown) => void)(event);
+ event.currentTarget = null;
+ await nextTick();
+ expect(detailCalls.builtin).toHaveBeenCalledWith("sql.query", "tools", undefined, byData(toolsetRow, "data-mcp-overview-toolset-open"));
+ expect(builtin(mounted.root).props["title-path"]).toBe("数据库");
+ });
+
+ it("opens plugin details from the global overview and keeps search behavior unchanged", async () => {
+ const { mounted, modelUpdates } = mountBrowser();
+ dispatch(byData(mounted.root, "data-mcp-view-mode", "overview"), "click");
+ await nextTick();
+ dispatch(byData(mounted.root, "data-mcp-overview-plugin-open"), "click");
+ expect(detailCalls.plugin).toHaveBeenCalledWith(plugin.pluginId, byData(mounted.root, "data-mcp-overview-plugin-open"));
+ await search(mounted.root, "dbx_nacos_get_config");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-overview"] !== undefined)).toEqual([]);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category-batch"] !== undefined)).toEqual([]);
+ expect(byData(mounted.root, "data-mcp-category", "nacos").props["aria-current"]).toBeUndefined();
+ await select(mounted.root, "nacos");
+ expect(modelUpdates).toHaveBeenLastCalledWith({ selected: "nacos", search: "", onlyEnabled: false, viewMode: "manage" });
+ expect(byData(mounted.root, "data-mcp-category", "nacos").props["aria-current"]).toBe("page");
+ });
+
+ it("keeps plugin discovery failures visible in the global overview", async () => {
+ const { mounted } = mountBrowser({ plugins: [{ ...plugin, discoveryError: "sidecar unavailable", tools: [] }] });
+ dispatch(byData(mounted.root, "data-mcp-view-mode", "overview"), "click");
+ await nextTick();
+ expect(hostText(byData(mounted.root, "data-mcp-overview-plugin", plugin.pluginId))).toContain("sidecar unavailable");
+ });
+
+ it("applies enabled-only filtering to plugins in the global overview", async () => {
+ const disabledPlugin = { ...plugin, grant: { ...plugin.grant, external: false } };
+ const { mounted } = mountBrowser({
+ plugins: [disabledPlugin],
+ modelValue: { selected: "database", search: "", onlyEnabled: true, viewMode: "overview" },
+ });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-overview-plugin"] !== undefined)).toEqual([]);
+ expect(hostText(byData(mounted.root, "data-mcp-overview-plugins"))).toContain("settings.mcpBrowser.emptyEnabled");
+ });
+
+ it("keeps the selected overview state on an enabled-only empty result and exposes catalog retry", async () => {
+ const { mounted, retry } = mountBrowser({
+ plugins: [],
+ allowedToolNames: [],
+ modelValue: { selected: "nacos", search: "", onlyEnabled: true, viewMode: "overview" },
+ });
+ expect(byData(mounted.root, "data-mcp-overview-empty")).toBeDefined();
+ expect(byData(mounted.root, "data-mcp-view-mode", "overview").props["aria-pressed"]).toBe(true);
+ await mounted.setProps({ loadError: "catalog unavailable" });
+ dispatch(byData(mounted.root, "data-mcp-overview-retry"), "click");
+ expect(retry).toHaveBeenCalledExactlyOnceWith();
+ expect(byData(mounted.root, "data-mcp-overview", undefined)).toBeDefined();
+ });
+
+ it("distinguishes a plugin from the built-in product with the same display name", async () => {
+ const { mounted } = mountBrowser();
+ const native = byData(mounted.root, "data-mcp-category", "nacos");
+ const extension = byData(mounted.root, "data-mcp-category", `plugin:${plugin.pluginId}`);
+ expect(hostText(native)).toContain("Nacos");
+ expect(hostText(extension)).toContain("Nacos");
+ expect(hostText(extension)).toContain("settings.mcpCapabilitiesFilterPlugin");
+ expect(hostText(extension)).toContain('settings.mcpPluginPendingTools {"count":1}');
+ await select(mounted.root, `plugin:${plugin.pluginId}`);
+ expect(plugins(mounted.root).props["selected-plugin-id"]).toBe(plugin.pluginId);
+ expect(plugins(mounted.root).props["list-hidden"]).toBe(false);
+ expect(builtin(mounted.root).props["list-hidden"]).toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category-batch"] !== undefined)).toEqual([]);
+ });
+
+ it("lets the compact shared Select navigate to the same categories", async () => {
+ const { mounted } = mountBrowser();
+ byData(mounted.root, "data-stub", "Select").props["onUpdate:modelValue"]("nacos");
+ await nextTick();
+ expect(byData(mounted.root, "data-mcp-category", "nacos").props["aria-current"]).toBe("page");
+ expect(builtin(mounted.root).props["visible-toolset-ids"]).toEqual(["nacos.config", "nacos.service"]);
+ });
+
+ it.each(["nacos", "no-matching-category"])("keeps compact category navigation available with sidebar filter %s", async (query) => {
+ const { mounted, modelUpdates } = mountBrowser({
+ allowedToolNames: ["dbx_list_tables"],
+ modelValue: { selected: "nacos", search: "", onlyEnabled: true, viewMode: "manage" },
+ });
+ const compactSelect = byData(mounted.root, "data-stub", "Select");
+ const destinations = () => findAll(compactSelect, (node) => node.props["data-stub"] === "SelectItem").map((node) => node.props.value);
+ const allDestinations = destinations();
+ byData(mounted.root, "data-mcp-builtin-filter").props["onUpdate:modelValue"](query);
+ await nextTick();
+
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category"] === "database")).toEqual([]);
+ expect(destinations()).toEqual(allDestinations);
+ expect(destinations()).toContain("database");
+ compactSelect.props["onUpdate:modelValue"]("database");
+ await nextTick();
+
+ expect(modelUpdates).toHaveBeenLastCalledWith({ selected: "database", search: "", onlyEnabled: true, viewMode: "manage" });
+ expect(builtin(mounted.root).props["visible-toolset-ids"]).toEqual(["sql.query", "sql.schema"]);
+ expect(builtin(mounted.root).props["allowed-tool-names"]).toEqual(["dbx_list_tables"]);
+ expect(byData(mounted.root, "data-mcp-builtin-filter").props.modelValue).toBe(query);
+ dispatch(byData(mounted.root, "data-mcp-clear-builtin-filter"), "click");
+ await nextTick();
+ expect(byData(mounted.root, "data-mcp-category", "database").props["aria-current"]).toBe("page");
+ });
+
+ it.each(["timestamp", "no-matching-plugin"])("keeps compact plugin navigation available with sidebar filter %s", async (query) => {
+ const secondPlugin: PluginMcpView = { ...plugin, pluginId: "com.example.timestamp-converter", pluginName: "Timestamp Converter" };
+ const { mounted } = mountBrowser({ plugins: [plugin, secondPlugin] });
+ const compactSelect = byData(mounted.root, "data-stub", "Select");
+ const destinations = () => findAll(compactSelect, (node) => node.props["data-stub"] === "SelectItem").map((node) => node.props.value);
+ const allDestinations = destinations();
+ byData(mounted.root, "data-mcp-plugin-filter").props["onUpdate:modelValue"](query);
+ await nextTick();
+
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category"] === `plugin:${plugin.pluginId}`)).toEqual([]);
+ expect(destinations()).toEqual(allDestinations);
+ expect(destinations()).toContain(`plugin:${plugin.pluginId}`);
+ compactSelect.props["onUpdate:modelValue"](`plugin:${plugin.pluginId}`);
+ await nextTick();
+
+ expect(plugins(mounted.root).props["selected-plugin-id"]).toBe(plugin.pluginId);
+ expect(plugins(mounted.root).props["list-hidden"]).toBe(false);
+ expect(byData(mounted.root, "data-mcp-plugin-filter").props.modelValue).toBe(query);
+ dispatch(byData(mounted.root, "data-mcp-clear-plugin-filter"), "click");
+ await nextTick();
+ expect(byData(mounted.root, "data-mcp-category", `plugin:${plugin.pluginId}`).props["aria-current"]).toBe("page");
+ });
+
+ it("searches across categories and opens a matching built-in tool with its category path and trigger", async () => {
+ const { mounted } = mountBrowser();
+ await search(mounted.root, "dbx_nacos_get_config");
+ const result = byData(mounted.root, "data-mcp-search-result", "nacos.config/dbx_nacos_get_config");
+ expect(hostText(result)).toContain("Nacos / 配置管理");
+ expect(builtin(mounted.root).props["list-hidden"]).toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category-batch"] !== undefined)).toEqual([]);
+ dispatch(result, "click");
+ await nextTick();
+ expect(detailCalls.builtin).toHaveBeenCalledWith("nacos.config", "tools", "dbx_nacos_get_config", result);
+ expect(builtin(mounted.root).props["title-path"]).toBe("Nacos");
+ });
+
+ it("opens plugin search matches through the plugin detail and tool handles", async () => {
+ const { mounted } = mountBrowser();
+ await search(mounted.root, "dbx_helper__inspect");
+ const toolResult = byData(mounted.root, "data-mcp-search-result", `${plugin.pluginId}/dbx_helper__inspect`);
+ dispatch(toolResult, "click");
+ expect(detailCalls.pluginTool).toHaveBeenCalledWith(plugin.pluginId, "dbx_helper__inspect", toolResult);
+ expect(detailCalls.builtin).not.toHaveBeenCalled();
+ await search(mounted.root, plugin.pluginId);
+ const pluginResult = byData(mounted.root, "data-mcp-search-result", plugin.pluginId);
+ dispatch(pluginResult, "click");
+ expect(detailCalls.plugin).toHaveBeenCalledWith(plugin.pluginId, pluginResult);
+ });
+
+ it("restores the previous category when search is cleared", async () => {
+ const { mounted } = mountBrowser();
+ await select(mounted.root, "nacos");
+ await search(mounted.root, "dbx_list_tables");
+ expect(byData(mounted.root, "data-mcp-category", "nacos").props["aria-current"]).toBeUndefined();
+ dispatch(byData(mounted.root, "data-mcp-clear-search"), "click");
+ await nextTick();
+ expect(byData(mounted.root, "data-mcp-category", "nacos").props["aria-current"]).toBe("page");
+ expect(builtin(mounted.root).props["visible-toolset-ids"]).toEqual(["nacos.config", "nacos.service"]);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-search-result"] !== undefined)).toEqual([]);
+ });
+
+ it("exits search when a navigation category is chosen", async () => {
+ const { mounted, modelUpdates } = mountBrowser();
+ await search(mounted.root, "config");
+ await select(mounted.root, "dbx");
+ expect(modelUpdates).toHaveBeenLastCalledWith({ selected: "dbx", search: "", onlyEnabled: false, viewMode: "manage" });
+ expect(builtin(mounted.root).props["list-hidden"]).toBe(false);
+ expect(builtin(mounted.root).props["visible-toolset-ids"]).toEqual(["core.discovery"]);
+ });
+
+ it("preserves category selection and navigation after the final enabled tool is turned off", async () => {
+ const { mounted, setTool } = mountBrowser({ allowedToolNames: ["dbx_list_tables"] });
+ dispatch(byData(mounted.root, "data-mcp-only-enabled"), "change", { target: { checked: true } });
+ await nextTick();
+ builtin(mounted.root).props["onSet:tool"]("dbx_list_tables", false);
+ expect(setTool).toHaveBeenCalledWith("dbx_list_tables", false);
+ await mounted.setProps({ allowedToolNames: [] });
+ expect(byData(mounted.root, "data-mcp-category", "database").props["aria-current"]).toBe("page");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category"] !== undefined)).toHaveLength(9);
+ expect(builtin(mounted.root).props["only-enabled"]).toBe(true);
+ expect(builtin(mounted.root).props["visible-toolset-ids"]).toEqual(["sql.query", "sql.schema"]);
+ expect(hostText(byData(mounted.root, "data-mcp-category-summary"))).toContain('"enabled":0');
+ });
+
+ it("emits a full category action even while only enabled tools are shown", async () => {
+ const { mounted, setCategory, setTool, setToolset } = mountBrowser({ allowedToolNames: ["dbx_list_tables"] });
+ dispatch(byData(mounted.root, "data-mcp-only-enabled"), "change", { target: { checked: true } });
+ await nextTick();
+ dispatch(byData(mounted.root, "data-mcp-category-enable"), "click");
+ await nextTick();
+ expect(setCategory).toHaveBeenCalledExactlyOnceWith("database", true);
+ expect(setTool).not.toHaveBeenCalled();
+ expect(setToolset).not.toHaveBeenCalled();
+ expect(hostText(byData(mounted.root, "data-mcp-category-summary"))).toContain('"total":2');
+ expect(hostText(byData(mounted.root, "data-mcp-batch-feedback"))).toContain("settings.mcpBrowser.batchChanged");
+ });
+
+ it("disables redundant batch actions and categories without tools", async () => {
+ const { mounted, setCategory } = mountBrowser();
+ expect(byData(mounted.root, "data-mcp-category-enable").props.disabled).toBe(true);
+ dispatch(byData(mounted.root, "data-mcp-category-enable"), "click");
+ expect(setCategory).not.toHaveBeenCalled();
+ dispatch(byData(mounted.root, "data-mcp-category-disable"), "click");
+ expect(setCategory).toHaveBeenCalledExactlyOnceWith("database", false);
+ await mounted.setProps({ allowedToolNames: [] });
+ expect(byData(mounted.root, "data-mcp-category-disable").props.disabled).toBe(true);
+ await select(mounted.root, "consul");
+ expect(byData(mounted.root, "data-mcp-category-enable").props.disabled).toBe(true);
+ expect(byData(mounted.root, "data-mcp-category-disable").props.disabled).toBe(true);
+ });
+
+ it.each([{ catalog: null }, { loading: true }, { loadError: "catalog unavailable" }, { disabled: true }])("prevents edits while the catalog is unavailable or settings are locked: %j", (state) => {
+ const { mounted, setCategory } = mountBrowser({ allowedToolNames: [], ...state });
+ expect(builtin(mounted.root).props.disabled).toBe(true);
+ expect(byData(mounted.root, "data-mcp-category-enable").props.disabled).toBe(true);
+ expect(byData(mounted.root, "data-mcp-category-disable").props.disabled).toBe(true);
+ dispatch(byData(mounted.root, "data-mcp-category-enable"), "click");
+ expect(setCategory).not.toHaveBeenCalled();
+ });
+
+ it("forwards catalog retry both from the built-in panel and search error state", async () => {
+ const { mounted, retry } = mountBrowser({ loadError: "catalog unavailable" });
+ builtin(mounted.root).props.onRetry();
+ expect(retry).toHaveBeenCalledTimes(1);
+ await search(mounted.root, "query");
+ const alert = findOne(mounted.root, (node) => node.props.role === "alert");
+ expect(hostText(alert)).toContain("catalog unavailable");
+ dispatch(
+ findOne(alert, (node) => node.type === "button"),
+ "click",
+ );
+ expect(retry).toHaveBeenCalledTimes(2);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-search-result"] !== undefined)).toEqual([]);
+ });
+
+ it("shows loading, error and empty plugin states and retries their source independently", async () => {
+ const { mounted, refreshPlugins, retry } = mountBrowser({ plugins: null, pluginsLoading: true });
+ expect(hostText(byData(mounted.root, "data-mcp-plugin-source-status"))).toContain("settings.mcpPluginsLoading");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-source-retry"] !== undefined)).toEqual([]);
+ await mounted.setProps({ pluginsLoading: false, pluginsError: "plugin unavailable" });
+ expect(hostText(byData(mounted.root, "data-mcp-plugin-source-status"))).toContain("plugin unavailable");
+ dispatch(byData(mounted.root, "data-mcp-plugin-source-retry"), "click");
+ expect(refreshPlugins).toHaveBeenCalledTimes(1);
+ expect(retry).not.toHaveBeenCalled();
+ await mounted.setProps({ pluginsError: "", plugins: [] });
+ expect(hostText(byData(mounted.root, "data-mcp-plugin-source-status"))).toContain("settings.mcpPluginsEmpty");
+ expect(builtin(mounted.root).props.disabled).toBe(false);
+ });
+
+ it("keeps plugin refresh available with a populated catalog and disables it while loading", async () => {
+ const { mounted, refreshPlugins } = mountBrowser();
+ const refresh = () => byData(mounted.root, "data-mcp-plugins-refresh-nav");
+ expect(refresh().props.disabled).not.toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-source-status"] !== undefined)).toEqual([]);
+ dispatch(refresh(), "click");
+ expect(refreshPlugins).toHaveBeenCalledTimes(1);
+ await mounted.setProps({ pluginsLoading: true });
+ expect(refresh().props.disabled).toBe(true);
+ dispatch(refresh(), "click");
+ expect(refreshPlugins).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows advanced controls only when that navigation entry is selected", async () => {
+ const { mounted } = mountBrowser();
+ expect(findAll(mounted.root, (node) => node.props["data-test-advanced-editor"] !== undefined)).toEqual([]);
+ await select(mounted.root, "advanced");
+ expect(hostText(byData(mounted.root, "data-mcp-advanced"))).toContain("工具白名单");
+ expect(builtin(mounted.root).props["list-hidden"]).toBe(true);
+ expect(plugins(mounted.root).props["list-hidden"]).toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category-batch"] !== undefined)).toEqual([]);
+ await search(mounted.root, "query");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-advanced"] !== undefined)).toEqual([]);
+ });
+
+ it("keeps built-in draft events and plugin persistence separate", async () => {
+ const { mounted, setTool, setToolset, setCategory, savePlugin, savedPlugin } = mountBrowser();
+ const entry = catalog.toolsets.find((item) => item.id === "sql.query")!;
+ builtin(mounted.root).props["onSet:tool"]("dbx_execute_query", false);
+ builtin(mounted.root).props["onSet:toolset"](entry, false);
+ expect(setTool).toHaveBeenCalledExactlyOnceWith("dbx_execute_query", false);
+ expect(setToolset).toHaveBeenCalledExactlyOnceWith(entry, false);
+ expect(savePlugin).not.toHaveBeenCalled();
+ await select(mounted.root, `plugin:${plugin.pluginId}`);
+ expect(plugins(mounted.root).props.save).toBe(savePlugin);
+ const saved = await plugins(mounted.root).props.save(plugin.pluginId, plugin.grant, false);
+ plugins(mounted.root).props.onSaved(saved);
+ expect(savePlugin).toHaveBeenCalledExactlyOnceWith(plugin.pluginId, plugin.grant, false);
+ expect(savedPlugin).toHaveBeenCalledExactlyOnceWith(plugin);
+ expect(setTool).toHaveBeenCalledTimes(1);
+ expect(setToolset).toHaveBeenCalledTimes(1);
+ expect(setCategory).not.toHaveBeenCalled();
+ });
+
+ it("hides plugin navigation, results and source controls when plugins are unsupported", async () => {
+ const { mounted } = mountBrowser({ showPlugins: false, pluginsError: "not supported" });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-category"] === `plugin:${plugin.pluginId}` || node.props["data-stub"] === "PluginPanel" || node.props["data-mcp-plugin-source-status"] !== undefined)).toEqual([]);
+ await search(mounted.root, "dbx_helper__inspect");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-search-result"] !== undefined)).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpDatabaseAccessDialog.spec.ts b/apps/desktop/src/components/settings/__tests__/McpDatabaseAccessDialog.spec.ts
new file mode 100644
index 0000000000..689f36e310
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpDatabaseAccessDialog.spec.ts
@@ -0,0 +1,387 @@
+// @vitest-environment happy-dom
+import { nextTick } from "vue";
+import { describe, expect, it, vi } from "vitest";
+import { dispatch, findAll, findOne, hostText, mountComponent } from "@/components/grid/__tests__/vueHostHarness";
+import type { ConnectionConfig } from "@/types/database";
+import { databaseAccess, type McpDatabaseAccess } from "@/lib/mcp/mcpDatabaseAccess";
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ const known: Record<string, string> = { "settings.mcpToolset.sqlSchema.title": "对象结构", "settings.mcpToolset.sqlSchema.description": "浏览表、字段和存储过程源码。" };
+ return `${known[key] ?? key}${values ? ` ${JSON.stringify(values)}` : ""}`;
+ },
+ }),
+}));
+
+vi.mock("@lucide/vue", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const icon = createPassthroughStub("Icon", "i");
+ return { AlertTriangle: icon, ChevronDown: icon, ChevronRight: icon, Loader2: icon, Minus: icon, Search: icon };
+});
+
+vi.mock("@/components/ui/badge", async () => ({ Badge: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Badge", "span") }));
+vi.mock("@/components/ui/button", async () => ({ Button: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Button", "button") }));
+vi.mock("@/components/ui/input", async () => ({ Input: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Input", "input") }));
+vi.mock("@/components/ui/tooltip", async () => ({ HelpTooltip: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("HelpTooltip", "button") }));
+vi.mock("@/components/ui/switch", async () => ({ Switch: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Switch", "button") }));
+vi.mock("@/components/ui/dialog", async () => {
+ const { defineComponent, h } = await import("vue");
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ return {
+ // Render the dialog body only while open, like the real portal.
+ Dialog: defineComponent({
+ name: "Dialog",
+ props: { open: Boolean },
+ emits: ["update:open"],
+ setup(props, { slots, emit }) {
+ return () => (props.open ? h("div", { "data-stub": "Dialog" }, [...(slots.default?.() ?? []), h("button", { "data-dialog-dismiss": "", onClick: () => emit("update:open", false) })]) : null);
+ },
+ }),
+ DialogContent: createPassthroughStub("DialogContent", "div"),
+ DialogDescription: createPassthroughStub("DialogDescription", "p"),
+ DialogHeader: createPassthroughStub("DialogHeader", "div"),
+ DialogTitle: createPassthroughStub("DialogTitle", "h2"),
+ };
+});
+
+vi.mock("@/components/ui/select", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ return {
+ Select: createPassthroughStub("Select", "div"),
+ SelectContent: createPassthroughStub("SelectContent", "div"),
+ SelectItem: createPassthroughStub("SelectItem", "div"),
+ SelectTrigger: createPassthroughStub("SelectTrigger", "button"),
+ SelectValue: createPassthroughStub("SelectValue", "span"),
+ };
+});
+
+import McpDatabaseAccessDialog from "../McpDatabaseAccessDialog.vue";
+const selected = (names: string[]): McpDatabaseAccess => ({ databaseScope: "selected", allowedDatabases: names, databasePolicies: [] });
+function mountDialog(extra: Record<string, unknown> = {}) {
+ const changes = vi.fn((value: McpDatabaseAccess) => {
+ void mounted.setProps({ value });
+ });
+ const mounted = mountComponent(McpDatabaseAccessDialog, {
+ open: true,
+ connection: { id: "c1", name: "Local", db_type: "mysql" } as ConnectionConfig,
+ value: selected([]),
+ savedValue: databaseAccess(),
+ inheritedLabel: "Read only · Group",
+ savedInheritedLabel: "Read only · Group",
+ savedVisible: true,
+ loadDatabases: vi.fn(async () => ["aaa", "abc", "ops"]),
+ save: vi.fn(async () => {}),
+ onChange: changes,
+ "onUpdate:open": (open: boolean) => {
+ void mounted.setProps({ open });
+ },
+ ...extra,
+ });
+ const get = (attr: string, value: string | undefined = undefined) => findOne(mounted.root, (node) => (value === undefined ? node.props[attr] !== undefined : node.props[attr] === value));
+ const click = async (attr: string) => {
+ dispatch(get(attr), "click");
+ await nextTick();
+ };
+ const check = async (name: string, checked = true) => {
+ dispatch(get("data-mcp-database-check", name), "change", { target: { checked } });
+ await nextTick();
+ };
+ const search = async (side: string, text: string) => {
+ get("data-mcp-database-search", side).props["onUpdate:modelValue"](text);
+ await nextTick();
+ };
+ const select = (attr: string, value: string | undefined = undefined) => findAll(mounted.root, (node) => node.props["data-stub"] === "Select").find((node) => findAll(node, (child) => (value === undefined ? child.props[attr] !== undefined : child.props[attr] === value)).length)!;
+ const choose = async (attr: string, value: string | undefined, setting: string) => {
+ select(attr, value).props["onUpdate:modelValue"](setting);
+ await nextTick();
+ };
+ return { mounted, changes, get, click, check, search, choose, select };
+}
+const settle = async () => {
+ await nextTick();
+ await nextTick();
+};
+
+describe("database access transfer dialog", () => {
+ it("selects databases, inherits permissions, overrides one, and restores inheritance", async () => {
+ const h = mountDialog();
+ await settle();
+ await h.check("left:aaa");
+ await h.check("left:abc");
+ await h.click("data-mcp-database-add");
+ expect(h.changes).toHaveBeenLastCalledWith(selected(["aaa", "abc"]));
+ expect(hostText(h.mounted.root)).toContain("Read only · Group");
+ await h.choose("data-mcp-database-level", "abc", "safe_write");
+ expect(h.changes.mock.lastCall![0].databasePolicies).toEqual([{ databaseName: "abc", readOnly: false, allowDangerousSql: false }]);
+ await h.choose("data-mcp-database-level", "abc", "inherit");
+ expect(h.changes.mock.lastCall![0].databasePolicies).toEqual([]);
+ await h.mounted.setProps({ inheritedLabel: "Full access · Connection" });
+ expect(hostText(h.get("data-mcp-database-parent-draft"))).toContain("Read only · Group");
+ expect(h.get("data-mcp-database-level", "abc").props["aria-description"]).toContain("Full access · Connection");
+ h.mounted.unmount();
+ });
+ it("confirms removal of overrides, supports cancelling, and removing the last database denies access", async () => {
+ const h = mountDialog({ value: { ...selected(["aaa"]), databasePolicies: [{ databaseName: "aaa", readOnly: true, allowDangerousSql: false }] } });
+ await settle();
+ await h.check("right:aaa");
+ await h.click("data-mcp-database-remove");
+ expect(h.changes).not.toHaveBeenCalled();
+ await h.click("data-mcp-database-confirm-cancel");
+ await h.check("right:aaa");
+ await h.click("data-mcp-database-remove");
+ await h.click("data-mcp-database-confirm");
+ expect(h.changes).toHaveBeenLastCalledWith(selected([]));
+ expect(hostText(h.mounted.root)).toContain("settings.mcpDatabaseNoneHint");
+ h.mounted.unmount();
+ });
+ it("confirms full access and clears overrides only after confirming an all-databases scope", async () => {
+ const h = mountDialog({ value: selected(["aaa"]) });
+ await settle();
+ await h.choose("data-mcp-database-level", "aaa", "high_risk_write");
+ expect(h.changes).not.toHaveBeenCalled();
+ await h.click("data-mcp-database-confirm");
+ expect(h.changes.mock.lastCall![0].databasePolicies[0].allowDangerousSql).toBe(true);
+ await h.choose("data-mcp-database-mode", undefined, "all");
+ await h.click("data-mcp-database-confirm");
+ expect(h.changes).toHaveBeenLastCalledWith(databaseAccess());
+ expect(hostText(h.mounted.root)).toContain("settings.mcpDatabaseAllHint");
+ h.mounted.unmount();
+ });
+ it("searches the entire discovered list beyond the render limit and adds every matching result", async () => {
+ const names = Array.from({ length: 260 }, (_, i) => `db_${String(i).padStart(3, "0")}`);
+ const load = vi.fn(async () => names);
+ const h = mountDialog({ loadDatabases: load });
+ await settle();
+ expect(findAll(h.get("data-mcp-database-pane", "left"), (n) => n.props["data-mcp-database-name"] !== undefined)).toHaveLength(100);
+ await h.click("data-mcp-database-more");
+ expect(findAll(h.get("data-mcp-database-pane", "left"), (n) => n.props["data-mcp-database-name"] !== undefined)).toHaveLength(200);
+ await h.search("left", "db_25");
+ dispatch(h.get("data-mcp-database-check-results", "left"), "change", { target: { checked: true } });
+ await nextTick();
+ await h.click("data-mcp-database-add");
+ expect(h.changes.mock.lastCall![0].allowedDatabases).toEqual(names.slice(250));
+ await h.search("left", "");
+ dispatch(h.get("data-mcp-database-check-results", "left"), "change", { target: { checked: true } });
+ await nextTick();
+ await h.click("data-mcp-database-add");
+ expect(h.changes.mock.lastCall![0].allowedDatabases).toEqual(names);
+ expect(h.changes.mock.lastCall![0].databaseScope).toBe("selected");
+ expect(load).toHaveBeenCalledOnce();
+ h.mounted.unmount();
+ });
+ it("retries failed discovery, preserves configured names and allows manual addition", async () => {
+ const load = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(["aaa", "aaa", "abc"]);
+ const h = mountDialog({ value: selected(["missing"]), loadDatabases: load });
+ await settle();
+ expect(hostText(h.mounted.root)).toContain("offline");
+ expect(hostText(h.get("data-mcp-database-pane", "right"))).toContain("missing");
+ h.get("data-mcp-database-manual").props["onUpdate:modelValue"]("new_db");
+ await nextTick();
+ await h.click("data-mcp-database-manual-add");
+ await h.click("data-mcp-database-refresh");
+ await settle();
+ expect(h.changes.mock.lastCall![0].allowedDatabases).toEqual(["missing", "new_db"]);
+ expect(h.get("data-mcp-database-level", "missing").props["aria-description"]).toContain("settings.mcpDatabaseNotDiscovered");
+ expect(findAll(h.get("data-mcp-database-pane", "left"), (n) => n.props["data-mcp-database-name"] !== undefined)).toHaveLength(2);
+ h.mounted.unmount();
+ });
+ it("sets permissions only for checked databases, restores inheritance, and keeps individual editing", async () => {
+ const save = vi.fn();
+ const initial = { ...selected(["aaa", "abc", "ops"]), databasePolicies: [{ databaseName: "ops", readOnly: true, allowDangerousSql: false }] };
+ const h = mountDialog({ value: initial, savedValue: initial, save });
+ await settle();
+ expect(h.select("data-mcp-database-batch-level").props.disabled).toBe(true);
+ await h.choose("data-mcp-database-batch-level", undefined, "safe_write");
+ expect(h.changes).not.toHaveBeenCalled();
+ await h.check("right:aaa");
+ await h.check("right:abc");
+ expect(h.get("data-mcp-database-batch-level").props["aria-label"]).toContain('"count":2');
+ for (const setting of ["read_only", "safe_write", "inherit"]) {
+ await h.choose("data-mcp-database-batch-level", undefined, setting);
+ expect(h.changes.mock.lastCall![0]).toEqual({
+ ...initial,
+ databasePolicies: [...(setting === "inherit" ? [] : ["aaa", "abc"].map((databaseName) => ({ databaseName, readOnly: setting === "read_only", allowDangerousSql: false }))), ...initial.databasePolicies],
+ });
+ }
+ await h.choose("data-mcp-database-level", "abc", "read_only");
+ expect(h.changes.mock.lastCall![0].databasePolicies).toEqual([{ databaseName: "abc", readOnly: true, allowDangerousSql: false }, ...initial.databasePolicies]);
+ await h.choose("data-mcp-database-batch-level", undefined, "inherit");
+ expect(h.changes.mock.lastCall![0]).toEqual(initial);
+ expect(save).not.toHaveBeenCalled();
+ h.mounted.unmount();
+ });
+ it("confirms a batch of full-access changes once and can cancel it", async () => {
+ const h = mountDialog({ value: selected(["aaa", "abc", "ops"]) });
+ await settle();
+ await h.check("right:aaa");
+ await h.check("right:abc");
+ await h.choose("data-mcp-database-batch-level", undefined, "high_risk_write");
+ expect(h.changes).not.toHaveBeenCalled();
+ expect(hostText(h.mounted.root)).toContain('settings.mcpDatabaseBatchHighRiskConfirm {"count":2}');
+ expect(h.select("data-mcp-database-batch-level").props.disabled).toBe(true);
+ await h.choose("data-mcp-database-batch-level", undefined, "read_only");
+ await h.choose("data-mcp-database-level", "ops", "safe_write");
+ expect(h.changes).not.toHaveBeenCalled();
+ await h.click("data-mcp-database-confirm-cancel");
+ expect(h.changes).not.toHaveBeenCalled();
+ await h.choose("data-mcp-database-batch-level", undefined, "high_risk_write");
+ await h.click("data-mcp-database-confirm");
+ expect(h.changes).toHaveBeenCalledOnce();
+ expect(h.changes.mock.lastCall![0]).toEqual({ ...selected(["aaa", "abc", "ops"]), databasePolicies: ["aaa", "abc"].map((databaseName) => ({ databaseName, readOnly: false, allowDangerousSql: true })) });
+ await h.choose("data-mcp-database-batch-level", undefined, "high_risk_write");
+ expect(h.changes).toHaveBeenCalledOnce();
+ expect(findAll(h.mounted.root, (node) => node.props["data-mcp-database-confirm"] !== undefined)).toHaveLength(0);
+ h.mounted.unmount();
+ });
+ it("updates every checked search result beyond the render limit and clears checks when searching", async () => {
+ const names = Array.from({ length: 260 }, (_, i) => `db_${String(i).padStart(3, "0")}`);
+ const h = mountDialog({ value: selected([...names, "other"]), loadDatabases: async () => [...names, "other"] });
+ await settle();
+ await h.search("right", "db_");
+ dispatch(h.get("data-mcp-database-check-results", "right"), "change", { target: { checked: true } });
+ await nextTick();
+ expect(findAll(h.get("data-mcp-database-pane", "right"), (n) => n.props["data-mcp-database-name"] !== undefined)).toHaveLength(100);
+ expect(h.get("data-mcp-database-batch-level").props["aria-label"]).toContain('"count":260');
+ await h.choose("data-mcp-database-batch-level", undefined, "read_only");
+ expect(h.changes.mock.lastCall![0]).toEqual({ ...selected([...names, "other"]), databasePolicies: names.map((databaseName) => ({ databaseName, readOnly: true, allowDangerousSql: false })) });
+ await h.search("right", "other");
+ expect(h.select("data-mcp-database-batch-level").props.disabled).toBe(true);
+ await h.choose("data-mcp-database-batch-level", undefined, "safe_write");
+ expect(h.changes).toHaveBeenCalledOnce();
+ h.mounted.unmount();
+ });
+ it("ignores stale checks after a database is removed and disables batch edits when locked", async () => {
+ const h = mountDialog({ value: selected(["aaa", "abc"]) });
+ await settle();
+ await h.check("right:aaa");
+ await h.check("right:abc");
+ await h.mounted.setProps({ value: selected(["abc"]) });
+ expect(h.get("data-mcp-database-batch-level").props["aria-label"]).toContain('"count":1');
+ await h.mounted.setProps({ disabled: true });
+ expect(h.select("data-mcp-database-batch-level").props.disabled).toBe(true);
+ await h.choose("data-mcp-database-batch-level", undefined, "read_only");
+ expect(h.changes).not.toHaveBeenCalled();
+ await h.mounted.setProps({ disabled: false });
+ await h.choose("data-mcp-database-batch-level", undefined, "read_only");
+ expect(h.changes).toHaveBeenLastCalledWith({ ...selected(["abc"]), databasePolicies: [{ databaseName: "abc", readOnly: true, allowDangerousSql: false }] });
+ h.mounted.unmount();
+ });
+ it("preserves searches, checked databases and pending confirmation when connection metadata refreshes", async () => {
+ const load = vi.fn(async () => ["aaa", "abc", "ops"]);
+ const h = mountDialog({ value: selected(["aaa", "abc", "ops"]), loadDatabases: load });
+ await settle();
+ await h.search("right", "a");
+ await h.check("right:aaa");
+ await h.check("right:abc");
+ await h.choose("data-mcp-database-batch-level", undefined, "high_risk_write");
+ await h.mounted.setProps({ connection: { id: "c1", name: "Updated Local", db_type: "mysql" } });
+ await settle();
+ expect(h.get("data-mcp-database-search", "right").props["model-value"]).toBe("a");
+ expect(h.get("data-mcp-database-check", "right:aaa").props.checked).toBe(true);
+ expect(h.get("data-mcp-database-check", "right:abc").props.checked).toBe(true);
+ expect(load).toHaveBeenCalledOnce();
+ await h.click("data-mcp-database-confirm");
+ expect(h.changes.mock.lastCall![0].databasePolicies).toHaveLength(2);
+ h.mounted.unmount();
+ });
+ it("ignores an old discovery after closing and reopening", async () => {
+ let resolveOld!: (names: string[]) => void;
+ const load = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<string[]>((resolve) => {
+ resolveOld = resolve;
+ }),
+ )
+ .mockResolvedValueOnce(["fresh"]);
+ const h = mountDialog({ loadDatabases: load });
+ await settle();
+ await h.click("data-mcp-database-close");
+ await h.mounted.setProps({ open: true });
+ await settle();
+ resolveOld(["stale"]);
+ await settle();
+ expect(hostText(h.mounted.root)).toContain("fresh");
+ expect(hostText(h.mounted.root)).not.toContain("stale");
+ h.mounted.unmount();
+ });
+ it("retains the draft on save failure, retries successfully and stays open", async () => {
+ const save = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("disk full"))
+ .mockImplementationOnce(async () => {
+ await h.mounted.setProps({ savedValue: selected(["aaa"]) });
+ });
+ const h = mountDialog({ value: selected(["aaa"]), save });
+ await settle();
+ await h.click("data-mcp-database-apply");
+ await settle();
+ expect(hostText(h.mounted.root)).toContain("disk full");
+ expect(h.get("data-mcp-database-apply").props.disabled).toBe(false);
+ expect(h.changes).not.toHaveBeenCalled();
+ await h.click("data-mcp-database-apply");
+ await settle();
+ expect(save).toHaveBeenCalledTimes(2);
+ expect(save).toHaveBeenLastCalledWith("c1");
+ expect(h.get("data-mcp-database-apply").props.disabled).toBe(true);
+ expect(hostText(h.mounted.root)).toContain("settings.mcpToolsetApplied");
+ expect(hostText(h.mounted.root)).not.toContain("disk full");
+ h.mounted.unmount();
+ });
+ it.each(["data-mcp-database-close", "data-dialog-dismiss"])("keeps selections and overrides when closing with %s", async (button) => {
+ const save = vi.fn();
+ const h = mountDialog({ save });
+ await settle();
+ await h.check("left:aaa");
+ await h.click("data-mcp-database-add");
+ await h.choose("data-mcp-database-level", "aaa", "read_only");
+ await h.click(button);
+ await h.mounted.setProps({ open: true });
+ await settle();
+ expect(hostText(h.get("data-mcp-database-pane", "right"))).toContain("aaa");
+ expect(h.changes.mock.lastCall![0].databasePolicies[0].readOnly).toBe(true);
+ expect(save).not.toHaveBeenCalled();
+ h.mounted.unmount();
+ });
+ it("locks changes and dismissal while saving and prevents duplicate submissions", async () => {
+ let finish!: () => void;
+ const save = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const h = mountDialog({ value: selected(["aaa"]), save });
+ await settle();
+ await h.check("right:aaa");
+ await h.click("data-mcp-database-apply");
+ expect(h.get("data-mcp-database-close").props.disabled).toBe(true);
+ expect(h.select("data-mcp-database-batch-level").props.disabled).toBe(true);
+ await h.choose("data-mcp-database-batch-level", undefined, "safe_write");
+ const event = new Event("keydown", { cancelable: true });
+ h.get("data-mcp-database-dialog").props.onEscapeKeyDown(event);
+ expect(event.defaultPrevented).toBe(true);
+ await h.click("data-dialog-dismiss");
+ expect(h.get("data-mcp-database-dialog")).toBeDefined();
+ await h.choose("data-mcp-database-level", "aaa", "read_only");
+ expect(h.changes).not.toHaveBeenCalled();
+ await h.click("data-mcp-database-apply");
+ expect(save).toHaveBeenCalledOnce();
+ finish();
+ await settle();
+ h.mounted.unmount();
+ });
+});
+
+it("restores the selected draft after an accidental all or none toggle", async () => {
+ const h = mountDialog({ value: selected(["aaa", "ops"]) });
+ await settle();
+ for (const scope of ["all", "none"]) {
+ await h.choose("data-mcp-database-mode", undefined, scope);
+ expect(h.changes.mock.lastCall![0].allowedDatabases).toEqual([]);
+ await h.choose("data-mcp-database-mode", undefined, "selected");
+ expect(h.changes).toHaveBeenLastCalledWith(selected(["aaa", "ops"]));
+ }
+ h.mounted.unmount();
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpDatabaseScopePicker.spec.ts b/apps/desktop/src/components/settings/__tests__/McpDatabaseScopePicker.spec.ts
deleted file mode 100644
index c43468f923..0000000000
--- a/apps/desktop/src/components/settings/__tests__/McpDatabaseScopePicker.spec.ts
+++ /dev/null
@@ -1,260 +0,0 @@
-// @vitest-environment happy-dom
-// MCP 数据库范围选择器回归测试:
-// 加载资源列表前先 ensureConnected(修复未连接的 SQL 连接报 Connection not found)。
-// 1) 正常流程:选择“仅指定数据库”→ 手工添加库名 → emit 携带 allowedDatabases。
-// 2) busy/disabled 期间手工添加被整体拦截,库名不再进入本地列表(修复静默丢失)。
-// 3) 重开对话框后已持久化的 allowedDatabases 重新显示并勾选(修复不回显)。
-
-import { createApp, nextTick, type App } from "vue";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-const mocks = vi.hoisted(() => ({
- listDatabases: vi.fn(),
- mongoListDatabases: vi.fn(),
- redisListDatabases: vi.fn(),
- ensureConnected: vi.fn(),
-}));
-
-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string, params?: Record<string, unknown>) => (params?.error === undefined ? key : `${key}:${String(params.error)}`) }) }));
-vi.mock("@/lib/backend/api", () => ({
- listDatabases: mocks.listDatabases,
- mongoListDatabases: mocks.mongoListDatabases,
- redisListDatabases: mocks.redisListDatabases,
-}));
-vi.mock("@/stores/connectionStore", () => ({
- useConnectionStore: () => ({ ensureConnected: mocks.ensureConnected }),
-}));
-vi.mock("@lucide/vue", async () => {
- const { defineComponent, h } = await import("vue");
- const Icon = defineComponent({ setup: () => () => h("i") });
- return { Check: Icon, ChevronLeft: Icon, ChevronRight: Icon, Loader2: Icon, Plus: Icon, RefreshCw: Icon, Search: Icon };
-});
-
-async function passthroughComponent() {
- const { defineComponent, h } = await import("vue");
- return defineComponent({
- inheritAttrs: false,
- setup:
- (_, { slots, attrs }) =>
- () =>
- h("div", { ...attrs }, slots.default?.()),
- });
-}
-vi.mock("@/components/ui/button", async () => ({ Button: await passthroughComponent() }));
-vi.mock("@/components/ui/badge", async () => ({ Badge: await passthroughComponent() }));
-vi.mock("@/components/ui/select", async () => ({
- Select: await passthroughComponent(),
- SelectContent: await passthroughComponent(),
- SelectItem: await passthroughComponent(),
- SelectTrigger: await passthroughComponent(),
- SelectValue: await passthroughComponent(),
-}));
-vi.mock("@/components/ui/input", async () => {
- const { defineComponent, h } = await import("vue");
- const Input = defineComponent({
- props: ["modelValue"],
- emits: ["update:modelValue"],
- setup:
- (props, { emit, attrs }) =>
- () =>
- h("input", {
- ...attrs,
- value: props.modelValue,
- onInput: (e: Event) => emit("update:modelValue", (e.target as HTMLInputElement).value),
- onKeydown: (e: KeyboardEvent) => {
- if (e.key === "Enter") {
- e.preventDefault();
- attrs.onKeydownEnter?.(e);
- }
- },
- }),
- });
- return { Input };
-});
-
-import McpDatabaseScopePicker from "@/components/settings/McpDatabaseScopePicker.vue";
-import type { McpConnectionPolicy } from "@/stores/settingsStore";
-import type { ConnectionConfig } from "@/types/database";
-
-function fakeConnection(id: string): ConnectionConfig {
- return { id, name: `conn-${id}`, db_type: "oracle" } as unknown as ConnectionConfig;
-}
-
-function emptyPolicy(connectionId: string, scope: McpConnectionPolicy["databaseScope"] = "all"): McpConnectionPolicy {
- return {
- connectionId,
- readOnly: false,
- allowDangerousSql: false,
- executionModeConfigured: false,
- executionModePolicyVersion: null,
- databaseScope: scope,
- allowedDatabases: [],
- databasePolicies: [],
- allowSalesforceDml: false,
- };
-}
-
-function mountHarness(policies: McpConnectionPolicy[], disabled = false) {
- const root = document.createElement("div");
- document.body.appendChild(root);
- const emitted = { policies: [] as McpConnectionPolicy[][] };
- const app = createApp(McpDatabaseScopePicker, {
- connections: [fakeConnection("oracle-1")],
- allowedConnectionIds: null,
- connectionPolicies: policies,
- disabled,
- busy: false,
- "onUpdate:connectionPolicies": (next: McpConnectionPolicy[]) => emitted.policies.push(next),
- });
- app.mount(root);
- harness = { app, root };
- return { app, emitted, root };
-}
-
-let harness: { app: App<Element>; root: HTMLElement } | null = null;
-
-beforeEach(() => {
- mocks.ensureConnected.mockReset().mockResolvedValue(undefined);
- mocks.listDatabases.mockReset().mockResolvedValue([{ name: "LOADED_DB" }]);
-});
-afterEach(() => {
- harness?.app?.unmount();
- harness = null;
- document.body.innerHTML = "";
-});
-
-function clickScopeRadio(root: HTMLElement, scope: string) {
- const radio = Array.from(root.querySelectorAll("[data-database-scope]")).find((el) => el.getAttribute("data-database-scope") === scope);
- if (!radio) throw new Error(`scope radio ${scope} not found`);
- radio.dispatchEvent(new MouseEvent("click"));
-}
-
-function manualInput(root: HTMLElement): HTMLInputElement {
- const input = Array.from(root.querySelectorAll("input")).find((i) => i.placeholder === "settings.mcpDatabaseManualPlaceholder");
- if (!input) throw new Error("manual input not found");
- return input as HTMLInputElement;
-}
-
-function loadButton(root: HTMLElement): HTMLElement {
- const candidates = Array.from(root.querySelectorAll("div,button")).filter((el) => el.textContent?.includes("settings.mcpDatabaseLoadButton"));
- const deepest = candidates.at(-1);
- if (!deepest) throw new Error("load button not found");
- return deepest as HTMLElement;
-}
-
-function addManualDatabase(root: HTMLElement, name: string) {
- const input = manualInput(root);
- input.value = name;
- input.dispatchEvent(new Event("input"));
- return nextTick().then(() => {
- input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter" }));
- return nextTick();
- });
-}
-
-describe("McpDatabaseScopePicker", () => {
- it("加载资源列表前先 ensureConnected(不激活侧边栏),未连接的 SQL 连接不再直接调 listDatabases", async () => {
- mocks.listDatabases.mockResolvedValue([{ name: "ORCL" }]);
- const first = mountHarness([]);
- await nextTick();
- clickScopeRadio(first.root, "selected");
- await nextTick();
- first.app.unmount();
- harness = null;
-
- const second = mountHarness([emptyPolicy("oracle-1", "selected")]);
- await nextTick();
- loadButton(second.root).click();
- await new Promise((r) => setTimeout(r, 10));
- await nextTick();
-
- expect(mocks.ensureConnected).toHaveBeenCalledWith("oracle-1", { activate: false });
- // ensureConnected 成功后加载数据库列表
- expect(mocks.listDatabases).toHaveBeenCalledWith("oracle-1");
- expect(second.root.textContent).toContain("ORCL");
- });
-
- it("加载失败时 ensureConnected 的连接错误透传到错误提示", async () => {
- mocks.ensureConnected.mockRejectedValue(new Error("ORA-12170: 连接超时"));
- const first = mountHarness([]);
- await nextTick();
- clickScopeRadio(first.root, "selected");
- await nextTick();
- first.app.unmount();
- harness = null;
-
- const second = mountHarness([emptyPolicy("oracle-1", "selected")]);
- await nextTick();
- loadButton(second.root).click();
- await new Promise((r) => setTimeout(r, 10));
- await nextTick();
-
- expect(second.root.textContent).toContain("settings.mcpDatabaseLoadFailed");
- expect(second.root.textContent).toContain("ORA-12170");
- expect(mocks.listDatabases).not.toHaveBeenCalled();
- });
-
- it("正常流程:选择 selected 后手工添加库名应 emit 携带 allowedDatabases", async () => {
- // 阶段一:初始无策略,点击“仅指定数据库”
- const first = mountHarness([]);
- await nextTick();
- clickScopeRadio(first.root, "selected");
- await nextTick();
- expect(first.emitted.policies.length).toBe(1);
- expect(first.emitted.policies[0][0].databaseScope).toBe("selected");
- first.app.unmount();
- harness = null;
-
- // 阶段二:模拟父组件 store 已回写 scope=selected,再手工添加库名
- const second = mountHarness([emptyPolicy("oracle-1", "selected")]);
- await nextTick();
- await addManualDatabase(second.root, "mydb");
-
- expect(second.emitted.policies.length).toBe(1);
- const policy = second.emitted.policies[0][0];
- expect(policy.databaseScope).toBe("selected");
- expect(policy.allowedDatabases).toEqual(["mydb"]);
- });
-
- it("竞态场景:disabled 期间手工添加被整体拦截,库名不再进入本地列表", async () => {
- const { emitted, root } = mountHarness([emptyPolicy("oracle-1", "selected")], true);
- await nextTick();
- await addManualDatabase(root, "mydb");
-
- expect(emitted.policies.length).toBe(0);
- expect(root.textContent).not.toContain("mydb");
- // 手工输入框本身也应被禁用
- expect(manualInput(root).hasAttribute("disabled")).toBe(true);
- });
-
- it("重开对话框场景:已持久化的 allowedDatabases 重新显示在列表中并处于勾选状态", async () => {
- // 模拟:策略已保存 scope=selected + allowedDatabases=["SAVEDDB"],加载缓存为空(新会话)
- const policy: McpConnectionPolicy = { ...emptyPolicy("oracle-1", "selected"), allowedDatabases: ["SAVEDDB"] };
- const { root } = mountHarness([policy]);
- await nextTick();
-
- expect(root.textContent).toContain("SAVEDDB");
- expect(root.textContent).not.toContain("settings.mcpDatabaseEmptyHint");
- const checkbox = Array.from(root.querySelectorAll('input[type="checkbox"]')).find((i) => i.value === "SAVEDDB" || i.closest("label")?.textContent?.includes("SAVEDDB"));
- expect(checkbox?.checked).toBe(true);
- });
-
- it("加载列表与已持久化库名取并集:手工添加过但服务器上不存在的库名仍可见", async () => {
- mocks.listDatabases.mockResolvedValue([{ name: "SERVER_DB" }]);
- const first = mountHarness([]);
- await nextTick();
- clickScopeRadio(first.root, "selected");
- await nextTick();
- first.app.unmount();
- harness = null;
-
- const second = mountHarness([{ ...emptyPolicy("oracle-1", "selected"), allowedDatabases: ["MANUAL_DB"] }]);
- await nextTick();
- loadButton(second.root).click();
- await new Promise((r) => setTimeout(r, 10));
- await nextTick();
-
- expect(second.root.textContent).toContain("SERVER_DB");
- expect(second.root.textContent).toContain("MANUAL_DB");
- });
-});
diff --git a/apps/desktop/src/components/settings/__tests__/McpDefaultAccessPanel.spec.ts b/apps/desktop/src/components/settings/__tests__/McpDefaultAccessPanel.spec.ts
new file mode 100644
index 0000000000..338c7de0d8
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpDefaultAccessPanel.spec.ts
@@ -0,0 +1,151 @@
+// @vitest-environment happy-dom
+
+import { createApp, h, nextTick, reactive } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import McpDefaultAccessPanel from "../McpDefaultAccessPanel.vue";
+import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
+import type { McpExecutionMode } from "@/lib/mcp/mcpPolicySelection";
+
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: (sql: string) => sql }) }));
+
+const cleanup: Array<() => void> = [];
+afterEach(() => cleanup.splice(0).forEach((unmount) => unmount()));
+
+function mountPanel(initial: { mode?: McpExecutionMode; disabled?: boolean; acceptMode?: boolean } = {}) {
+ const props = reactive({ mode: initial.mode ?? "read_only", disabled: initial.disabled ?? false });
+ const setMode = vi.fn((mode: McpExecutionMode) => {
+ if (initial.acceptMode !== false) props.mode = mode;
+ });
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp({ render: () => h(McpDefaultAccessPanel, { ...props, "onSet:mode": setMode }) });
+ app.mount(root);
+ cleanup.push(() => {
+ app.unmount();
+ root.remove();
+ });
+ const radio = (mode: McpExecutionMode) => root.querySelector<HTMLButtonElement>(`[data-mcp-execution-mode="${mode}"]`)!;
+ return { root, props, setMode, radio };
+}
+
+describe("McpDefaultAccessPanel", () => {
+ it("shows three permissions and starts with the explanation table collapsed", () => {
+ const { root, radio } = mountPanel();
+ expect(root.querySelectorAll('[role="radio"]')).toHaveLength(3);
+ expect(radio("read_only").getAttribute("aria-checked")).toBe("true");
+ expect(radio("read_only").tabIndex).toBe(0);
+ expect(radio("safe_write").tabIndex).toBe(-1);
+ expect(root.querySelector<HTMLDetailsElement>("[data-mcp-permission-help]")!.open).toBe(false);
+ expect(root.querySelector("[data-mcp-high-risk-confirmation]")).toBeNull();
+ });
+
+ it("updates permissions without exposing call-safety controls in the default panel", async () => {
+ const { root, radio, setMode } = mountPanel();
+ radio("safe_write").click();
+ await nextTick();
+ expect(setMode).toHaveBeenCalledExactlyOnceWith("safe_write");
+ expect(radio("safe_write").getAttribute("aria-checked")).toBe("true");
+ expect(root.querySelector("[data-mcp-mode-description]")!.textContent).toContain("settings.mcpExecutionModeSafeWriteDescription");
+ expect(root.querySelector("[data-mcp-high-risk-confirmation]")).toBeNull();
+ });
+
+ it("explains that creating connections allows data-write access but removal requires full access", async () => {
+ const { root } = mountPanel({ mode: "safe_write" });
+ root.querySelector<HTMLElement>("[data-mcp-permission-help] summary")!.click();
+ await nextTick();
+ const rows = Array.from(root.querySelectorAll("tbody tr"));
+ const permissions = (label: string) => {
+ const row = rows.find((candidate) => candidate.querySelector("th")?.textContent === label)!;
+ return Array.from(row.querySelectorAll("td")).map((cell) => cell.textContent?.trim());
+ };
+ expect(permissions("settings.mcpCapabilityConnectionCreate")).toEqual(["settings.mcpCapabilityBlocked", "settings.mcpCapabilityAllowed", "settings.mcpCapabilityAllowed"]);
+ expect(permissions("settings.mcpCapabilityConnectionRemove")).toEqual(["settings.mcpCapabilityBlocked", "settings.mcpCapabilityBlocked", "settings.mcpCapabilityAllowed"]);
+ });
+
+ it("supports arrow, Home and End navigation with focus on the selected radio", async () => {
+ const { radio } = mountPanel();
+ for (const [from, key, to] of [
+ ["read_only", "ArrowRight", "safe_write"],
+ ["safe_write", "End", "high_risk_write"],
+ ["high_risk_write", "ArrowRight", "read_only"],
+ ["read_only", "ArrowLeft", "high_risk_write"],
+ ["high_risk_write", "Home", "read_only"],
+ ] as const) {
+ radio(from).focus();
+ radio(from).dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
+ await nextTick();
+ expect(document.activeElement).toBe(radio(to));
+ expect(radio(to).getAttribute("aria-checked")).toBe("true");
+ expect(radio(to).tabIndex).toBe(0);
+ }
+ });
+
+ it("keeps focus and selection when the parent cancels the full-access change", async () => {
+ const { radio, setMode } = mountPanel({ mode: "safe_write", acceptMode: false });
+ radio("safe_write").focus();
+ radio("safe_write").dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
+ await nextTick();
+ expect(setMode).toHaveBeenCalledExactlyOnceWith("high_risk_write");
+ expect(radio("safe_write").getAttribute("aria-checked")).toBe("true");
+ expect(document.activeElement).toBe(radio("safe_write"));
+ });
+
+ it("moves keyboard focus into the real confirmation dialog and preserves selection on cancellation", async () => {
+ const state = reactive({ mode: "safe_write" as McpExecutionMode, pending: false });
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp({
+ render: () =>
+ h("div", [
+ h(McpDefaultAccessPanel, {
+ mode: state.mode,
+ "onSet:mode": (mode) => {
+ if (mode === "high_risk_write") state.pending = true;
+ else state.mode = mode;
+ },
+ }),
+ h(DangerConfirmDialog, {
+ open: state.pending,
+ initialFocus: "cancel",
+ closeOnConfirm: false,
+ "onUpdate:open": (open) => {
+ state.pending = open;
+ },
+ onConfirm: () => {
+ state.pending = false;
+ state.mode = "high_risk_write";
+ },
+ }),
+ ]),
+ });
+ app.mount(root);
+ cleanup.push(() => {
+ app.unmount();
+ root.remove();
+ });
+ const radio = root.querySelector<HTMLButtonElement>('[data-mcp-execution-mode="safe_write"]')!;
+ radio.focus();
+ radio.dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true, cancelable: true }));
+ await vi.waitFor(() => expect(document.activeElement?.textContent).toBe("dangerDialog.cancel"));
+ expect(state.mode).toBe("safe_write");
+ (document.activeElement as HTMLButtonElement).click();
+ await vi.waitFor(() => expect(state.pending).toBe(false));
+ expect(radio.getAttribute("aria-checked")).toBe("true");
+ await vi.waitFor(() => expect(document.activeElement).toBe(radio));
+ radio.dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true, cancelable: true }));
+ await vi.waitFor(() => expect(document.activeElement?.textContent).toBe("dangerDialog.cancel"));
+ const confirm = Array.from(document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')).find((button) => button.textContent?.trim() === "dangerDialog.confirm")!;
+ confirm.click();
+ await vi.waitFor(() => expect(state.mode).toBe("high_risk_write"));
+ });
+
+ it("disables edits while settings are loading or saving", async () => {
+ const { radio, setMode } = mountPanel({ mode: "safe_write", disabled: true });
+ expect(radio("read_only").disabled).toBe(true);
+ radio("read_only").click();
+ radio("safe_write").dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
+ await nextTick();
+ expect(setMode).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpPluginCapabilities.spec.ts b/apps/desktop/src/components/settings/__tests__/McpPluginCapabilities.spec.ts
new file mode 100644
index 0000000000..5ee937d0c3
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpPluginCapabilities.spec.ts
@@ -0,0 +1,510 @@
+// @vitest-environment happy-dom
+
+import { nextTick } from "vue";
+import { describe, expect, it, vi } from "vitest";
+import { dispatch, findAll, findOne, hostText, mountComponent } from "@/components/grid/__tests__/vueHostHarness";
+import type { PluginMcpToolView, PluginMcpView } from "@/types/mcpCatalog";
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({
+ t: (key: string, values?: Record<string, unknown>) => `${key}${values ? ` ${JSON.stringify(values)}` : ""}`,
+ }),
+}));
+
+vi.mock("@lucide/vue", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const icon = createPassthroughStub("Icon", "i");
+ return { AlertTriangle: icon, ChevronDown: icon, ChevronRight: icon, Loader2: icon, Puzzle: icon, RefreshCw: icon };
+});
+
+vi.mock("@/components/ui/button", async () => ({ Button: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Button", "button") }));
+vi.mock("@/components/ui/switch", async () => ({ Switch: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Switch", "button") }));
+vi.mock("@/components/ui/dialog", async () => {
+ const { defineComponent, h } = await import("vue");
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ return {
+ Dialog: defineComponent({
+ name: "Dialog",
+ props: { open: Boolean },
+ setup(props, { slots }) {
+ return () => (props.open ? h("div", { "data-stub": "Dialog" }, slots.default?.()) : null);
+ },
+ }),
+ DialogContent: createPassthroughStub("DialogContent", "div"),
+ DialogDescription: createPassthroughStub("DialogDescription", "p"),
+ DialogHeader: createPassthroughStub("DialogHeader", "div"),
+ DialogTitle: createPassthroughStub("DialogTitle", "h2"),
+ };
+});
+
+import McpPluginCapabilities from "@/components/settings/McpPluginCapabilities.vue";
+
+function tool(name: string, access: PluginMcpToolView["access"], exposure: PluginMcpToolView["exposure"] = "exposed"): PluginMcpToolView {
+ return {
+ name,
+ description: `${name} description`,
+ toolset: "default",
+ access,
+ exposure,
+ parameters: name === "list_dir" ? [{ name: "path", valueType: "string", required: true, description: "Absolute path" }] : [],
+ };
+}
+
+function plugin(patch: Partial<PluginMcpView> = {}): PluginMcpView {
+ return {
+ pluginId: "io.dbx.ssh",
+ pluginName: "Terminal",
+ version: "1.4.0",
+ authorAllowsExternal: true,
+ hasSavedGrant: true,
+ grant: { external: true, ceiling: "write", approvedTools: { list_dir: "read", upload: "write" }, disabledTools: [] },
+ toolsets: [{ id: "default", title: null, description: null }],
+ tools: [tool("list_dir", "read"), tool("upload", "write"), tool("exec", "full", "aboveCeiling")],
+ discoveryError: null,
+ ...patch,
+ };
+}
+
+function mountCards(plugins: PluginMcpView[], save = vi.fn(async (pluginId: string) => plugins.find((entry) => entry.pluginId === pluginId)!), props: Record<string, unknown> = {}) {
+ const saved = vi.fn();
+ const refresh = vi.fn();
+ const mounted = mountComponent(McpPluginCapabilities, { plugins, save, onSaved: saved, onRefresh: refresh, ...props });
+ return { mounted, save, saved, refresh };
+}
+
+function cardSwitch(root: ReturnType<typeof mountComponent>["root"], pluginId: string) {
+ const card = findOne(root, (node) => node.props["data-mcp-plugin"] === pluginId);
+ return findAll(card, (node) => node.props["data-stub"] === "Switch").at(-1)!;
+}
+
+function flip(node: ReturnType<typeof findOne>, value: boolean) {
+ (node.props["onUpdate:modelValue"] as (value: boolean) => void)(value);
+}
+
+describe("McpPluginCapabilities", () => {
+ it("summarizes each plugin card", () => {
+ const { mounted } = mountCards([plugin(), plugin({ pluginId: "io.vendor.k8s", pluginName: "Kubernetes", authorAllowsExternal: false, grant: { ...plugin().grant, external: false } })]);
+ const terminal = hostText(findOne(mounted.root, (node) => node.props["data-mcp-plugin"] === "io.dbx.ssh"));
+ expect(terminal).toContain('settings.mcpPluginToolCount {"exposed":2,"total":3}');
+ expect(terminal).toContain("settings.mcpPluginCeilingSummary");
+ const k8s = hostText(findOne(mounted.root, (node) => node.props["data-mcp-plugin"] === "io.vendor.k8s"));
+ expect(k8s).toContain("settings.mcpPluginAuthorClosed");
+ expect(cardSwitch(mounted.root, "io.vendor.k8s").props.disabled).toBe(true);
+ });
+
+ it("opens the authorization dialog on first enable and saves with approveCurrent", async () => {
+ const fresh = plugin({ hasSavedGrant: false, grant: { external: false, ceiling: "full", approvedTools: {}, disabledTools: [] }, tools: [tool("list_dir", "read", "pluginDisabled"), tool("exec", "full", "pluginDisabled")] });
+ const { mounted, save } = mountCards([fresh]);
+ flip(cardSwitch(mounted.root, "io.dbx.ssh"), true);
+ await nextTick();
+ expect(save).not.toHaveBeenCalled();
+ const dialog = findOne(mounted.root, (node) => node.props["data-mcp-plugin-authorize"] !== undefined);
+ expect(findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-level"] === "write").props["aria-pressed"]).toBe(true);
+ // Default ceiling caps at write, so exec (full) is shown as hidden.
+ expect(hostText(findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-tool"] === "exec"))).toContain("settings.mcpPluginAuthorizeExcluded");
+ dispatch(
+ findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-level"] === "full"),
+ "click",
+ );
+ await nextTick();
+ expect(findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-level"] === "full").props["aria-pressed"]).toBe(true);
+ expect(findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-level"] === "write").props["aria-pressed"]).toBe(false);
+ expect(hostText(findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-tool"] === "exec"))).toContain("settings.mcpPluginAuthorizeIncluded");
+ dispatch(
+ findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-confirm"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ expect(save).toHaveBeenCalledWith("io.dbx.ssh", { external: true, ceiling: "full", approvedTools: {}, disabledTools: [] }, true);
+ });
+
+ it("switches a reviewed plugin off and on without the dialog", async () => {
+ const { mounted, save } = mountCards([plugin()]);
+ flip(cardSwitch(mounted.root, "io.dbx.ssh"), false);
+ await nextTick();
+ expect(save).toHaveBeenCalledWith("io.dbx.ssh", { external: false, ceiling: "write", approvedTools: { list_dir: "read", upload: "write" }, disabledTools: [] }, false);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-authorize"] !== undefined)).toEqual([]);
+ });
+
+ it("flags pending tools and routes review through the dialog", async () => {
+ const pending = plugin({ tools: [tool("list_dir", "read"), tool("new_upload", "write", "pendingApproval")] });
+ const { mounted } = mountCards([pending]);
+ expect(hostText(mounted.root)).toContain('settings.mcpPluginPendingTools {"count":1}');
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-review"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ const dialog = findOne(mounted.root, (node) => node.props["data-mcp-plugin-authorize"] !== undefined);
+ expect(hostText(findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-tool"] === "new_upload"))).toContain("settings.mcpPluginExposure.pendingApproval");
+ });
+
+ it("edits ceiling and single tools in the detail and shows tool parameters", async () => {
+ const { mounted, save } = mountCards([plugin()]);
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-open"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-plugin-detail"] !== undefined);
+ expect(hostText(findOne(detail, (node) => node.props["data-mcp-plugin-tool"] === "exec"))).toContain("settings.mcpPluginExposure.aboveCeiling");
+
+ dispatch(
+ findOne(detail, (node) => node.props["data-mcp-plugin-ceiling-level"] === "full"),
+ "click",
+ );
+ await nextTick();
+ expect(save).toHaveBeenLastCalledWith("io.dbx.ssh", expect.objectContaining({ ceiling: "full" }), false);
+
+ const upload = findOne(detail, (node) => node.props["data-mcp-plugin-tool"] === "upload");
+ flip(
+ findOne(upload, (node) => node.props["data-stub"] === "Switch"),
+ false,
+ );
+ await nextTick();
+ expect(save).toHaveBeenLastCalledWith("io.dbx.ssh", expect.objectContaining({ disabledTools: ["upload"] }), false);
+
+ const listDir = findOne(detail, (node) => node.props["data-mcp-plugin-tool"] === "list_dir");
+ dispatch(
+ findOne(listDir, (node) => node.props["data-mcp-plugin-tool-toggle"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ const expanded = hostText(findOne(listDir, (node) => node.props["data-mcp-plugin-tool-detail"] !== undefined));
+ expect(expanded).toContain("Absolute path");
+ expect(expanded).toContain("settings.mcpAccessLevel.read");
+ });
+
+ it("reports save failures on the card list", async () => {
+ const save = vi.fn(async () => {
+ throw new Error("disk full");
+ });
+ const { mounted } = mountCards([plugin()], save);
+ flip(cardSwitch(mounted.root, "io.dbx.ssh"), false);
+ await nextTick();
+ await nextTick();
+ expect(hostText(findOne(mounted.root, (node) => node.props["data-mcp-plugin-save-error"] !== undefined))).toContain('settings.mcpPluginSaveFailed {"name":"Terminal","message":"disk full"}');
+ });
+
+ it("marks undeclared tools as never exposed and leaves them out of authorization", async () => {
+ const undeclared: PluginMcpToolView = { ...tool("raw_exec", "full", "undeclared"), access: null };
+ const fresh = plugin({ hasSavedGrant: false, grant: { external: false, ceiling: "read", approvedTools: {}, disabledTools: [] }, tools: [tool("list_dir", "read", "pluginDisabled"), undeclared] });
+ const { mounted } = mountCards([fresh]);
+ expect(hostText(findOne(mounted.root, (node) => node.props["data-mcp-plugin-undeclared"] !== undefined))).toContain('settings.mcpPluginUndeclaredCount {"count":1}');
+ flip(cardSwitch(mounted.root, "io.dbx.ssh"), true);
+ await nextTick();
+ const dialog = findOne(mounted.root, (node) => node.props["data-mcp-plugin-authorize"] !== undefined);
+ expect(findAll(dialog, (node) => node.props["data-mcp-plugin-authorize-tool"] === "raw_exec")).toEqual([]);
+ expect(hostText(findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-undeclared"] !== undefined))).toContain('"names":"raw_exec"');
+ });
+
+ it("shows the empty state", () => {
+ const { mounted } = mountCards([]);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugins-empty"] !== undefined)).toHaveLength(1);
+ });
+
+ it("renders the selected plugin controls inline without requiring the card dialog", () => {
+ const { mounted } = mountCards([plugin(), plugin({ pluginId: "io.vendor.other", pluginName: "Other plugin" })], undefined, { selectedPluginId: "io.dbx.ssh", search: "no matching tool" });
+ const inline = findOne(mounted.root, (node) => node.props["data-mcp-plugin-inline"] === "io.dbx.ssh");
+ expect(hostText(inline)).toContain("Terminal");
+ expect(hostText(inline)).toContain("settings.mcpBrowser.pluginImmediate");
+ expect(hostText(inline)).toContain("settings.mcpCapabilitiesFilterPlugin");
+ expect(hostText(mounted.root)).not.toContain("Other plugin");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-open"] !== undefined)).toHaveLength(0);
+ expect(findAll(mounted.root, (node) => node.props["data-stub"] === "Dialog")).toHaveLength(0);
+ expect(findAll(inline, (node) => node.props["data-mcp-plugin-tool"] !== undefined)).toHaveLength(3);
+ expect(findAll(inline, (node) => node.props["data-mcp-plugin-ceiling-level"] !== undefined)).toHaveLength(3);
+ expect(findOne(inline, (node) => node.props["data-mcp-plugin-ceiling-level"] === "write").props["aria-pressed"]).toBe(true);
+ expect(findOne(inline, (node) => node.props["data-mcp-plugin-ceiling-level"] === "read").props["aria-pressed"]).toBe(false);
+ expect(findOne(inline, (node) => node.props["data-mcp-plugin-master"] !== undefined).props["model-value"]).toBe(true);
+ });
+
+ it("keeps author-closed plugin details readable while disabling their controls", () => {
+ const closed = plugin({ authorAllowsExternal: false });
+ const { mounted } = mountCards([closed], undefined, { selectedPluginId: closed.pluginId });
+ expect(hostText(mounted.root)).toContain("settings.mcpPluginAuthorClosed");
+ expect(findOne(mounted.root, (node) => node.props["data-mcp-plugin-master"] !== undefined).props.disabled).toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-tool"] !== undefined)).toHaveLength(3);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-ceiling-level"] !== undefined).every((node) => node.props.disabled)).toBe(true);
+ });
+
+ it("filters by the configured grant while retaining enabled tools that cannot be exposed", () => {
+ const view = plugin({
+ grant: { ...plugin().grant, disabledTools: ["upload"] },
+ tools: [tool("list_dir", "read", "aboveCeiling"), tool("upload", "write", "toolDisabled"), tool("new_tool", "write", "pendingApproval"), tool("undeclared", null, "undeclared")],
+ });
+ const { mounted } = mountCards([view], undefined, { selectedPluginId: view.pluginId, onlyEnabled: true });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-tool"] !== undefined).map((node) => node.props["data-mcp-plugin-tool"])).toEqual(["list_dir", "new_tool"]);
+ expect(hostText(mounted.root)).toContain('settings.mcpPluginToolCount {"exposed":0,"total":4}');
+ expect(hostText(mounted.root)).toContain("settings.mcpPluginExposure.aboveCeiling");
+ expect(hostText(mounted.root)).toContain("settings.mcpPluginExposure.pendingApproval");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-review"] !== undefined)).toHaveLength(1);
+ });
+
+ it("retains the saved grant and displays an inline error after immediate save fails", async () => {
+ const view = plugin();
+ const save = vi.fn(async () => {
+ throw new Error("disk full");
+ });
+ const { mounted, saved } = mountCards([view], save, { selectedPluginId: view.pluginId });
+ const master = findOne(mounted.root, (node) => node.props["data-mcp-plugin-master"] !== undefined);
+ flip(master, false);
+ await nextTick();
+ await nextTick();
+ expect(saved).not.toHaveBeenCalled();
+ expect(master.props["model-value"]).toBe(true);
+ expect(master.props.disabled).toBe(false);
+ expect(view.grant.external).toBe(true);
+ expect(hostText(findOne(mounted.root, (node) => node.props["data-mcp-plugin-save-error"] !== undefined))).toContain("disk full");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-saved"] !== undefined)).toHaveLength(0);
+ });
+
+ it("locks the selected plugin during save and ignores duplicate changes", async () => {
+ const view = plugin();
+ let finish!: (value: PluginMcpView) => void;
+ const save = vi.fn(
+ () =>
+ new Promise<PluginMcpView>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { mounted } = mountCards([view], save, { selectedPluginId: view.pluginId });
+ const master = findOne(mounted.root, (node) => node.props["data-mcp-plugin-master"] !== undefined);
+ flip(master, false);
+ await nextTick();
+ expect(master.props.disabled).toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-stub"] === "Switch").every((node) => node.props.disabled)).toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-ceiling-level"] !== undefined).every((node) => node.props.disabled)).toBe(true);
+ expect(hostText(mounted.root)).toContain("settings.mcpBrowser.pluginSaving");
+ flip(master, true);
+ const toolSwitch = findOne(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-tool"] === "upload"),
+ (node) => node.props["data-stub"] === "Switch",
+ );
+ flip(toolSwitch, false);
+ expect(save).toHaveBeenCalledTimes(1);
+ finish({ ...view, grant: { ...view.grant, external: false } });
+ await nextTick();
+ await nextTick();
+ expect(master.props.disabled).toBe(false);
+ expect(hostText(mounted.root)).toContain("settings.mcpBrowser.pluginSaved");
+ });
+
+ it("preserves the parent save lock after remounting while the first request is pending", async () => {
+ const view = plugin();
+ let finish!: (value: PluginMcpView) => void;
+ const save = vi.fn(
+ () =>
+ new Promise<PluginMcpView>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const first = mountCards([view], save, { selectedPluginId: view.pluginId });
+ flip(
+ findOne(first.mounted.root, (node) => node.props["data-mcp-plugin-master"] !== undefined),
+ false,
+ );
+ await nextTick();
+ first.mounted.unmount();
+
+ const { mounted } = mountCards([view], save, { selectedPluginId: view.pluginId, pendingPluginIds: [view.pluginId] });
+ const master = findOne(mounted.root, (node) => node.props["data-mcp-plugin-master"] !== undefined);
+ expect(master.props.disabled).toBe(true);
+ expect(hostText(mounted.root)).toContain("settings.mcpBrowser.pluginSaving");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-ceiling-level"] !== undefined).every((node) => node.props.disabled)).toBe(true);
+ expect(findAll(mounted.root, (node) => node.props["data-stub"] === "Switch").every((node) => node.props.disabled)).toBe(true);
+ flip(master, false);
+ flip(
+ findOne(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-tool"] === "upload"),
+ (node) => node.props["data-stub"] === "Switch",
+ ),
+ false,
+ );
+ expect(save).toHaveBeenCalledTimes(1);
+
+ finish({ ...view, grant: { ...view.grant, external: false } });
+ await nextTick();
+ await mounted.setProps({ pendingPluginIds: [], plugins: [{ ...view, grant: { ...view.grant, external: false } }] });
+ expect(master.props.disabled).toBe(false);
+ expect(master.props["model-value"]).toBe(false);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-saving"] !== undefined)).toHaveLength(0);
+ });
+
+ it("merges external and local save locks per plugin without blocking other plugins", async () => {
+ const pending = plugin({ tools: [tool("new_tool", "write", "pendingApproval")] });
+ const available = plugin({ pluginId: "io.dbx.other", pluginName: "Other plugin" });
+ let finish!: (value: PluginMcpView) => void;
+ const save = vi.fn(
+ () =>
+ new Promise<PluginMcpView>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { mounted } = mountCards([pending, available], save, { selectedPluginId: pending.pluginId, pendingPluginIds: [pending.pluginId] });
+ const review = findOne(mounted.root, (node) => node.props["data-mcp-plugin-review"] !== undefined);
+ expect(review.props.disabled).toBe(true);
+ dispatch(review, "click");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-authorize"] !== undefined)).toHaveLength(0);
+ await mounted.setProps({ selectedPluginId: available.pluginId });
+ const master = findOne(mounted.root, (node) => node.props["data-mcp-plugin-master"] !== undefined);
+ expect(master.props.disabled).toBe(false);
+ flip(master, false);
+ await nextTick();
+ expect(save).toHaveBeenCalledTimes(1);
+ expect(master.props.disabled).toBe(true);
+ await mounted.setProps({ pendingPluginIds: [pending.pluginId, available.pluginId] });
+ finish(available);
+ await nextTick();
+ await nextTick();
+ expect(master.props.disabled).toBe(true);
+ await mounted.setProps({ pendingPluginIds: [pending.pluginId] });
+ expect(master.props.disabled).toBe(false);
+ });
+
+ it("retains the authorization dialog and its failure reason, locking all actions while saving", async () => {
+ const fresh = plugin({ hasSavedGrant: false, grant: { ...plugin().grant, external: false } });
+ let fail!: (error: Error) => void;
+ const save = vi.fn(
+ () =>
+ new Promise<PluginMcpView>((_resolve, reject) => {
+ fail = reject;
+ }),
+ );
+ const { mounted } = mountCards([fresh], save, { selectedPluginId: fresh.pluginId });
+ flip(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-master"] !== undefined),
+ true,
+ );
+ await nextTick();
+ const dialog = findOne(mounted.root, (node) => node.props["data-mcp-plugin-authorize"] !== undefined);
+ dispatch(
+ findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-confirm"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ expect(findAll(dialog, (node) => node.type === "button").every((node) => node.props.disabled)).toBe(true);
+ fail(new Error("permission denied"));
+ await nextTick();
+ await nextTick();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-authorize"] !== undefined)).toHaveLength(1);
+ expect(hostText(findOne(dialog, (node) => node.props["data-mcp-plugin-authorize-error"] !== undefined))).toContain("permission denied");
+ expect(fresh.grant.external).toBe(false);
+ });
+
+ it("keeps pending authorization available in the selected view", async () => {
+ const view = plugin({ tools: [tool("new_tool", "write", "pendingApproval")] });
+ const { mounted, save } = mountCards([view], undefined, { selectedPluginId: view.pluginId });
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-review"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ expect(save).not.toHaveBeenCalled();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-authorize-tool"] === "new_tool")).toHaveLength(1);
+ });
+
+ it("shows distinct empty, filtered, and removed-plugin states", async () => {
+ const view = plugin({ tools: [] });
+ const { mounted, refresh } = mountCards([view], undefined, { selectedPluginId: view.pluginId });
+ expect(hostText(mounted.root)).toContain("settings.mcpPluginNoTools");
+ await mounted.setProps({ plugins: [plugin({ grant: { ...plugin().grant, external: false } })], onlyEnabled: true });
+ expect(hostText(mounted.root)).toContain("settings.mcpBrowser.pluginOnlyEnabledEmpty");
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-master"] !== undefined)).toHaveLength(1);
+ await mounted.setProps({ plugins: [] });
+ expect(hostText(mounted.root)).toContain("settings.mcpBrowser.pluginUnavailable");
+ const refreshButton = findOne(mounted.root, (node) => node.props["data-mcp-plugins-refresh"] !== undefined);
+ dispatch(refreshButton, "click");
+ expect(refresh).toHaveBeenCalledOnce();
+ await mounted.setProps({ loading: true });
+ expect(refreshButton.props.disabled).toBe(true);
+ dispatch(refreshButton, "click");
+ expect(refresh).toHaveBeenCalledOnce();
+ });
+
+ it.each([false, true])("retains an expanded tool after filters, tool disable, and plugin disable (search dialog: %s)", async (listHidden) => {
+ const view = plugin();
+ const { mounted } = mountCards([view], undefined, { selectedPluginId: view.pluginId, listHidden });
+ await mounted.exposed.value.openTool(view.pluginId, "list_dir");
+ const disabledTools = { ...view, grant: { ...view.grant, disabledTools: ["list_dir", "upload"] } };
+ await mounted.setProps({ plugins: [disabledTools], onlyEnabled: true });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-tool"] !== undefined).map((node) => node.props["data-mcp-plugin-tool"])).toEqual(["list_dir", "exec"]);
+ expect(hostText(findOne(mounted.root, (node) => node.props["data-mcp-plugin-tool-detail"] !== undefined))).toContain("Absolute path");
+ await mounted.setProps({ plugins: [{ ...disabledTools, grant: { ...disabledTools.grant, external: false } }] });
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-tool"] !== undefined).map((node) => node.props["data-mcp-plugin-tool"])).toEqual(["list_dir"]);
+ const row = findOne(mounted.root, (node) => node.props["data-mcp-plugin-tool"] === "list_dir");
+ expect(findOne(row, (node) => node.props["data-stub"] === "Switch").props.disabled).toBe(true);
+ dispatch(
+ findOne(row, (node) => node.props["data-mcp-plugin-tool-toggle"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-tool"] !== undefined)).toHaveLength(0);
+ });
+
+ it("opens a search tool directly while the list is hidden and restores trigger focus", async () => {
+ const view = plugin();
+ const { mounted } = mountCards([view], undefined, { selectedPluginId: view.pluginId, listHidden: true });
+ const trigger = document.createElement("button");
+ document.body.append(trigger);
+ const focus = vi.spyOn(trigger, "focus");
+ try {
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-detail"] !== undefined)).toHaveLength(0);
+ await mounted.exposed.value.openTool(view.pluginId, "list_dir", trigger);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-inline"] !== undefined)).toHaveLength(0);
+ expect(findAll(mounted.root, (node) => node.props["data-mcp-plugin-open"] !== undefined)).toHaveLength(0);
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-plugin-detail"] !== undefined);
+ const expanded = findOne(detail, (node) => node.props["data-mcp-plugin-tool-detail"] !== undefined);
+ expect(hostText(expanded)).toContain("Absolute path");
+ const preventDefault = vi.fn();
+ dispatch(detail, "closeAutoFocus", { preventDefault });
+ expect(preventDefault).toHaveBeenCalledOnce();
+ expect(focus).toHaveBeenCalledOnce();
+ } finally {
+ trigger.remove();
+ }
+ });
+
+ it("restores the search fallback when the detail trigger was removed", async () => {
+ const view = plugin();
+ const focusFallback = vi.fn();
+ const { mounted } = mountCards([view], undefined, { listHidden: true, focusFallback });
+ const trigger = document.createElement("button");
+ document.body.append(trigger);
+ await mounted.exposed.value.openTool(view.pluginId, "list_dir", trigger);
+ trigger.remove();
+ const detail = findOne(mounted.root, (node) => node.props["data-mcp-plugin-detail"] !== undefined);
+ const preventDefault = vi.fn();
+ dispatch(detail, "closeAutoFocus", { preventDefault });
+ expect(preventDefault).toHaveBeenCalledOnce();
+ expect(focusFallback).toHaveBeenCalledOnce();
+ });
+
+ it("restores authorization trigger focus and falls back after the trigger disappears", async () => {
+ const view = plugin({ tools: [tool("new_tool", "write", "pendingApproval")] });
+ const focusFallback = vi.fn();
+ const { mounted } = mountCards([view], undefined, { selectedPluginId: view.pluginId, focusFallback });
+ const trigger = document.createElement("button");
+ document.body.append(trigger);
+ const focus = vi.spyOn(trigger, "focus");
+ try {
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-review"] !== undefined),
+ "click",
+ { currentTarget: trigger },
+ );
+ await nextTick();
+ const dialog = findOne(mounted.root, (node) => node.props["data-mcp-plugin-authorize"] !== undefined);
+ const preventDefault = vi.fn();
+ dispatch(dialog, "closeAutoFocus", { preventDefault });
+ expect(preventDefault).toHaveBeenCalledOnce();
+ expect(focus).toHaveBeenCalledOnce();
+ expect(focusFallback).not.toHaveBeenCalled();
+ trigger.remove();
+ dispatch(dialog, "closeAutoFocus", { preventDefault });
+ expect(focusFallback).toHaveBeenCalledOnce();
+ } finally {
+ trigger.remove();
+ }
+ });
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpPluginScopeEditor.spec.ts b/apps/desktop/src/components/settings/__tests__/McpPluginScopeEditor.spec.ts
new file mode 100644
index 0000000000..a3c9753204
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpPluginScopeEditor.spec.ts
@@ -0,0 +1,231 @@
+// @vitest-environment happy-dom
+
+import { nextTick } from "vue";
+import { describe, expect, it, vi } from "vitest";
+import { dispatch, findAll, findOne, hostText, mountComponent } from "@/components/grid/__tests__/vueHostHarness";
+import type { McpAccessPolicy } from "@/types/mcpCatalog";
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => `${key}${values ? ` ${JSON.stringify(values)}` : ""}` }),
+}));
+vi.mock("@lucide/vue", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const icon = createPassthroughStub("Icon", "i");
+ return { Loader2: icon, Plus: icon, X: icon };
+});
+vi.mock("@/components/ui/button", async () => ({ Button: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Button", "button") }));
+vi.mock("@/components/ui/input", async () => ({ Input: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Input", "input") }));
+vi.mock("@/components/ui/select", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ return {
+ Select: createPassthroughStub("Select", "div"),
+ SelectContent: createPassthroughStub("SelectContent", "div"),
+ SelectItem: createPassthroughStub("SelectItem", "div"),
+ SelectTrigger: createPassthroughStub("SelectTrigger", "button"),
+ SelectValue: createPassthroughStub("SelectValue", "span"),
+ };
+});
+
+import McpPluginScopeEditor from "@/components/settings/McpPluginScopeEditor.vue";
+
+const policy: McpAccessPolicy = {
+ version: 2,
+ defaultAccess: "write",
+ rules: [
+ { target: { kind: "connection", id: "k1" }, subScope: "selected" },
+ { target: { kind: "scope", connectionId: "k1", scope: "namespace", value: "staging" }, visible: true, access: "read" },
+ { target: { kind: "scope", connectionId: "k1", scope: "namespace", value: "dev" }, visible: true },
+ { target: { kind: "scope", connectionId: "other", scope: "namespace", value: "x" }, visible: true },
+ ],
+};
+
+function mountEditor(save = vi.fn(async () => policy)) {
+ const saved = vi.fn();
+ const mounted = mountComponent(McpPluginScopeEditor, { connectionId: "k1", kind: "namespace", title: "Namespace", policy, save, onSaved: saved });
+ return { mounted, save, saved };
+}
+
+function selects(root: ReturnType<typeof mountComponent>["root"]) {
+ return findAll(root, (node) => node.props["data-stub"] === "Select");
+}
+
+describe("McpPluginScopeEditor", () => {
+ it("lists this connection's scope values sorted, with their levels", () => {
+ const { mounted } = mountEditor();
+ const values = findAll(mounted.root, (node) => node.props["data-mcp-plugin-scope-value"] !== undefined).map((node) => node.props["data-mcp-plugin-scope-value"]);
+ expect(values).toEqual(["dev", "staging"]);
+ expect(selects(mounted.root)[0].props["model-value"] ?? selects(mounted.root)[0].props.modelValue).toBe("selected");
+ expect(hostText(mounted.root)).toContain('settings.mcpPluginScopeSelected {"count":2}');
+ });
+
+ it("adds a value as visible, changes levels, and removes values", async () => {
+ const { mounted, save, saved } = mountEditor();
+ const input = findOne(mounted.root, (node) => node.props["data-stub"] === "Input");
+ (input.props["onUpdate:modelValue"] as (value: string) => void)("prod");
+ await nextTick();
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-scope-add"] === "k1"),
+ "click",
+ );
+ await nextTick();
+ expect(save).toHaveBeenLastCalledWith("k1", "namespace", "prod", { visible: true }, null);
+ await nextTick();
+ expect(saved).toHaveBeenCalledWith(policy);
+
+ (selects(mounted.root)[1].props["onUpdate:modelValue"] as (value: string) => void)("full");
+ await nextTick();
+ expect(save).toHaveBeenLastCalledWith("k1", "namespace", "dev", { visible: true, access: "full" }, null);
+ // Controls are disabled while a save is in flight; let it settle first.
+ await nextTick();
+ await nextTick();
+
+ const remove = findAll(mounted.root, (node) => node.type === "button" && node.props["aria-label"] === "settings.mcpToolCustomRemove")[0];
+ dispatch(remove, "click");
+ await nextTick();
+ expect(save).toHaveBeenLastCalledWith("k1", "namespace", "dev", null, null);
+ });
+
+ it("switches the admission mode", async () => {
+ const { mounted, save, saved } = mountEditor();
+ expect(hostText(mounted.root)).toContain("settings.mcpBrowser.pluginImmediate");
+ (selects(mounted.root)[0].props["onUpdate:modelValue"] as (value: string) => void)("none");
+ // Scope edits persist directly, without any settings-dialog Apply action.
+ expect(save).toHaveBeenCalledWith("k1", "namespace", null, null, "none");
+ await nextTick();
+ await nextTick();
+ expect(saved).toHaveBeenCalledWith(policy);
+ mounted.unmount();
+ });
+
+ it("does not replace a saved read-only scope when the same name is added again", async () => {
+ const { mounted, save } = mountEditor();
+ const input = findOne(mounted.root, (node) => node.props["data-stub"] === "Input");
+ (input.props["onUpdate:modelValue"] as (value: string) => void)(" staging ");
+ await nextTick();
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-scope-add"] === "k1"),
+ "click",
+ );
+ await nextTick();
+ expect(save).not.toHaveBeenCalled();
+ const scope = findOne(mounted.root, (node) => node.props["data-mcp-plugin-scope-value"] === "staging");
+ expect(selects(scope)[0].props["model-value"] ?? selects(scope)[0].props.modelValue).toBe("read");
+ mounted.unmount();
+ });
+
+ it("retains a new scope after failure and clears it only after a successful retry", async () => {
+ const save = vi.fn().mockRejectedValueOnce(new Error("scope save failed")).mockResolvedValue(policy);
+ const { mounted, saved } = mountEditor(save);
+ const input = findOne(mounted.root, (node) => node.props["data-stub"] === "Input");
+ (input.props["onUpdate:modelValue"] as (value: string) => void)("prod");
+ await nextTick();
+ const add = () =>
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-scope-add"] === "k1"),
+ "click",
+ );
+ add();
+ await vi.waitFor(() => expect(hostText(mounted.root)).toContain("scope save failed"));
+ expect(input.props.modelValue).toBe("prod");
+ expect(saved).not.toHaveBeenCalled();
+ add();
+ await vi.waitFor(() => expect(saved).toHaveBeenCalledWith(policy));
+ await nextTick();
+ expect(input.props.modelValue).toBe("");
+ expect(save).toHaveBeenCalledTimes(2);
+ expect(save).toHaveBeenLastCalledWith("k1", "namespace", "prod", { visible: true }, null);
+ mounted.unmount();
+ });
+
+ it("rejects a second scope mutation while the first save is pending", async () => {
+ let finish!: (value: McpAccessPolicy) => void;
+ const save = vi.fn(
+ () =>
+ new Promise<McpAccessPolicy>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { mounted } = mountEditor(save);
+ const mode = selects(mounted.root)[0].props["onUpdate:modelValue"] as (value: string) => void;
+ mode("none");
+ // A second event can arrive before Vue renders disabled controls.
+ mode("all");
+ expect(save).toHaveBeenCalledTimes(1);
+ finish(policy);
+ await nextTick();
+ await nextTick();
+ mounted.unmount();
+ });
+
+ it.each(["inherit", "full"])("preserves scope visibility and ceilings when changing access to %s", async (access) => {
+ const restricted: McpAccessPolicy = {
+ ...policy,
+ rules: [policy.rules[0], { target: { kind: "scope", connectionId: "k1", scope: "namespace", value: "staging" }, visible: false, access: "read", ceiling: "read", toolsetCeilings: { admin: "none" } }],
+ };
+ const save = vi.fn(async () => restricted);
+ const mounted = mountComponent(McpPluginScopeEditor, { connectionId: "k1", kind: "namespace", title: "Namespace", policy: restricted, save });
+ (selects(mounted.root)[1].props["onUpdate:modelValue"] as (value: string) => void)(access);
+ await nextTick();
+ expect(save).toHaveBeenCalledExactlyOnceWith(
+ "k1",
+ "namespace",
+ "staging",
+ {
+ visible: false,
+ ceiling: "read",
+ toolsetCeilings: { admin: "none" },
+ ...(access === "full" ? { access: "full" } : {}),
+ },
+ null,
+ );
+ mounted.unmount();
+ });
+
+ it.each(["disabled", "loading"])("does not save while scope controls are %s", async (state) => {
+ const save = vi.fn(async () => policy);
+ const mounted = mountComponent(McpPluginScopeEditor, { connectionId: "k1", kind: "namespace", title: "Namespace", policy: state === "loading" ? null : policy, disabled: state === "disabled", save });
+ (selects(mounted.root)[0].props["onUpdate:modelValue"] as (value: string) => void)("none");
+ await nextTick();
+ expect(save).not.toHaveBeenCalled();
+ mounted.unmount();
+ });
+
+ it("keeps the saved scope and shows an error if an immediate save fails", async () => {
+ const { mounted, save, saved } = mountEditor(
+ vi.fn(async () => {
+ throw new Error("scope save failed");
+ }),
+ );
+ (selects(mounted.root)[0].props["onUpdate:modelValue"] as (value: string) => void)("none");
+ expect(save).toHaveBeenCalledOnce();
+ await nextTick();
+ await nextTick();
+ expect(saved).not.toHaveBeenCalled();
+ expect(selects(mounted.root)[0].props["model-value"] ?? selects(mounted.root)[0].props.modelValue).toBe("selected");
+ expect(hostText(mounted.root)).toContain("scope save failed");
+ expect(hostText(mounted.root)).toContain("settings.mcpBrowser.pluginImmediate");
+ mounted.unmount();
+ });
+
+ it("loads scope values from the plugin sidecar as selectable entries", async () => {
+ const listValues = vi.fn(async () => ({ values: ["prod", "dev", "prod"] }));
+ const mounted = mountComponent(McpPluginScopeEditor, {
+ connectionId: "k1",
+ pluginId: "plugin.demo",
+ kind: "namespace",
+ title: "Namespace",
+ policy,
+ save: vi.fn(async () => policy),
+ listValues,
+ });
+ dispatch(
+ findOne(mounted.root, (node) => node.props["data-mcp-plugin-scope-list"] !== undefined),
+ "click",
+ );
+ await nextTick();
+ await nextTick();
+ expect(listValues).toHaveBeenCalledWith("plugin.demo", "k1");
+ expect(hostText(mounted.root)).toContain("prod");
+ expect(hostText(mounted.root)).toContain("dev");
+ });
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpPluginToolsModeSetting.spec.ts b/apps/desktop/src/components/settings/__tests__/McpPluginToolsModeSetting.spec.ts
new file mode 100644
index 0000000000..a1c01ce5bd
--- /dev/null
+++ b/apps/desktop/src/components/settings/__tests__/McpPluginToolsModeSetting.spec.ts
@@ -0,0 +1,85 @@
+// @vitest-environment happy-dom
+
+import { createApp, h, nextTick, reactive } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import McpPluginToolsModeSetting from "../McpPluginToolsModeSetting.vue";
+import { normalizeMcpGlobalPolicy, type McpGlobalPolicy } from "@/stores/settingsStore";
+
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+
+const cleanups: Array<() => void> = [];
+afterEach(() => cleanups.splice(0).forEach((cleanup) => cleanup()));
+
+function mountSetting(initial: Partial<McpGlobalPolicy> = {}, disabled = false) {
+ const props = reactive({ modelValue: normalizeMcpGlobalPolicy(initial).pluginToolsMode, disabled });
+ const update = vi.fn((value: McpGlobalPolicy["pluginToolsMode"]) => {
+ props.modelValue = value;
+ });
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp({ render: () => h(McpPluginToolsModeSetting, { ...props, "onUpdate:modelValue": update }) });
+ app.mount(root);
+ cleanups.push(() => {
+ app.unmount();
+ root.remove();
+ });
+ const details = root.querySelector<HTMLDetailsElement>("details")!;
+ const trigger = root.querySelector<HTMLButtonElement>("[data-mcp-plugin-tools-mode-trigger]")!;
+ async function choose(label: string) {
+ details.open = true;
+ trigger.focus();
+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true }));
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="option"]')).toHaveLength(3));
+ const option = Array.from(document.querySelectorAll<HTMLElement>('[role="option"]')).find((item) => item.textContent?.trim() === label)!;
+ option.focus();
+ option.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
+ await nextTick();
+ await vi.waitFor(() => expect(trigger.getAttribute("aria-expanded")).toBe("false"));
+ }
+ return { props, update, root, details, trigger, choose };
+}
+
+describe("McpPluginToolsModeSetting", () => {
+ it("starts collapsed with the flat default and changes modes using the real select", async () => {
+ const { root, details, props, update, choose } = mountSetting();
+ expect(details.open).toBe(false);
+ expect(root.querySelector("summary")!.textContent).toContain("settings.mcpPluginToolsModeFlat");
+ expect(update).not.toHaveBeenCalled();
+ await choose("settings.mcpPluginToolsModeLazy");
+ expect(props.modelValue).toBe("lazy");
+ expect(root.querySelector("#mcp-plugin-tools-mode-description")!.textContent).toBe("settings.mcpPluginToolsModeLazyDescription");
+ await choose("settings.mcpPluginToolsModeFlat");
+ expect(props.modelValue).toBe("flat");
+ expect(update.mock.calls.map(([value]) => value)).toEqual(["lazy", "flat"]);
+ });
+
+ it.each(["auto", "flat", "lazy"] as const)("preserves saved %s mode on mount and while collapsing the setting", async (pluginToolsMode) => {
+ const { props, update, details, root } = mountSetting({ configured: true, pluginToolsMode });
+ expect(props.modelValue).toBe(pluginToolsMode);
+ const label = { auto: "Auto", flat: "Flat", lazy: "Lazy" }[pluginToolsMode];
+ expect(root.querySelector("summary")!.textContent).toContain(`settings.mcpPluginToolsMode${label}`);
+ details.open = true;
+ await nextTick();
+ details.open = false;
+ await nextTick();
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it("keeps automatic mode available as an explicit compatibility choice", async () => {
+ const { choose, props, root } = mountSetting({ configured: true, pluginToolsMode: "auto" });
+ await choose("settings.mcpPluginToolsModeLazy");
+ await choose("settings.mcpPluginToolsModeAuto");
+ expect(props.modelValue).toBe("auto");
+ expect(root.querySelector("#mcp-plugin-tools-mode-description")!.textContent).toBe("settings.mcpPluginToolsModeAutoDescription");
+ });
+
+ it("disables changes while policy loading or saving prevents editing", async () => {
+ const { trigger, details, update } = mountSetting({}, true);
+ details.open = true;
+ expect(trigger.disabled).toBe(true);
+ trigger.click();
+ await nextTick();
+ expect(document.querySelector('[role="option"]')).toBeNull();
+ expect(update).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/components/settings/__tests__/McpResourceScopePicker.spec.ts b/apps/desktop/src/components/settings/__tests__/McpResourceScopePicker.spec.ts
deleted file mode 100644
index 73674e67be..0000000000
--- a/apps/desktop/src/components/settings/__tests__/McpResourceScopePicker.spec.ts
+++ /dev/null
@@ -1,355 +0,0 @@
-// @vitest-environment happy-dom
-
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { dispatch, findAll, findOne, hostText, mountComponent } from "@/components/grid/__tests__/vueHostHarness";
-import type { ConnectionConfig, SidebarLayout } from "@/types/database";
-
-vi.mock("vue-i18n", () => ({
- useI18n: () => ({
- t: (key: string, values?: Record<string, unknown>) => `${key}${values ? ` ${JSON.stringify(values)}` : ""}`,
- }),
-}));
-
-vi.mock("@lucide/vue", async () => {
- const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
- const icon = createPassthroughStub("Icon", "i");
- return { ChevronDown: icon, ChevronRight: icon, Database: icon, Folder: icon, Search: icon };
-});
-
-vi.mock("@/components/ui/badge", async () => ({ Badge: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Badge", "span") }));
-vi.mock("@/components/ui/button", async () => ({ Button: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Button", "button") }));
-vi.mock("@/components/ui/input", async () => ({ Input: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Input", "input") }));
-vi.mock("@/components/ui/select", async () => {
- const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
- return {
- Select: createPassthroughStub("Select", "div"),
- SelectContent: createPassthroughStub("SelectContent", "div"),
- SelectItem: createPassthroughStub("SelectItem", "div"),
- SelectTrigger: createPassthroughStub("SelectTrigger", "button"),
- SelectValue: createPassthroughStub("SelectValue", "span"),
- };
-});
-
-import McpResourceScopePicker from "@/components/settings/McpResourceScopePicker.vue";
-
-function connection(id: string): ConnectionConfig {
- return {
- id,
- name: `${id}-name`,
- db_type: "mysql",
- host: "127.0.0.1",
- port: 3306,
- username: "test",
- password: "",
- };
-}
-
-const DML_LABEL = "settings.mcpConnectionPolicyAllowSalesforceDml";
-
-function salesforceDmlCheckboxes(root: ReturnType<typeof mountComponent>["root"]) {
- return findAll(root, (node) => node.type === "input" && node.props["aria-label"] === DML_LABEL);
-}
-
-const layout: SidebarLayout = {
- groups: [{ id: "g1", name: "Group 1", collapsed: false }],
- order: [
- { type: "group", id: "g1", children: [{ type: "connection", id: "c1" }] },
- { type: "connection", id: "c2" },
- ],
-};
-
-const connections = [connection("c1"), connection("c2")];
-
-function mountPicker(props: Record<string, unknown> = {}) {
- const update = vi.fn();
- const mounted = mountComponent(McpResourceScopePicker, {
- layout,
- connections,
- allowedGroupIds: [],
- allowedConnectionIds: [],
- "onUpdate:scope": update,
- ...props,
- });
- return { mounted, update };
-}
-
-function modeButton(root: ReturnType<typeof mountComponent>["root"], mode: "all" | "custom") {
- return findOne(root, (node) => node.type === "button" && node.props["data-scope-mode"] === mode);
-}
-
-describe("McpResourceScopePicker", () => {
- let confirmMock: ReturnType<typeof vi.fn>;
-
- beforeEach(() => {
- confirmMock = vi.fn().mockReturnValue(true);
- vi.stubGlobal("confirm", confirmMock);
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it("emits allow-all when switching from a custom group and connection selection", () => {
- const { mounted, update } = mountPicker({
- allowedGroupIds: ["g1"],
- allowedConnectionIds: ["c2"],
- });
-
- dispatch(modeButton(mounted.root, "all"), "click");
-
- expect(update).toHaveBeenCalledWith({ allowedGroupIds: [], allowedConnectionIds: null });
- });
-
- it("restores the previous custom selection after switching to all connections and back", async () => {
- const customScope = { allowedGroupIds: ["g1"], allowedConnectionIds: ["c2"] };
- const { mounted, update } = mountPicker(customScope);
-
- dispatch(modeButton(mounted.root, "all"), "click");
- expect(confirmMock).toHaveBeenCalledWith("settings.mcpResourceScopeAllConfirm");
- await mounted.setProps({ allowedGroupIds: [], allowedConnectionIds: null });
- dispatch(modeButton(mounted.root, "custom"), "click");
-
- expect(update).toHaveBeenLastCalledWith(customScope);
- });
-
- it("keeps the custom scope without emitting when the all-connections confirm is cancelled", () => {
- confirmMock.mockReturnValue(false);
- const { mounted, update } = mountPicker({
- allowedGroupIds: ["g1"],
- allowedConnectionIds: ["c2"],
- });
-
- dispatch(modeButton(mounted.root, "all"), "click");
-
- expect(confirmMock).toHaveBeenCalledWith("settings.mcpResourceScopeAllConfirm");
- expect(modeButton(mounted.root, "all").props["aria-checked"]).toBe(false);
- expect(update).not.toHaveBeenCalled();
- });
-
- it("starts custom scope empty when there is no previous custom snapshot", () => {
- const { mounted, update } = mountPicker({
- allowedGroupIds: [],
- allowedConnectionIds: null,
- });
-
- dispatch(modeButton(mounted.root, "custom"), "click");
-
- expect(update).toHaveBeenCalledWith({ allowedGroupIds: [], allowedConnectionIds: [] });
- });
-
- it("restores an empty custom selection after switching away from it", async () => {
- const { mounted, update } = mountPicker({
- allowedGroupIds: [],
- allowedConnectionIds: [],
- });
-
- dispatch(modeButton(mounted.root, "all"), "click");
- expect(confirmMock).not.toHaveBeenCalled();
- await mounted.setProps({ allowedGroupIds: [], allowedConnectionIds: null });
- dispatch(modeButton(mounted.root, "custom"), "click");
-
- expect(update).toHaveBeenLastCalledWith({ allowedGroupIds: [], allowedConnectionIds: [] });
- });
-
- it("does not emit while disabled", () => {
- const { mounted, update } = mountPicker({
- allowedGroupIds: ["g1"],
- allowedConnectionIds: ["c2"],
- disabled: true,
- });
-
- dispatch(modeButton(mounted.root, "all"), "click");
-
- expect(update).not.toHaveBeenCalled();
- });
-
- it("does not emit while busy", () => {
- const { mounted, update } = mountPicker({
- allowedGroupIds: ["g1"],
- allowedConnectionIds: ["c2"],
- busy: true,
- });
-
- dispatch(modeButton(mounted.root, "all"), "click");
-
- expect(update).not.toHaveBeenCalled();
- });
-});
-
-describe("McpResourceScopePicker Salesforce DML opt-in", () => {
- const sfdc = { ...connection("c2"), db_type: "salesforce" } as unknown as ConnectionConfig;
-
- function mountWithSalesforce(props: Record<string, unknown> = {}) {
- const setDml = vi.fn();
- const mounted = mountComponent(McpResourceScopePicker, {
- layout,
- connections: [connection("c1"), sfdc],
- allowedGroupIds: [],
- allowedConnectionIds: ["c1", "c2"],
- "onSet:connection-salesforce-dml": setDml,
- ...props,
- });
- return { mounted, setDml };
- }
-
- it("offers the write opt-in only on Salesforce connections", () => {
- const { mounted } = mountWithSalesforce();
-
- const checkboxes = salesforceDmlCheckboxes(mounted.root);
- expect(checkboxes).toHaveLength(1);
- expect(checkboxes[0].props.checked).toBe(false);
- });
-
- it("hides the opt-in until the connection is inside the exposed scope", async () => {
- const { mounted } = mountWithSalesforce({ allowedConnectionIds: ["c1"] });
- expect(salesforceDmlCheckboxes(mounted.root)).toHaveLength(0);
-
- await mounted.setProps({ allowedConnectionIds: ["c1", "c2"] });
- expect(salesforceDmlCheckboxes(mounted.root)).toHaveLength(1);
- });
-
- it("emits the connection id and the requested state", () => {
- const { mounted, setDml } = mountWithSalesforce();
-
- dispatch(salesforceDmlCheckboxes(mounted.root)[0], "change", { target: { checked: true } });
-
- expect(setDml).toHaveBeenCalledWith("c2", true);
- });
-
- it("shows a persisted opt-in as checked and a read-only rule as off", () => {
- const optedIn = mountWithSalesforce({
- connectionPolicies: [{ connectionId: "c2", readOnly: false, allowDangerousSql: false, allowSalesforceDml: true }],
- });
- expect(salesforceDmlCheckboxes(optedIn.mounted.root)[0].props.checked).toBe(true);
-
- // Read-only is a hard ceiling server-side, so the switch must not look enabled here.
- const readOnly = mountWithSalesforce({
- connectionPolicies: [{ connectionId: "c2", readOnly: true, allowDangerousSql: false, allowSalesforceDml: true }],
- });
- expect(salesforceDmlCheckboxes(readOnly.mounted.root)[0].props.checked).toBe(false);
- });
-
- it("does not emit while the policy controls are disabled", () => {
- const { mounted, setDml } = mountWithSalesforce({ disabled: true });
-
- dispatch(salesforceDmlCheckboxes(mounted.root)[0], "change", { target: { checked: true } });
-
- expect(setDml).not.toHaveBeenCalled();
- });
-});
-
-describe("issue #11503 persisted execution-policy visibility", () => {
- const policies = [{ connectionId: "c2", readOnly: false, allowDangerousSql: false, executionModeConfigured: true }];
- function safeWriteEditors(root: ReturnType<typeof mountComponent>["root"]) {
- return findAll(root, (node) => node.type === "div" && node.props["data-stub"] === "Select" && node.props["model-value"] === "safe_write");
- }
-
- it("detects the persisted editor when the connection is explicitly selected", () => {
- const { mounted } = mountPicker({ allowedConnectionIds: ["c2"], connectionPolicies: policies });
- expect(safeWriteEditors(mounted.root)).toHaveLength(1);
- mounted.unmount();
- });
-
- it("exposes a persisted safe-write exception in all-connections scope", () => {
- const { mounted } = mountPicker({ allowedConnectionIds: null, connectionPolicies: policies });
- expect(safeWriteEditors(mounted.root)).toHaveLength(1);
- mounted.unmount();
- });
-
- it("exposes a persisted exception after reopening and switching to custom without selecting it again", async () => {
- const { mounted, update } = mountPicker({ allowedConnectionIds: null, connectionPolicies: policies });
- dispatch(modeButton(mounted.root, "custom"), "click");
- expect(update).toHaveBeenCalledWith({ allowedGroupIds: [], allowedConnectionIds: [] });
- await mounted.setProps(update.mock.calls[0][0]);
- expect(safeWriteEditors(mounted.root)).toHaveLength(1);
- mounted.unmount();
- });
-
- it("edits and resets an exception without adding the connection to the visible scope", async () => {
- const setPolicy = vi.fn();
- const { mounted, update } = mountPicker({ allowedConnectionIds: [], connectionPolicies: policies, "onSet:connection-policy": setPolicy });
- const editor = safeWriteEditors(mounted.root)[0];
- expect(hostText(mounted.root)).toContain("settings.mcpPolicyExceptionOutsideScope");
- editor.props["onUpdate:modelValue"]("read_only");
- expect(setPolicy).toHaveBeenLastCalledWith("c2", "read_only");
- editor.props["onUpdate:modelValue"]("inherit");
- expect(setPolicy).toHaveBeenLastCalledWith("c2", "inherit");
- expect(update).not.toHaveBeenCalled();
- await mounted.setProps({ connectionPolicies: [] });
- expect(hostText(mounted.root)).not.toContain("settings.mcpPolicyExceptionsTitle");
- mounted.unmount();
- });
-
- it("keeps a collapsed group's connection exception visible and avoids duplicate editors after expansion", async () => {
- const { mounted } = mountPicker({ allowedGroupIds: ["g1"], connectionPolicies: [{ ...policies[0], connectionId: "c1" }] });
- expect(safeWriteEditors(mounted.root)).toHaveLength(1);
- expect(hostText(mounted.root)).toContain("settings.mcpPolicyExceptionInScope");
- const expand = findOne(mounted.root, (node) => node.type === "button" && node.props["aria-label"] === "Group 1");
- dispatch(expand, "click");
- await mounted.setProps({});
- expect(safeWriteEditors(mounted.root)).toHaveLength(1);
- expect(hostText(mounted.root)).not.toContain("settings.mcpPolicyExceptionsTitle");
- mounted.unmount();
- });
-
- it("keeps exceptions discoverable when the resource search filters out their inline editor", async () => {
- const { mounted } = mountPicker({ allowedConnectionIds: ["c2"], connectionPolicies: policies });
- const search = findOne(mounted.root, (node) => node.type === "input" && node.props.placeholder === "settings.mcpResourceScopeSearch");
- search.props["onUpdate:modelValue"]("no-such-resource");
- await mounted.setProps({});
- expect(safeWriteEditors(mounted.root)).toHaveLength(1);
- expect(hostText(mounted.root)).toContain("settings.mcpPolicyExceptionsTitle");
- mounted.unmount();
- });
-
- it("exposes and resets a nested group exception in all-connections scope", () => {
- const setPolicy = vi.fn();
- const { mounted, update } = mountPicker({
- allowedConnectionIds: null,
- layout: { groups: [...layout.groups, { id: "g2", name: "Nested", collapsed: false }], order: [{ type: "group", id: "g1", children: [{ type: "group", id: "g2", children: [{ type: "connection", id: "c1" }] }] }] },
- groupPolicies: [{ groupId: "g2", readOnly: false, allowDangerousSql: true }],
- "onSet:group-policy": setPolicy,
- });
- expect(hostText(mounted.root)).toContain("Group 1 / Nested");
- const editor = findOne(mounted.root, (node) => node.props["data-stub"] === "Select" && node.props["model-value"] === "high_risk_write");
- editor.props["onUpdate:modelValue"]("inherit");
- expect(setPolicy).toHaveBeenCalledWith("g2", "inherit");
- expect(update).not.toHaveBeenCalled();
- mounted.unmount();
- });
-
- it("ignores database-scope-only and deleted-resource rules", () => {
- const { mounted } = mountPicker({
- allowedConnectionIds: null,
- connectionPolicies: [
- { ...policies[0], executionModeConfigured: false },
- { ...policies[0], connectionId: "deleted" },
- ],
- groupPolicies: [{ groupId: "deleted", readOnly: false, allowDangerousSql: true }],
- });
- expect(hostText(mounted.root)).not.toContain("settings.mcpPolicyExceptionsTitle");
- mounted.unmount();
- });
-
- it.each([{ disabled: true }, { busy: true }])("disables exception editing with %j", (props) => {
- const { mounted } = mountPicker({ allowedConnectionIds: null, connectionPolicies: policies, ...props });
- expect(safeWriteEditors(mounted.root)[0].props.disabled).toBe(true);
- mounted.unmount();
- });
-
- it("exposes a saved Salesforce DML opt-in even without an execution-mode override", () => {
- const setDml = vi.fn();
- const { mounted, update } = mountPicker({
- allowedConnectionIds: null,
- connections: [connection("c1"), { ...connection("c2"), db_type: "salesforce" }],
- connectionPolicies: [{ ...policies[0], executionModeConfigured: false, allowSalesforceDml: true }],
- "onSet:connection-salesforce-dml": setDml,
- });
- const checkbox = salesforceDmlCheckboxes(mounted.root)[0];
- expect(checkbox.props.checked).toBe(true);
- dispatch(checkbox, "change", { target: { checked: false } });
- expect(setDml).toHaveBeenCalledWith("c2", false);
- expect(update).not.toHaveBeenCalled();
- mounted.unmount();
- });
-});
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 5a4e5ce7a7..5291cbd4fe 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -84,6 +84,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: '"{name}" "{connection}" bağlantısındakı məlumatları oxumaq istəyir. Bu bağlantı açıq olduqca plagin, Plagin Mərkəzində girişi ləğv edənə qədər orada yalnız oxuma sorğuları icra edə bilər. İcazə verilsin?',
dataAccessConsentTitle: "Məlumat girişi sorğusu",
+ mcpToolsBadge: "MCP alətləri",
+ mcpToolsBadgeHint: "This plugin provides MCP alətləri. Enable and authorize them in Settings → MCP → Qabiliyyətlər.",
+ mcpToolsFilter: "Only plugins with MCP alətləri ({count})",
+ externalMcp: {
+ title: "Xarici MCP müştəriləri",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → Qabiliyyətlər.",
+ notOffered: "Müəllif bu əlavənin alətlərini xarici MCP müştərilərinə açmayıb.",
+ },
aiTools: {
title: "Daxili süni intellekt alətləri",
description: "Standart olaraq söndürüldü: DBX süni intellekt köməkçisi (Agent rejimi) yalnız bu açar yanık olduqda açıq plagin bağlantılarında bu plaginin alətlərini çağıra bilər. Salt oxunan olmayan alətlər hər çağrıda təsdiq istəyir.",
@@ -6221,6 +6229,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "MCP aləti",
+ mcpClient: "MCP müştərisi",
+ mcpTransport: "MCP nəqliyyatı",
+ mcpAccess: "MCP giriş icazəsi",
+ mcpConfirmation: "MCP təsdiqi",
kind: "Növ",
operation: "Əməliyyat",
connection: "Əlaqə",
@@ -8609,6 +8621,303 @@ export default withEnglishFallback({
mcpUninstallConfirm: "DBX MCP Server silinsin? Tənzimlənmiş MCP müştəriləri artıq onu başlada bilməyəcək.",
mcpUninstallFailed: "Quraşdırmanın silinməsi uğursuz oldu: {error}",
mcpConfig: "MCP konfiqurasiyası",
+ mcpCapabilitiesFilterLabel: "Qabiliyyət filtri",
+ mcpCapabilitiesFilterAll: "Hamısı",
+ mcpCapabilitiesFilterBuiltin: "Daxili",
+ mcpCapabilitiesFilterPlugin: "Əlavə",
+ mcpCapabilitiesOnlyEnabled: "Yalnız aktivləri göstər",
+ mcpPluginScopeLoad: "Plagindən oxu",
+ mcpPluginToolsMode: "Plugin alətlərinin xarici müştərilərə təqdimatı",
+ mcpPluginToolsModeDescription: "DBX-in icazəli plugin alətlərini MCP müştərilərinə necə təqdim edəcəyini seçin. Saxlamaq üçün aşağıdakı Tətbiq et düyməsini basın.",
+ mcpPluginToolsModeAuto: "Avtomatik (uyğunluq)",
+ mcpPluginToolsModeFlat: "Birbaşa siyahı (standart)",
+ mcpPluginToolsModeLazy: "Tələb üzrə kəşf",
+ mcpPluginToolsModeFlatDescription: "Müştərilərin birbaşa çağıra bilməsi üçün icazəli plugin alətlərini ayrı-ayrı göstərir.",
+ mcpPluginToolsModeLazyDescription: "Ümumi plugin axtarış və çağırış alətləri təqdim edir, təfərrüatları lazım olduqda əldə edir. DBX ümumi bölməsində plugin axtarışını və çağırışını aktivləşdirin.",
+ mcpPluginToolsModeAutoDescription: "Əvvəlki avtomatik keçidi saxlayır: ümumilikdə 40-a qədər plugin aləti birbaşa göstərilir, daha çox olduqda tələb üzrə kəşf istifadə olunur.",
+ mcpCallSafety: "Çağırış təhlükəsizliyi",
+ mcpCallSafetyLegacy: "Köhnə müvəqqəti icazə",
+ mcpCallSafetyEnabled: "Hər yüksək riskli çağırışı təsdiqlə",
+ mcpCallSafetyDisabled: "Əlavə təsdiq yoxdur",
+ mcpCallSafetyLegacyHint: "Köhnə davranış saxlanılır: məlumat yazma bəzi yüksək riskli əməliyyatlara müvəqqəti icazə verə bilər; tam giriş təsdiq istəmir. Yeni qayda yetərsiz icazələri rədd edir və tam girişdə də təsdiq istəyir.",
+ mcpCallSafetyMigrate: "Yeni təsdiq qaydasını istifadə et",
+ mcpCallSafetyDisableLegacy: "Köhnə icazəni söndür",
+ mcpCallSafetyConfirm: "Yüksək riskli alət çağırışlarından əvvəl təsdiq istə",
+ mcpCallSafetyHint: "Yüksək riskli kimi tanınan daxili və plagin çağırışlarına aiddir. Əvvəl icazələr yoxlanılır; tam giriş də bu qaydaya tabedir. Təsdiq icazələri artırmır.",
+ mcpCallSafetyDesktopHint: "DBX masaüstü tələb olunur və yalnız cari çağırış təsdiqlənir. Təsdiq mümkün olmadıqda, rədd edildikdə və ya vaxt bitdikdə icra edilmir. Yalnız oxuma və istehsal mühafizəsi saxlanılır. Saxlamaq üçün Tətbiq et seçin.",
+ mcpToolApprovalGenericTitle: "Yüksək riskli çağırışı təsdiqlə",
+ mcpToolApprovalPluginTitle: "{plugin} əlavəsinin yüksək riskli alətini təsdiqləyin",
+ 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",
+ mcpToolApprovalTarget: "Hədəf",
+ mcpManagementCapabilities: "Qabiliyyətlər",
+ mcpOpenCallHistory: "MCP çağırış tarixçəsinə bax",
+ mcpAccessTreeTitle: "Girişə nəzarət",
+ mcpAccessTreeDescription: "Qruplar, əlaqələr və verilənlər bazaları üçün icazələr təyin edin. Miras alma üst səviyyənin parametrini istifadə edir; qüvvədə olan icazə və mənbə ayrıca göstərilir.",
+ mcpAccessTreeSummary: "{visible}/{total} bağlantı görünür · istisnalar: {groups} qrup, {connections} bağlantı, {databases} verilənlər bazası",
+ mcpAccessTreeScopeLabel: "Bağlantı görünürlüğü",
+ mcpAccessTreeScopeAll: "Bütün əlaqələr",
+ mcpAccessTreeScopeCustom: "Yalnız seçilənlər",
+ mcpAccessTreeSearchPlaceholder: "Qrup, bağlantı və ya verilənlər bazası axtarın",
+ mcpAccessTreeExceptionsOnly: "Yalnız ayrıca parametrləri göstər",
+ mcpAccessTreeColumnResource: "Resurs",
+ mcpAccessTreeColumnVisible: "Görünən",
+ mcpAccessTreeColumnSetting: "İcazə",
+ mcpAccessTreeColumnEffective: "Effektiv",
+ mcpAccessTreeInherit: "Miras al",
+ mcpAccessTreeGroupPartiallyVisible: "Bəzi bağlantılar görünür ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "Bütün cari bağlantılar görünür ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Yalnız alt elementlərə icazə verilib, bütün qrupa deyil. Gələcək bağlantılar daxil olmaqla bütün qrupa icazə vermək üçün işarələyin.",
+ mcpAccessTreeGroupDefaultHint: "Qrupun standart icazələri ayrıca icazəsi olmayan alt elementlərə tətbiq olunur. Bağlantıların görünməsini dəyişmir.",
+ mcpAccessTreeHidden: "MCP üçün görünmür",
+ mcpAccessTreeSourceGlobal: "qlobal standart",
+ mcpAccessTreeSourceGroup: "{group} qrupundan",
+ mcpAccessTreeSourceConnection: "bağlantı ayarı",
+ mcpAccessTreeSourceDatabase: "verilənlər bazası ayarı",
+ mcpAccessTreeGroupCount: "{count} bağlantı",
+ mcpAccessTreeLegacy: "köhnə format",
+ mcpAccessTreeLegacyHint: "Köhnə versiyada saxlanılıb: yalnız bağlantının miras aldığı icazələri məhdudlaşdıra bilər. Adi ayara çevirmək üçün icazəni yenidən seçin.",
+ mcpAccessTreeCoveredByGroup: "Görünən through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "Yüksək risk allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "Verilənlər bazaları",
+ mcpAccessTreeDatabaseScopeAll: "Bütün verilənlər bazaları",
+ mcpAccessTreeDatabaseScopeSelected: "Seçilmiş ({count})",
+ mcpAccessTreeDatabaseScopeNone: "Verilənlər bazası yoxdur",
+ mcpDatabaseRemoveConfirm: "Seçilmiş bazaların silinməsi onların xüsusi icazələrini də silir. Davam edilsin?",
+ mcpDatabaseUnavailable: "Baza icazə ayarları əlçatan deyil. Yüklənmənin bitməsini gözləyin və ya yenidən cəhd edin.",
+ mcpDatabaseConfigure: "Verilənlər bazası girişini tənzimlə",
+ mcpDatabaseOverrideCount: "{count} xüsusi icazə",
+ mcpDatabaseDialogTitle: "{name} / Verilənlər bazasına giriş",
+ mcpDatabaseDialogDescription: "Bazaları və icazələri seçin. Sağa köçürmə yalnız tətbiq edildikdən sonra qüvvəyə minir.",
+ mcpDatabaseInherited: "İrsən alınan icazə: {level}",
+ mcpDatabaseSavedInherited: "Üst icazələrdə tətbiq edilməmiş dəyişikliklər var. Yalnız baza girişini tətbiq etdikdə saxlanmış icazələr irsən alınır: {level}",
+ mcpDatabaseHiddenConnection: "Bu bağlantı hazırda MCP üçün gizlidir. Baza icazələrinin tətbiqi bağlantını görünən etmir.",
+ mcpDatabaseAllHint: "Mövcud və gələcək bazalar bağlantının icazələrindən istifadə edir.",
+ mcpDatabaseNoneHint: "Tətbiqdən sonra bütün bazalara giriş qadağan ediləcək.",
+ mcpDatabaseLoaded: "Bu hesaba görünən {count} baza yükləndi",
+ mcpDatabaseRefresh: "Siyahını yenilə",
+ mcpDatabaseAddSelected: "Əlavə et →",
+ mcpDatabaseRemoveSelected: "← Sil",
+ mcpDatabaseAvailable: "Seçilməyib ({count})",
+ mcpDatabaseSelected: "Seçilib ({count})",
+ mcpDatabaseSearch: "Baza adını axtar",
+ mcpDatabaseSelectResults: "Cari axtarış nəticələrini seç ({count})",
+ mcpDatabaseBatchLevel: "İşarələnənlərə icazə təyin et ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "İşarələnmiş {count} verilənlər bazasına tam giriş verilsin? Bağlantının yalnız oxuma və istehsal mühiti qorunmaları qüvvədə qalır.",
+ mcpDatabaseNotDiscovered: "Bu sorğuda tapılmadı",
+ mcpDatabaseShowMore: "Daha çox göstər ({shown}/{total})",
+ mcpDatabaseSaveHint: "Yalnız bu bağlantının baza əhatəsini və icazələrini saxlayır. Digər saxlanmamış dəyişikliklər qorunur.",
+ mcpDatabaseApply: "Baza icazələrini tətbiq et",
+ mcpAccessTreePickDatabases: "Verilənlər bazalarını seç",
+ mcpAccessTreePickerTitle: "Verilənlər bazaları of {name}",
+ mcpAccessTreeLoadingDatabases: "Verilənlər bazaları yüklənir...",
+ mcpAccessTreeLoadDatabasesFailed: "Verilənlər bazaları yüklənmədi: {error}. Adları yenə də əl ilə əlavə edə bilərsiniz.",
+ mcpAccessTreeManualDatabase: "Verilənlər bazası adı əlavə edin",
+ mcpAccessTreeNoMatch: "Uyğun resurs yoxdur",
+ mcpAccessTreeEmpty: "Hələ əlaqə yoxdur",
+ mcpAccessTreeFootnote: "Üstünlük: verilənlər bazası > bağlantı > ən yaxın qrup > üst qrup > qlobal standart. Bağlantının yalnız oxuma qoruması, istehsal mühitinin qoruması və verilənlər bazası hesabının icazələri həmişə qüvvədədir.",
+ mcpAccessTreeNacosNamespace: "Ad sahəsi",
+ mcpPluginScopeAll: "Hamısı ({title})",
+ mcpPluginScopeSelected: "Seçilmiş ({count})",
+ mcpPluginScopeNone: "Xeyr {title}",
+ mcpPluginScopeAdd: "{title} əlavə edin",
+ mcpBrowser: {
+ viewMode: "Baxış rejimi",
+ viewManage: "Kateqoriya idarəetməsi",
+ viewOverview: "Qlobal icmal",
+ overviewSummary: "{toolsets} alət dəsti · {total} alət · {enabled} aktiv",
+ overviewPluginsHint: "Plugin alətlərini və avtorizasiyanı nəzərdən keçirin. Təfərrüatlar üçün plagini açın.",
+ overviewOpenDetails: "Təfərrüatlara bax",
+ expandCategory: "Kateqoriyanı genişləndir",
+ collapseCategory: "Kateqoriyanı yığ",
+ builtin: "Daxili imkanlar",
+ plugins: "Plagin genişləndirmələri",
+ advanced: "Əlavə parametrlər",
+ navigation: "İmkan kateqoriyaları",
+ searchPlaceholder: "Kateqoriya, imkan, plagin və ya alət axtarın…",
+ clearSearch: "Axtarışı təmizlə",
+ searchResults: "Axtarış nəticələri",
+ categoryCount: "{count} alət dəsti",
+ summary: "{toolsets} alət dəsti · {total} alət · {enabled} aktiv",
+ enableCategory: "Bu kateqoriyanın hamısını aktivləşdir",
+ disableCategory: "Bu kateqoriyanın hamısını deaktiv et",
+ draftHint: "Alət dəstini təfərrüatlar bölməsindən tətbiq edin və ya gözləyən bütün parametrləri saxlamaq üçün aşağıdakı Tətbiq et düyməsini istifadə edin.",
+ batchChanged: "Bu kateqoriyanın alətləri dəyişdirildi. Saxlamaq üçün “Tətbiq et” düyməsinə basın",
+ coverageHint: "Uyğun bağlantılar bağlantı növünə görə sayılır, faktiki icazə əhatəsini göstərmir.",
+ uncovered: "{count} bağlantı üçün daxili alət dəstəyi yoxdur",
+ viewDetails: "Təfərrüatlara bax",
+ emptyEnabled: "Bu kateqoriyada aktiv alət yoxdur. Konfiqurasiya üçün “Yalnız aktivləri göstər” seçimini söndürün.",
+ retry: "Yenidən cəhd et",
+ enabledToolCount: "{enabled}/{total} aktiv",
+ partialEnabled: "Qismən aktiv",
+ coverageConnections: "{count} bağlantıda istifadə edilə bilər",
+ coveragePartialConnections: "{count} bağlantı qismən dəstəklənir",
+ noMatchingConnections: "Uyğun bağlantı yoxdur",
+ resourceScopes: "Resurs əhatələri",
+ pluginImmediate: "Dəyişikliklər dərhal saxlanılır və aşağıdakı “Tətbiq et / Ləğv et” düymələrindən asılı deyil",
+ pluginSaving: "Saxlanılır…",
+ pluginSaved: "Saxlanıldı",
+ pluginOnlyEnabledEmpty: "Aktiv alət yoxdur. Baxmaq üçün “Yalnız aktivləri göstər” seçimini söndürün.",
+ pluginUnavailable: "Bu plagin artıq əlçatan deyil. Plagin siyahısını yeniləyin",
+ resourceKind: {
+ database: "Verilənlər bazası",
+ dbIndex: "Məntiqi verilənlər bazası",
+ topic: "Mövzu",
+ queue: "Növbə",
+ org: "Təşkilat",
+ namespace: "Ad məkanı",
+ },
+ category: {
+ database: { title: "Verilənlər bazaları", description: "Verilənləri sorğulayın, sessiya və tranzaksiyaları idarə edin, obyekt strukturlarına baxın və Redis əmrlərini icra edin." },
+ nacos: { title: "Nacos", description: "Konfiqurasiyaları, xidmətləri və instansiyaları idarə edin." },
+ consul: { title: "Consul", description: "KV qeydlərini idarə edin, xidmətləri aşkarlayın və sağlamlıq vəziyyətinə baxın." },
+ mq: { title: "Mesaj növbələri", description: "Mesajları oxuyun və göndərin." },
+ salesforce: { title: "Salesforce", description: "İstifadəçi məlumatlarını sorğulayın və verilənlər üzərində əməliyyat aparın." },
+ dbx: { title: "DBX ümumi", description: "Məhsullar arasında ortaq imkanlar: bağlantıların aşkarlanması, iş sahəsi ilə inteqrasiya, bağlantıların idarə edilməsi, plaginlərin aşkarlanması və çağırılması." },
+ other: { title: "Digər imkanlar", description: "Hələ kateqoriyaya aid edilməyən alət dəstlərinə baxın və onları konfiqurasiya edin." },
+ },
+ },
+ mcpCapabilitiesTitle: "MCP qabiliyyətləri",
+ mcpCapabilitiesDescription: "Daxili MCP alətləri grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the database types it applies to.",
+ mcpCapabilitiesLoading: "MCP qabiliyyətləri yüklənir...",
+ mcpCapabilitiesLoadFailed: "Failed to load MCP qabiliyyətləri: {error}",
+ mcpCapabilitiesSearchPlaceholder: "İmkan və ya alət axtarın",
+ mcpCapabilitiesSearchEmpty: "Uyğun qabiliyyət yoxdur",
+ mcpToolsetToolCount: "{enabled}/{total} alət",
+ mcpAccessLevelClassified: "Hər çağırış üçün",
+ mcpCoverageTypes: "{count} verilənlər bazası növü",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Bağlantıya bağlı deyil",
+ mcpCoverageUsableConnections: "{count} bağlantınızda istifadə oluna bilər",
+ mcpCoverageNoUsableConnections: "Bağlantılarınızın heç biri bundan istifadə etmir",
+ mcpCoveragePartialConnections: "{count} bağlantı yalnız bəzi alətləri dəstəkləyir",
+ mcpCoverageUncoveredConnections: "{count} connections have no MCP alətləri yet: {names}",
+ mcpCoverageSearchPlaceholder: "Verilənlər bazası növlərini axtarın",
+ mcpCoverageSearchEmpty: "Xeyr matching database types",
+ mcpCoverageLegend: "Yalnız dəstəklənən növlər göstərilir. Vurğulanan növlər bağlantılarınıza uyğundur; * qrupdakı bəzi alətlərin növü dəstəkləmədiyini bildirir (təfərrüatlar üçün göstəricini üzərinə gətirin).",
+ mcpCoverageTypeUnsupportedTool: "{tool} tərəfindən dəstəklənmir",
+ mcpCoverageCategoryOther: "Digər",
+ mcpCoveragePartialTool: "{tool}, {total} növdən {count} növü dəstəkləyir",
+ mcpToolDetailSkippedConnections: "Mövcud deyil: {names}",
+ mcpToolDetailCoverage: "Dəstəklənən verilənlər bazası növləri ({count})",
+ mcpToolDetailParameterDefault: "standart: {value}",
+ mcpToolDetailParameterDescription: "Təsvir",
+ mcpToolDetailParameterRequiredNo: "Xeyr",
+ mcpToolDetailParameterRequiredYes: "Bəli",
+ mcpToolDetailParameterRequired: "Tələb olunur",
+ mcpToolDetailParameterType: "Növ",
+ mcpToolDetailParameterName: "Ad",
+ mcpToolDetailNoParameters: "Parametr yoxdur",
+ mcpToolDetailParameters: "Parametrlər",
+ mcpToolDetailDescription: "Model üçün təsvir",
+ mcpToolDetailAccessClassified: "Hər çağırışda təsnif edilir (ifadəyə görə oxuma, yazma və ya yüksək risk)",
+ mcpToolDetailAccess: "Giriş səviyyəsi",
+ mcpToolDetailSummary: "Xülasə",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "{count} bağlantınız bundan istifadə edə bilməz",
+ mcpToolsetDetailTools: "Alətlər",
+ mcpToolsetDetailCoverage: "Əhatə dairəsi",
+ mcpToolsetApply: "Bu alət dəstini tətbiq et",
+ mcpToolsetApplying: "Tətbiq edilir…",
+ mcpToolsetPending: "{count} alət dəyişikliyi hələ tətbiq edilməyib",
+ mcpToolsetApplied: "Cari konfiqurasiya tətbiq edilib",
+ mcpToolsetCloseKeepsDraft: "Bağladıqda dəyişikliklər saxlanılır. Onları Parametrlər səhifəsindən də tətbiq edə bilərsiniz.",
+ mcpToolsetApplyFailed: "Tətbiq etmək alınmadı: {error}. Dəyişikliklər saxlanılıb; yenidən cəhd edin.",
+ mcpToolsetApplyUnavailable: "Alət parametrləri əlçatan deyil. Yüklənmənin bitməsini gözləyin və ya yenidən cəhd edin.",
+ mcpToolsetDetailClose: "Bağla",
+ mcpPluginToolEntriesTitle: "Əlavə alətlərinin qeydləri",
+ mcpPluginsTitle: "Pluginlər",
+ mcpPluginsDescription: "Pluginlər that provide MCP alətləri. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "Yenilə",
+ mcpPluginsLoading: "Plugin alətləri yüklənir...",
+ mcpPluginsLoadFailed: "Əlavənin alətləri yüklənmədi: {error}",
+ mcpPluginsEmpty: "Quraşdırılmış plugin MCP alətləri təqdim etmir.",
+ mcpPluginSaveFailed: "{name} saxlanılmadı: {message}",
+ mcpPluginAuthorClosed: "Müəllif xarici MCP girişini açmayıb",
+ mcpPluginDiscoveryFailed: "Alət kəşfi uğursuz oldu",
+ mcpPluginToolCount: "{exposed}/{total} alət təqdim olunur",
+ mcpPluginToolCountOff: "{total} alət, söndürülüb",
+ mcpPluginCeilingSummary: "Üst hədd: {level}",
+ mcpPluginPendingTools: "{count} yeni alət təsdiq tələb edir",
+ mcpPluginReview: "Nəzərdən keçir",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Alət kəşfi uğursuz oldu: {error}",
+ mcpPluginCeilingTitle: "Avtorizasiya həddi",
+ mcpPluginCeilingDescription: "Üst həddi aşan alətlər MCP müştərilərindən gizli qalır. Faktiki çağırışlar resurs icazələrinə və bağlantı görünürlüğü qaydalarına da uyğun olmalıdır.",
+ mcpPluginEnableFirst: "Üst həddi və alətləri dəyişmək üçün əlavəni aktivləşdirin.",
+ mcpPluginDefaultToolset: "Alətlər",
+ mcpPluginNoTools: "This plugin lists no MCP alətləri right now.",
+ mcpPluginAuthorizeTitle: "Avtorizasiya et {name} for MCP",
+ mcpPluginAuthorizeDescription: "Əlavənin icazə həddini seçin. Aşağıda elan edilən bütün alətlər təsdiqlənir; sonradan əlavə edilən və ya elan edilmiş səviyyəsi yüksələn alətlər oxumadan artıq icazə tələb edərsə, yenidən təsdiq istəyəcək.",
+ mcpPluginAuthorizeTools: "Alətlər ({count})",
+ mcpPluginAuthorizeIncluded: "Açıq",
+ mcpPluginAuthorizeExcluded: "Gizli",
+ mcpPluginAuthorizeFootnote: "Daha sonra əlavənin təfərrüatlarında üst həddi dəyişə və ya ayrı-ayrı alətləri söndürə bilərsiniz.",
+ mcpPluginAccessUndeclared: "Elan edilməyib by the author — never exposed",
+ mcpPluginUndeclaredCount: "{count} alət manifestdə elan edilməyib və gizli qalır",
+ mcpPluginUndeclaredTools: "{count} alətin giriş səviyyəsi əlavənin manifestində elan edilməyib və bu alətlər heç vaxt təqdim olunmayacaq: {names}",
+ mcpPluginAuthorizeCancel: "Ləğv et",
+ mcpPluginAuthorizeConfirm: "Avtorizasiya et",
+ mcpPluginToolEntriesHint: "Əlavə: plagin alətləri üçün icazə siyahısı qeydləri. dbx_*__* bütün plagin alətlərinə, dbx_<prefix>__* isə bir plaginə icazə verir. Plagin keçidləri əlçatan alətləri müəyyən edir; bu qeydlər əlavə filtr yaradır.",
+ mcpPluginAllowlistBlocked: "MCP alətlərinin icazə siyahısında plagin qeydi yoxdur, buna görə plagin keçidlərinin vəziyyətindən asılı olmayaraq bütün plagin alətləri gizli qalır.",
+ mcpPluginAllowlistAllow: "Plugin alətlərinə icazə ver",
+ mcpPluginExposure: {
+ exposed: "Açıq",
+ undeclared: "Elan edilməyib",
+ pluginDisabled: "Plugin söndürülüb",
+ toolDisabled: "Söndürülüb",
+ aboveCeiling: "Həddi aşır",
+ pendingApproval: "Təsdiq tələb olunur",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Yalnız oxu",
+ write: "Oxu və yaz",
+ full: "Tam (yüksək risk daxil)",
+ },
+ mcpAccessLevel: {
+ read: "Oxu",
+ write: "Yaz",
+ full: "Yüksək risk",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "Kəşf və kontekst", description: "Bağlantıları və verilənlər bazalarını siyahılayın, model üçün sxem kontekstini alın." },
+ sqlQuery: { title: "SQL sorğusu", description: "Sorğuları və skriptləri icra edin. Hər ifadənin riski hər çağırışda təsnif edilir." },
+ sqlSession: { title: "Sessiyalar və tranzaksiyalar", description: "Çağırışlar arasında eyni sessiyanı saxlayın və tranzaksiyaları idarə edin." },
+ sqlSchema: { title: "Sxem obyektləri", description: "Cədvəllərə, sütunlara və prosedurların mənbə koduna baxın." },
+ redis: { title: "Redis əmrləri", description: "Redis əmrlərini icra edin." },
+ mq: { title: "Mesajların oxunması və göndərilməsi", description: "Kafka, RocketMQ və RabbitMQ mesajlarını oxuyun və göndərin." },
+ salesforce: { title: "İstifadəçi məlumatları və verilən əməliyyatları", description: "Cari istifadəçini müəyyən edin və tək qeydləri yazın." },
+ workbench: { title: "İş masası", description: "DBX daxilində cədvəlləri açın və sorğu nəticələrini göstərin." },
+ adminConnections: { title: "Əlaqələrin idarə edilməsi", description: "DBX bağlantılarını əlavə edin, çoxaldın və silin." },
+ pluginRouter: { title: "Plaginlərin aşkarlanması və çağırılması", description: "Əlavə alətlərini ehtiyac olduqda tapın və vahid yönləndirici vasitəsilə çağırın." },
+ nacosConfig: { title: "Konfiqurasiya idarəetməsi", description: "Oxu, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "Xidmət idarəetməsi", description: "Xidmətləri və instansiyaları siyahılayın; instansiyaları aktivləşdirin, söndürün və çəkilərini dəyişin." },
+ consulKv: { title: "KV idarəetməsi", description: "Müqayisə edib yeniləmə (CAS) ilə Consul KV açarlarını siyahılayın, oxuyun, yazın və silin." },
+ consulService: { title: "Xidmətlərin aşkarlanması və sağlamlığı", description: "Xidmət və qovşaq kataloqu, xidmətin sağlamlığı və texniki xidmət rejimi." },
+ },
+ mcpToolNacosListNamespaces: "Nacos ad məkanlarını siyahılayın",
+ mcpToolNacosListConfigs: "Nacos konfiqurasiyalarını siyahılayın",
+ mcpToolNacosGetConfig: "Oxu Nacos config",
+ mcpToolNacosConfigHistory: "Nacos konfiqurasiya tarixçəsi",
+ mcpToolNacosPublishConfig: "Nacos konfiqurasiyasını yayımlayın",
+ mcpToolNacosDeleteConfig: "Nacos konfiqurasiyasını silin",
+ mcpToolNacosListServices: "Nacos xidmətlərini siyahılayın",
+ mcpToolNacosListInstances: "Nacos instansiyalarını siyahılayın",
+ mcpToolNacosUpdateInstance: "Nacos instansiyasını yeniləyin",
+ mcpToolNacosSearchConfigs: "Nacos konfiqurasiyalarını axtarın",
+ mcpToolNacosRollbackConfig: "Nacos konfiqurasiyasını geri qaytarın",
+ mcpToolNacosGetService: "Nacos xidmətinə baxın",
+ mcpToolNacosRegisterInstance: "Nacos instansiyasını qeydiyyata alın",
+ mcpToolNacosDeregisterInstance: "Nacos instansiyasının qeydiyyatını ləğv edin",
+ mcpToolConsulKvList: "Consul KV açarlarını siyahılayın",
+ mcpToolConsulKvGet: "Oxu Consul KV key",
+ mcpToolConsulKvPut: "Yaz Consul KV key",
+ mcpToolConsulKvDelete: "Consul KV açarını silin",
+ mcpToolConsulListServices: "Consul xidmətlərini siyahılayın",
+ mcpToolConsulListNodes: "Consul qovşaqlarını siyahılayın",
+ mcpToolConsulServiceHealth: "Consul xidmətinin sağlamlığı",
+ mcpToolConsulSetMaintenance: "Consul texniki xidmət rejimi",
mcpConfigOptionsHint:
"DBX hər MCP müştərisi üçün əlaqələrə girişi və icra icazələrini mərkəzləşdirilmiş şəkildə idarə edir. Yaradılan konfiqurasiyalar yalnız MCP serverini başlatmaq və bu DBX nüsxəsinə qoşulmaq üçün lazım olan icra mühiti parametrlərini ehtiva edir; icazə və ya əlaqə əhatəsi dəyişənlərini ehtiva etmir.",
mcpScopeConnection: "MCP üçün icazə verilən əlaqələr",
@@ -8659,7 +8968,8 @@ export default withEnglishFallback({
mcpOpenCodeConfigPath: "Qlobal səviyyədə ~/.config/opencode/opencode.json və ya layihə səviyyəsində opencode.json.",
mcpPiConfigPath: "Əvvəlcə Pi MCP adapter plaginini quraşdırın: pi install npm:pi-mcp-adapter. Sonra ~/.pi/agent/mcp.json (qlobal) və ya .mcp.json (layihə) faylında yadda saxlayın, yoxlamaq üçün /mcp, Pi-də tətbiq etmək üçün isə /reload əmrini işlədin.",
mcpExecutionMode: "MCP üçün qlobal standart icazə",
- mcpExecutionModeDescription: "Əlaqə və ya verilənlər bazası icazəsi tənzimlənmədikdə istifadə olunan standartı təyin edir. Əlaqənin standartları və verilənlər bazası parametrləri əhatə dairəsinə görə onu əvəz edə bilər.",
+ mcpExecutionModeDescription: "Ayrıca icazəsi olmayan resurslar bu standartdan istifadə edir. Fərqli icazələri aşağıdakı giriş nəzarətində təyin edin.",
+ mcpPermissionsDraftHint: "Ümumi, qrup və bağlantı dəyişiklikləri aşağıdakı Tətbiq et düyməsi ilə saxlanır. Baza icazələri öz pəncərəsində də tətbiq edilə bilər. Alt əhatələr dərhal saxlanır. Qaralamaları ləğv etmək saxlanmış dəyişiklikləri geri qaytarmır.",
mcpExecutionModeReadOnly: "Yalnız oxuma",
mcpExecutionModeSafeWrite: "Məlumatları oxuma/yazma",
mcpExecutionModeRecommended: "Tövsiyə olunur",
@@ -8669,14 +8979,15 @@ export default withEnglishFallback({
mcpExecutionModeHighRiskWriteDescription:
"Məlumatların oxunması/yazılması ilə yanaşı, bütün cədvəli əhatə edən dəyişikliklərə, DDL-ə, TRUNCATE-ə, verilənlər bazasının təmizlənməsinə və digər yüksək riskli əməliyyatlara icazə verir. İstehsal mühitinin və əlaqənin yalnız oxuma mühafizəsi qüvvədə qalır.",
mcpExecutionModeHighRiskConfirm: "Tam giriş bütün cədvəli əhatə edən dəyişikliklərə, DDL-ə, TRUNCATE-ə, verilənlər bazasının təmizlənməsinə və digər yüksək riskli əməliyyatlara icazə verir. Aktivləşdirilsin?",
- mcpCapabilityTitle: "İmkanların müqayisəsi",
- mcpCapabilityDescription: "Bunlar nümunə əməliyyatlardır; DBX-in etibarlı şəkildə təsnif edə bilmədiyi sorğular tam giriş tələb edir.",
+ mcpCapabilityTitle: "İcazələr haqqında",
+ mcpCapabilityDescription: "Cədvəl giriş səviyyələrini göstərir; alətlər İmkanlar bölməsində də açılmalıdır. Yetərsiz icazələr rədd edilir. Çağırış təhlükəsizliyi təsdiqi ayrıca idarə edir və köhnə icazəni izah edir.",
mcpCapabilityOperation: "İmkan",
mcpCapabilityRead: "Sorğular və oxuma əməliyyatları",
mcpCapabilityScopedMutation: "Əhatəsi məhdud məlumat dəyişiklikləri (INSERT, süzgəcli UPDATE/DELETE, açıq göstərilmiş açarların yazılması/silinməsi)",
mcpCapabilityBroadMutation: "Bütün cədvəli əhatə edən yeniləmə/silmə və məlumatların təmizlənməsi",
mcpCapabilitySchemaAdmin: "DDL, struktur dəyişiklikləri və yüksək riskli idarəetmə",
- mcpCapabilityConnectionManagement: "MCP əlaqələrini əlavə et/çıxar",
+ mcpCapabilityConnectionCreate: "MCP əlaqələri əlavə et/çoxalt (qlobal standart icazə)",
+ mcpCapabilityConnectionRemove: "MCP əlaqələrini sil (qlobal standart icazə)",
mcpCapabilityAllowed: "İcazə verilir",
mcpCapabilityBlocked: "Bloklanıb",
mcpQueryTimeout: "Sorğunun gözləmə müddəti (saniyə)",
@@ -8684,6 +8995,9 @@ export default withEnglishFallback({
mcpQueryTimeoutInvalid: "Saniyələrin sayını mənfi olmayan tam ədəd kimi daxil edin və ya əlaqə parametrini götürmək üçün boş saxlayın.",
mcpCapabilityAlwaysEnforced: "Hər rejimdə əlaqə icazə siyahısı, əlaqənin yalnız oxuma mühafizəsi, istehsal mühitinin mühafizəsi və verilənlər bazası hesabının icazələri qüvvədə qalır.",
mcpPolicySaveFailed: "MCP giriş siyasətini yadda saxlamaq mümkün olmadı: {error}",
+ mcpPolicyRetry: "Yenidən cəhd et",
+ mcpPolicyRecover: "MCP icazələrini ehtiyat nüsxəyə köçür və sıfırla",
+ mcpPolicyRecoverConfirm: "Bu əməliyyat zədələnmiş siyasətin ehtiyat nüsxəsini dərhal saxlayacaq və yadda saxlanmamış dəyişikliklər daxil olmaqla MCP icazələrini sıfırlayacaq. Yenidən konfiqurasiya edilənədək bütün bağlantılar və alətlər bloklanacaq. Davam edilsin?",
mcpPolicyLoadFailed: "MCP giriş siyasətini yükləmək mümkün olmadı: {error}",
mcpDetectionTiming: "Bu səhifə açıldıqda DBX avtomatik yoxlayır; yeniləmək üçün Yenidən yoxla düyməsindən istifadə edin.",
mcpNpmBoundary: "DBX MCP-nin vəziyyətini yoxlayır; quraşdırma, yeniləmə və quraşdırmanın silinməsi aşkarlanmış npm, pnpm və ya bun icra mühiti vasitəsilə həyata keçirilir.",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 0b959ec0f0..56955bc4a3 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -805,6 +805,14 @@ export default {
pluginPlatform: {
dataAccessConsent: '"{name}" wants to read data from the connection "{connection}". While that connection is open, the plugin can run read-only queries on it until you revoke access in the Plugin Center. Allow?',
dataAccessConsentTitle: "Data Access Request",
+ mcpToolsBadge: "MCP tools",
+ mcpToolsBadgeHint: "This plugin provides MCP tools. Enable and authorize them in Settings → MCP → Capabilities.",
+ mcpToolsFilter: "Only plugins with MCP tools ({count})",
+ externalMcp: {
+ title: "External MCP clients",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → Capabilities.",
+ notOffered: "The author has not opened this plugin's tools to external MCP clients.",
+ },
aiTools: {
title: "Built-in AI tools",
description: "Off by default: the DBX AI assistant (Agent mode) can call this plugin's tools on its open connections only while this switch is on. Tools that are not declared read-only still ask for your approval before every call.",
@@ -8438,6 +8446,10 @@ export default {
},
detail: {
mcpTool: "MCP tool",
+ mcpClient: "MCP client",
+ mcpTransport: "MCP transport",
+ mcpAccess: "MCP access",
+ mcpConfirmation: "MCP confirmation",
kind: "Type",
operation: "Operation",
connection: "Connection",
@@ -11174,7 +11186,8 @@ export default {
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json globally, or opencode.json at the project level.",
mcpPiConfigPath: "First install the Pi MCP adapter plugin: pi install npm:pi-mcp-adapter. Then save to ~/.pi/agent/mcp.json (global) or .mcp.json (project), run /mcp to verify, and /reload to pick it up in Pi.",
mcpExecutionMode: "MCP global default permission",
- mcpExecutionModeDescription: "Sets the default used when no connection or database permission is configured. Connection defaults and database settings can override it by scope.",
+ mcpExecutionModeDescription: "Resources without their own permission use this default. Set different permissions in Access control below.",
+ mcpPermissionsDraftHint: "Global, group and connection changes use Apply below. Database permissions can also be applied in their dialog. Namespace and other sub-scope settings save immediately. Discarding drafts does not undo saved changes.",
mcpExecutionModeReadOnly: "Read only",
mcpExecutionModeSafeWrite: "Data read/write",
mcpExecutionModeRecommended: "Recommended",
@@ -11183,21 +11196,37 @@ export default {
mcpExecutionModeSafeWriteDescription: "Allows regular INSERT, filtered UPDATE/DELETE, verifiably scoped MongoDB changes, and ordinary Redis writes or explicit-key deletion; blocks table-wide and structural changes.",
mcpExecutionModeHighRiskWriteDescription: "In addition to data read/write, allows table-wide changes, DDL, TRUNCATE, database clearing, and other high-risk operations. Production and connection read-only protections still apply.",
mcpExecutionModeHighRiskConfirm: "Full access allows table-wide changes, DDL, TRUNCATE, database clearing, and other high-risk operations. Enable it?",
- mcpPromptHighRiskSql: "Ask before high-risk SQL (desktop only; read-only and production safeguards remain)",
+ mcpCallSafety: "Call safety",
+ mcpCallSafetyLegacy: "Legacy temporary authorization",
+ mcpCallSafetyEnabled: "Confirm each high-risk call",
+ mcpCallSafetyDisabled: "No additional confirmation",
+ mcpCallSafetyLegacyHint: "Legacy behavior is preserved: data-write access can temporarily run some high-risk operations after confirmation; full access does not prompt. Switching policies rejects insufficient permissions and also confirms high-risk calls with full access.",
+ mcpCallSafetyMigrate: "Use the new confirmation policy",
+ mcpCallSafetyDisableLegacy: "Disable legacy authorization",
+ mcpCallSafetyConfirm: "Request human confirmation before high-risk tool calls",
+ mcpCallSafetyHint: "Applies to built-in and plugin calls identified as high-risk. Permissions are checked first; full access also follows this policy. Confirmation never grants additional access.",
+ mcpCallSafetyDesktopHint: "Confirmation requires DBX desktop and approves only the current call. Unavailable, denied or timed-out confirmations do not execute. Read-only and production protections always apply. Click Apply to save changes.",
+ mcpToolApprovalGenericTitle: "Confirm high-risk tool call",
mcpSqlApprovalTitle: "MCP high-risk SQL approval",
+ mcpToolApprovalPluginTitle: "Confirm high-risk {plugin} tool",
+ 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",
+ mcpToolApprovalTarget: "Target",
mcpSqlApprovalScope: "Connection: {connection} · Database: {database}",
mcpSqlApprovalOnce: "This request only",
mcpSqlApprovalHour: "Allow on this database for 1 hour",
mcpSqlApprovalDay: "Allow on this database for 1 day",
mcpSqlApprovalDeny: "Deny",
- mcpCapabilityTitle: "Capability comparison",
- mcpCapabilityDescription: "These are representative operations; requests DBX cannot classify reliably require full access.",
+ mcpCapabilityTitle: "Permission details",
+ mcpCapabilityDescription: "The table describes access levels; tools must also be enabled under Capabilities. Insufficient permissions are rejected. Call safety controls confirmation separately and explains legacy temporary authorization.",
mcpCapabilityOperation: "Capability",
mcpCapabilityRead: "Queries and reads",
mcpCapabilityScopedMutation: "Scoped data changes (INSERT, filtered UPDATE/DELETE, explicit-key writes/deletion)",
mcpCapabilityBroadMutation: "Table-wide updates/deletes and data clearing",
mcpCapabilitySchemaAdmin: "DDL, structural changes, and high-risk administration",
- mcpCapabilityConnectionManagement: "Add/remove MCP connections",
+ mcpCapabilityConnectionCreate: "Add/duplicate MCP connections (global default permission)",
+ mcpCapabilityConnectionRemove: "Remove MCP connections (global default permission)",
mcpCapabilityAllowed: "Allowed",
mcpCapabilityBlocked: "Blocked",
mcpQueryTimeout: "Query timeout (seconds)",
@@ -11208,6 +11237,9 @@ export default {
mcpQueryTimeoutSaveStatus_failed: "Save failed",
mcpCapabilityAlwaysEnforced: "Every mode remains subject to the connection allowlist, connection read-only protection, production protection, and database-account permissions.",
mcpPolicySaveFailed: "Failed to save the MCP access policy: {error}",
+ mcpPolicyRetry: "Retry",
+ mcpPolicyRecover: "Back up and reset MCP permissions",
+ mcpPolicyRecoverConfirm: "This immediately backs up the damaged policy and resets MCP permissions, including unsaved permission changes. All connections and tools will be blocked until you configure them again. Continue?",
mcpPolicyLoadFailed: "Failed to load the MCP access policy: {error}",
mcpDetectionTiming: "DBX checks automatically when this page opens; use Check again to refresh.",
mcpNpmBoundary: "DBX checks MCP status; installation, upgrades, and uninstallation run through the detected npm, pnpm, or bun runtime.",
@@ -11298,6 +11330,265 @@ export default {
mcpDatabaseEmptyHint: "Click 'Load resource list' to fetch the database list, or add allowed databases manually.",
mcpManagementAccess: "Access methods",
mcpManagementPermissions: "Permission management",
+ mcpManagementCapabilities: "Capabilities",
+ mcpOpenCallHistory: "View MCP call history",
+ mcpAccessTreeTitle: "Access control",
+ mcpAccessTreeDescription: "Set permissions for groups, connections and databases. Inherit uses the parent setting; Effective shows the resulting permission and its source.",
+ mcpAccessTreeSummary: "{visible}/{total} connections visible · exceptions: {groups} groups, {connections} connections, {databases} databases",
+ mcpAccessTreeScopeLabel: "Connection visibility",
+ mcpAccessTreeScopeAll: "All connections",
+ mcpAccessTreeScopeCustom: "Selected only",
+ mcpAccessTreeSearchPlaceholder: "Search groups, connections or databases",
+ mcpAccessTreeExceptionsOnly: "Only show individual settings",
+ mcpAccessTreeColumnResource: "Resource",
+ mcpAccessTreeColumnVisible: "Visible",
+ mcpAccessTreeColumnSetting: "Permission",
+ mcpAccessTreeColumnEffective: "Effective",
+ mcpAccessTreeInherit: "Inherit",
+ mcpAccessTreeGroupPartiallyVisible: "Some connections visible ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "All current connections visible ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Only child items are authorized, not the entire group. Check to allow the whole group, including future connections.",
+ mcpAccessTreeGroupDefaultHint: "Group defaults apply to child items without their own permission setting. They do not change connection visibility.",
+ mcpAccessTreeHidden: "Not visible to MCP",
+ mcpAccessTreeSourceGlobal: "global default",
+ mcpAccessTreeSourceGroup: "from group {group}",
+ mcpAccessTreeSourceConnection: "connection setting",
+ mcpAccessTreeSourceDatabase: "database setting",
+ mcpAccessTreeGroupCount: "{count} connections",
+ mcpAccessTreeLegacy: "legacy",
+ mcpAccessTreeLegacyHint: "Saved by an older version: it can only narrow what the connection inherits. Choose a permission again to make it a regular setting.",
+ mcpAccessTreeCoveredByGroup: "Visible through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "High risk allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "Databases",
+ mcpAccessTreeDatabaseScopeAll: "All databases",
+ mcpAccessTreeDatabaseScopeSelected: "Selected ({count})",
+ mcpAccessTreeDatabaseScopeNone: "No databases",
+ mcpDatabaseRemoveConfirm: "Removing the selected databases also removes their permission overrides. Continue?",
+ mcpDatabaseUnavailable: "Database access settings are unavailable. Wait for loading to finish or retry.",
+ mcpDatabaseConfigure: "Configure database access",
+ mcpDatabaseOverrideCount: "{count} overrides",
+ mcpDatabaseDialogTitle: "{name} / Database access",
+ mcpDatabaseDialogDescription: "Select databases and set their permissions. Moving an item to the right takes effect only after applying.",
+ mcpDatabaseInherited: "Inherited access: {level}",
+ mcpDatabaseSavedInherited: "Parent permissions have pending changes. Applying only database access still inherits the saved permissions: {level}",
+ mcpDatabaseHiddenConnection: "This connection is currently hidden from MCP. Applying database access does not expose the connection.",
+ mcpDatabaseAllHint: "Includes existing and future databases, using the connection permissions.",
+ mcpDatabaseNoneHint: "Applying will deny access to every database.",
+ mcpDatabaseLoaded: "Loaded {count} databases visible to this account",
+ mcpDatabaseRefresh: "Refresh databases",
+ mcpDatabaseAddSelected: "Add →",
+ mcpDatabaseRemoveSelected: "← Remove",
+ mcpDatabaseAvailable: "Not selected ({count})",
+ mcpDatabaseSelected: "Selected ({count})",
+ mcpDatabaseSearch: "Search database names",
+ mcpDatabaseSelectResults: "Select current search results ({count})",
+ mcpDatabaseBatchLevel: "Set access for checked ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "Allow full access for {count} checked databases? Connection read-only and production protections still apply.",
+ mcpDatabaseNotDiscovered: "Not found in this discovery",
+ mcpDatabaseShowMore: "Show more ({shown}/{total} shown)",
+ mcpDatabaseSaveHint: "Saves only this connection’s database scope and individual permissions. Other drafts are retained.",
+ mcpDatabaseApply: "Apply database access",
+ mcpAccessTreePickDatabases: "Choose databases",
+ mcpAccessTreePickerTitle: "Databases of {name}",
+ mcpAccessTreeLoadingDatabases: "Loading databases...",
+ mcpAccessTreeLoadDatabasesFailed: "Could not load databases: {error}. You can still add names manually.",
+ mcpAccessTreeManualDatabase: "Add a database name",
+ mcpAccessTreeNoMatch: "No matching resources",
+ mcpAccessTreeEmpty: "No connections yet",
+ mcpAccessTreeFootnote: "Priority: database > connection > closest group > parent group > global default. Connection read-only protection, production protection and database credentials always apply on top.",
+ mcpAccessTreeNacosNamespace: "Namespace",
+ mcpPluginScopeAll: "All ({title})",
+ mcpPluginScopeSelected: "Selected ({count})",
+ mcpPluginScopeNone: "No {title}",
+ mcpPluginScopeAdd: "Add {title}",
+ mcpPluginScopeLoad: "Read from plugin",
+ mcpPluginToolsMode: "External plugin tool delivery",
+ mcpPluginToolsModeDescription: "Choose how DBX provides authorized plugin tools to MCP clients. Click Apply at the bottom to save changes.",
+ mcpPluginToolsModeAuto: "Automatic (compatibility)",
+ mcpPluginToolsModeFlat: "List directly (default)",
+ mcpPluginToolsModeLazy: "Lazy discovery",
+ mcpPluginToolsModeFlatDescription: "List each authorized plugin tool so clients can call it directly.",
+ mcpPluginToolsModeLazyDescription: "Provide shared plugin discovery and invocation tools, fetching tool details when needed. Enable Plugin discovery and invocation under DBX general.",
+ mcpPluginToolsModeAutoDescription: "Keep the existing automatic behavior: list directly with up to 40 plugin tools in total, otherwise use on-demand discovery.",
+ mcpBrowser: {
+ viewMode: "View mode",
+ viewManage: "Category management",
+ viewOverview: "Global overview",
+ overviewSummary: "{toolsets} toolsets · {total} tools · {enabled} enabled",
+ overviewPluginsHint: "Review plugin tools and authorization. Open a plugin for details.",
+ overviewOpenDetails: "View details",
+ expandCategory: "Expand category",
+ collapseCategory: "Collapse category",
+ builtin: "Built-in capabilities",
+ plugins: "Plugin extensions",
+ advanced: "Advanced settings",
+ navigation: "Capability categories",
+ searchPlaceholder: "Search categories, capabilities, plugins or tools…",
+ clearSearch: "Clear search",
+ searchResults: "Search results",
+ categoryCount: "{count} toolsets",
+ summary: "{toolsets} toolsets · {total} tools · {enabled} enabled",
+ enableCategory: "Enable all in this category",
+ disableCategory: "Disable all in this category",
+ draftHint: "Apply a toolset in its details, or use Apply below to save all pending settings.",
+ batchChanged: "Tools in this category updated. Click Apply to save",
+ coverageHint: "Applicable connections are counted by connection type, not actual authorization scope.",
+ uncovered: "{count} connections have no built-in tool coverage",
+ viewDetails: "View details",
+ emptyEnabled: "No tools are enabled in this category. Turn off “Only show enabled” to configure them.",
+ retry: "Retry",
+ enabledToolCount: "{enabled}/{total} enabled",
+ partialEnabled: "Partially enabled",
+ coverageConnections: "Applies to {count} connections",
+ coveragePartialConnections: "{count} partially supported",
+ noMatchingConnections: "No applicable connections",
+ resourceScopes: "Resource scopes",
+ pluginImmediate: "Changes save immediately, independently of Apply / Cancel at the bottom",
+ pluginSaving: "Saving…",
+ pluginSaved: "Saved",
+ pluginOnlyEnabledEmpty: "No tools are enabled. Turn off “Only show enabled” to see them.",
+ pluginUnavailable: "This plugin is no longer available. Refresh the plugin list",
+ resourceKind: {
+ database: "Database",
+ dbIndex: "Logical database",
+ topic: "Topic",
+ queue: "Queue",
+ org: "Organization",
+ namespace: "Namespace",
+ },
+ category: {
+ database: { title: "Databases", description: "Query data, manage sessions and transactions, browse object structures and run Redis commands." },
+ nacos: { title: "Nacos", description: "Manage configurations, services and instances." },
+ consul: { title: "Consul", description: "Manage KV entries, discover services and view health status." },
+ mq: { title: "Message queues", description: "Read and send messages." },
+ salesforce: { title: "Salesforce", description: "Look up identity and work with data." },
+ dbx: { title: "DBX shared", description: "Capabilities shared across products: connection discovery, workbench integration, connection management, and plugin discovery and invocation." },
+ other: { title: "Other capabilities", description: "View and configure toolsets that have not been categorized yet." },
+ },
+ },
+ mcpCapabilitiesTitle: "MCP capabilities",
+ mcpCapabilitiesFilterLabel: "Capability filter",
+ mcpCapabilitiesFilterAll: "All",
+ mcpCapabilitiesFilterBuiltin: "Built-in",
+ mcpCapabilitiesFilterPlugin: "Plugin",
+ mcpCapabilitiesOnlyEnabled: "Only show enabled",
+ mcpCapabilitiesDescription: "Built-in MCP tools grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the database types it applies to.",
+ mcpCapabilitiesLoading: "Loading MCP capabilities...",
+ mcpCapabilitiesLoadFailed: "Failed to load MCP capabilities: {error}",
+ mcpCapabilitiesSearchPlaceholder: "Search capabilities or tools",
+ mcpCapabilitiesSearchEmpty: "No matching capabilities",
+ mcpToolsetToolCount: "{enabled}/{total} tools",
+ mcpAccessLevelClassified: "Per call",
+ mcpCoverageTypes: "{count} database types",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Not tied to a connection",
+ mcpCoverageUsableConnections: "Used by {count} of your connections",
+ mcpCoverageNoUsableConnections: "None of your connections use it",
+ mcpCoveragePartialConnections: "{count} connections support only some tools",
+ mcpCoverageUncoveredConnections: "{count} connections have no MCP tools yet: {names}",
+ mcpCoverageSearchPlaceholder: "Search database types",
+ mcpCoverageSearchEmpty: "No matching database types",
+ mcpCoverageLegend: "Only supported types are listed. Highlighted types match your connections; * means some tools in this group don't support the type (hover for details).",
+ mcpCoverageTypeUnsupportedTool: "Not supported by {tool}",
+ mcpCoverageCategoryOther: "Other",
+ mcpCoveragePartialTool: "{tool} supports {count} of {total}",
+ mcpToolDetailSkippedConnections: "Not available on: {names}",
+ mcpToolDetailCoverage: "Supported database types ({count})",
+ mcpToolDetailParameterDefault: "default: {value}",
+ mcpToolDetailParameterDescription: "Description",
+ mcpToolDetailParameterRequiredNo: "No",
+ mcpToolDetailParameterRequiredYes: "Yes",
+ mcpToolDetailParameterRequired: "Required",
+ mcpToolDetailParameterType: "Type",
+ mcpToolDetailParameterName: "Name",
+ mcpToolDetailNoParameters: "No parameters",
+ mcpToolDetailParameters: "Parameters",
+ mcpToolDetailDescription: "Model-facing description",
+ mcpToolDetailAccessClassified: "Classified per call (read, write, or high risk by statement)",
+ mcpToolDetailAccess: "Access level",
+ mcpToolDetailSummary: "Summary",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "{count} of your connections can't use it",
+ mcpToolsetDetailTools: "Tools",
+ mcpToolsetDetailCoverage: "Coverage",
+ mcpToolsetApply: "Apply this toolset",
+ mcpToolsetApplying: "Applying…",
+ mcpToolsetPending: "{count} tool changes not yet applied",
+ mcpToolsetApplied: "Current configuration applied",
+ mcpToolsetCloseKeepsDraft: "Closing keeps your changes. You can also apply them from Settings.",
+ mcpToolsetApplyFailed: "Could not apply: {error}. Your changes are kept; try again.",
+ mcpToolsetApplyUnavailable: "Tool settings are unavailable. Wait for loading to finish or retry.",
+ mcpToolsetDetailClose: "Close",
+ mcpPluginToolEntriesTitle: "Plugin tool entries",
+ mcpPluginsTitle: "Plugins",
+ mcpPluginsDescription: "Plugins that provide MCP tools. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "Refresh",
+ mcpPluginsLoading: "Loading plugin tools...",
+ mcpPluginsLoadFailed: "Failed to load plugin tools: {error}",
+ mcpPluginsEmpty: "No installed plugin provides MCP tools.",
+ mcpPluginSaveFailed: "Failed to save {name}: {message}",
+ mcpPluginAuthorClosed: "The author has not opened it to external MCP",
+ mcpPluginDiscoveryFailed: "Tool discovery failed",
+ mcpPluginToolCount: "{exposed}/{total} tools exposed",
+ mcpPluginToolCountOff: "{total} tools, off",
+ mcpPluginCeilingSummary: "Ceiling: {level}",
+ mcpPluginPendingTools: "{count} new tools need confirmation",
+ mcpPluginReview: "Review",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Tool discovery failed: {error}",
+ mcpPluginCeilingTitle: "Authorization ceiling",
+ mcpPluginCeilingDescription: "Tools above the ceiling stay hidden from MCP clients. Actual calls must also satisfy resource permissions and connection visibility rules.",
+ mcpPluginEnableFirst: "Turn the plugin on to change its ceiling and tools.",
+ mcpPluginDefaultToolset: "Tools",
+ mcpPluginNoTools: "This plugin lists no MCP tools right now.",
+ mcpPluginAuthorizeTitle: "Authorize {name} for MCP",
+ mcpPluginAuthorizeDescription: "Choose how far this plugin's tools may go. Every declared tool below is accepted; tools added later, or tools whose declared level rises, that need more than read access will ask again.",
+ mcpPluginAuthorizeTools: "Tools ({count})",
+ mcpPluginAuthorizeIncluded: "Exposed",
+ mcpPluginAuthorizeExcluded: "Hidden",
+ mcpPluginAuthorizeFootnote: "You can change the ceiling or switch off single tools later in the plugin detail.",
+ mcpPluginAccessUndeclared: "Not declared by the author — never exposed",
+ mcpPluginUndeclaredCount: "{count} tools are not declared in the manifest and stay hidden",
+ mcpPluginUndeclaredTools: "{count} tools are not declared with an access level in the plugin manifest and will never be exposed: {names}",
+ mcpPluginAuthorizeCancel: "Cancel",
+ mcpPluginAuthorizeConfirm: "Authorize",
+ mcpPluginToolEntriesHint: "Advanced: allowlist entries for plugin tools. dbx_*__* allows every plugin tool, dbx_<prefix>__* one plugin. Plugin switches determine which tools are available; these entries add another filter.",
+ mcpPluginAllowlistBlocked: "The MCP tool allowlist has no plugin entry, so every plugin tool stays hidden regardless of the plugin switches.",
+ mcpPluginAllowlistAllow: "Allow plugin tools",
+ mcpPluginExposure: {
+ exposed: "Exposed",
+ undeclared: "Not declared",
+ pluginDisabled: "Plugin off",
+ toolDisabled: "Switched off",
+ aboveCeiling: "Above ceiling",
+ pendingApproval: "Needs confirmation",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Read only",
+ write: "Read & write",
+ full: "Full (incl. high risk)",
+ },
+ mcpAccessLevel: {
+ read: "Read",
+ write: "Write",
+ full: "High risk",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "Discovery & context", description: "List connections and databases, and fetch schema context for the model." },
+ sqlQuery: { title: "SQL query", description: "Run queries and scripts. Each statement's risk is classified per call." },
+ sqlSession: { title: "Sessions & transactions", description: "Pin a session across calls and control transactions." },
+ sqlSchema: { title: "Schema objects", description: "Browse tables, columns, and routine source." },
+ redis: { title: "Redis commands", description: "Run Redis commands." },
+ mq: { title: "Read and send messages", description: "Peek and send Kafka, RocketMQ, and RabbitMQ messages." },
+ salesforce: { title: "Identity and data operations", description: "Identify the current user and write single records." },
+ workbench: { title: "Workbench", description: "Open tables and show query results inside DBX." },
+ adminConnections: { title: "Connection management", description: "Add, duplicate, and remove DBX connections." },
+ pluginRouter: { title: "Plugin discovery and invocation", description: "Discover plugin tools on demand and call them through one router." },
+ nacosConfig: { title: "Configuration management", description: "Read, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "Service management", description: "List services and instances; bring instances online/offline or change weights." },
+ consulKv: { title: "KV management", description: "List, read, write and delete Consul KV keys with compare-and-set." },
+ consulService: { title: "Service discovery and health", description: "Catalog services and nodes, service health, maintenance mode." },
+ },
mcpTransportLabel: "Connection type",
mcpRuntimeSettings: "Runtime settings",
mcpTransportLocalStdio: "Local stdio",
@@ -11407,6 +11698,28 @@ export default {
mcpToolPluginList: "Plugin catalog",
mcpToolPluginTools: "Plugin tool listing",
mcpToolPluginCall: "Call plugin tools",
+ mcpToolNacosListNamespaces: "List Nacos namespaces",
+ mcpToolNacosListConfigs: "List Nacos configs",
+ mcpToolNacosGetConfig: "Read Nacos config",
+ mcpToolNacosConfigHistory: "Nacos config history",
+ mcpToolNacosPublishConfig: "Publish Nacos config",
+ mcpToolNacosDeleteConfig: "Delete Nacos config",
+ mcpToolNacosListServices: "List Nacos services",
+ mcpToolNacosListInstances: "List Nacos instances",
+ mcpToolNacosUpdateInstance: "Update Nacos instance",
+ mcpToolNacosSearchConfigs: "Search Nacos configs",
+ mcpToolNacosRollbackConfig: "Rollback Nacos config",
+ mcpToolNacosGetService: "Read Nacos service",
+ mcpToolNacosRegisterInstance: "Register Nacos instance",
+ mcpToolNacosDeregisterInstance: "Deregister Nacos instance",
+ mcpToolConsulKvList: "List Consul KV keys",
+ mcpToolConsulKvGet: "Read Consul KV key",
+ mcpToolConsulKvPut: "Write Consul KV key",
+ mcpToolConsulKvDelete: "Delete Consul KV key",
+ mcpToolConsulListServices: "List Consul services",
+ mcpToolConsulListNodes: "List Consul nodes",
+ mcpToolConsulServiceHealth: "Consul service health",
+ mcpToolConsulSetMaintenance: "Consul maintenance mode",
supportInfoTitle: "Support information",
supportInfoDescription: "Copy these environment details when filing issues or asking for help.",
supportInfoCopy: "Copy support info",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 36ea437523..a529d5e1bc 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -612,6 +612,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: '"{name}" quiere leer datos de la conexión "{connection}". Mientras esa conexión esté abierta, el plugin podrá ejecutar consultas de solo lectura en ella hasta que revoques el acceso en el Centro de plugins. ¿Permitir?',
dataAccessConsentTitle: "Solicitud de acceso a datos",
+ mcpToolsBadge: "Herramientas MCP",
+ mcpToolsBadgeHint: "This plugin provides Herramientas MCP. Enable and authorize them in Settings → MCP → Capacidades.",
+ mcpToolsFilter: "Solo plugins con herramientas MCP ({count})",
+ externalMcp: {
+ title: "Clientes MCP externos",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → Capacidades.",
+ notOffered: "El autor no ha habilitado las herramientas de este complemento para clientes MCP externos.",
+ },
aiTools: {
title: "Herramientas de IA integradas",
description: "Desactivado por defecto: el asistente de IA de DBX (modo Agent) solo puede usar las herramientas de este plugin en sus conexiones abiertas mientras el interruptor esté encendido. Las herramientas no declaradas de solo lectura seguirán pidiendo aprobación en cada llamada.",
@@ -7466,6 +7474,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "Herramienta MCP",
+ mcpClient: "Cliente MCP",
+ mcpTransport: "Transporte MCP",
+ mcpAccess: "Acceso MCP",
+ mcpConfirmation: "Confirmación MCP",
kind: "Tipo",
operation: "Operación",
connection: "Conexión",
@@ -9856,6 +9868,303 @@ export default withEnglishFallback({
mcpUninstallConfirm: "¿Desinstalar el servidor MCP de DBX? Los clientes MCP configurados ya no podrán iniciarlo.",
mcpUninstallFailed: "Error al desinstalar: {error}",
mcpConfig: "Configuración de MCP",
+ mcpCapabilitiesFilterLabel: "Filtro de capacidades",
+ mcpCapabilitiesFilterAll: "Todas",
+ mcpCapabilitiesFilterBuiltin: "Integradas",
+ mcpCapabilitiesFilterPlugin: "Complemento",
+ mcpCapabilitiesOnlyEnabled: "Mostrar solo activadas",
+ mcpPluginScopeLoad: "Leer del plugin",
+ mcpPluginToolsMode: "Cómo DBX ofrece herramientas de plugins",
+ mcpPluginToolsModeDescription: "Elige cómo DBX ofrece las herramientas autorizadas de plugins a los clientes MCP. Pulsa Aplicar al pie para guardar los cambios.",
+ mcpPluginToolsModeAuto: "Automático (compatibilidad)",
+ mcpPluginToolsModeFlat: "Listar directamente (predeterminado)",
+ mcpPluginToolsModeLazy: "Descubrimiento bajo demanda",
+ mcpPluginToolsModeFlatDescription: "Lista cada herramienta autorizada para que los clientes puedan invocarla directamente.",
+ mcpPluginToolsModeLazyDescription: "Ofrece herramientas comunes de descubrimiento e invocación y obtiene los detalles cuando se necesitan. Activa el descubrimiento e invocación de plugins en DBX general.",
+ mcpPluginToolsModeAutoDescription: "Conserva el cambio automático existente: lista directamente hasta 40 herramientas de plugins en total; con más, usa el descubrimiento bajo demanda.",
+ mcpCallSafety: "Seguridad de llamadas",
+ mcpCallSafetyLegacy: "Autorización temporal heredada",
+ mcpCallSafetyEnabled: "Confirmar cada llamada de alto riesgo",
+ mcpCallSafetyDisabled: "Sin confirmación adicional",
+ mcpCallSafetyLegacyHint: "Se conserva el comportamiento anterior: escritura de datos puede autorizar temporalmente algunas operaciones de alto riesgo; acceso completo no pregunta. La nueva política rechaza permisos insuficientes y confirma también con acceso completo.",
+ mcpCallSafetyMigrate: "Usar la nueva política",
+ mcpCallSafetyDisableLegacy: "Desactivar autorización heredada",
+ mcpCallSafetyConfirm: "Pedir confirmación antes de llamadas de alto riesgo",
+ mcpCallSafetyHint: "Se aplica a llamadas integradas y de plugins identificadas como de alto riesgo. Primero se verifican permisos, incluso con acceso completo. Confirmar nunca amplía permisos.",
+ mcpCallSafetyDesktopHint: "Requiere DBX de escritorio y solo aprueba la llamada actual. Sin confirmación, rechazada o caducada, no se ejecuta. Las protecciones de solo lectura y producción permanecen. Pulsa Aplicar para guardar.",
+ mcpToolApprovalGenericTitle: "Confirmar llamada de alto riesgo",
+ mcpToolApprovalPluginTitle: "Confirmar herramienta de alto riesgo de {plugin}",
+ 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",
+ mcpToolApprovalTarget: "Destino",
+ mcpManagementCapabilities: "Capacidades",
+ mcpOpenCallHistory: "Ver historial de llamadas MCP",
+ mcpAccessTreeTitle: "Control de acceso",
+ mcpAccessTreeDescription: "Configure permisos para grupos, conexiones y bases de datos. Heredar usa el ajuste superior; el permiso efectivo muestra el resultado y su origen.",
+ mcpAccessTreeSummary: "{visible}/{total} conexiones visibles · excepciones: {groups} grupos, {connections} conexiones, {databases} bases de datos",
+ mcpAccessTreeScopeLabel: "Visibilidad de conexiones",
+ mcpAccessTreeScopeAll: "Todas las conexiones",
+ mcpAccessTreeScopeCustom: "Solo seleccionadas",
+ mcpAccessTreeSearchPlaceholder: "Buscar grupos, conexiones o bases de datos",
+ mcpAccessTreeExceptionsOnly: "Solo mostrar ajustes individuales",
+ mcpAccessTreeColumnResource: "Recurso",
+ mcpAccessTreeColumnVisible: "Visible",
+ mcpAccessTreeColumnSetting: "Permiso",
+ mcpAccessTreeColumnEffective: "Efectivo",
+ mcpAccessTreeInherit: "Heredar",
+ mcpAccessTreeGroupPartiallyVisible: "Algunas conexiones visibles ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "Todas las conexiones actuales visibles ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Solo están autorizados elementos secundarios, no todo el grupo. Marque para permitir todo el grupo, incluidas las conexiones futuras.",
+ mcpAccessTreeGroupDefaultHint: "Los permisos predeterminados del grupo se aplican a elementos secundarios sin permisos propios. No cambian la visibilidad de las conexiones.",
+ mcpAccessTreeHidden: "No visible para MCP",
+ mcpAccessTreeSourceGlobal: "valor global predeterminado",
+ mcpAccessTreeSourceGroup: "del grupo {group}",
+ mcpAccessTreeSourceConnection: "ajuste de conexión",
+ mcpAccessTreeSourceDatabase: "ajuste de base de datos",
+ mcpAccessTreeGroupCount: "{count} conexiones",
+ mcpAccessTreeLegacy: "heredado",
+ mcpAccessTreeLegacyHint: "Guardado por una versión anterior: solo puede restringir los permisos heredados por la conexión. Vuelva a elegir un permiso para convertirlo en una configuración normal.",
+ mcpAccessTreeCoveredByGroup: "Visible mediante un grupo padre seleccionado",
+ mcpAccessTreeHighRiskConfirm: "Alto riesgo allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "Bases de datos",
+ mcpAccessTreeDatabaseScopeAll: "Todas las bases de datos",
+ mcpAccessTreeDatabaseScopeSelected: "Seleccionadas ({count})",
+ mcpAccessTreeDatabaseScopeNone: "Ninguna base de datos",
+ mcpDatabaseRemoveConfirm: "Quitar las bases seleccionadas también elimina sus permisos específicos. ¿Continuar?",
+ mcpDatabaseUnavailable: "La configuración de acceso a bases de datos no está disponible. Espere a que termine la carga o reintente.",
+ mcpDatabaseConfigure: "Configurar acceso a bases de datos",
+ mcpDatabaseOverrideCount: "{count} permisos específicos",
+ mcpDatabaseDialogTitle: "{name} / Acceso a bases de datos",
+ mcpDatabaseDialogDescription: "Seleccione bases de datos y sus permisos. Moverlas a la derecha solo surte efecto al aplicar.",
+ mcpDatabaseInherited: "Permisos heredados: {level}",
+ mcpDatabaseSavedInherited: "Hay cambios pendientes en permisos superiores. Al aplicar solo este ámbito, se heredan los permisos guardados: {level}",
+ mcpDatabaseHiddenConnection: "Esta conexión está oculta para MCP. Aplicar estos permisos no hace visible la conexión.",
+ mcpDatabaseAllHint: "Incluye bases de datos actuales y futuras con los permisos de la conexión.",
+ mcpDatabaseNoneHint: "Al aplicar, se denegará el acceso a todas las bases de datos.",
+ mcpDatabaseLoaded: "Se cargaron {count} bases de datos visibles para esta cuenta",
+ mcpDatabaseRefresh: "Actualizar lista",
+ mcpDatabaseAddSelected: "Añadir →",
+ mcpDatabaseRemoveSelected: "← Quitar",
+ mcpDatabaseAvailable: "Sin seleccionar ({count})",
+ mcpDatabaseSelected: "Seleccionadas ({count})",
+ mcpDatabaseSearch: "Buscar bases de datos",
+ mcpDatabaseSelectResults: "Seleccionar resultados actuales ({count})",
+ mcpDatabaseBatchLevel: "Permisos de marcadas ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "¿Permitir acceso completo a las {count} bases de datos marcadas? Se mantienen las protecciones de solo lectura de la conexión y del entorno de producción.",
+ mcpDatabaseNotDiscovered: "No encontrada en esta consulta",
+ mcpDatabaseShowMore: "Mostrar más ({shown}/{total})",
+ mcpDatabaseSaveHint: "Guarda solo el ámbito y los permisos de bases de datos de esta conexión. Conserva los demás cambios pendientes.",
+ mcpDatabaseApply: "Aplicar permisos de bases de datos",
+ mcpAccessTreePickDatabases: "Elegir bases de datos",
+ mcpAccessTreePickerTitle: "Bases de datos of {name}",
+ mcpAccessTreeLoadingDatabases: "Cargando bases de datos...",
+ mcpAccessTreeLoadDatabasesFailed: "No se pudieron cargar las bases de datos: {error}. Aún puede añadir nombres manualmente.",
+ mcpAccessTreeManualDatabase: "Añadir un nombre de base de datos",
+ mcpAccessTreeNoMatch: "No hay recursos coincidentes",
+ mcpAccessTreeEmpty: "Aún no hay conexiones",
+ mcpAccessTreeFootnote: "Priority: database > connection > closest group > parent group > valor global predeterminado. Connection read-only protection, production protection and database credentials always apply on top.",
+ mcpAccessTreeNacosNamespace: "Espacio de nombres",
+ mcpPluginScopeAll: "Todos ({title})",
+ mcpPluginScopeSelected: "Seleccionados ({count})",
+ mcpPluginScopeNone: "Ningún recurso ({title})",
+ mcpPluginScopeAdd: "Añadir {title}",
+ mcpBrowser: {
+ viewMode: "Modo de vista",
+ viewManage: "Gestión por categorías",
+ viewOverview: "Vista general",
+ overviewSummary: "{toolsets} conjuntos de herramientas · {total} herramientas · {enabled} activadas",
+ overviewPluginsHint: "Revisa las herramientas y la autorización del plugin. Abre un plugin para ver los detalles.",
+ overviewOpenDetails: "Ver detalles",
+ expandCategory: "Expandir categoría",
+ collapseCategory: "Contraer categoría",
+ builtin: "Capacidades integradas",
+ plugins: "Extensiones de plugins",
+ advanced: "Configuración avanzada",
+ navigation: "Categorías de capacidades",
+ searchPlaceholder: "Buscar categorías, capacidades, plugins o herramientas…",
+ clearSearch: "Borrar búsqueda",
+ searchResults: "Resultados de búsqueda",
+ categoryCount: "{count} conjuntos de herramientas",
+ summary: "{toolsets} conjuntos · {total} herramientas · {enabled} activadas",
+ enableCategory: "Activar toda esta categoría",
+ disableCategory: "Desactivar toda esta categoría",
+ draftHint: "Aplica un conjunto desde sus detalles o usa Aplicar abajo para guardar todos los ajustes pendientes.",
+ batchChanged: "Herramientas de esta categoría modificadas. Pulsa Aplicar para guardar",
+ coverageHint: "Las conexiones compatibles se cuentan por tipo de conexión, no por el alcance real de autorización.",
+ uncovered: "{count} conexiones sin cobertura de herramientas integradas",
+ viewDetails: "Ver detalles",
+ emptyEnabled: "No hay herramientas activadas en esta categoría. Desmarca «Mostrar solo activadas» para configurarlas.",
+ retry: "Reintentar",
+ enabledToolCount: "{enabled}/{total} activadas",
+ partialEnabled: "Activada parcialmente",
+ coverageConnections: "Compatible con {count} conexiones",
+ coveragePartialConnections: "{count} con compatibilidad parcial",
+ noMatchingConnections: "Sin conexiones compatibles",
+ resourceScopes: "Ámbitos de recursos",
+ pluginImmediate: "Los cambios se guardan de inmediato, independientemente de Aplicar / Cancelar al pie",
+ pluginSaving: "Guardando…",
+ pluginSaved: "Guardado",
+ pluginOnlyEnabledEmpty: "No hay herramientas activadas. Desmarca «Mostrar solo activadas» para verlas.",
+ pluginUnavailable: "Este plugin ya no está disponible. Actualiza la lista de plugins",
+ resourceKind: {
+ database: "Base de datos",
+ dbIndex: "Base de datos lógica",
+ topic: "Tema",
+ queue: "Cola",
+ org: "Organización",
+ namespace: "Espacio de nombres",
+ },
+ category: {
+ database: { title: "Bases de datos", description: "Consulta datos, gestiona sesiones y transacciones, explora estructuras de objetos y ejecuta comandos Redis." },
+ nacos: { title: "Nacos", description: "Gestiona configuraciones, servicios e instancias." },
+ consul: { title: "Consul", description: "Gestiona entradas KV, descubre servicios y consulta su estado de salud." },
+ mq: { title: "Colas de mensajes", description: "Lee y envía mensajes." },
+ salesforce: { title: "Salesforce", description: "Consulta la identidad y opera con datos." },
+ dbx: { title: "DBX compartido", description: "Capacidades compartidas entre productos: descubrimiento de conexiones, integración con el entorno de trabajo, gestión de conexiones y descubrimiento e invocación de plugins." },
+ other: { title: "Otras capacidades", description: "Consulta y configura los conjuntos de herramientas que aún no tienen categoría." },
+ },
+ },
+ mcpCapabilitiesTitle: "Capacidades de MCP",
+ mcpCapabilitiesDescription: "Integrado Herramientas MCP grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the tipos de base de datos it applies to.",
+ mcpCapabilitiesLoading: "Cargando capacidades de MCP...",
+ mcpCapabilitiesLoadFailed: "Failed to load Capacidades de MCP: {error}",
+ mcpCapabilitiesSearchPlaceholder: "Buscar capacidades o herramientas",
+ mcpCapabilitiesSearchEmpty: "No hay capacidades coincidentes",
+ mcpToolsetToolCount: "{enabled}/{total} herramientas",
+ mcpAccessLevelClassified: "Por llamada",
+ mcpCoverageTypes: "{count} tipos de base de datos",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Sin conexión asociada",
+ mcpCoverageUsableConnections: "Lo usan {count} de sus conexiones",
+ mcpCoverageNoUsableConnections: "Ninguna de sus conexiones lo usa",
+ mcpCoveragePartialConnections: "{count} conexiones solo admiten algunas herramientas",
+ mcpCoverageUncoveredConnections: "{count} connections have no Herramientas MCP yet: {names}",
+ mcpCoverageSearchPlaceholder: "Search tipos de base de datos",
+ mcpCoverageSearchEmpty: "No matching tipos de base de datos",
+ mcpCoverageLegend: "Solo se muestran los tipos compatibles. Los resaltados corresponden a sus conexiones; * indica que algunas herramientas del grupo no admiten ese tipo (pase el cursor para ver detalles).",
+ mcpCoverageTypeUnsupportedTool: "No compatible con {tool}",
+ mcpCoverageCategoryOther: "Otro",
+ mcpCoveragePartialTool: "{tool} admite {count} de {total}",
+ mcpToolDetailSkippedConnections: "No disponible en: {names}",
+ mcpToolDetailCoverage: "Supported tipos de base de datos ({count})",
+ mcpToolDetailParameterDefault: "predeterminado: {value}",
+ mcpToolDetailParameterDescription: "Descripción",
+ mcpToolDetailParameterRequiredNo: "No",
+ mcpToolDetailParameterRequiredYes: "Sí",
+ mcpToolDetailParameterRequired: "Obligatorio",
+ mcpToolDetailParameterType: "Tipo",
+ mcpToolDetailParameterName: "Nombre",
+ mcpToolDetailNoParameters: "Sin parámetros",
+ mcpToolDetailParameters: "Parámetros",
+ mcpToolDetailDescription: "Descripción para el modelo",
+ mcpToolDetailAccessClassified: "Clasificado en cada llamada (lectura, escritura o alto riesgo según la sentencia)",
+ mcpToolDetailAccess: "Nivel de acceso",
+ mcpToolDetailSummary: "Resumen",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "{count} de sus conexiones no pueden usarlo",
+ mcpToolsetDetailTools: "Herramientas",
+ mcpToolsetDetailCoverage: "Cobertura",
+ mcpToolsetApply: "Aplicar este conjunto",
+ mcpToolsetApplying: "Aplicando…",
+ mcpToolsetPending: "{count} cambios de herramientas sin aplicar",
+ mcpToolsetApplied: "Configuración actual aplicada",
+ mcpToolsetCloseKeepsDraft: "Al cerrar se conservan los cambios. También puedes aplicarlos desde Ajustes.",
+ mcpToolsetApplyFailed: "No se pudo aplicar: {error}. Los cambios se conservan; vuelve a intentarlo.",
+ mcpToolsetApplyUnavailable: "La configuración de herramientas no está disponible. Espera a que termine la carga o vuelve a intentarlo.",
+ mcpToolsetDetailClose: "Cerrar",
+ mcpPluginToolEntriesTitle: "Entradas de herramientas de complementos",
+ mcpPluginsTitle: "Plugins",
+ mcpPluginsDescription: "Plugins that provide Herramientas MCP. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "Actualizar",
+ mcpPluginsLoading: "Cargando herramientas del plugin...",
+ mcpPluginsLoadFailed: "Error al cargar las herramientas de complementos: {error}",
+ mcpPluginsEmpty: "Ningún plugin instalado proporciona herramientas MCP.",
+ mcpPluginSaveFailed: "Error al guardar {name}: {message}",
+ mcpPluginAuthorClosed: "El autor no lo ha habilitado para MCP externo",
+ mcpPluginDiscoveryFailed: "Falló el descubrimiento de herramientas",
+ mcpPluginToolCount: "{exposed}/{total} herramientas expuestas",
+ mcpPluginToolCountOff: "{total} herramientas, desactivadas",
+ mcpPluginCeilingSummary: "Límite: {level}",
+ mcpPluginPendingTools: "{count} herramientas nuevas requieren confirmación",
+ mcpPluginReview: "Revisar",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Falló el descubrimiento de herramientas: {error}",
+ mcpPluginCeilingTitle: "Límite de autorización",
+ mcpPluginCeilingDescription: "Las herramientas que superan el límite permanecen ocultas para los clientes MCP. Las llamadas también deben cumplir los permisos de los recursos y las reglas de visibilidad de las conexiones.",
+ mcpPluginEnableFirst: "Active el complemento para cambiar su límite y sus herramientas.",
+ mcpPluginDefaultToolset: "Herramientas",
+ mcpPluginNoTools: "This plugin lists no Herramientas MCP right now.",
+ mcpPluginAuthorizeTitle: "Autorizar {name} for MCP",
+ mcpPluginAuthorizeDescription: "Elija el límite de permisos de este complemento. Se aceptan todas las herramientas declaradas a continuación; las herramientas añadidas después o cuyo nivel declarado aumente volverán a pedir confirmación si requieren más que lectura.",
+ mcpPluginAuthorizeTools: "Herramientas ({count})",
+ mcpPluginAuthorizeIncluded: "Expuesto",
+ mcpPluginAuthorizeExcluded: "Oculta",
+ mcpPluginAuthorizeFootnote: "Después podrá cambiar el límite o desactivar herramientas individuales en los detalles del complemento.",
+ mcpPluginAccessUndeclared: "No declarado por el autor — never exposed",
+ mcpPluginUndeclaredCount: "{count} herramientas no están declaradas en el manifiesto y permanecen ocultas",
+ mcpPluginUndeclaredTools: "{count} herramientas no tienen un nivel de acceso declarado en el manifiesto del complemento y nunca se expondrán: {names}",
+ mcpPluginAuthorizeCancel: "Cancelar",
+ mcpPluginAuthorizeConfirm: "Autorizar",
+ mcpPluginToolEntriesHint: "Avanzado: entradas permitidas para herramientas de plugins. dbx_*__* permite todas las herramientas de plugins y dbx_<prefix>__* las de un plugin. Los interruptores de plugins determinan qué herramientas están disponibles; estas entradas añaden otro filtro.",
+ mcpPluginAllowlistBlocked: "La lista de herramientas MCP permitidas no contiene entradas de plugins, por lo que sus herramientas permanecen ocultas independientemente de los interruptores de plugins.",
+ mcpPluginAllowlistAllow: "Permitir herramientas del plugin",
+ mcpPluginExposure: {
+ exposed: "Expuesto",
+ undeclared: "No declarado",
+ pluginDisabled: "Plugin desactivado",
+ toolDisabled: "Desactivado",
+ aboveCeiling: "Por encima del límite",
+ pendingApproval: "Requiere confirmación",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Solo lectura",
+ write: "Lectura y escritura",
+ full: "Completo (incluido alto riesgo)",
+ },
+ mcpAccessLevel: {
+ read: "Lectura",
+ write: "Escritura",
+ full: "Alto riesgo",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "Descubrimiento y contexto", description: "Enumerar conexiones y bases de datos y obtener el contexto del esquema para el modelo." },
+ sqlQuery: { title: "Consulta SQL", description: "Ejecutar consultas y scripts. El riesgo de cada sentencia se clasifica en cada llamada." },
+ sqlSession: { title: "Sesiones y transacciones", description: "Mantener una sesión entre llamadas y controlar transacciones." },
+ sqlSchema: { title: "Objetos del esquema", description: "Explorar tablas, columnas y código fuente de rutinas." },
+ redis: { title: "Comandos Redis", description: "Ejecutar comandos Redis." },
+ mq: { title: "Lectura y envío de mensajes", description: "Leer y enviar mensajes de Kafka, RocketMQ y RabbitMQ." },
+ salesforce: { title: "Identidad y operaciones de datos", description: "Identificar al usuario actual y escribir registros individuales." },
+ workbench: { title: "Área de trabajo", description: "Abrir tablas y mostrar resultados de consultas en DBX." },
+ adminConnections: { title: "Gestión de conexiones", description: "Añadir, duplicar y eliminar conexiones de DBX." },
+ pluginRouter: { title: "Descubrimiento e invocación de plugins", description: "Descubrir herramientas de complementos bajo demanda e invocarlas mediante un único enrutador." },
+ nacosConfig: { title: "Gestión de configuraciones", description: "Lectura, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "Gestión de servicios", description: "Enumerar servicios e instancias; activar o desactivar instancias y cambiar sus pesos." },
+ consulKv: { title: "Gestión de KV", description: "Enumerar, leer, escribir y eliminar claves KV de Consul con comparación y actualización (CAS)." },
+ consulService: { title: "Descubrimiento y salud de servicios", description: "Catálogo de servicios y nodos, estado de los servicios y modo de mantenimiento." },
+ },
+ mcpToolNacosListNamespaces: "Listar espacios de nombres de Nacos",
+ mcpToolNacosListConfigs: "Listar configuraciones de Nacos",
+ mcpToolNacosGetConfig: "Leer configuración de Nacos",
+ mcpToolNacosConfigHistory: "Historial de configuración de Nacos",
+ mcpToolNacosPublishConfig: "Publicar configuración de Nacos",
+ mcpToolNacosDeleteConfig: "Eliminar configuración de Nacos",
+ mcpToolNacosListServices: "Listar servicios de Nacos",
+ mcpToolNacosListInstances: "Listar instancias de Nacos",
+ mcpToolNacosUpdateInstance: "Actualizar instancia de Nacos",
+ mcpToolNacosSearchConfigs: "Buscar configuraciones de Nacos",
+ mcpToolNacosRollbackConfig: "Revertir configuración de Nacos",
+ mcpToolNacosGetService: "Consultar servicio de Nacos",
+ mcpToolNacosRegisterInstance: "Registrar instancia de Nacos",
+ mcpToolNacosDeregisterInstance: "Dar de baja instancia de Nacos",
+ mcpToolConsulKvList: "Listar claves de Consul KV",
+ mcpToolConsulKvGet: "Leer clave de Consul KV",
+ mcpToolConsulKvPut: "Escribir clave de Consul KV",
+ mcpToolConsulKvDelete: "Eliminar clave de Consul KV",
+ mcpToolConsulListServices: "Listar servicios de Consul",
+ mcpToolConsulListNodes: "Listar nodos de Consul",
+ mcpToolConsulServiceHealth: "Estado del servicio de Consul",
+ mcpToolConsulSetMaintenance: "Modo de mantenimiento de Consul",
mcpConfigOptionsHint:
"DBX controla de forma central el acceso a conexiones y los permisos de ejecución para todos los clientes MCP. La configuración generada solo contiene los parámetros de ejecución necesarios para iniciar el servidor MCP y conectarlo a esta instancia de DBX, sin variables de permisos ni de ámbito de conexión.",
mcpScopeConnection: "Conexiones permitidas para MCP",
@@ -9905,7 +10214,8 @@ export default withEnglishFallback({
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json global, o opencode.json a nivel de proyecto.",
mcpPiConfigPath: "Primero instala el plugin adaptador de MCP para Pi: pi install npm:pi-mcp-adapter. Luego guarda en ~/.pi/agent/mcp.json (global) o .mcp.json (proyecto), ejecuta /mcp para verificar y /reload para que Pi lo detecte.",
mcpExecutionMode: "Permiso predeterminado global de MCP",
- mcpExecutionModeDescription: "Define el valor predeterminado cuando no hay permiso de conexión o base de datos. Los ajustes de conexión y base de datos pueden reemplazarlo por alcance.",
+ mcpExecutionModeDescription: "Los recursos sin un permiso propio usan este valor predeterminado. Configure permisos diferentes en el control de acceso de abajo.",
+ mcpPermissionsDraftHint: "Los cambios globales, de grupo y de conexión usan Aplicar al pie. Los permisos de bases de datos también se pueden aplicar en su diálogo. Los subámbitos se guardan inmediatamente. Descartar borradores no revierte cambios guardados.",
mcpExecutionModeReadOnly: "Solo lectura",
mcpExecutionModeSafeWrite: "Lectura y escritura de datos",
mcpExecutionModeRecommended: "Recomendado",
@@ -9914,21 +10224,21 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "Permite INSERT normales, UPDATE/DELETE con filtros efectivos, cambios MongoDB de alcance verificable y escrituras Redis normales o borrado de claves explícitas; bloquea cambios globales y estructurales.",
mcpExecutionModeHighRiskWriteDescription: "Además de leer y escribir datos, permite cambios de tablas completas, DDL, TRUNCATE, vaciado de bases de datos y otras operaciones de alto riesgo. Las protecciones de producción y solo lectura siguen activas.",
mcpExecutionModeHighRiskConfirm: "El acceso completo permite cambios de tablas completas, DDL, TRUNCATE, vaciado de bases de datos y otras operaciones de alto riesgo. ¿Quieres activarlo?",
- mcpPromptHighRiskSql: "Solicitar confirmación para SQL de alto riesgo (solo escritorio; se mantienen las protecciones de solo lectura y producción)",
mcpSqlApprovalTitle: "Aprobación de SQL de alto riesgo de MCP",
mcpSqlApprovalScope: "Conexión: {connection} · Base de datos: {database}",
mcpSqlApprovalOnce: "Solo esta solicitud",
mcpSqlApprovalHour: "Permitir en esta base de datos durante 1 hora",
mcpSqlApprovalDay: "Permitir en esta base de datos durante 1 día",
mcpSqlApprovalDeny: "Denegar",
- mcpCapabilityTitle: "Comparación de capacidades",
- mcpCapabilityDescription: "Estas son operaciones representativas; las solicitudes que DBX no puede clasificar de forma fiable requieren acceso completo.",
+ mcpCapabilityTitle: "Detalles de permisos",
+ mcpCapabilityDescription: "La tabla describe permisos; habilita también las herramientas en Capacidades. Se rechazan permisos insuficientes. Seguridad de llamadas controla la confirmación y explica la autorización heredada.",
mcpCapabilityOperation: "Capacidad",
mcpCapabilityRead: "Consultas y lecturas",
mcpCapabilityScopedMutation: "Cambios de datos acotados (INSERT, UPDATE/DELETE filtrados, escritura/borrado de claves explícitas)",
mcpCapabilityBroadMutation: "Actualizaciones/borrados de tablas completas y vaciado de datos",
mcpCapabilitySchemaAdmin: "DDL, cambios estructurales y administración de alto riesgo",
- mcpCapabilityConnectionManagement: "Agregar/eliminar conexiones MCP",
+ mcpCapabilityConnectionCreate: "Agregar/duplicar conexiones MCP (permiso global predeterminado)",
+ mcpCapabilityConnectionRemove: "Eliminar conexiones MCP (permiso global predeterminado)",
mcpCapabilityAllowed: "Permitido",
mcpCapabilityBlocked: "Bloqueado",
mcpQueryTimeout: "Tiempo de espera de consulta (segundos)",
@@ -9936,6 +10246,9 @@ export default withEnglishFallback({
mcpQueryTimeoutInvalid: "Introduce un número entero no negativo de segundos o déjalo vacío para heredar la configuración de la conexión.",
mcpCapabilityAlwaysEnforced: "Todos los modos siguen sujetos a la lista de conexiones permitidas, la protección de solo lectura, la protección de producción y los permisos de la cuenta de base de datos.",
mcpPolicySaveFailed: "No se pudo guardar la política de acceso MCP: {error}",
+ mcpPolicyRetry: "Reintentar",
+ mcpPolicyRecover: "Respaldar y restablecer permisos MCP",
+ mcpPolicyRecoverConfirm: "Se respaldará la política dañada y se restablecerán los permisos MCP, incluidos los cambios sin guardar. Todas las conexiones y herramientas quedarán bloqueadas hasta que las configure de nuevo. ¿Continuar?",
mcpPolicyLoadFailed: "No se pudo cargar la política de acceso MCP: {error}",
mcpDetectionTiming: "DBX comprueba automáticamente al abrir esta página; usa Comprobar de nuevo para actualizar.",
mcpNpmBoundary: "DBX solo comprueba y explica el estado de MCP; la instalación y actualización siguen usando npm, pnpm o bun.",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 24a0c83386..a78a84258b 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -123,6 +123,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: '"{name}" ingin membaca data dari koneksi "{connection}". Selama koneksi tersebut terbuka, plugin dapat menjalankan kueri read-only pada koneksi itu hingga Anda mencabut aksesnya di Plugin Center. Izinkan?',
dataAccessConsentTitle: "Permintaan Akses Data",
+ mcpToolsBadge: "Alat MCP",
+ mcpToolsBadgeHint: "This plugin provides Alat MCP. Enable and authorize them in Settings → MCP → Kapabilitas.",
+ mcpToolsFilter: "Only plugins with Alat MCP ({count})",
+ externalMcp: {
+ title: "Klien MCP eksternal",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → Kapabilitas.",
+ notOffered: "Penulis belum membuka alat plugin ini untuk klien MCP eksternal.",
+ },
aiTools: {
title: "Alat AI bawaan",
description: "Nonaktif secara default: asisten AI DBX (mode Agent) hanya dapat memanggil alat plugin ini pada koneksi terbuka miliknya selama sakelar ini aktif. Alat yang tidak dideklarasikan read-only tetap meminta persetujuan Anda sebelum setiap pemanggilan.",
@@ -6886,6 +6894,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "Tool MCP",
+ mcpClient: "Klien MCP",
+ mcpTransport: "Transport MCP",
+ mcpAccess: "Akses MCP",
+ mcpConfirmation: "Konfirmasi MCP",
kind: "Tipe",
operation: "Operasi",
connection: "Koneksi",
@@ -9429,6 +9441,303 @@ export default withEnglishFallback({
mcpUninstallConfirm: "Hapus pemasangan Server MCP DBX? Klien MCP yang dikonfigurasi tidak akan dapat memulainya lagi.",
mcpUninstallFailed: "Penghapusan pemasangan gagal: {error}",
mcpConfig: "Konfigurasi MCP",
+ mcpCapabilitiesFilterLabel: "Filter kemampuan",
+ mcpCapabilitiesFilterAll: "Semua",
+ mcpCapabilitiesFilterBuiltin: "Bawaan",
+ mcpCapabilitiesFilterPlugin: "Pengaya",
+ mcpCapabilitiesOnlyEnabled: "Hanya tampilkan yang aktif",
+ mcpPluginScopeLoad: "Baca dari plugin",
+ mcpPluginToolsMode: "Penyediaan alat plugin ke klien",
+ mcpPluginToolsModeDescription: "Pilih cara DBX menyediakan alat plugin yang diizinkan kepada klien MCP. Klik Terapkan di bagian bawah untuk menyimpan.",
+ mcpPluginToolsModeAuto: "Otomatis (kompatibilitas)",
+ mcpPluginToolsModeFlat: "Tampilkan langsung (default)",
+ mcpPluginToolsModeLazy: "Penemuan sesuai permintaan",
+ mcpPluginToolsModeFlatDescription: "Menampilkan setiap alat plugin yang diizinkan agar klien dapat memanggilnya langsung.",
+ mcpPluginToolsModeLazyDescription: "Menyediakan alat penemuan dan pemanggilan plugin bersama, mengambil detail saat dibutuhkan. Aktifkan penemuan dan pemanggilan plugin di DBX umum.",
+ mcpPluginToolsModeAutoDescription: "Mempertahankan perilaku otomatis sebelumnya: tampilkan langsung hingga total 40 alat plugin, selebihnya gunakan penemuan sesuai permintaan.",
+ mcpCallSafety: "Keamanan panggilan",
+ mcpCallSafetyLegacy: "Otorisasi sementara lama",
+ mcpCallSafetyEnabled: "Konfirmasi setiap panggilan berisiko tinggi",
+ mcpCallSafetyDisabled: "Tanpa konfirmasi tambahan",
+ mcpCallSafetyLegacyHint: "Perilaku lama dipertahankan: akses tulis data dapat mengizinkan sementara beberapa operasi berisiko tinggi; akses penuh tidak meminta konfirmasi. Kebijakan baru menolak izin yang kurang dan mengonfirmasi juga pada akses penuh.",
+ mcpCallSafetyMigrate: "Gunakan kebijakan baru",
+ mcpCallSafetyDisableLegacy: "Nonaktifkan otorisasi lama",
+ mcpCallSafetyConfirm: "Minta konfirmasi sebelum panggilan berisiko tinggi",
+ mcpCallSafetyHint: "Berlaku untuk panggilan bawaan dan plugin yang dikenali berisiko tinggi. Izin diperiksa terlebih dahulu, termasuk akses penuh. Konfirmasi tidak pernah meningkatkan izin.",
+ mcpCallSafetyDesktopHint: "Memerlukan DBX desktop dan hanya menyetujui panggilan saat ini. Konfirmasi tidak tersedia, ditolak, atau kedaluwarsa tidak dijalankan. Perlindungan hanya baca dan produksi tetap berlaku. Klik Terapkan untuk menyimpan.",
+ mcpToolApprovalGenericTitle: "Konfirmasi panggilan berisiko tinggi",
+ mcpToolApprovalPluginTitle: "Konfirmasi alat berisiko tinggi dari {plugin}",
+ 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",
+ mcpToolApprovalTarget: "Target operasi",
+ mcpManagementCapabilities: "Kapabilitas",
+ mcpOpenCallHistory: "Lihat riwayat panggilan MCP",
+ mcpAccessTreeTitle: "Kontrol akses",
+ mcpAccessTreeDescription: "Atur izin untuk grup, koneksi, dan database. Warisi menggunakan pengaturan induk; izin efektif menampilkan hasil dan sumbernya.",
+ mcpAccessTreeSummary: "{visible}/{total} koneksi terlihat · pengecualian: {groups} grup, {connections} koneksi, {databases} basis data",
+ mcpAccessTreeScopeLabel: "Visibilitas koneksi",
+ mcpAccessTreeScopeAll: "Semua koneksi",
+ mcpAccessTreeScopeCustom: "Hanya yang dipilih",
+ mcpAccessTreeSearchPlaceholder: "Cari grup, koneksi, atau basis data",
+ mcpAccessTreeExceptionsOnly: "Hanya tampilkan pengaturan tersendiri",
+ mcpAccessTreeColumnResource: "Sumber daya",
+ mcpAccessTreeColumnVisible: "Terlihat",
+ mcpAccessTreeColumnSetting: "Izin",
+ mcpAccessTreeColumnEffective: "Efektif",
+ mcpAccessTreeInherit: "Warisi",
+ mcpAccessTreeGroupPartiallyVisible: "Sebagian koneksi terlihat ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "Semua koneksi saat ini terlihat ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Hanya item anak yang diizinkan, bukan seluruh grup. Centang untuk mengizinkan seluruh grup, termasuk koneksi baru di masa mendatang.",
+ mcpAccessTreeGroupDefaultHint: "Izin default grup berlaku untuk item anak tanpa pengaturan izin sendiri. Visibilitas koneksi tidak berubah.",
+ mcpAccessTreeHidden: "Tidak terlihat oleh MCP",
+ mcpAccessTreeSourceGlobal: "default global",
+ mcpAccessTreeSourceGroup: "dari grup {group}",
+ mcpAccessTreeSourceConnection: "pengaturan koneksi",
+ mcpAccessTreeSourceDatabase: "pengaturan basis data",
+ mcpAccessTreeGroupCount: "{count} koneksi",
+ mcpAccessTreeLegacy: "format lama",
+ mcpAccessTreeLegacyHint: "Disimpan oleh versi lama: hanya dapat membatasi izin yang diwarisi koneksi. Pilih izin kembali untuk menjadikannya pengaturan biasa.",
+ mcpAccessTreeCoveredByGroup: "Terlihat through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "Risiko tinggi allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "Database",
+ mcpAccessTreeDatabaseScopeAll: "Semua database",
+ mcpAccessTreeDatabaseScopeSelected: "Dipilih ({count})",
+ mcpAccessTreeDatabaseScopeNone: "Tidak ada database",
+ mcpDatabaseRemoveConfirm: "Menghapus basis data yang dipilih juga menghapus izin khususnya. Lanjutkan?",
+ mcpDatabaseUnavailable: "Pengaturan izin basis data tidak tersedia. Tunggu pemuatan selesai atau coba lagi.",
+ mcpDatabaseConfigure: "Atur akses basis data",
+ mcpDatabaseOverrideCount: "{count} izin khusus",
+ mcpDatabaseDialogTitle: "{name} / Akses basis data",
+ mcpDatabaseDialogDescription: "Pilih basis data dan izinnya. Pemindahan ke kanan baru berlaku setelah diterapkan.",
+ mcpDatabaseInherited: "Izin warisan: {level}",
+ mcpDatabaseSavedInherited: "Ada perubahan izin induk yang belum diterapkan. Menerapkan akses basis data saja tetap mewarisi izin tersimpan: {level}",
+ mcpDatabaseHiddenConnection: "Koneksi ini tersembunyi dari MCP. Menerapkan izin basis data tidak menampilkan koneksi.",
+ mcpDatabaseAllHint: "Mencakup basis data saat ini dan yang akan datang dengan izin koneksi.",
+ mcpDatabaseNoneHint: "Penerapan akan menolak akses ke semua basis data.",
+ mcpDatabaseLoaded: "Memuat {count} basis data yang terlihat oleh akun ini",
+ mcpDatabaseRefresh: "Segarkan daftar",
+ mcpDatabaseAddSelected: "Tambah →",
+ mcpDatabaseRemoveSelected: "← Hapus",
+ mcpDatabaseAvailable: "Belum dipilih ({count})",
+ mcpDatabaseSelected: "Dipilih ({count})",
+ mcpDatabaseSearch: "Cari nama basis data",
+ mcpDatabaseSelectResults: "Pilih hasil pencarian saat ini ({count})",
+ mcpDatabaseBatchLevel: "Atur izin yang dicentang ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "Izinkan akses penuh untuk {count} database yang dicentang? Perlindungan koneksi hanya baca dan lingkungan produksi tetap berlaku.",
+ mcpDatabaseNotDiscovered: "Tidak ditemukan pada pencarian ini",
+ mcpDatabaseShowMore: "Tampilkan lagi ({shown}/{total})",
+ mcpDatabaseSaveHint: "Hanya menyimpan cakupan dan izin basis data koneksi ini. Perubahan lain yang belum disimpan tetap dipertahankan.",
+ mcpDatabaseApply: "Terapkan izin basis data",
+ mcpAccessTreePickDatabases: "Pilih database",
+ mcpAccessTreePickerTitle: "Database of {name}",
+ mcpAccessTreeLoadingDatabases: "Memuat database...",
+ mcpAccessTreeLoadDatabasesFailed: "Gagal memuat basis data: {error}. Anda tetap dapat menambahkan nama secara manual.",
+ mcpAccessTreeManualDatabase: "Tambahkan nama basis data",
+ mcpAccessTreeNoMatch: "Tidak ada sumber daya yang cocok",
+ mcpAccessTreeEmpty: "Belum ada koneksi",
+ mcpAccessTreeFootnote: "Prioritas: basis data > koneksi > grup terdekat > grup induk > default global. Perlindungan hanya-baca koneksi, perlindungan produksi, dan izin akun basis data tetap berlaku.",
+ mcpAccessTreeNacosNamespace: "Namespace",
+ mcpPluginScopeAll: "Semua ({title})",
+ mcpPluginScopeSelected: "Dipilih ({count})",
+ mcpPluginScopeNone: "Tidak {title}",
+ mcpPluginScopeAdd: "Tambahkan {title}",
+ mcpBrowser: {
+ viewMode: "Mode tampilan",
+ viewManage: "Manajemen kategori",
+ viewOverview: "Ikhtisar global",
+ overviewSummary: "{toolsets} kumpulan alat · {total} alat · {enabled} aktif",
+ overviewPluginsHint: "Tinjau alat dan otorisasi plugin. Buka plugin untuk melihat detail.",
+ overviewOpenDetails: "Lihat detail",
+ expandCategory: "Perluas kategori",
+ collapseCategory: "Ciutkan kategori",
+ builtin: "Kemampuan bawaan",
+ plugins: "Ekstensi plugin",
+ advanced: "Pengaturan lanjutan",
+ navigation: "Kategori kemampuan",
+ searchPlaceholder: "Cari kategori, kemampuan, plugin, atau alat…",
+ clearSearch: "Hapus pencarian",
+ searchResults: "Hasil pencarian",
+ categoryCount: "{count} kumpulan alat",
+ summary: "{toolsets} kumpulan · {total} alat · {enabled} aktif",
+ enableCategory: "Aktifkan semua dalam kategori ini",
+ disableCategory: "Nonaktifkan semua dalam kategori ini",
+ draftHint: "Terapkan kumpulan alat dari detailnya, atau gunakan Terapkan di bawah untuk menyimpan semua pengaturan yang tertunda.",
+ batchChanged: "Alat dalam kategori ini diubah. Klik Terapkan untuk menyimpan",
+ coverageHint: "Koneksi yang sesuai dihitung berdasarkan jenis koneksi, bukan cakupan otorisasi sebenarnya.",
+ uncovered: "{count} koneksi belum didukung alat bawaan",
+ viewDetails: "Lihat detail",
+ emptyEnabled: "Tidak ada alat aktif dalam kategori ini. Nonaktifkan “Hanya tampilkan yang aktif” untuk mengaturnya.",
+ retry: "Coba lagi",
+ enabledToolCount: "{enabled}/{total} aktif",
+ partialEnabled: "Aktif sebagian",
+ coverageConnections: "Berlaku untuk {count} koneksi",
+ coveragePartialConnections: "{count} didukung sebagian",
+ noMatchingConnections: "Tidak ada koneksi yang sesuai",
+ resourceScopes: "Cakupan sumber daya",
+ pluginImmediate: "Perubahan langsung disimpan, terlepas dari Terapkan / Batal di bagian bawah",
+ pluginSaving: "Menyimpan…",
+ pluginSaved: "Tersimpan",
+ pluginOnlyEnabledEmpty: "Tidak ada alat aktif. Nonaktifkan “Hanya tampilkan yang aktif” untuk melihatnya.",
+ pluginUnavailable: "Plugin ini tidak lagi tersedia. Segarkan daftar plugin",
+ resourceKind: {
+ database: "Basis data",
+ dbIndex: "Basis data logis",
+ topic: "Topik",
+ queue: "Antrean",
+ org: "Organisasi",
+ namespace: "Namespace",
+ },
+ category: {
+ database: { title: "Basis data", description: "Kueri data, kelola sesi dan transaksi, jelajahi struktur objek, dan jalankan perintah Redis." },
+ nacos: { title: "Nacos", description: "Kelola konfigurasi, layanan, dan instans." },
+ consul: { title: "Consul", description: "Kelola entri KV, temukan layanan, dan lihat status kesehatannya." },
+ mq: { title: "Antrean pesan", description: "Baca dan kirim pesan." },
+ salesforce: { title: "Salesforce", description: "Cari informasi identitas dan operasikan data." },
+ dbx: { title: "DBX bersama", description: "Kemampuan bersama lintas produk: penemuan koneksi, integrasi ruang kerja, pengelolaan koneksi, serta penemuan dan pemanggilan plugin." },
+ other: { title: "Kemampuan lainnya", description: "Lihat dan atur kumpulan alat yang belum dikategorikan." },
+ },
+ },
+ mcpCapabilitiesTitle: "Kapabilitas MCP",
+ mcpCapabilitiesDescription: "Bawaan Alat MCP grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the database types it applies to.",
+ mcpCapabilitiesLoading: "Memuat kapabilitas MCP...",
+ mcpCapabilitiesLoadFailed: "Failed to load Kapabilitas MCP: {error}",
+ mcpCapabilitiesSearchPlaceholder: "Cari kemampuan atau alat",
+ mcpCapabilitiesSearchEmpty: "Tidak ada kapabilitas yang cocok",
+ mcpToolsetToolCount: "{enabled}/{total} alat",
+ mcpAccessLevelClassified: "Per panggilan",
+ mcpCoverageTypes: "{count} jenis basis data",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Tidak terikat pada koneksi",
+ mcpCoverageUsableConnections: "Digunakan oleh {count} koneksi Anda",
+ mcpCoverageNoUsableConnections: "Tidak ada koneksi Anda yang menggunakannya",
+ mcpCoveragePartialConnections: "{count} koneksi hanya mendukung sebagian alat",
+ mcpCoverageUncoveredConnections: "{count} connections have no Alat MCP yet: {names}",
+ mcpCoverageSearchPlaceholder: "Cari jenis basis data",
+ mcpCoverageSearchEmpty: "Tidak matching database types",
+ mcpCoverageLegend: "Hanya jenis yang didukung yang ditampilkan. Jenis yang disorot sesuai dengan koneksi Anda; * berarti sebagian alat dalam grup tidak mendukung jenis tersebut (arahkan penunjuk untuk detail).",
+ mcpCoverageTypeUnsupportedTool: "Tidak didukung oleh {tool}",
+ mcpCoverageCategoryOther: "Lainnya",
+ mcpCoveragePartialTool: "{tool} mendukung {count} dari {total}",
+ mcpToolDetailSkippedConnections: "Tidak tersedia pada: {names}",
+ mcpToolDetailCoverage: "Jenis basis data yang didukung ({count})",
+ mcpToolDetailParameterDefault: "default: {value}",
+ mcpToolDetailParameterDescription: "Deskripsi",
+ mcpToolDetailParameterRequiredNo: "Tidak",
+ mcpToolDetailParameterRequiredYes: "Ya",
+ mcpToolDetailParameterRequired: "Wajib",
+ mcpToolDetailParameterType: "Tipe",
+ mcpToolDetailParameterName: "Nama",
+ mcpToolDetailNoParameters: "Tanpa parameter",
+ mcpToolDetailParameters: "Parameter",
+ mcpToolDetailDescription: "Deskripsi untuk model",
+ mcpToolDetailAccessClassified: "Diklasifikasikan per panggilan (baca, tulis, atau risiko tinggi sesuai pernyataan)",
+ mcpToolDetailAccess: "Tingkat akses",
+ mcpToolDetailSummary: "Ringkasan",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "{count} koneksi Anda tidak dapat menggunakannya",
+ mcpToolsetDetailTools: "Alat",
+ mcpToolsetDetailCoverage: "Cakupan",
+ mcpToolsetApply: "Terapkan kumpulan ini",
+ mcpToolsetApplying: "Menerapkan…",
+ mcpToolsetPending: "{count} perubahan alat belum diterapkan",
+ mcpToolsetApplied: "Konfigurasi saat ini sudah diterapkan",
+ mcpToolsetCloseKeepsDraft: "Menutup tetap mempertahankan perubahan. Anda juga dapat menerapkannya dari Pengaturan.",
+ mcpToolsetApplyFailed: "Gagal menerapkan: {error}. Perubahan tetap disimpan sebagai draf; coba lagi.",
+ mcpToolsetApplyUnavailable: "Pengaturan alat belum tersedia. Tunggu hingga pemuatan selesai atau coba lagi.",
+ mcpToolsetDetailClose: "Tutup",
+ mcpPluginToolEntriesTitle: "Entri alat plugin",
+ mcpPluginsTitle: "Plugin",
+ mcpPluginsDescription: "Plugin that provide Alat MCP. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "Segarkan",
+ mcpPluginsLoading: "Memuat alat plugin...",
+ mcpPluginsLoadFailed: "Gagal memuat alat plugin: {error}",
+ mcpPluginsEmpty: "Tidak ada plugin terpasang yang menyediakan alat MCP.",
+ mcpPluginSaveFailed: "Gagal menyimpan {name}: {message}",
+ mcpPluginAuthorClosed: "Penulis belum membukanya untuk MCP eksternal",
+ mcpPluginDiscoveryFailed: "Penemuan alat gagal",
+ mcpPluginToolCount: "{exposed}/{total} alat diekspos",
+ mcpPluginToolCountOff: "{total} alat, nonaktif",
+ mcpPluginCeilingSummary: "Batas: {level}",
+ mcpPluginPendingTools: "{count} alat baru memerlukan konfirmasi",
+ mcpPluginReview: "Tinjau",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Penemuan alat gagal: {error}",
+ mcpPluginCeilingTitle: "Batas otorisasi",
+ mcpPluginCeilingDescription: "Alat di atas batas tetap tersembunyi dari klien MCP. Panggilan juga harus memenuhi izin sumber daya dan aturan visibilitas koneksi.",
+ mcpPluginEnableFirst: "Aktifkan plugin untuk mengubah batas izin dan alatnya.",
+ mcpPluginDefaultToolset: "Alat",
+ mcpPluginNoTools: "This plugin lists no Alat MCP right now.",
+ mcpPluginAuthorizeTitle: "Otorisasi {name} for MCP",
+ mcpPluginAuthorizeDescription: "Pilih batas izin alat plugin ini. Semua alat yang dideklarasikan di bawah disetujui; alat yang ditambahkan kemudian atau tingkat deklarasinya meningkat akan meminta konfirmasi lagi jika memerlukan izin di atas baca.",
+ mcpPluginAuthorizeTools: "Alat ({count})",
+ mcpPluginAuthorizeIncluded: "Terbuka",
+ mcpPluginAuthorizeExcluded: "Tersembunyi",
+ mcpPluginAuthorizeFootnote: "Anda dapat mengubah batas atau menonaktifkan alat tertentu nanti di detail plugin.",
+ mcpPluginAccessUndeclared: "Tidak dideklarasikan by the author — never exposed",
+ mcpPluginUndeclaredCount: "{count} alat tidak dideklarasikan dalam manifes dan tetap tersembunyi",
+ mcpPluginUndeclaredTools: "{count} alat tidak memiliki tingkat akses yang dideklarasikan dalam manifes plugin dan tidak akan diekspos: {names}",
+ mcpPluginAuthorizeCancel: "Batal",
+ mcpPluginAuthorizeConfirm: "Otorisasi",
+ mcpPluginToolEntriesHint: "Lanjutan: entri daftar izin untuk alat plugin. dbx_*__* mengizinkan semua alat plugin, dbx_<prefix>__* mengizinkan satu plugin. Sakelar plugin menentukan alat yang tersedia; entri ini menambahkan filter lain.",
+ mcpPluginAllowlistBlocked: "Daftar izin alat MCP tidak memiliki entri plugin, sehingga semua alat plugin tetap tersembunyi terlepas dari sakelar plugin.",
+ mcpPluginAllowlistAllow: "Izinkan alat plugin",
+ mcpPluginExposure: {
+ exposed: "Terbuka",
+ undeclared: "Tidak dideklarasikan",
+ pluginDisabled: "Plugin nonaktif",
+ toolDisabled: "Dimatikan",
+ aboveCeiling: "Di atas batas",
+ pendingApproval: "Perlu konfirmasi",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Hanya baca",
+ write: "Baca & tulis",
+ full: "Penuh (termasuk risiko tinggi)",
+ },
+ mcpAccessLevel: {
+ read: "Baca",
+ write: "Tulis",
+ full: "Risiko tinggi",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "Penemuan & konteks", description: "Tampilkan koneksi dan basis data, serta ambil konteks skema untuk model." },
+ sqlQuery: { title: "Kueri SQL", description: "Jalankan kueri dan skrip. Risiko setiap pernyataan diklasifikasikan per panggilan." },
+ sqlSession: { title: "Sesi & transaksi", description: "Pertahankan sesi antar panggilan dan kendalikan transaksi." },
+ sqlSchema: { title: "Objek skema", description: "Telusuri tabel, kolom, dan kode sumber rutin." },
+ redis: { title: "Perintah Redis", description: "Jalankan perintah Redis." },
+ mq: { title: "Baca dan kirim pesan", description: "Baca dan kirim pesan Kafka, RocketMQ, dan RabbitMQ." },
+ salesforce: { title: "Identitas dan operasi data", description: "Identifikasi pengguna saat ini dan tulis satu rekaman." },
+ workbench: { title: "Ruang kerja", description: "Buka tabel dan tampilkan hasil kueri di DBX." },
+ adminConnections: { title: "Manajemen koneksi", description: "Tambah, duplikasi, dan hapus koneksi DBX." },
+ pluginRouter: { title: "Penemuan dan pemanggilan plugin", description: "Temukan alat plugin sesuai kebutuhan dan panggil melalui satu perute." },
+ nacosConfig: { title: "Pengelolaan konfigurasi", description: "Baca, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "Pengelolaan layanan", description: "Tampilkan layanan dan instans; aktifkan atau nonaktifkan instans dan ubah bobotnya." },
+ consulKv: { title: "Pengelolaan KV", description: "Tampilkan, baca, tulis, dan hapus kunci Consul KV dengan perbandingan dan pembaruan (CAS)." },
+ consulService: { title: "Penemuan dan kesehatan layanan", description: "Katalog layanan dan simpul, kesehatan layanan, serta mode pemeliharaan." },
+ },
+ mcpToolNacosListNamespaces: "Daftar namespace Nacos",
+ mcpToolNacosListConfigs: "Daftar konfigurasi Nacos",
+ mcpToolNacosGetConfig: "Baca Nacos config",
+ mcpToolNacosConfigHistory: "Riwayat konfigurasi Nacos",
+ mcpToolNacosPublishConfig: "Publikasikan konfigurasi Nacos",
+ mcpToolNacosDeleteConfig: "Hapus konfigurasi Nacos",
+ mcpToolNacosListServices: "Daftar layanan Nacos",
+ mcpToolNacosListInstances: "Daftar instans Nacos",
+ mcpToolNacosUpdateInstance: "Perbarui instans Nacos",
+ mcpToolNacosSearchConfigs: "Cari konfigurasi Nacos",
+ mcpToolNacosRollbackConfig: "Pulihkan konfigurasi Nacos",
+ mcpToolNacosGetService: "Lihat layanan Nacos",
+ mcpToolNacosRegisterInstance: "Daftarkan instans Nacos",
+ mcpToolNacosDeregisterInstance: "Batalkan pendaftaran instans Nacos",
+ mcpToolConsulKvList: "Daftar kunci Consul KV",
+ mcpToolConsulKvGet: "Baca Consul KV key",
+ mcpToolConsulKvPut: "Tulis Consul KV key",
+ mcpToolConsulKvDelete: "Hapus kunci Consul KV",
+ mcpToolConsulListServices: "Daftar layanan Consul",
+ mcpToolConsulListNodes: "Daftar simpul Consul",
+ mcpToolConsulServiceHealth: "Kesehatan layanan Consul",
+ mcpToolConsulSetMaintenance: "Mode pemeliharaan Consul",
mcpConfigOptionsHint: "DBX mengontrol akses koneksi dan izin eksekusi secara terpusat untuk setiap klien MCP. Konfigurasi yang dihasilkan hanya berisi pengaturan runtime yang diperlukan untuk memulai server MCP dan terhubung ke instans DBX ini, tanpa variabel izin atau cakupan koneksi.",
mcpScopeConnection: "Koneksi yang diizinkan untuk MCP",
mcpScopeConnectionDescription: "DBX hanya mengekspos koneksi yang dipilih ke MCP. Perubahan berlaku untuk setiap klien MCP.",
@@ -9477,7 +9786,8 @@ export default withEnglishFallback({
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json secara global, atau opencode.json pada tingkat proyek.",
mcpPiConfigPath: "Pasang terlebih dahulu plugin adaptor Pi MCP: pi install npm:pi-mcp-adapter. Lalu simpan ke ~/.pi/agent/mcp.json (global) atau .mcp.json (proyek), jalankan /mcp untuk memverifikasi, dan /reload untuk menerapkannya di Pi.",
mcpExecutionMode: "Izin default global MCP",
- mcpExecutionModeDescription: "Mengatur default yang digunakan saat tidak ada izin koneksi atau database yang dikonfigurasi. Default koneksi dan pengaturan database dapat menimpanya sesuai cakupan.",
+ mcpExecutionModeDescription: "Sumber daya tanpa izin tersendiri menggunakan default ini. Atur izin yang berbeda di kontrol akses di bawah.",
+ mcpPermissionsDraftHint: "Perubahan global, grup, dan koneksi menggunakan Terapkan di bawah. Izin basis data juga dapat diterapkan dalam dialognya. Subcakupan langsung disimpan. Membuang draf tidak membatalkan perubahan tersimpan.",
mcpExecutionModeReadOnly: "Hanya baca",
mcpExecutionModeSafeWrite: "Baca/tulis data",
mcpExecutionModeRecommended: "Direkomendasikan",
@@ -9486,14 +9796,15 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "Mengizinkan INSERT biasa, UPDATE/DELETE yang difilter, perubahan MongoDB dengan cakupan yang dapat diverifikasi, dan penulisan Redis biasa atau penghapusan key eksplisit; memblokir perubahan seluruh tabel dan struktural.",
mcpExecutionModeHighRiskWriteDescription: "Selain baca/tulis data, mengizinkan perubahan seluruh tabel, DDL, TRUNCATE, pembersihan database, dan operasi berisiko tinggi lainnya. Perlindungan produksi dan read-only koneksi tetap berlaku.",
mcpExecutionModeHighRiskConfirm: "Akses penuh mengizinkan perubahan seluruh tabel, DDL, TRUNCATE, pembersihan database, dan operasi berisiko tinggi lainnya. Aktifkan?",
- mcpCapabilityTitle: "Perbandingan kapabilitas",
- mcpCapabilityDescription: "Ini adalah operasi representatif; permintaan yang tidak dapat diklasifikasikan DBX secara andal memerlukan akses penuh.",
+ mcpCapabilityTitle: "Penjelasan izin",
+ mcpCapabilityDescription: "Tabel menjelaskan izin; alat juga harus diaktifkan di Kemampuan. Izin yang kurang ditolak. Keamanan panggilan mengatur konfirmasi dan menjelaskan otorisasi lama.",
mcpCapabilityOperation: "Kapabilitas",
mcpCapabilityRead: "Kueri dan pembacaan",
mcpCapabilityScopedMutation: "Perubahan data bercakupan (INSERT, UPDATE/DELETE yang difilter, penulisan/penghapusan key eksplisit)",
mcpCapabilityBroadMutation: "Pembaruan/penghapusan seluruh tabel dan pembersihan data",
mcpCapabilitySchemaAdmin: "DDL, perubahan struktural, dan administrasi berisiko tinggi",
- mcpCapabilityConnectionManagement: "Tambah/hapus koneksi MCP",
+ mcpCapabilityConnectionCreate: "Tambah/duplikat koneksi MCP (izin default global)",
+ mcpCapabilityConnectionRemove: "Hapus koneksi MCP (izin default global)",
mcpCapabilityAllowed: "Diizinkan",
mcpCapabilityBlocked: "Diblokir",
mcpQueryTimeout: "Batas waktu kueri (detik)",
@@ -9504,6 +9815,9 @@ export default withEnglishFallback({
mcpQueryTimeoutSaveStatus_failed: "Gagal menyimpan",
mcpCapabilityAlwaysEnforced: "Setiap mode tetap tunduk pada daftar izin koneksi, perlindungan read-only koneksi, perlindungan produksi, dan izin akun database.",
mcpPolicySaveFailed: "Gagal menyimpan kebijakan akses MCP: {error}",
+ mcpPolicyRetry: "Coba lagi",
+ mcpPolicyRecover: "Cadangkan dan reset izin MCP",
+ mcpPolicyRecoverConfirm: "Tindakan ini segera mencadangkan kebijakan yang rusak dan mereset izin MCP, termasuk perubahan izin yang belum disimpan. Semua koneksi dan alat akan diblokir hingga Anda mengonfigurasinya kembali. Lanjutkan?",
mcpPolicyLoadFailed: "Gagal memuat kebijakan akses MCP: {error}",
mcpDetectionTiming: "DBX memeriksa secara otomatis saat halaman ini dibuka; gunakan Periksa lagi untuk menyegarkan.",
mcpNpmBoundary: "DBX memeriksa status MCP; pemasangan, peningkatan, dan penghapusan pemasangan berjalan melalui runtime npm, pnpm, atau bun yang terdeteksi.",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 79cf034b3e..1646157c46 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -609,6 +609,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: '"{name}" vuole leggere i dati della connessione "{connection}". Finché la connessione è aperta, il plugin potrà eseguire query di sola lettura su di essa finché non revochi l\'accesso nel Centro plugin. Consentire?',
dataAccessConsentTitle: "Richiesta di accesso ai dati",
+ mcpToolsBadge: "Strumenti MCP",
+ mcpToolsBadgeHint: "This plugin provides Strumenti MCP. Enable and authorize them in Settings → MCP → Funzionalità.",
+ mcpToolsFilter: "Solo plugin con strumenti MCP ({count})",
+ externalMcp: {
+ title: "Client MCP esterni",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → Funzionalità.",
+ notOffered: "L'autore non ha abilitato gli strumenti di questo plugin per i client MCP esterni.",
+ },
aiTools: {
title: "Strumenti IA integrati",
description: "Disattivato per impostazione predefinita: l'assistente IA di DBX (modalità Agent) può usare gli strumenti di questo plugin sulle connessioni aperte solo con l'interruttore acceso. Gli strumenti non di sola lettura chiederanno comunque approvazione a ogni chiamata.",
@@ -7279,6 +7287,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "Strumento MCP",
+ mcpClient: "Client MCP",
+ mcpTransport: "Trasporto MCP",
+ mcpAccess: "Accesso MCP",
+ mcpConfirmation: "Conferma MCP",
kind: "Tipo",
operation: "Operazione",
connection: "Connessione",
@@ -9607,6 +9619,303 @@ export default withEnglishFallback({
mcpInstallSuccess: "Installazione completata",
mcpInstallFailed: "Installazione fallita",
mcpConfig: "Configurazione MCP",
+ mcpCapabilitiesFilterLabel: "Filtro capacità",
+ mcpCapabilitiesFilterAll: "Tutte",
+ mcpCapabilitiesFilterBuiltin: "Integrate",
+ mcpCapabilitiesFilterPlugin: "Estensione",
+ mcpCapabilitiesOnlyEnabled: "Mostra solo attivati",
+ mcpPluginScopeLoad: "Leggi dal plugin",
+ mcpPluginToolsMode: "Fornitura esterna degli strumenti dei plugin",
+ mcpPluginToolsModeDescription: "Scegli come DBX fornisce gli strumenti autorizzati dei plugin ai client MCP. Fai clic su Applica in basso per salvare.",
+ mcpPluginToolsModeAuto: "Automatica (compatibilità)",
+ mcpPluginToolsModeFlat: "Elenca direttamente (predefinito)",
+ mcpPluginToolsModeLazy: "Scoperta su richiesta",
+ mcpPluginToolsModeFlatDescription: "Elenca ogni strumento autorizzato affinché i client possano richiamarlo direttamente.",
+ mcpPluginToolsModeLazyDescription: "Offre strumenti comuni di ricerca e invocazione, recuperando i dettagli quando necessario. Abilita la ricerca e invocazione dei plugin in DBX generale.",
+ mcpPluginToolsModeAutoDescription: "Mantiene il comportamento automatico esistente: elenca direttamente fino a 40 strumenti dei plugin in totale; oltre tale soglia usa la scoperta su richiesta.",
+ mcpCallSafety: "Sicurezza delle chiamate",
+ mcpCallSafetyLegacy: "Autorizzazione temporanea precedente",
+ mcpCallSafetyEnabled: "Conferma ogni chiamata ad alto rischio",
+ mcpCallSafetyDisabled: "Nessuna conferma aggiuntiva",
+ mcpCallSafetyLegacyHint: "Il comportamento precedente è mantenuto: la scrittura dati può autorizzare temporaneamente alcune operazioni ad alto rischio; l’accesso completo non chiede conferma. La nuova politica rifiuta permessi insufficienti e conferma anche con accesso completo.",
+ mcpCallSafetyMigrate: "Usa la nuova politica",
+ mcpCallSafetyDisableLegacy: "Disattiva autorizzazione precedente",
+ mcpCallSafetyConfirm: "Richiedi conferma prima delle chiamate ad alto rischio",
+ mcpCallSafetyHint: "Si applica alle chiamate integrate e dei plugin identificate come ad alto rischio. Prima si verificano i permessi, anche con accesso completo. La conferma non amplia mai i permessi.",
+ mcpCallSafetyDesktopHint: "Richiede DBX desktop e approva solo la chiamata corrente. Conferme non disponibili, negate o scadute impediscono l’esecuzione. Restano le protezioni di sola lettura e produzione. Premi Applica per salvare.",
+ mcpToolApprovalGenericTitle: "Conferma chiamata ad alto rischio",
+ mcpToolApprovalPluginTitle: "Conferma lo strumento ad alto rischio di {plugin}",
+ 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",
+ mcpToolApprovalTarget: "Destinazione",
+ mcpManagementCapabilities: "Funzionalità",
+ mcpOpenCallHistory: "Visualizza cronologia chiamate MCP",
+ mcpAccessTreeTitle: "Controllo accessi",
+ mcpAccessTreeDescription: "Imposta i permessi per gruppi, connessioni e database. Eredita usa il valore del livello superiore; il permesso effettivo mostra il risultato e la sua origine.",
+ mcpAccessTreeSummary: "{visible}/{total} connessioni visibili · eccezioni: {groups} gruppi, {connections} connessioni, {databases} database",
+ mcpAccessTreeScopeLabel: "Visibilità connessioni",
+ mcpAccessTreeScopeAll: "Tutte le connessioni",
+ mcpAccessTreeScopeCustom: "Solo selezionate",
+ mcpAccessTreeSearchPlaceholder: "Cerca gruppi, connessioni o database",
+ mcpAccessTreeExceptionsOnly: "Mostra solo impostazioni specifiche",
+ mcpAccessTreeColumnResource: "Risorsa",
+ mcpAccessTreeColumnVisible: "Visibile",
+ mcpAccessTreeColumnSetting: "Permesso",
+ mcpAccessTreeColumnEffective: "Effettivo",
+ mcpAccessTreeInherit: "Eredita",
+ mcpAccessTreeGroupPartiallyVisible: "Alcune connessioni visibili ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "Tutte le connessioni attuali visibili ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Sono autorizzati solo elementi figli, non tutto il gruppo. Selezionare per consentire tutto il gruppo, incluse le connessioni future.",
+ mcpAccessTreeGroupDefaultHint: "I permessi predefiniti del gruppo si applicano agli elementi figli senza permessi propri. Non modificano la visibilità delle connessioni.",
+ mcpAccessTreeHidden: "Non visibile a MCP",
+ mcpAccessTreeSourceGlobal: "predefinito globale",
+ mcpAccessTreeSourceGroup: "dal gruppo {group}",
+ mcpAccessTreeSourceConnection: "impostazione connessione",
+ mcpAccessTreeSourceDatabase: "impostazione database",
+ mcpAccessTreeGroupCount: "{count} connessioni",
+ mcpAccessTreeLegacy: "precedente",
+ mcpAccessTreeLegacyHint: "Salvato da una versione precedente: può solo restringere i permessi ereditati dalla connessione. Scegli nuovamente un permesso per convertirlo in un'impostazione normale.",
+ mcpAccessTreeCoveredByGroup: "Visibile through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "Alto rischio allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "Database",
+ mcpAccessTreeDatabaseScopeAll: "Tutti i database",
+ mcpAccessTreeDatabaseScopeSelected: "Selezionati ({count})",
+ mcpAccessTreeDatabaseScopeNone: "Nessun database",
+ mcpDatabaseRemoveConfirm: "Rimuovere i database selezionati elimina anche i loro permessi specifici. Continuare?",
+ mcpDatabaseUnavailable: "Le impostazioni di accesso ai database non sono disponibili. Attendi il caricamento o riprova.",
+ mcpDatabaseConfigure: "Configura accesso ai database",
+ mcpDatabaseOverrideCount: "{count} permessi specifici",
+ mcpDatabaseDialogTitle: "{name} / Accesso ai database",
+ mcpDatabaseDialogDescription: "Seleziona i database e i permessi. Lo spostamento a destra ha effetto solo dopo l’applicazione.",
+ mcpDatabaseInherited: "Permessi ereditati: {level}",
+ mcpDatabaseSavedInherited: "Ci sono modifiche non applicate ai permessi superiori. Applicando solo questo ambito si ereditano i permessi salvati: {level}",
+ mcpDatabaseHiddenConnection: "Questa connessione è nascosta a MCP. Applicare i permessi dei database non rende visibile la connessione.",
+ mcpDatabaseAllHint: "Include database attuali e futuri con i permessi della connessione.",
+ mcpDatabaseNoneHint: "L’applicazione negherà l’accesso a tutti i database.",
+ mcpDatabaseLoaded: "Caricati {count} database visibili a questo account",
+ mcpDatabaseRefresh: "Aggiorna elenco",
+ mcpDatabaseAddSelected: "Aggiungi →",
+ mcpDatabaseRemoveSelected: "← Rimuovi",
+ mcpDatabaseAvailable: "Non selezionati ({count})",
+ mcpDatabaseSelected: "Selezionati ({count})",
+ mcpDatabaseSearch: "Cerca nomi di database",
+ mcpDatabaseSelectResults: "Seleziona i risultati correnti ({count})",
+ mcpDatabaseBatchLevel: "Permessi delle selezionate ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "Consentire accesso completo a {count} database selezionati? Restano attive le protezioni di sola lettura della connessione e di produzione.",
+ mcpDatabaseNotDiscovered: "Non trovato in questa ricerca",
+ mcpDatabaseShowMore: "Mostra altri ({shown}/{total})",
+ mcpDatabaseSaveHint: "Salva solo l’ambito e i permessi dei database di questa connessione. Mantiene le altre modifiche non salvate.",
+ mcpDatabaseApply: "Applica permessi dei database",
+ mcpAccessTreePickDatabases: "Scegli database",
+ mcpAccessTreePickerTitle: "Database of {name}",
+ mcpAccessTreeLoadingDatabases: "Caricamento database...",
+ mcpAccessTreeLoadDatabasesFailed: "Impossibile caricare i database: {error}. Puoi comunque aggiungere i nomi manualmente.",
+ mcpAccessTreeManualDatabase: "Aggiungi un nome di database",
+ mcpAccessTreeNoMatch: "Nessuna risorsa corrispondente",
+ mcpAccessTreeEmpty: "Nessuna connessione",
+ mcpAccessTreeFootnote: "Priority: database > connection > closest group > parent group > predefinito globale. Connection read-only protection, production protection and database credentials always apply on top.",
+ mcpAccessTreeNacosNamespace: "Spazio dei nomi",
+ mcpPluginScopeAll: "Tutti ({title})",
+ mcpPluginScopeSelected: "Selezionati ({count})",
+ mcpPluginScopeNone: "Nessuna risorsa ({title})",
+ mcpPluginScopeAdd: "Aggiungi {title}",
+ mcpBrowser: {
+ viewMode: "Modalità di visualizzazione",
+ viewManage: "Gestione categorie",
+ viewOverview: "Panoramica globale",
+ overviewSummary: "{toolsets} gruppi di strumenti · {total} strumenti · {enabled} attivati",
+ overviewPluginsHint: "Esamina strumenti e autorizzazioni dei plugin. Apri un plugin per i dettagli.",
+ overviewOpenDetails: "Visualizza dettagli",
+ expandCategory: "Espandi categoria",
+ collapseCategory: "Comprimi categoria",
+ builtin: "Funzionalità integrate",
+ plugins: "Estensioni dei plugin",
+ advanced: "Impostazioni avanzate",
+ navigation: "Categorie di funzionalità",
+ searchPlaceholder: "Cerca categorie, funzionalità, plugin o strumenti…",
+ clearSearch: "Cancella ricerca",
+ searchResults: "Risultati di ricerca",
+ categoryCount: "{count} gruppi di strumenti",
+ summary: "{toolsets} gruppi · {total} strumenti · {enabled} attivati",
+ enableCategory: "Attiva tutta questa categoria",
+ disableCategory: "Disattiva tutta questa categoria",
+ draftHint: "Applica un gruppo nei dettagli oppure usa Applica in basso per salvare tutte le impostazioni in sospeso.",
+ batchChanged: "Strumenti di questa categoria modificati. Fai clic su Applica per salvare",
+ coverageHint: "Le connessioni compatibili sono conteggiate per tipo, non in base all'ambito effettivo di autorizzazione.",
+ uncovered: "{count} connessioni senza copertura di strumenti integrati",
+ viewDetails: "Vedi dettagli",
+ emptyEnabled: "Nessuno strumento attivato in questa categoria. Deseleziona «Mostra solo attivati» per configurarli.",
+ retry: "Riprova",
+ enabledToolCount: "{enabled}/{total} attivati",
+ partialEnabled: "Parzialmente attivata",
+ coverageConnections: "Compatibile con {count} connessioni",
+ coveragePartialConnections: "{count} supportate parzialmente",
+ noMatchingConnections: "Nessuna connessione compatibile",
+ resourceScopes: "Ambiti delle risorse",
+ pluginImmediate: "Le modifiche vengono salvate subito, indipendentemente da Applica / Annulla in basso",
+ pluginSaving: "Salvataggio…",
+ pluginSaved: "Salvato",
+ pluginOnlyEnabledEmpty: "Nessuno strumento attivato. Deseleziona «Mostra solo attivati» per visualizzarli.",
+ pluginUnavailable: "Questo plugin non è più disponibile. Aggiorna l'elenco dei plugin",
+ resourceKind: {
+ database: "Database",
+ dbIndex: "Database logico",
+ topic: "Argomento",
+ queue: "Coda",
+ org: "Organizzazione",
+ namespace: "Spazio dei nomi",
+ },
+ category: {
+ database: { title: "Database", description: "Interroga i dati, gestisci sessioni e transazioni, esplora le strutture degli oggetti ed esegui comandi Redis." },
+ nacos: { title: "Nacos", description: "Gestisci configurazioni, servizi e istanze." },
+ consul: { title: "Consul", description: "Gestisci le voci KV, scopri i servizi e visualizzane lo stato di salute." },
+ mq: { title: "Code di messaggi", description: "Leggi e invia messaggi." },
+ salesforce: { title: "Salesforce", description: "Consulta l'identità e opera sui dati." },
+ dbx: { title: "DBX condiviso", description: "Funzionalità condivise tra prodotti: rilevamento delle connessioni, integrazione con l'area di lavoro, gestione delle connessioni e rilevamento e chiamata dei plugin." },
+ other: { title: "Altre funzionalità", description: "Visualizza e configura i gruppi di strumenti non ancora categorizzati." },
+ },
+ },
+ mcpCapabilitiesTitle: "Funzionalità MCP",
+ mcpCapabilitiesDescription: "Integrato Strumenti MCP grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the tipi di database it applies to.",
+ mcpCapabilitiesLoading: "Caricamento funzionalità MCP...",
+ mcpCapabilitiesLoadFailed: "Failed to load Funzionalità MCP: {error}",
+ mcpCapabilitiesSearchPlaceholder: "Cerca funzionalità o strumenti",
+ mcpCapabilitiesSearchEmpty: "Nessuna funzionalità corrispondente",
+ mcpToolsetToolCount: "{enabled}/{total} strumenti",
+ mcpAccessLevelClassified: "Per chiamata",
+ mcpCoverageTypes: "{count} tipi di database",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Non legato a una connessione",
+ mcpCoverageUsableConnections: "Usato da {count} delle tue connessioni",
+ mcpCoverageNoUsableConnections: "Nessuna delle tue connessioni lo usa",
+ mcpCoveragePartialConnections: "{count} connessioni supportano solo alcuni strumenti",
+ mcpCoverageUncoveredConnections: "{count} connections have no Strumenti MCP yet: {names}",
+ mcpCoverageSearchPlaceholder: "Search tipi di database",
+ mcpCoverageSearchEmpty: "No matching tipi di database",
+ mcpCoverageLegend: "Sono elencati solo i tipi supportati. Quelli evidenziati corrispondono alle tue connessioni; * indica che alcuni strumenti del gruppo non supportano quel tipo (passa il puntatore per i dettagli).",
+ mcpCoverageTypeUnsupportedTool: "Non supportato da {tool}",
+ mcpCoverageCategoryOther: "Altro",
+ mcpCoveragePartialTool: "{tool} supporta {count} su {total}",
+ mcpToolDetailSkippedConnections: "Non disponibile su: {names}",
+ mcpToolDetailCoverage: "Supported tipi di database ({count})",
+ mcpToolDetailParameterDefault: "predefinito: {value}",
+ mcpToolDetailParameterDescription: "Descrizione",
+ mcpToolDetailParameterRequiredNo: "No",
+ mcpToolDetailParameterRequiredYes: "Sì",
+ mcpToolDetailParameterRequired: "Obbligatorio",
+ mcpToolDetailParameterType: "Tipo",
+ mcpToolDetailParameterName: "Nome",
+ mcpToolDetailNoParameters: "Nessun parametro",
+ mcpToolDetailParameters: "Parametri",
+ mcpToolDetailDescription: "Descrizione per il modello",
+ mcpToolDetailAccessClassified: "Classificato a ogni chiamata (lettura, scrittura o alto rischio in base all'istruzione)",
+ mcpToolDetailAccess: "Livello di accesso",
+ mcpToolDetailSummary: "Riepilogo",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "{count} delle tue connessioni non possono usarlo",
+ mcpToolsetDetailTools: "Strumenti",
+ mcpToolsetDetailCoverage: "Copertura",
+ mcpToolsetApply: "Applica questo gruppo",
+ mcpToolsetApplying: "Applicazione…",
+ mcpToolsetPending: "{count} modifiche agli strumenti non applicate",
+ mcpToolsetApplied: "Configurazione attuale applicata",
+ mcpToolsetCloseKeepsDraft: "La chiusura mantiene le modifiche. Puoi applicarle anche dalle Impostazioni.",
+ mcpToolsetApplyFailed: "Applicazione non riuscita: {error}. Le modifiche sono conservate; riprova.",
+ mcpToolsetApplyUnavailable: "La configurazione degli strumenti non è disponibile. Attendi il caricamento o riprova.",
+ mcpToolsetDetailClose: "Chiudi",
+ mcpPluginToolEntriesTitle: "Voci degli strumenti dei plugin",
+ mcpPluginsTitle: "Plugin",
+ mcpPluginsDescription: "Plugin that provide Strumenti MCP. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "Aggiorna",
+ mcpPluginsLoading: "Caricamento strumenti plugin...",
+ mcpPluginsLoadFailed: "Impossibile caricare gli strumenti dei plugin: {error}",
+ mcpPluginsEmpty: "Nessun plugin installato fornisce strumenti MCP.",
+ mcpPluginSaveFailed: "Impossibile salvare {name}: {message}",
+ mcpPluginAuthorClosed: "L'autore non lo ha abilitato per MCP esterno",
+ mcpPluginDiscoveryFailed: "Individuazione strumenti non riuscita",
+ mcpPluginToolCount: "{exposed}/{total} strumenti esposti",
+ mcpPluginToolCountOff: "{total} strumenti, disattivati",
+ mcpPluginCeilingSummary: "Limite: {level}",
+ mcpPluginPendingTools: "{count} nuovi strumenti richiedono conferma",
+ mcpPluginReview: "Esamina",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Individuazione strumenti non riuscita: {error}",
+ mcpPluginCeilingTitle: "Limite autorizzazione",
+ mcpPluginCeilingDescription: "Gli strumenti oltre il limite restano nascosti ai client MCP. Le chiamate devono rispettare anche i permessi delle risorse e le regole di visibilità delle connessioni.",
+ mcpPluginEnableFirst: "Attiva il plugin per modificarne il limite e gli strumenti.",
+ mcpPluginDefaultToolset: "Strumenti",
+ mcpPluginNoTools: "This plugin lists no Strumenti MCP right now.",
+ mcpPluginAuthorizeTitle: "Autorizza {name} for MCP",
+ mcpPluginAuthorizeDescription: "Scegli il limite dei permessi del plugin. Tutti gli strumenti dichiarati sotto vengono accettati; gli strumenti aggiunti in seguito o con un livello dichiarato aumentato richiederanno una nuova conferma se necessitano di più della sola lettura.",
+ mcpPluginAuthorizeTools: "Strumenti ({count})",
+ mcpPluginAuthorizeIncluded: "Esposto",
+ mcpPluginAuthorizeExcluded: "Nascosto",
+ mcpPluginAuthorizeFootnote: "In seguito puoi modificare il limite o disattivare singoli strumenti nei dettagli del plugin.",
+ mcpPluginAccessUndeclared: "Non dichiarato dall’autore — never exposed",
+ mcpPluginUndeclaredCount: "{count} strumenti non sono dichiarati nel manifest e restano nascosti",
+ mcpPluginUndeclaredTools: "{count} strumenti non hanno un livello di accesso dichiarato nel manifest del plugin e non saranno mai esposti: {names}",
+ mcpPluginAuthorizeCancel: "Annulla",
+ mcpPluginAuthorizeConfirm: "Autorizza",
+ mcpPluginToolEntriesHint: "Avanzato: voci consentite per gli strumenti dei plugin. dbx_*__* consente tutti gli strumenti dei plugin, dbx_<prefix>__* quelli di un plugin. Gli interruttori dei plugin determinano quali strumenti sono disponibili; queste voci aggiungono un ulteriore filtro.",
+ mcpPluginAllowlistBlocked: "L’elenco degli strumenti MCP consentiti non contiene voci di plugin, quindi i loro strumenti restano nascosti indipendentemente dagli interruttori dei plugin.",
+ mcpPluginAllowlistAllow: "Consenti strumenti plugin",
+ mcpPluginExposure: {
+ exposed: "Esposto",
+ undeclared: "Non dichiarato",
+ pluginDisabled: "Plugin disattivato",
+ toolDisabled: "Disattivato",
+ aboveCeiling: "Oltre il limite",
+ pendingApproval: "Richiede conferma",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Sola lettura",
+ write: "Lettura e scrittura",
+ full: "Completo (incl. alto rischio)",
+ },
+ mcpAccessLevel: {
+ read: "Lettura",
+ write: "Scrittura",
+ full: "Alto rischio",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "Individuazione e contesto", description: "Elenca connessioni e database e ottieni il contesto dello schema per il modello." },
+ sqlQuery: { title: "Query SQL", description: "Esegui query e script. Il rischio di ogni istruzione viene classificato a ogni chiamata." },
+ sqlSession: { title: "Sessioni e transazioni", description: "Mantieni una sessione tra le chiamate e controlla le transazioni." },
+ sqlSchema: { title: "Oggetti schema", description: "Esplora tabelle, colonne e codice sorgente delle routine." },
+ redis: { title: "Comandi Redis", description: "Esegui comandi Redis." },
+ mq: { title: "Lettura e invio di messaggi", description: "Leggi e invia messaggi Kafka, RocketMQ e RabbitMQ." },
+ salesforce: { title: "Identità e operazioni sui dati", description: "Identifica l'utente corrente e scrivi singoli record." },
+ workbench: { title: "Area di lavoro", description: "Apri tabelle e mostra risultati delle query in DBX." },
+ adminConnections: { title: "Gestione connessioni", description: "Aggiungi, duplica e rimuovi connessioni DBX." },
+ pluginRouter: { title: "Rilevamento e chiamata dei plugin", description: "Scopri gli strumenti dei plugin su richiesta e invocali tramite un unico router." },
+ nacosConfig: { title: "Gestione configurazioni", description: "Lettura, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "Gestione servizi", description: "Elenca servizi e istanze; attiva o disattiva le istanze e modifica i pesi." },
+ consulKv: { title: "Gestione KV", description: "Elenca, leggi, scrivi ed elimina chiavi KV di Consul con confronto e aggiornamento (CAS)." },
+ consulService: { title: "Rilevamento e salute dei servizi", description: "Catalogo di servizi e nodi, stato dei servizi e modalità manutenzione." },
+ },
+ mcpToolNacosListNamespaces: "Elenca namespace Nacos",
+ mcpToolNacosListConfigs: "Elenca configurazioni Nacos",
+ mcpToolNacosGetConfig: "Leggi configurazione Nacos",
+ mcpToolNacosConfigHistory: "Cronologia configurazione Nacos",
+ mcpToolNacosPublishConfig: "Pubblica configurazione Nacos",
+ mcpToolNacosDeleteConfig: "Elimina configurazione Nacos",
+ mcpToolNacosListServices: "Elenca servizi Nacos",
+ mcpToolNacosListInstances: "Elenca istanze Nacos",
+ mcpToolNacosUpdateInstance: "Aggiorna istanza Nacos",
+ mcpToolNacosSearchConfigs: "Cerca configurazioni Nacos",
+ mcpToolNacosRollbackConfig: "Ripristina configurazione Nacos",
+ mcpToolNacosGetService: "Consulta servizio Nacos",
+ mcpToolNacosRegisterInstance: "Registra istanza Nacos",
+ mcpToolNacosDeregisterInstance: "Annulla registrazione istanza Nacos",
+ mcpToolConsulKvList: "Elenca chiavi Consul KV",
+ mcpToolConsulKvGet: "Leggi chiave Consul KV",
+ mcpToolConsulKvPut: "Scrivi chiave Consul KV",
+ mcpToolConsulKvDelete: "Elimina chiave Consul KV",
+ mcpToolConsulListServices: "Elenca servizi Consul",
+ mcpToolConsulListNodes: "Elenca nodi Consul",
+ mcpToolConsulServiceHealth: "Stato servizio Consul",
+ mcpToolConsulSetMaintenance: "Modalità manutenzione Consul",
mcpConfigOptionsHint:
"DBX controlla centralmente l'accesso alle connessioni e i permessi di esecuzione per tutti i client MCP. La configurazione generata contiene solo i parametri di runtime necessari per avviare il server MCP e collegarlo a questa istanza DBX, senza variabili di autorizzazione o ambito connessione.",
mcpScopeConnection: "Connessioni consentite per MCP",
@@ -9655,7 +9964,8 @@ export default withEnglishFallback({
mcpWindsurfConfigPath: "Windsurf può usare ~/.codeium/windsurf/mcp_config.json.",
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json globalmente, o opencode.json a livello di progetto.",
mcpExecutionMode: "Permesso predefinito globale MCP",
- mcpExecutionModeDescription: "Imposta il valore predefinito usato quando non è configurato un permesso di connessione o database. Le impostazioni più specifiche possono sostituirlo.",
+ mcpExecutionModeDescription: "Le risorse senza un permesso specifico usano questo valore predefinito. Imposta permessi diversi nel controllo accessi qui sotto.",
+ mcpPermissionsDraftHint: "Le modifiche globali, di gruppo e di connessione usano Applica in basso. I permessi dei database si possono applicare anche nella finestra dedicata. I sottoambiti si salvano subito. Scartare le bozze non annulla le modifiche salvate.",
mcpExecutionModeReadOnly: "Sola lettura",
mcpExecutionModeSafeWrite: "Lettura e scrittura dati",
mcpExecutionModeRecommended: "Consigliato",
@@ -9664,21 +9974,21 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "Consente INSERT normali, UPDATE/DELETE con filtri effettivi, modifiche MongoDB con ambito verificabile e normali scritture Redis o eliminazione di chiavi esplicite; blocca modifiche globali e strutturali.",
mcpExecutionModeHighRiskWriteDescription: "Oltre alla lettura e scrittura dati, consente modifiche a intere tabelle, DDL, TRUNCATE, svuotamento del database e altre operazioni ad alto rischio. Le protezioni di produzione e sola lettura restano attive.",
mcpExecutionModeHighRiskConfirm: "L'accesso completo consente modifiche a intere tabelle, DDL, TRUNCATE, svuotamento del database e altre operazioni ad alto rischio. Abilitarlo?",
- mcpPromptHighRiskSql: "Chiedi conferma per SQL ad alto rischio (solo desktop; restano attive le protezioni di sola lettura e produzione)",
mcpSqlApprovalTitle: "Approvazione SQL ad alto rischio MCP",
mcpSqlApprovalScope: "Connessione: {connection} · Database: {database}",
mcpSqlApprovalOnce: "Solo questa richiesta",
mcpSqlApprovalHour: "Consenti su questo database per 1 ora",
mcpSqlApprovalDay: "Consenti su questo database per 1 giorno",
mcpSqlApprovalDeny: "Rifiuta",
- mcpCapabilityTitle: "Confronto delle capacità",
- mcpCapabilityDescription: "Queste sono operazioni rappresentative; le richieste che DBX non può classificare in modo affidabile richiedono l'accesso completo.",
+ mcpCapabilityTitle: "Dettagli dei permessi",
+ mcpCapabilityDescription: "La tabella descrive i permessi; gli strumenti vanno abilitati in Funzionalità. I permessi insufficienti sono rifiutati. Sicurezza delle chiamate gestisce la conferma e spiega l’autorizzazione precedente.",
mcpCapabilityOperation: "Capacità",
mcpCapabilityRead: "Query e letture",
mcpCapabilityScopedMutation: "Modifiche dati circoscritte (INSERT, UPDATE/DELETE filtrati, scrittura/eliminazione di chiavi esplicite)",
mcpCapabilityBroadMutation: "Aggiornamenti/eliminazioni di intere tabelle e svuotamento dati",
mcpCapabilitySchemaAdmin: "DDL, modifiche strutturali e amministrazione ad alto rischio",
- mcpCapabilityConnectionManagement: "Aggiunta/rimozione connessioni MCP",
+ mcpCapabilityConnectionCreate: "Aggiunta/duplicazione connessioni MCP (autorizzazione globale predefinita)",
+ mcpCapabilityConnectionRemove: "Rimozione connessioni MCP (autorizzazione globale predefinita)",
mcpCapabilityAllowed: "Consentito",
mcpCapabilityBlocked: "Bloccato",
mcpQueryTimeout: "Timeout query (secondi)",
@@ -9686,6 +9996,9 @@ export default withEnglishFallback({
mcpQueryTimeoutInvalid: "Inserisci un numero intero non negativo di secondi o lascia vuoto per ereditare l'impostazione della connessione.",
mcpCapabilityAlwaysEnforced: "Tutte le modalità restano soggette all'elenco delle connessioni consentite, alla protezione di sola lettura, alla protezione di produzione e ai permessi dell'account database.",
mcpPolicySaveFailed: "Impossibile salvare la policy di accesso MCP: {error}",
+ mcpPolicyRetry: "Riprova",
+ mcpPolicyRecover: "Esegui il backup e reimposta i permessi MCP",
+ mcpPolicyRecoverConfirm: "Questa operazione salva subito una copia della configurazione danneggiata e reimposta i permessi MCP, incluse le modifiche non salvate. Tutte le connessioni e gli strumenti saranno bloccati fino alla nuova configurazione. Continuare?",
mcpPolicyLoadFailed: "Impossibile caricare la policy di accesso MCP: {error}",
mcpDetectionTiming: "DBX esegue la verifica automaticamente all'apertura di questa pagina; usa di nuovo Verifica per aggiornare.",
mcpNpmBoundary: "DBX verifica e spiega solo lo stato di MCP; l'installazione e gli aggiornamenti vengono comunque eseguiti tramite npm, pnpm o bun.",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 01d8d9a721..c832007489 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -610,6 +610,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: "「{name}」が接続「{connection}」のデータの読み取りを要求しています。許可すると、プラグインセンターで取り消すまで、この接続が開いている間はプラグインが読み取り専用クエリを実行できます。許可しますか?",
dataAccessConsentTitle: "データアクセスの要求",
+ mcpToolsBadge: "MCP ツール",
+ mcpToolsBadgeHint: "This plugin provides MCP ツール. Enable and authorize them in Settings → MCP → 機能.",
+ mcpToolsFilter: "Only plugins with MCP ツール ({count})",
+ externalMcp: {
+ title: "外部 MCP クライアント",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → 機能.",
+ notOffered: "作成者はこのプラグインのツールを外部 MCP クライアントに公開していません。",
+ },
aiTools: {
title: "組み込み AI ツール",
description: "デフォルトはオフです:このスイッチが有効な間のみ、DBX AIアシスタント(Agentモード)が開いているこのプラグインの接続でツールを呼び出せます。読み取り専用以外のツールは毎回承認を求めます。",
@@ -7291,6 +7299,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "MCP ツール",
+ mcpClient: "MCP クライアント",
+ mcpTransport: "MCP トランスポート",
+ mcpAccess: "MCP アクセス権限",
+ mcpConfirmation: "MCP 確認",
kind: "タイプ",
operation: "操作",
connection: "接続",
@@ -9587,6 +9599,303 @@ export default withEnglishFallback({
mcpInstallSuccess: "インストール成功",
mcpInstallFailed: "インストール失敗",
mcpConfig: "MCP設定",
+ mcpCapabilitiesFilterLabel: "機能フィルター",
+ mcpCapabilitiesFilterAll: "すべて",
+ mcpCapabilitiesFilterBuiltin: "組み込み",
+ mcpCapabilitiesFilterPlugin: "プラグイン",
+ mcpCapabilitiesOnlyEnabled: "有効なものだけ表示",
+ mcpPluginScopeLoad: "プラグインから読み取る",
+ mcpPluginToolsMode: "外部へのプラグインツール提供方法",
+ mcpPluginToolsModeDescription: "DBX が承認済みのプラグインツールを MCP クライアントに提供する方法を設定します。変更は下部の「適用」で保存されます。",
+ mcpPluginToolsModeAuto: "自動(互換モード)",
+ mcpPluginToolsModeFlat: "直接一覧(既定)",
+ mcpPluginToolsModeLazy: "オンデマンド検出",
+ mcpPluginToolsModeFlatDescription: "承認済みの各プラグインツールを一覧に表示し、クライアントが直接呼び出せるようにします。",
+ mcpPluginToolsModeLazyDescription: "共通のプラグイン検索・呼び出しツールを提供し、必要なときに詳細を取得します。DBX 共通のプラグイン検出と呼び出しを有効にしてください。",
+ mcpPluginToolsModeAutoDescription: "従来の自動切替を維持します。プラグインツールの合計が 40 個以下なら直接一覧、それを超える場合はオンデマンド検出を使用します。",
+ mcpCallSafety: "呼び出しの安全性",
+ mcpCallSafetyLegacy: "旧方式の一時承認",
+ mcpCallSafetyEnabled: "高リスク呼び出しを毎回確認",
+ mcpCallSafetyDisabled: "追加確認なし",
+ mcpCallSafetyLegacyHint: "旧方式を維持します。データ読み書きでは一部の高リスク操作を確認後に一時許可し、フルアクセスでは確認しません。新方式では権限不足を拒否し、フルアクセスでも高リスク呼び出しを毎回確認します。",
+ mcpCallSafetyMigrate: "新しい確認方式に切り替え",
+ mcpCallSafetyDisableLegacy: "旧方式の一時承認を無効化",
+ mcpCallSafetyConfirm: "高リスクのツール呼び出し前に人の確認を求める",
+ mcpCallSafetyHint: "高リスクと判定された組み込み・プラグインの呼び出しが対象です。権限を先に検証し、フルアクセスでも確認します。確認で権限は昇格しません。",
+ mcpCallSafetyDesktopHint: "DBX デスクトップで現在の呼び出しだけを承認します。確認不可・拒否・タイムアウト時は実行しません。読み取り専用・本番保護は常に有効です。「適用」で保存します。",
+ mcpToolApprovalGenericTitle: "高リスクのツール呼び出しを確認",
+ mcpToolApprovalPluginTitle: "{plugin} の高リスクツールを確認",
+ mcpToolApprovalRedisTitle: "危険な Redis コマンドを確認",
+ mcpToolApprovalDescription: "An MCP クライアント wants to run a high-risk operation. Allow it only if you expect this call.",
+ mcpToolApprovalTool: "ツール",
+ mcpToolApprovalTarget: "対象",
+ mcpManagementCapabilities: "機能",
+ mcpOpenCallHistory: "MCP 呼び出し履歴を表示",
+ mcpAccessTreeTitle: "アクセス制御",
+ mcpAccessTreeDescription: "グループ、接続、データベースごとに権限を設定します。「継承」は上位の設定を使用し、有効な権限の列に最終的な権限と継承元を表示します。",
+ mcpAccessTreeSummary: "表示可能な接続 {visible}/{total} · 個別設定: グループ {groups}、接続 {connections}、データベース {databases}",
+ mcpAccessTreeScopeLabel: "接続の公開範囲",
+ mcpAccessTreeScopeAll: "すべての接続",
+ mcpAccessTreeScopeCustom: "選択したもののみ",
+ mcpAccessTreeSearchPlaceholder: "グループ、接続、データベースを検索",
+ mcpAccessTreeExceptionsOnly: "個別設定のみ表示",
+ mcpAccessTreeColumnResource: "リソース",
+ mcpAccessTreeColumnVisible: "表示",
+ mcpAccessTreeColumnSetting: "権限",
+ mcpAccessTreeColumnEffective: "有効値",
+ mcpAccessTreeInherit: "継承",
+ mcpAccessTreeGroupPartiallyVisible: "一部の接続が表示可能({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "現在のすべての接続が表示可能({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "子項目のみ許可されており、グループ全体は許可されていません。チェックすると、今後追加される接続を含むグループ全体が許可されます。",
+ mcpAccessTreeGroupDefaultHint: "グループの既定権限は、独自の権限が設定されていない子項目に適用されます。接続の表示範囲は変わりません。",
+ mcpAccessTreeHidden: "MCP には非公開",
+ mcpAccessTreeSourceGlobal: "グローバル既定値",
+ mcpAccessTreeSourceGroup: "グループ {group} から継承",
+ mcpAccessTreeSourceConnection: "接続の設定",
+ mcpAccessTreeSourceDatabase: "データベースの設定",
+ mcpAccessTreeGroupCount: "{count} 接続",
+ mcpAccessTreeLegacy: "旧形式",
+ mcpAccessTreeLegacyHint: "旧バージョンで保存された設定です。接続が継承する権限を制限することしかできません。権限を選び直すと通常の設定になります。",
+ mcpAccessTreeCoveredByGroup: "表示 through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "高リスク allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "データベース",
+ mcpAccessTreeDatabaseScopeAll: "すべてのデータベース",
+ mcpAccessTreeDatabaseScopeSelected: "選択済み ({count})",
+ mcpAccessTreeDatabaseScopeNone: "データベースなし",
+ mcpDatabaseRemoveConfirm: "選択したデータベースを削除すると、その個別権限も削除されます。続行しますか?",
+ mcpDatabaseUnavailable: "データベース権限設定は現在利用できません。読み込み完了を待つか再試行してください。",
+ mcpDatabaseConfigure: "データベース権限を設定",
+ mcpDatabaseOverrideCount: "個別設定 {count} 件",
+ mcpDatabaseDialogTitle: "{name} / データベースアクセス",
+ mcpDatabaseDialogDescription: "データベースを選択し、権限を設定します。右側への移動は適用後に有効になります。",
+ mcpDatabaseInherited: "継承する権限:{level}",
+ mcpDatabaseSavedInherited: "上位権限に未適用の変更があります。データベース権限のみを適用すると、保存済みの権限を継承します:{level}",
+ mcpDatabaseHiddenConnection: "この接続は現在 MCP に非表示です。データベース権限の適用では接続は公開されません。",
+ mcpDatabaseAllHint: "現在と今後追加するデータベースを含み、接続権限を使用します。",
+ mcpDatabaseNoneHint: "適用後、すべてのデータベースへのアクセスを拒否します。",
+ mcpDatabaseLoaded: "このアカウントで表示可能な {count} 件を取得しました",
+ mcpDatabaseRefresh: "一覧を更新",
+ mcpDatabaseAddSelected: "追加 →",
+ mcpDatabaseRemoveSelected: "← 削除",
+ mcpDatabaseAvailable: "未選択({count})",
+ mcpDatabaseSelected: "選択済み({count})",
+ mcpDatabaseSearch: "データベース名を検索",
+ mcpDatabaseSelectResults: "現在の検索結果を選択({count})",
+ mcpDatabaseBatchLevel: "チェックしたDBの権限設定({count})",
+ mcpDatabaseBatchHighRiskConfirm: "チェックした {count} 個のデータベースにフルアクセスを許可しますか?接続の読み取り専用設定と本番環境の保護は引き続き適用されます。",
+ mcpDatabaseNotDiscovered: "今回の取得では見つかりません",
+ mcpDatabaseShowMore: "さらに表示({shown}/{total} 件表示)",
+ mcpDatabaseSaveHint: "この接続のデータベース範囲と個別権限のみを保存します。他の未保存の変更は保持します。",
+ mcpDatabaseApply: "データベース権限を適用",
+ mcpAccessTreePickDatabases: "データベースを選択",
+ mcpAccessTreePickerTitle: "データベース of {name}",
+ mcpAccessTreeLoadingDatabases: "データベースを読み込み中…",
+ mcpAccessTreeLoadDatabasesFailed: "データベースを読み込めませんでした: {error}。名前は手動で追加できます。",
+ mcpAccessTreeManualDatabase: "データベース名を追加",
+ mcpAccessTreeNoMatch: "一致するリソースはありません",
+ mcpAccessTreeEmpty: "接続はまだありません",
+ mcpAccessTreeFootnote: "優先順位: データベース > 接続 > 最も近いグループ > 親グループ > グローバル既定値。接続の読み取り専用設定、本番環境の保護、データベースアカウントの権限は常に適用されます。",
+ mcpAccessTreeNacosNamespace: "名前空間",
+ mcpPluginScopeAll: "すべて ({title})",
+ mcpPluginScopeSelected: "選択済み ({count})",
+ mcpPluginScopeNone: "いいえ {title}",
+ mcpPluginScopeAdd: "{title} を追加",
+ mcpBrowser: {
+ viewMode: "表示モード",
+ viewManage: "カテゴリ管理",
+ viewOverview: "全体概要",
+ overviewSummary: "{toolsets} ツールセット · {total} ツール · {enabled} 件が有効",
+ overviewPluginsHint: "プラグインのツールと認証を確認します。詳細を開くにはプラグインを選択してください。",
+ overviewOpenDetails: "詳細を表示",
+ expandCategory: "カテゴリを展開",
+ collapseCategory: "カテゴリを折りたたむ",
+ builtin: "組み込み機能",
+ plugins: "プラグイン拡張",
+ advanced: "詳細設定",
+ navigation: "機能カテゴリ",
+ searchPlaceholder: "カテゴリ、機能、プラグイン、ツールを検索…",
+ clearSearch: "検索をクリア",
+ searchResults: "検索結果",
+ categoryCount: "{count} 個のツールセット",
+ summary: "{toolsets} 個のツールセット · {total} 個のツール · {enabled} 個が有効",
+ enableCategory: "このカテゴリをすべて有効化",
+ disableCategory: "このカテゴリをすべて無効化",
+ draftHint: "詳細画面でツールセットを適用するか、下部の「適用」ですべての未適用設定を保存できます。",
+ batchChanged: "このカテゴリのツールを変更しました。「適用」で反映されます",
+ coverageHint: "対象接続数は接続の種類に基づく集計であり、実際の認可範囲ではありません。",
+ uncovered: "{count} 個の接続に対応する組み込みツールがありません",
+ viewDetails: "詳細を見る",
+ emptyEnabled: "このカテゴリに有効なツールはありません。「有効なものだけ表示」を解除して設定できます。",
+ retry: "再試行",
+ enabledToolCount: "{enabled}/{total} 個が有効",
+ partialEnabled: "一部が有効",
+ coverageConnections: "{count} 個の接続に対応",
+ coveragePartialConnections: "{count} 個は一部のみ対応",
+ noMatchingConnections: "対象の接続はありません",
+ resourceScopes: "リソース範囲",
+ pluginImmediate: "変更は即時保存され、下部の「適用 / キャンセル」の影響を受けません",
+ pluginSaving: "保存中…",
+ pluginSaved: "保存済み",
+ pluginOnlyEnabledEmpty: "有効なツールはありません。「有効なものだけ表示」を解除すると表示されます。",
+ pluginUnavailable: "このプラグインは利用できなくなりました。プラグイン一覧を更新してください",
+ resourceKind: {
+ database: "データベース",
+ dbIndex: "論理データベース",
+ topic: "トピック",
+ queue: "キュー",
+ org: "組織",
+ namespace: "名前空間",
+ },
+ category: {
+ database: { title: "データベース", description: "データの検索、セッションとトランザクションの管理、オブジェクト構造の閲覧、Redis コマンドの実行。" },
+ nacos: { title: "Nacos", description: "設定、サービス、インスタンスを管理します。" },
+ consul: { title: "Consul", description: "KV の管理、サービスの検出、ヘルス状態の確認を行います。" },
+ mq: { title: "メッセージキュー", description: "メッセージを読み取り、送信します。" },
+ salesforce: { title: "Salesforce", description: "ユーザー情報の確認とデータ操作を行います。" },
+ dbx: { title: "DBX 共通", description: "製品間で共有する機能:接続の検出、ワークベンチ連携、接続管理、プラグインの検出と呼び出し。" },
+ other: { title: "その他の機能", description: "未分類のツールセットをここで確認・設定できます。" },
+ },
+ },
+ mcpCapabilitiesTitle: "MCP 機能",
+ mcpCapabilitiesDescription: "組み込み MCP ツール grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the database types it applies to.",
+ mcpCapabilitiesLoading: "MCP 機能を読み込み中…",
+ mcpCapabilitiesLoadFailed: "Failed to load MCP 機能: {error}",
+ mcpCapabilitiesSearchPlaceholder: "機能やツールを検索",
+ mcpCapabilitiesSearchEmpty: "一致する機能はありません",
+ mcpToolsetToolCount: "{enabled}/{total} ツール",
+ mcpAccessLevelClassified: "呼び出しごと",
+ mcpCoverageTypes: "{count} 種類のデータベース",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "接続に依存しません",
+ mcpCoverageUsableConnections: "{count} 件の接続で利用できます",
+ mcpCoverageNoUsableConnections: "利用できる接続がありません",
+ mcpCoveragePartialConnections: "{count} 件の接続は一部のツールのみ対応しています",
+ mcpCoverageUncoveredConnections: "{count} connections have no MCP ツール yet: {names}",
+ mcpCoverageSearchPlaceholder: "データベースの種類を検索",
+ mcpCoverageSearchEmpty: "いいえ matching database types",
+ mcpCoverageLegend: "対応する種類のみ表示します。強調表示は登録済みの接続に対応する種類です。* はグループ内の一部ツールが非対応であることを示します(ポインターを合わせると詳細を表示)。",
+ mcpCoverageTypeUnsupportedTool: "{tool} は非対応",
+ mcpCoverageCategoryOther: "その他",
+ mcpCoveragePartialTool: "{tool}: {total} 種類中 {count} 種類に対応",
+ mcpToolDetailSkippedConnections: "利用不可: {names}",
+ mcpToolDetailCoverage: "対応データベースの種類 ({count})",
+ mcpToolDetailParameterDefault: "既定値: {value}",
+ mcpToolDetailParameterDescription: "説明",
+ mcpToolDetailParameterRequiredNo: "いいえ",
+ mcpToolDetailParameterRequiredYes: "はい",
+ mcpToolDetailParameterRequired: "必須",
+ mcpToolDetailParameterType: "種類",
+ mcpToolDetailParameterName: "名前",
+ mcpToolDetailNoParameters: "パラメーターなし",
+ mcpToolDetailParameters: "パラメーター",
+ mcpToolDetailDescription: "モデル向けの説明",
+ mcpToolDetailAccessClassified: "呼び出しごとに判定(文に応じて読み取り、書き込み、高リスク)",
+ mcpToolDetailAccess: "アクセスレベル",
+ mcpToolDetailSummary: "概要",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "{count} 件の接続では利用できません",
+ mcpToolsetDetailTools: "ツール",
+ mcpToolsetDetailCoverage: "対応範囲",
+ mcpToolsetApply: "このツールセットを適用",
+ mcpToolsetApplying: "適用中…",
+ mcpToolsetPending: "未適用のツール変更:{count} 件",
+ mcpToolsetApplied: "現在の設定は適用済みです",
+ mcpToolsetCloseKeepsDraft: "閉じても変更は保持されます。設定画面でまとめて適用することもできます。",
+ mcpToolsetApplyFailed: "適用できませんでした:{error}。変更は保持されています。再試行してください。",
+ mcpToolsetApplyUnavailable: "現在ツールを設定できません。読み込みの完了を待つか、再試行してください。",
+ mcpToolsetDetailClose: "閉じる",
+ mcpPluginToolEntriesTitle: "プラグイン tool entries",
+ mcpPluginsTitle: "プラグイン",
+ mcpPluginsDescription: "プラグイン that provide MCP ツール. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "更新",
+ mcpPluginsLoading: "プラグインツールを読み込み中…",
+ mcpPluginsLoadFailed: "プラグインツールの読み込みに失敗しました: {error}",
+ mcpPluginsEmpty: "インストール済みプラグインに MCP ツールはありません",
+ mcpPluginSaveFailed: "{name} の保存に失敗しました: {message}",
+ mcpPluginAuthorClosed: "作成者は外部 MCP に公開していません",
+ mcpPluginDiscoveryFailed: "ツールの検出に失敗しました",
+ mcpPluginToolCount: "{exposed}/{total} ツールを公開",
+ mcpPluginToolCountOff: "{total} ツール、無効",
+ mcpPluginCeilingSummary: "上限: {level}",
+ mcpPluginPendingTools: "{count} 個の新しいツールに確認が必要です",
+ mcpPluginReview: "確認",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "ツールの検出に失敗しました: {error}",
+ mcpPluginCeilingTitle: "認可上限",
+ mcpPluginCeilingDescription: "上限を超えるツールは MCP クライアントに公開されません。実際の呼び出しには、リソースの権限と接続の公開範囲の制限も適用されます。",
+ mcpPluginEnableFirst: "上限やツールを変更するにはプラグインを有効にしてください。",
+ mcpPluginDefaultToolset: "ツール",
+ mcpPluginNoTools: "This plugin lists no MCP ツール right now.",
+ mcpPluginAuthorizeTitle: "認可 {name} for MCP",
+ mcpPluginAuthorizeDescription: "プラグインの権限上限を選択してください。以下の宣言済みツールはすべて承認されます。今後追加されるツールや宣言された権限レベルが上がったツールが、読み取りを超える権限を必要とする場合は再確認します。",
+ mcpPluginAuthorizeTools: "ツール ({count})",
+ mcpPluginAuthorizeIncluded: "公開",
+ mcpPluginAuthorizeExcluded: "非公開",
+ mcpPluginAuthorizeFootnote: "後からプラグインの詳細で上限を変更したり、個別のツールを無効にしたりできます。",
+ mcpPluginAccessUndeclared: "未宣言 by the author — never exposed",
+ mcpPluginUndeclaredCount: "{count} 個のツールはマニフェストで宣言されておらず、非公開のままです",
+ mcpPluginUndeclaredTools: "{count} 個のツールにはプラグインのマニフェストで権限レベルが宣言されていないため、公開されません: {names}",
+ mcpPluginAuthorizeCancel: "キャンセル",
+ mcpPluginAuthorizeConfirm: "認可",
+ mcpPluginToolEntriesHint: "詳細設定:プラグインツールの許可リストです。dbx_*__* はすべてのプラグインツール、dbx_<prefix>__* は特定のプラグインを許可します。プラグインのスイッチで利用可能なツールが決まり、このリストでさらに絞り込まれます。",
+ mcpPluginAllowlistBlocked: "MCP ツールの許可リストにプラグインの項目がないため、プラグインのスイッチに関係なく、プラグインツールは表示されません。",
+ mcpPluginAllowlistAllow: "プラグインツールを許可",
+ mcpPluginExposure: {
+ exposed: "公開",
+ undeclared: "未宣言",
+ pluginDisabled: "プラグイン無効",
+ toolDisabled: "無効",
+ aboveCeiling: "上限超過",
+ pendingApproval: "確認が必要",
+ },
+ mcpPluginCeilingLevel: {
+ read: "読み取り専用",
+ write: "読み書き",
+ full: "完全(高リスクを含む)",
+ },
+ mcpAccessLevel: {
+ read: "読み取り",
+ write: "書き込み",
+ full: "高リスク",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "検出とコンテキスト", description: "接続とデータベースを一覧表示し、モデル向けのスキーマ情報を取得します。" },
+ sqlQuery: { title: "SQL クエリ", description: "クエリやスクリプトを実行します。各文のリスクは呼び出しごとに判定されます。" },
+ sqlSession: { title: "セッションとトランザクション", description: "呼び出し間でセッションを維持し、トランザクションを制御します。" },
+ sqlSchema: { title: "スキーマオブジェクト", description: "テーブル、列、ルーチンのソースを参照します。" },
+ redis: { title: "Redis コマンド", description: "Redis コマンドを実行します。" },
+ mq: { title: "メッセージの読み取りと送信", description: "Kafka、RocketMQ、RabbitMQ のメッセージを読み取り、送信します。" },
+ salesforce: { title: "ユーザー情報とデータ操作", description: "現在のユーザーを確認し、単一レコードを書き込みます。" },
+ workbench: { title: "ワークベンチ", description: "DBX 内でテーブルを開き、クエリ結果を表示します。" },
+ adminConnections: { title: "接続管理", description: "DBX の接続を追加、複製、削除します。" },
+ pluginRouter: { title: "プラグインの検出と呼び出し", description: "必要に応じてプラグインツールを検出し、共通のルーターから呼び出します。" },
+ nacosConfig: { title: "設定管理", description: "読み取り, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "サービス管理", description: "サービスとインスタンスを一覧表示し、インスタンスのオンライン状態や重みを変更します。" },
+ consulKv: { title: "KV 管理", description: "比較と更新(CAS)を使用して Consul KV キーを一覧表示、読み取り、書き込み、削除します。" },
+ consulService: { title: "サービス検出とヘルス状態", description: "サービスとノードのカタログ、サービスの健全性、メンテナンスモードを扱います。" },
+ },
+ mcpToolNacosListNamespaces: "Nacos 名前空間を一覧表示",
+ mcpToolNacosListConfigs: "Nacos 設定を一覧表示",
+ mcpToolNacosGetConfig: "読み取り Nacos config",
+ mcpToolNacosConfigHistory: "Nacos 設定履歴",
+ mcpToolNacosPublishConfig: "Nacos 設定を公開",
+ mcpToolNacosDeleteConfig: "Nacos 設定を削除",
+ mcpToolNacosListServices: "Nacos サービスを一覧表示",
+ mcpToolNacosListInstances: "Nacos インスタンスを一覧表示",
+ mcpToolNacosUpdateInstance: "Nacos インスタンスを更新",
+ mcpToolNacosSearchConfigs: "Nacos 設定を検索",
+ mcpToolNacosRollbackConfig: "Nacos 設定をロールバック",
+ mcpToolNacosGetService: "Nacos サービスを参照",
+ mcpToolNacosRegisterInstance: "Nacos インスタンスを登録",
+ mcpToolNacosDeregisterInstance: "Nacos インスタンスの登録を解除",
+ mcpToolConsulKvList: "Consul KV キーを一覧表示",
+ mcpToolConsulKvGet: "読み取り Consul KV key",
+ mcpToolConsulKvPut: "書き込み Consul KV key",
+ mcpToolConsulKvDelete: "Consul KV キーを削除",
+ mcpToolConsulListServices: "Consul サービスを一覧表示",
+ mcpToolConsulListNodes: "Consul ノードを一覧表示",
+ mcpToolConsulServiceHealth: "Consul サービスの健全性",
+ mcpToolConsulSetMaintenance: "Consul メンテナンスモード",
mcpConfigOptionsHint: "接続範囲と実行権限はDBXがすべてのMCPクライアントに一元適用します。生成される設定にはMCP Serverの起動と現在のDBXへの接続に必要な実行パラメーターのみが含まれ、権限や接続範囲の変数は含まれません。",
mcpScopeConnection: "MCPに許可する接続",
mcpScopeConnectionDescription: "DBXは選択した接続だけをMCPに公開します。変更はすべてのMCPクライアントに適用されます。",
@@ -9634,7 +9943,8 @@ export default withEnglishFallback({
mcpWindsurfConfigPath: "Windsurfは ~/.codeium/windsurf/mcp_config.json を使用できます。",
mcpOpenCodeConfigPath: "グローバル ~/.config/opencode/opencode.json、プロジェクト opencode.json。",
mcpExecutionMode: "MCP グローバル既定権限",
- mcpExecutionModeDescription: "接続またはデータベースの権限が未設定の場合に使う既定値です。接続既定とデータベース設定はスコープに応じてこれを上書きできます。",
+ mcpExecutionModeDescription: "個別の権限がないリソースはこの既定値を使用します。異なる権限は下のアクセス制御で設定してください。",
+ mcpPermissionsDraftHint: "全体・グループ・接続の変更は下部の「適用」で有効になります。データベース権限はダイアログからも適用できます。名前空間などの子範囲は即時保存されます。下書きを破棄しても保存済みの変更は戻りません。",
mcpExecutionModeReadOnly: "読み取り専用",
mcpExecutionModeSafeWrite: "データ読み書き",
mcpExecutionModeRecommended: "推奨",
@@ -9643,21 +9953,21 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "通常のINSERT、有効な条件付きUPDATE/DELETE、範囲を検証できるMongoDB変更、通常のRedis書き込みや明示キー削除を許可し、テーブル全体や構造の変更を拒否します。",
mcpExecutionModeHighRiskWriteDescription: "データ読み書きに加えて、テーブル全体の変更、DDL、TRUNCATE、データベース消去などの高リスク操作を許可します。本番環境と接続の読み取り専用保護は引き続き適用されます。",
mcpExecutionModeHighRiskConfirm: "フルアクセスでは、テーブル全体の変更、DDL、TRUNCATE、データベース消去などの高リスク操作を実行できます。有効にしますか?",
- mcpPromptHighRiskSql: "高リスク SQL の実行前に確認する(デスクトップ版のみ。読み取り専用・本番環境の保護は維持)",
mcpSqlApprovalTitle: "MCP 高リスク SQL の承認",
mcpSqlApprovalScope: "接続: {connection} · データベース: {database}",
mcpSqlApprovalOnce: "今回のリクエストのみ",
mcpSqlApprovalHour: "このデータベースで 1 時間許可",
mcpSqlApprovalDay: "このデータベースで 1 日許可",
mcpSqlApprovalDeny: "拒否",
- mcpCapabilityTitle: "権限と機能の比較",
- mcpCapabilityDescription: "代表的な操作を示しています。DBXが確実に分類できないリクエストにはフルアクセスが必要です。",
+ mcpCapabilityTitle: "権限の説明",
+ mcpCapabilityDescription: "表はアクセス権限を示します。ツールは「機能」で有効化が必要です。権限不足は拒否します。確認と旧方式の一時承認は「呼び出しの安全性」で管理します。",
mcpCapabilityOperation: "機能",
mcpCapabilityRead: "クエリと読み取り",
mcpCapabilityScopedMutation: "範囲を限定したデータ変更(INSERT、条件付きUPDATE/DELETE、明示キーの書き込み/削除)",
mcpCapabilityBroadMutation: "テーブル全体の更新/削除とデータ消去",
mcpCapabilitySchemaAdmin: "DDL、構造変更、高リスク管理コマンド",
- mcpCapabilityConnectionManagement: "MCP接続の追加/削除",
+ mcpCapabilityConnectionCreate: "MCP 接続の追加/複製(グローバル既定権限)",
+ mcpCapabilityConnectionRemove: "MCP 接続の削除(グローバル既定権限)",
mcpCapabilityAllowed: "許可",
mcpCapabilityBlocked: "禁止",
mcpQueryTimeout: "クエリタイムアウト(秒)",
@@ -9665,6 +9975,9 @@ export default withEnglishFallback({
mcpQueryTimeoutInvalid: "秒数を負でない整数で入力するか、空にして接続設定を継承してください。",
mcpCapabilityAlwaysEnforced: "すべてのモードで、接続許可リスト、接続の読み取り専用保護、本番環境保護、データベースアカウント権限が引き続き適用されます。",
mcpPolicySaveFailed: "MCPアクセスポリシーを保存できませんでした: {error}",
+ mcpPolicyRetry: "再試行",
+ mcpPolicyRecover: "MCP 権限をバックアップしてリセット",
+ mcpPolicyRecoverConfirm: "破損したポリシーを直ちにバックアップし、未保存の変更を含む MCP 権限をリセットします。再設定するまで全接続とツールが無効になります。続行しますか?",
mcpPolicyLoadFailed: "MCPアクセスポリシーを読み込めませんでした: {error}",
mcpDetectionTiming: "このページを開くとDBXが自動的に確認します。更新するには再確認を使用してください。",
mcpNpmBoundary: "DBXはMCPステータスの確認と説明のみを行います。インストールとアップグレードはnpm、pnpm、またはbunを通じて実行されます。",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index e53b879259..2eeb92edb2 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -608,6 +608,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: '"{name}" 플러그인이 "{connection}" 연결의 데이터 읽기를 요청합니다. 허용하면 플러그인 센터에서 취소할 때까지 이 연결이 열려 있는 동안 플러그인이 읽기 전용 쿼리를 실행할 수 있습니다. 허용하시겠습니까?',
dataAccessConsentTitle: "데이터 액세스 요청",
+ mcpToolsBadge: "MCP 도구",
+ mcpToolsBadgeHint: "This plugin provides MCP 도구. Enable and authorize them in Settings → MCP → 기능.",
+ mcpToolsFilter: "Only plugins with MCP 도구 ({count})",
+ externalMcp: {
+ title: "외부 MCP 클라이언트",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → 기능.",
+ notOffered: "작성자가 이 플러그인의 도구를 외부 MCP 클라이언트에 공개하지 않았습니다.",
+ },
aiTools: {
title: "내장 AI 도구",
description: "기본값은 꺼짐입니다: 이 스위치가 켜져 있는 동안에만 DBX AI 어시스턴트(Agent 모드)가 열려 있는 이 플러그인의 연결에서 도구를 호출할 수 있습니다. 읽기 전용이 아닌 도구는 호출할 때마다 승인을 요청합니다.",
@@ -7225,6 +7233,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "MCP 도구",
+ mcpClient: "MCP 클라이언트",
+ mcpTransport: "MCP 전송 방식",
+ mcpAccess: "MCP 접근 권한",
+ mcpConfirmation: "MCP 확인",
kind: "유형",
operation: "작업",
connection: "연결",
@@ -9756,6 +9768,303 @@ export default withEnglishFallback({
mcpInstallSuccess: "설치 성공",
mcpInstallFailed: "설치 실패",
mcpConfig: "MCP 설정",
+ mcpCapabilitiesFilterLabel: "기능 필터",
+ mcpCapabilitiesFilterAll: "전체",
+ mcpCapabilitiesFilterBuiltin: "내장",
+ mcpCapabilitiesFilterPlugin: "플러그인",
+ mcpCapabilitiesOnlyEnabled: "활성화된 항목만 표시",
+ mcpPluginScopeLoad: "플러그인에서 읽기",
+ mcpPluginToolsMode: "외부 플러그인 도구 제공 방식",
+ mcpPluginToolsModeDescription: "DBX가 승인된 플러그인 도구를 MCP 클라이언트에 제공하는 방식을 설정합니다. 하단의 적용을 클릭하면 저장됩니다.",
+ mcpPluginToolsModeAuto: "자동 (호환 모드)",
+ mcpPluginToolsModeFlat: "직접 나열 (기본값)",
+ mcpPluginToolsModeLazy: "필요할 때 검색",
+ mcpPluginToolsModeFlatDescription: "승인된 플러그인 도구를 각각 나열하여 클라이언트가 직접 호출할 수 있게 합니다.",
+ mcpPluginToolsModeLazyDescription: "공통 플러그인 검색 및 호출 도구를 제공하고 필요할 때 세부 정보를 가져옵니다. DBX 공통에서 플러그인 검색 및 호출을 켜세요.",
+ mcpPluginToolsModeAutoDescription: "기존 자동 전환을 유지합니다. 플러그인 도구 총수가 40개 이하면 직접 나열하고, 초과하면 필요할 때 검색합니다.",
+ mcpCallSafety: "호출 안전",
+ mcpCallSafetyLegacy: "기존 임시 승인",
+ mcpCallSafetyEnabled: "고위험 호출마다 확인",
+ mcpCallSafetyDisabled: "추가 확인 없음",
+ mcpCallSafetyLegacyHint: "기존 동작을 유지합니다. 데이터 읽기·쓰기는 확인 후 일부 고위험 작업을 임시 허용하며 전체 접근은 묻지 않습니다. 새 정책은 권한 부족을 거부하고 전체 접근의 고위험 호출도 매번 확인합니다.",
+ mcpCallSafetyMigrate: "새 확인 정책 사용",
+ mcpCallSafetyDisableLegacy: "기존 임시 승인 끄기",
+ mcpCallSafetyConfirm: "고위험 도구 호출 전에 사용자 확인 요청",
+ mcpCallSafetyHint: "고위험으로 식별된 내장 및 플러그인 호출에 적용됩니다. 권한을 먼저 검사하며 전체 접근도 확인합니다. 확인으로 권한이 상승하지 않습니다.",
+ mcpCallSafetyDesktopHint: "DBX 데스크톱에서 현재 호출만 승인합니다. 확인 불가, 거부, 시간 초과 시 실행하지 않습니다. 읽기 전용 및 운영 환경 보호는 항상 적용됩니다. 적용을 눌러 저장하세요.",
+ mcpToolApprovalGenericTitle: "고위험 도구 호출 확인",
+ mcpToolApprovalPluginTitle: "{plugin} 고위험 도구 확인",
+ mcpToolApprovalRedisTitle: "위험한 Redis 명령 확인",
+ mcpToolApprovalDescription: "An MCP 클라이언트 wants to run a high-risk operation. Allow it only if you expect this call.",
+ mcpToolApprovalTool: "도구",
+ mcpToolApprovalTarget: "대상",
+ mcpManagementCapabilities: "기능",
+ mcpOpenCallHistory: "MCP 호출 기록 보기",
+ mcpAccessTreeTitle: "액세스 제어",
+ mcpAccessTreeDescription: "그룹, 연결, 데이터베이스의 권한을 설정합니다. 상속은 상위 설정을 사용하며, 적용 권한 열에 최종 권한과 출처가 표시됩니다.",
+ mcpAccessTreeSummary: "표시 가능한 연결 {visible}/{total} · 개별 설정: 그룹 {groups}개, 연결 {connections}개, 데이터베이스 {databases}개",
+ mcpAccessTreeScopeLabel: "연결 공개 범위",
+ mcpAccessTreeScopeAll: "모든 연결",
+ mcpAccessTreeScopeCustom: "선택 항목만",
+ mcpAccessTreeSearchPlaceholder: "그룹, 연결 또는 데이터베이스 검색",
+ mcpAccessTreeExceptionsOnly: "개별 설정만 표시",
+ mcpAccessTreeColumnResource: "리소스",
+ mcpAccessTreeColumnVisible: "표시",
+ mcpAccessTreeColumnSetting: "권한",
+ mcpAccessTreeColumnEffective: "최종 적용",
+ mcpAccessTreeInherit: "상속",
+ mcpAccessTreeGroupPartiallyVisible: "일부 연결 표시 가능 ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "현재 모든 연결 표시 가능 ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "하위 항목만 허용되었으며 전체 그룹은 허용되지 않았습니다. 체크하면 앞으로 추가될 연결을 포함한 전체 그룹이 허용됩니다.",
+ mcpAccessTreeGroupDefaultHint: "그룹 기본 권한은 별도 권한 설정이 없는 하위 항목에 적용됩니다. 연결의 표시 범위는 변경되지 않습니다.",
+ mcpAccessTreeHidden: "MCP에 표시되지 않음",
+ mcpAccessTreeSourceGlobal: "전역 기본값",
+ mcpAccessTreeSourceGroup: "그룹 {group}에서 상속",
+ mcpAccessTreeSourceConnection: "연결 설정",
+ mcpAccessTreeSourceDatabase: "데이터베이스 설정",
+ mcpAccessTreeGroupCount: "연결 {count}개",
+ mcpAccessTreeLegacy: "이전 형식",
+ mcpAccessTreeLegacyHint: "이전 버전에서 저장된 설정으로, 연결이 상속하는 권한을 제한만 할 수 있습니다. 권한을 다시 선택하면 일반 설정으로 전환됩니다.",
+ mcpAccessTreeCoveredByGroup: "표시 through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "높은 위험 allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "데이터베이스",
+ mcpAccessTreeDatabaseScopeAll: "모든 데이터베이스",
+ mcpAccessTreeDatabaseScopeSelected: "선택됨 ({count})",
+ mcpAccessTreeDatabaseScopeNone: "데이터베이스 없음",
+ mcpDatabaseRemoveConfirm: "선택한 데이터베이스를 제거하면 해당 개별 권한도 삭제됩니다. 계속할까요?",
+ mcpDatabaseUnavailable: "데이터베이스 권한 설정을 사용할 수 없습니다. 로딩이 끝날 때까지 기다리거나 다시 시도하세요.",
+ mcpDatabaseConfigure: "데이터베이스 권한 설정",
+ mcpDatabaseOverrideCount: "개별 설정 {count}개",
+ mcpDatabaseDialogTitle: "{name} / 데이터베이스 접근",
+ mcpDatabaseDialogDescription: "데이터베이스를 선택하고 권한을 설정하세요. 오른쪽으로 이동한 항목은 적용 후에 반영됩니다.",
+ mcpDatabaseInherited: "상속 권한: {level}",
+ mcpDatabaseSavedInherited: "상위 권한에 미적용 변경이 있습니다. 데이터베이스 권한만 적용하면 저장된 권한을 상속합니다: {level}",
+ mcpDatabaseHiddenConnection: "이 연결은 현재 MCP에 숨겨져 있습니다. 데이터베이스 권한을 적용해도 연결이 공개되지 않습니다.",
+ mcpDatabaseAllHint: "현재 및 향후 추가되는 데이터베이스에 연결 권한을 사용합니다.",
+ mcpDatabaseNoneHint: "적용하면 모든 데이터베이스 접근이 차단됩니다.",
+ mcpDatabaseLoaded: "이 계정에 표시되는 데이터베이스 {count}개를 불러왔습니다",
+ mcpDatabaseRefresh: "목록 새로 고침",
+ mcpDatabaseAddSelected: "추가 →",
+ mcpDatabaseRemoveSelected: "← 제거",
+ mcpDatabaseAvailable: "미선택 ({count})",
+ mcpDatabaseSelected: "선택됨 ({count})",
+ mcpDatabaseSearch: "데이터베이스 이름 검색",
+ mcpDatabaseSelectResults: "현재 검색 결과 선택 ({count})",
+ mcpDatabaseBatchLevel: "체크한 DB 권한 설정 ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "체크한 데이터베이스 {count}개에 전체 접근을 허용할까요? 연결의 읽기 전용 설정과 운영 환경 보호는 계속 적용됩니다.",
+ mcpDatabaseNotDiscovered: "이번 조회에서 찾지 못함",
+ mcpDatabaseShowMore: "더 보기 ({shown}/{total} 표시)",
+ mcpDatabaseSaveHint: "이 연결의 데이터베이스 범위와 개별 권한만 저장합니다. 다른 미저장 변경은 유지됩니다.",
+ mcpDatabaseApply: "데이터베이스 권한 적용",
+ mcpAccessTreePickDatabases: "데이터베이스 선택",
+ mcpAccessTreePickerTitle: "데이터베이스 of {name}",
+ mcpAccessTreeLoadingDatabases: "데이터베이스 로드 중…",
+ mcpAccessTreeLoadDatabasesFailed: "데이터베이스를 불러오지 못했습니다: {error}. 이름은 수동으로 추가할 수 있습니다.",
+ mcpAccessTreeManualDatabase: "데이터베이스 이름 추가",
+ mcpAccessTreeNoMatch: "일치하는 리소스가 없습니다",
+ mcpAccessTreeEmpty: "연결이 없습니다",
+ mcpAccessTreeFootnote: "우선순위: 데이터베이스 > 연결 > 가장 가까운 그룹 > 상위 그룹 > 전역 기본값. 연결의 읽기 전용 보호, 운영 환경 보호 및 데이터베이스 계정 권한은 항상 적용됩니다.",
+ mcpAccessTreeNacosNamespace: "네임스페이스",
+ mcpPluginScopeAll: "전체 ({title})",
+ mcpPluginScopeSelected: "선택됨 ({count})",
+ mcpPluginScopeNone: "아니요 {title}",
+ mcpPluginScopeAdd: "{title} 추가",
+ mcpBrowser: {
+ viewMode: "보기 모드",
+ viewManage: "카테고리 관리",
+ viewOverview: "전체 개요",
+ overviewSummary: "도구 모음 {toolsets}개 · 도구 {total}개 · {enabled}개 활성화",
+ overviewPluginsHint: "플러그인 도구와 권한을 확인하세요. 자세한 내용은 플러그인을 여세요.",
+ overviewOpenDetails: "세부 정보 보기",
+ expandCategory: "분류 펼치기",
+ collapseCategory: "분류 접기",
+ builtin: "기본 제공 기능",
+ plugins: "플러그인 확장",
+ advanced: "고급 설정",
+ navigation: "기능 분류",
+ searchPlaceholder: "분류, 기능, 플러그인 또는 도구 검색…",
+ clearSearch: "검색 지우기",
+ searchResults: "검색 결과",
+ categoryCount: "도구 모음 {count}개",
+ summary: "도구 모음 {toolsets}개 · 도구 {total}개 · {enabled}개 활성화",
+ enableCategory: "이 분류 모두 활성화",
+ disableCategory: "이 분류 모두 비활성화",
+ draftHint: "상세 화면에서 도구 모음을 적용하거나 하단의 적용 버튼으로 대기 중인 모든 설정을 저장하세요.",
+ batchChanged: "이 분류의 도구를 변경했습니다. ‘적용’을 클릭하면 반영됩니다",
+ coverageHint: "사용 가능한 연결 수는 연결 유형을 기준으로 집계하며, 실제 권한 범위를 나타내지 않습니다.",
+ uncovered: "연결 {count}개에 대응하는 기본 제공 도구가 없습니다",
+ viewDetails: "상세 보기",
+ emptyEnabled: "이 분류에 활성화된 도구가 없습니다. ‘활성화된 항목만 표시’를 해제하여 설정할 수 있습니다.",
+ retry: "다시 시도",
+ enabledToolCount: "{enabled}/{total}개 활성화",
+ partialEnabled: "일부 활성화",
+ coverageConnections: "연결 {count}개에 사용 가능",
+ coveragePartialConnections: "{count}개는 일부만 지원",
+ noMatchingConnections: "사용 가능한 연결 없음",
+ resourceScopes: "리소스 범위",
+ pluginImmediate: "변경 사항은 즉시 저장되며 하단의 ‘적용 / 취소’에 영향을 받지 않습니다",
+ pluginSaving: "저장 중…",
+ pluginSaved: "저장됨",
+ pluginOnlyEnabledEmpty: "활성화된 도구가 없습니다. ‘활성화된 항목만 표시’를 해제하면 표시됩니다.",
+ pluginUnavailable: "이 플러그인은 더 이상 사용할 수 없습니다. 플러그인 목록을 새로 고치세요",
+ resourceKind: {
+ database: "데이터베이스",
+ dbIndex: "논리 데이터베이스",
+ topic: "토픽",
+ queue: "큐",
+ org: "조직",
+ namespace: "네임스페이스",
+ },
+ category: {
+ database: { title: "데이터베이스", description: "데이터 쿼리, 세션 및 트랜잭션 관리, 객체 구조 탐색, Redis 명령 실행." },
+ nacos: { title: "Nacos", description: "설정, 서비스 및 인스턴스를 관리합니다." },
+ consul: { title: "Consul", description: "KV 관리, 서비스 검색 및 상태 확인을 수행합니다." },
+ mq: { title: "메시지 큐", description: "메시지를 읽고 보냅니다." },
+ salesforce: { title: "Salesforce", description: "사용자 정보를 조회하고 데이터를 처리합니다." },
+ dbx: { title: "DBX 공통", description: "제품 간 공유 기능: 연결 검색, 워크벤치 연동, 연결 관리, 플러그인 검색 및 호출." },
+ other: { title: "기타 기능", description: "아직 분류되지 않은 도구 모음을 여기서 확인하고 설정할 수 있습니다." },
+ },
+ },
+ mcpCapabilitiesTitle: "MCP 기능",
+ mcpCapabilitiesDescription: "내장 MCP 도구 grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the database types it applies to.",
+ mcpCapabilitiesLoading: "MCP 기능 로드 중…",
+ mcpCapabilitiesLoadFailed: "Failed to load MCP 기능: {error}",
+ mcpCapabilitiesSearchPlaceholder: "기능 또는 도구 검색",
+ mcpCapabilitiesSearchEmpty: "일치하는 기능이 없습니다",
+ mcpToolsetToolCount: "도구 {enabled}/{total}개",
+ mcpAccessLevelClassified: "호출별",
+ mcpCoverageTypes: "데이터베이스 유형 {count}개",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "연결에 종속되지 않음",
+ mcpCoverageUsableConnections: "연결 {count}개에서 사용 가능",
+ mcpCoverageNoUsableConnections: "사용 가능한 연결이 없습니다",
+ mcpCoveragePartialConnections: "연결 {count}개는 일부 도구만 지원합니다",
+ mcpCoverageUncoveredConnections: "{count} connections have no MCP 도구 yet: {names}",
+ mcpCoverageSearchPlaceholder: "데이터베이스 유형 검색",
+ mcpCoverageSearchEmpty: "아니요 matching database types",
+ mcpCoverageLegend: "지원하는 유형만 표시합니다. 강조된 유형은 등록된 연결에 해당합니다. *는 그룹의 일부 도구가 해당 유형을 지원하지 않음을 뜻합니다(포인터를 올리면 상세 정보 표시).",
+ mcpCoverageTypeUnsupportedTool: "{tool}에서 지원하지 않음",
+ mcpCoverageCategoryOther: "기타",
+ mcpCoveragePartialTool: "{tool}: {total}개 중 {count}개 지원",
+ mcpToolDetailSkippedConnections: "사용할 수 없음: {names}",
+ mcpToolDetailCoverage: "지원하는 데이터베이스 유형 ({count})",
+ mcpToolDetailParameterDefault: "기본값: {value}",
+ mcpToolDetailParameterDescription: "설명",
+ mcpToolDetailParameterRequiredNo: "아니요",
+ mcpToolDetailParameterRequiredYes: "예",
+ mcpToolDetailParameterRequired: "필수",
+ mcpToolDetailParameterType: "유형",
+ mcpToolDetailParameterName: "이름",
+ mcpToolDetailNoParameters: "매개변수 없음",
+ mcpToolDetailParameters: "매개변수",
+ mcpToolDetailDescription: "모델에 제공되는 설명",
+ mcpToolDetailAccessClassified: "호출마다 분류 (문장에 따라 읽기, 쓰기 또는 고위험)",
+ mcpToolDetailAccess: "액세스 수준",
+ mcpToolDetailSummary: "요약",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "연결 {count}개에서 사용할 수 없습니다",
+ mcpToolsetDetailTools: "도구",
+ mcpToolsetDetailCoverage: "지원 범위",
+ mcpToolsetApply: "이 도구 모음 적용",
+ mcpToolsetApplying: "적용 중…",
+ mcpToolsetPending: "아직 적용되지 않은 도구 변경 {count}개",
+ mcpToolsetApplied: "현재 설정이 적용되었습니다",
+ mcpToolsetCloseKeepsDraft: "닫아도 변경 사항은 유지됩니다. 설정 화면에서 한꺼번에 적용할 수도 있습니다.",
+ mcpToolsetApplyFailed: "적용 실패: {error}. 변경 사항은 유지됩니다. 다시 시도하세요.",
+ mcpToolsetApplyUnavailable: "현재 도구를 설정할 수 없습니다. 로딩이 끝날 때까지 기다리거나 다시 시도하세요.",
+ mcpToolsetDetailClose: "닫기",
+ mcpPluginToolEntriesTitle: "플러그인 tool entries",
+ mcpPluginsTitle: "플러그인",
+ mcpPluginsDescription: "플러그인 that provide MCP 도구. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "새로 고침",
+ mcpPluginsLoading: "플러그인 도구 로드 중…",
+ mcpPluginsLoadFailed: "플러그인 도구를 불러오지 못했습니다: {error}",
+ mcpPluginsEmpty: "설치된 플러그인이 MCP 도구를 제공하지 않습니다",
+ mcpPluginSaveFailed: "{name} 저장 실패: {message}",
+ mcpPluginAuthorClosed: "작성자가 외부 MCP에 공개하지 않았습니다",
+ mcpPluginDiscoveryFailed: "도구 검색 실패",
+ mcpPluginToolCount: "도구 {exposed}/{total}개 공개",
+ mcpPluginToolCountOff: "도구 {total}개, 꺼짐",
+ mcpPluginCeilingSummary: "상한: {level}",
+ mcpPluginPendingTools: "새 도구 {count}개를 확인해야 합니다",
+ mcpPluginReview: "검토",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "도구 검색 실패: {error}",
+ mcpPluginCeilingTitle: "권한 상한",
+ mcpPluginCeilingDescription: "상한을 넘는 도구는 MCP 클라이언트에 표시되지 않습니다. 실제 호출은 리소스 권한과 연결 공개 범위 규칙도 충족해야 합니다.",
+ mcpPluginEnableFirst: "상한과 도구를 변경하려면 플러그인을 켜세요.",
+ mcpPluginDefaultToolset: "도구",
+ mcpPluginNoTools: "This plugin lists no MCP 도구 right now.",
+ mcpPluginAuthorizeTitle: "승인 {name} for MCP",
+ mcpPluginAuthorizeDescription: "플러그인의 권한 상한을 선택하세요. 아래에 선언된 모든 도구가 승인됩니다. 이후 추가되거나 선언된 권한 수준이 높아진 도구가 읽기보다 높은 권한을 요구하면 다시 확인합니다.",
+ mcpPluginAuthorizeTools: "도구 ({count})",
+ mcpPluginAuthorizeIncluded: "노출됨",
+ mcpPluginAuthorizeExcluded: "숨김",
+ mcpPluginAuthorizeFootnote: "나중에 플러그인 상세 정보에서 상한을 변경하거나 개별 도구를 끌 수 있습니다.",
+ mcpPluginAccessUndeclared: "선언되지 않음 by the author — never exposed",
+ mcpPluginUndeclaredCount: "도구 {count}개는 매니페스트에 선언되지 않아 숨겨진 상태로 유지됩니다",
+ mcpPluginUndeclaredTools: "도구 {count}개는 플러그인 매니페스트에 접근 수준이 선언되지 않아 공개되지 않습니다: {names}",
+ mcpPluginAuthorizeCancel: "취소",
+ mcpPluginAuthorizeConfirm: "승인",
+ mcpPluginToolEntriesHint: "고급: 플러그인 도구 허용 목록입니다. dbx_*__*는 모든 플러그인 도구를, dbx_<prefix>__*는 특정 플러그인을 허용합니다. 플러그인 스위치로 사용 가능한 도구를 정하고 이 목록으로 추가 필터링합니다.",
+ mcpPluginAllowlistBlocked: "MCP 도구 허용 목록에 플러그인 항목이 없으므로 플러그인 스위치 설정과 관계없이 모든 플러그인 도구가 숨겨집니다.",
+ mcpPluginAllowlistAllow: "플러그인 도구 허용",
+ mcpPluginExposure: {
+ exposed: "노출됨",
+ undeclared: "선언되지 않음",
+ pluginDisabled: "플러그인 꺼짐",
+ toolDisabled: "꺼짐",
+ aboveCeiling: "상한 초과",
+ pendingApproval: "확인 필요",
+ },
+ mcpPluginCeilingLevel: {
+ read: "읽기 전용",
+ write: "읽기 및 쓰기",
+ full: "전체 (고위험 포함)",
+ },
+ mcpAccessLevel: {
+ read: "읽기",
+ write: "쓰기",
+ full: "높은 위험",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "검색 및 컨텍스트", description: "연결과 데이터베이스를 나열하고 모델에 제공할 스키마 정보를 가져옵니다." },
+ sqlQuery: { title: "SQL 쿼리", description: "쿼리와 스크립트를 실행합니다. 각 문장의 위험은 호출마다 분류합니다." },
+ sqlSession: { title: "세션 및 트랜잭션", description: "호출 간에 세션을 유지하고 트랜잭션을 제어합니다." },
+ sqlSchema: { title: "스키마 개체", description: "테이블, 열 및 루틴 소스를 살펴봅니다." },
+ redis: { title: "Redis 명령", description: "Redis 명령을 실행합니다." },
+ mq: { title: "메시지 읽기 및 전송", description: "Kafka, RocketMQ 및 RabbitMQ 메시지를 읽고 보냅니다." },
+ salesforce: { title: "사용자 정보 조회 및 데이터 작업", description: "현재 사용자를 확인하고 개별 레코드를 씁니다." },
+ workbench: { title: "워크벤치", description: "DBX에서 테이블을 열고 쿼리 결과를 표시합니다." },
+ adminConnections: { title: "연결 관리", description: "DBX 연결을 추가, 복제 및 삭제합니다." },
+ pluginRouter: { title: "플러그인 검색 및 호출", description: "필요할 때 플러그인 도구를 검색하고 공통 라우터로 호출합니다." },
+ nacosConfig: { title: "설정 관리", description: "읽기, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "서비스 관리", description: "서비스와 인스턴스를 나열하고 인스턴스의 온라인 상태 또는 가중치를 변경합니다." },
+ consulKv: { title: "KV 관리", description: "비교 후 갱신(CAS)을 사용하여 Consul KV 키를 나열하고 읽고 쓰고 삭제합니다." },
+ consulService: { title: "서비스 검색 및 상태", description: "서비스와 노드 카탈로그, 서비스 상태 및 유지보수 모드를 다룹니다." },
+ },
+ mcpToolNacosListNamespaces: "Nacos 네임스페이스 목록",
+ mcpToolNacosListConfigs: "Nacos 설정 목록",
+ mcpToolNacosGetConfig: "읽기 Nacos config",
+ mcpToolNacosConfigHistory: "Nacos 설정 기록",
+ mcpToolNacosPublishConfig: "Nacos 설정 게시",
+ mcpToolNacosDeleteConfig: "Nacos 설정 삭제",
+ mcpToolNacosListServices: "Nacos 서비스 목록",
+ mcpToolNacosListInstances: "Nacos 인스턴스 목록",
+ mcpToolNacosUpdateInstance: "Nacos 인스턴스 갱신",
+ mcpToolNacosSearchConfigs: "Nacos 설정 검색",
+ mcpToolNacosRollbackConfig: "Nacos 설정 롤백",
+ mcpToolNacosGetService: "Nacos 서비스 조회",
+ mcpToolNacosRegisterInstance: "Nacos 인스턴스 등록",
+ mcpToolNacosDeregisterInstance: "Nacos 인스턴스 등록 해제",
+ mcpToolConsulKvList: "Consul KV 키 목록",
+ mcpToolConsulKvGet: "읽기 Consul KV key",
+ mcpToolConsulKvPut: "쓰기 Consul KV key",
+ mcpToolConsulKvDelete: "Consul KV 키 삭제",
+ mcpToolConsulListServices: "Consul 서비스 목록",
+ mcpToolConsulListNodes: "Consul 노드 목록",
+ mcpToolConsulServiceHealth: "Consul 서비스 상태",
+ mcpToolConsulSetMaintenance: "Consul 유지보수 모드",
mcpConfigOptionsHint: "DBX가 모든 MCP 클라이언트에 대해 연결 접근과 실행 권한을 중앙에서 제어합니다. 생성된 설정에는 MCP 서버를 시작하고 이 DBX 인스턴스에 연결하는 데 필요한 런타임 설정만 포함되며, 권한이나 연결 범위 변수는 없습니다.",
mcpScopeConnection: "MCP에 허용된 연결",
mcpScopeConnectionDescription: "DBX는 선택한 연결만 MCP에 노출합니다. 변경 사항은 모든 MCP 클라이언트에 적용됩니다.",
@@ -9803,7 +10112,8 @@ export default withEnglishFallback({
mcpWindsurfConfigPath: "Windsurf는 ~/.codeium/windsurf/mcp_config.json을 사용할 수 있습니다.",
mcpOpenCodeConfigPath: "전역으로 ~/.config/opencode/opencode.json, 또는 프로젝트 수준의 opencode.json입니다.",
mcpExecutionMode: "MCP 전역 기본 권한",
- mcpExecutionModeDescription: "연결 또는 데이터베이스 권한이 없을 때 사용할 기본값입니다. 연결 기본값과 데이터베이스 설정은 범위에 따라 이를 재정의할 수 있습니다.",
+ mcpExecutionModeDescription: "별도 권한이 없는 리소스는 이 기본값을 사용합니다. 다른 권한은 아래 액세스 제어에서 설정하세요.",
+ mcpPermissionsDraftHint: "전역, 그룹 및 연결 변경은 하단의 적용으로 반영됩니다. 데이터베이스 권한은 대화 상자에서도 적용할 수 있습니다. 네임스페이스 등 하위 범위는 즉시 저장됩니다. 초안을 버려도 저장된 변경은 취소되지 않습니다.",
mcpExecutionModeReadOnly: "읽기 전용",
mcpExecutionModeSafeWrite: "데이터 읽기/쓰기",
mcpExecutionModeRecommended: "권장",
@@ -9812,21 +10122,21 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "일반 INSERT, 필터링된 UPDATE/DELETE, 범위가 확인된 MongoDB 변경 및 일반 Redis 쓰기나 명시적 키 삭제를 허용하며 테이블 전체 및 구조 변경을 차단합니다.",
mcpExecutionModeHighRiskWriteDescription: "데이터 읽기/쓰기 외에 테이블 전체 변경, DDL, TRUNCATE, 데이터베이스 비우기 및 기타 고위험 작업을 허용합니다. 프로덕션 및 연결 읽기 전용 보호는 여전히 적용됩니다.",
mcpExecutionModeHighRiskConfirm: "전체 접근은 테이블 전체 변경, DDL, TRUNCATE, 데이터베이스 비우기 및 기타 고위험 작업을 허용합니다. 활성화하시겠습니까?",
- mcpPromptHighRiskSql: "고위험 SQL 실행 전 확인 요청(데스크톱 전용; 읽기 전용 및 운영 환경 보호 유지)",
mcpSqlApprovalTitle: "MCP 고위험 SQL 승인",
mcpSqlApprovalScope: "연결: {connection} · 데이터베이스: {database}",
mcpSqlApprovalOnce: "이번 요청에만 허용",
mcpSqlApprovalHour: "이 데이터베이스에서 1시간 허용",
mcpSqlApprovalDay: "이 데이터베이스에서 1일 허용",
mcpSqlApprovalDeny: "거부",
- mcpCapabilityTitle: "기능 비교",
- mcpCapabilityDescription: "대표적인 작업입니다. DBX가 안정적으로 분류할 수 없는 요청은 전체 접근이 필요합니다.",
+ mcpCapabilityTitle: "권한 설명",
+ mcpCapabilityDescription: "표는 접근 권한을 설명합니다. 도구는 기능에서 활성화해야 합니다. 권한 부족은 거부하며 확인과 기존 임시 승인은 호출 안전에서 별도로 관리합니다.",
mcpCapabilityOperation: "기능",
mcpCapabilityRead: "쿼리 및 읽기",
mcpCapabilityScopedMutation: "범위가 지정된 데이터 변경 (INSERT, 필터링된 UPDATE/DELETE, 명시적 키 쓰기/삭제)",
mcpCapabilityBroadMutation: "테이블 전체 수정/삭제 및 데이터 비우기",
mcpCapabilitySchemaAdmin: "DDL, 구조 변경 및 고위험 관리",
- mcpCapabilityConnectionManagement: "MCP 연결 추가/제거",
+ mcpCapabilityConnectionCreate: "MCP 연결 추가/복제 (전역 기본 권한)",
+ mcpCapabilityConnectionRemove: "MCP 연결 삭제 (전역 기본 권한)",
mcpCapabilityAllowed: "허용됨",
mcpCapabilityBlocked: "차단됨",
mcpQueryTimeout: "쿼리 시간 제한(초)",
@@ -9834,6 +10144,9 @@ export default withEnglishFallback({
mcpQueryTimeoutInvalid: "음수가 아닌 정수(초)를 입력하거나 비워 두어 연결 설정을 상속하십시오.",
mcpCapabilityAlwaysEnforced: "모든 모드는 연결 허용 목록, 연결 읽기 전용 보호, 프로덕션 보호 및 데이터베이스 계정 권한의 적용을 받습니다.",
mcpPolicySaveFailed: "MCP 접근 정책 저장 실패: {error}",
+ mcpPolicyRetry: "다시 시도",
+ mcpPolicyRecover: "MCP 권한 백업 및 초기화",
+ mcpPolicyRecoverConfirm: "손상된 정책을 즉시 백업하고 저장하지 않은 변경 사항을 포함한 MCP 권한을 초기화합니다. 다시 설정할 때까지 모든 연결과 도구가 차단됩니다. 계속하시겠습니까?",
mcpPolicyLoadFailed: "MCP 접근 정책 불러오기 실패: {error}",
mcpDetectionTiming: "DBX는 이 페이지를 열 때 자동으로 확인합니다. 새로고침하려면 다시 확인을 사용하세요.",
mcpNpmBoundary: "DBX는 MCP 상태를 확인하고 설명만 합니다. 설치와 업그레이드는 여전히 npm, pnpm 또는 bun을 통해 실행됩니다.",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 0f4b14a0bb..a47963b7a1 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -211,6 +211,15 @@ export default withEnglishFallback({
docs,
dataDictionary,
pluginPlatform: {
+ mcpToolsBadge: "Narzędzia MCP",
+ mcpToolsBadgeHint: "Ta wtyczka udostępnia narzędzia MCP. Włącz je i nadaj uprawnienia w Ustawienia → MCP → Możliwości.",
+ mcpToolsFilter: "Tylko wtyczki z narzędziami MCP ({count})",
+ externalMcp: {
+ title: "Zewnętrzni klienci MCP",
+ offered: "Autor zezwala na udostępnianie narzędzi zewnętrznym klientom MCP (Claude Code, Cursor, …). Włącz je i określ ich uprawnienia w Ustawienia → MCP → Możliwości.",
+ notOffered: "Autor nie udostępnił narzędzi tej wtyczki zewnętrznym klientom MCP.",
+ },
+
dataAccessConsent: "Wtyczka „{name}” chce odczytywać dane z połączenia „{connection}”. Dopóki połączenie jest otwarte, może wykonywać zapytania tylko do odczytu, aż cofniesz zgodę w Centrum wtyczek. Zezwolić?",
dataAccessConsentTitle: "Prośba o dostęp do danych",
aiTools: {
@@ -6928,6 +6937,11 @@ export default withEnglishFallback({
redis_command: "Redis",
},
detail: {
+ mcpClient: "Klient MCP",
+ mcpTransport: "Transport MCP",
+ mcpAccess: "Dostęp MCP",
+ mcpConfirmation: "Potwierdzenie MCP",
+
mcpTool: "Narzędzie MCP",
kind: "Typ",
operation: "Operacja",
@@ -8223,6 +8237,375 @@ export default withEnglishFallback({
exportDiffSuccess: "Różnice wyeksportowane: {path}",
},
settings: {
+ mcpPermissionsDraftHint: "Zmiany globalne, grup i połączeń wymagają przycisku Zastosuj poniżej. Uprawnienia baz można też zastosować w ich oknie. Przestrzenie nazw i inne podzakresy zapisują się od razu. Odrzucenie zmian roboczych nie cofa zapisanych ustawień.",
+ mcpCallSafety: "Bezpieczeństwo wywołań",
+ mcpCallSafetyLegacy: "Starsza autoryzacja tymczasowa",
+ mcpCallSafetyEnabled: "Potwierdzaj każde wywołanie wysokiego ryzyka",
+ mcpCallSafetyDisabled: "Bez dodatkowego potwierdzenia",
+ mcpCallSafetyLegacyHint:
+ "Zachowano starsze działanie: uprawnienia zapisu danych pozwalają tymczasowo wykonać niektóre operacje wysokiego ryzyka po potwierdzeniu; pełny dostęp nie wymaga potwierdzenia. Nowa polityka odrzuca niewystarczające uprawnienia i wymaga potwierdzenia wywołań wysokiego ryzyka także przy pełnym dostępie.",
+ mcpCallSafetyMigrate: "Użyj nowej polityki potwierdzania",
+ mcpCallSafetyDisableLegacy: "Wyłącz starszą autoryzację",
+ mcpCallSafetyConfirm: "Żądaj potwierdzenia użytkownika przed wywołaniem narzędzi wysokiego ryzyka",
+ mcpCallSafetyHint: "Dotyczy wywołań wbudowanych i wtyczek uznanych za wysokie ryzyko. Najpierw sprawdzane są uprawnienia; pełny dostęp także podlega tej polityce. Potwierdzenie nigdy nie nadaje dodatkowych uprawnień.",
+ mcpCallSafetyDesktopHint: "Potwierdzenie wymaga aplikacji desktopowej DBX i dotyczy tylko bieżącego wywołania. Brak potwierdzenia, odmowa lub przekroczenie czasu blokuje wykonanie. Ochrona tylko do odczytu i środowiska produkcyjnego zawsze obowiązuje. Kliknij Zastosuj, aby zapisać zmiany.",
+ mcpToolApprovalGenericTitle: "Potwierdź wywołanie wysokiego ryzyka",
+ mcpToolApprovalPluginTitle: "Potwierdź narzędzie wysokiego ryzyka: {plugin}",
+ 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",
+ mcpToolApprovalTarget: "Cel",
+ mcpCapabilityConnectionCreate: "Dodawanie/powielanie połączeń MCP (globalne uprawnienia domyślne)",
+ mcpCapabilityConnectionRemove: "Usuwanie połączeń MCP (globalne uprawnienia domyślne)",
+ mcpAuthTabConnectionsTitle: "Grupy i połączenia",
+ mcpAuthTabDatabasesTitle: "Zakres baz danych",
+ mcpAuthTabOverridesTitle: "Domyślne uprawnienia",
+ mcpAuthTabCapabilitiesTitle: "Efektywny dostęp i narzędzia",
+ mcpManagementCapabilities: "Możliwości",
+ mcpOpenCallHistory: "Pokaż historię wywołań MCP",
+ mcpAccessTreeTitle: "Kontrola dostępu",
+ mcpAccessTreeDescription: "Ustaw uprawnienia grup, połączeń i baz danych. Dziedziczenie używa ustawienia nadrzędnego; efektywne uprawnienie pokazuje wynik i jego źródło.",
+ mcpAccessTreeSummary: "Widoczne połączenia: {visible}/{total} · wyjątki: grupy {groups}, połączenia {connections}, bazy {databases}",
+ mcpAccessTreeScopeLabel: "Widoczność połączeń",
+ mcpAccessTreeScopeAll: "Wszystkie połączenia",
+ mcpAccessTreeScopeCustom: "Tylko wybrane",
+ mcpAccessTreeSearchPlaceholder: "Szukaj grup, połączeń lub baz danych",
+ mcpAccessTreeExceptionsOnly: "Pokaż tylko ustawienia indywidualne",
+ mcpAccessTreeColumnResource: "Zasób",
+ mcpAccessTreeColumnVisible: "Widoczny",
+ mcpAccessTreeColumnSetting: "Uprawnienie",
+ mcpAccessTreeColumnEffective: "Efektywne",
+ mcpAccessTreeInherit: "Dziedzicz",
+ mcpAccessTreeGroupPartiallyVisible: "Część połączeń widoczna ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "Wszystkie bieżące połączenia widoczne ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Uprawnienia mają tylko elementy podrzędne, nie cała grupa. Zaznacz, aby zezwolić na całą grupę, także przyszłe połączenia.",
+ mcpAccessTreeGroupDefaultHint: "Ustawienia domyślne grupy dotyczą elementów podrzędnych bez własnych uprawnień. Nie zmieniają widoczności połączeń.",
+ mcpAccessTreeHidden: "Niewidoczny dla MCP",
+ mcpAccessTreeSourceGlobal: "globalne domyślne",
+ mcpAccessTreeSourceGroup: "z grupy {group}",
+ mcpAccessTreeSourceConnection: "ustawienie połączenia",
+ mcpAccessTreeSourceDatabase: "ustawienie bazy danych",
+ mcpAccessTreeGroupCount: "Połączenia: {count}",
+ mcpAccessTreeLegacy: "starsze",
+ mcpAccessTreeLegacyHint: "Zapisane przez starszą wersję: może tylko ograniczać uprawnienia dziedziczone przez połączenie. Wybierz uprawnienie ponownie, aby użyć zwykłego ustawienia.",
+ mcpAccessTreeCoveredByGroup: "Widoczne przez wybraną grupę nadrzędną",
+ mcpAccessTreeHighRiskConfirm: "Wysokie ryzyko zezwala na DDL, DROP, TRUNCATE i bezwarunkowy zapis w tym zasobie. Kontynuować?",
+ mcpAccessTreeDatabases: "Bazy danych",
+ mcpAccessTreeDatabaseScopeAll: "Wszystkie bazy danych",
+ mcpAccessTreeDatabaseScopeSelected: "Wybrane ({count})",
+ mcpAccessTreeDatabaseScopeNone: "Żadne bazy danych",
+ mcpDatabaseRemoveConfirm: "Usunięcie wybranych baz usuwa również ich indywidualne uprawnienia. Kontynuować?",
+ mcpDatabaseUnavailable: "Ustawienia dostępu do baz są niedostępne. Poczekaj na zakończenie ładowania lub ponów próbę.",
+ mcpDatabaseConfigure: "Konfiguruj dostęp do baz danych",
+ mcpDatabaseOverrideCount: "Wyjątki: {count}",
+ mcpDatabaseDialogTitle: "{name} / Dostęp do baz danych",
+ mcpDatabaseDialogDescription: "Wybierz bazy i ustaw ich uprawnienia. Przeniesienie na prawą stronę zaczyna działać dopiero po zastosowaniu.",
+ mcpDatabaseInherited: "Dziedziczony dostęp: {level}",
+ mcpDatabaseSavedInherited: "Uprawnienia nadrzędne mają niezapisane zmiany. Zastosowanie tylko dostępu do baz nadal dziedziczy zapisane uprawnienia: {level}",
+ mcpDatabaseHiddenConnection: "To połączenie jest obecnie ukryte przed MCP. Zastosowanie dostępu do baz nie udostępnia połączenia.",
+ mcpDatabaseAllHint: "Obejmuje obecne i przyszłe bazy, używając uprawnień połączenia.",
+ mcpDatabaseNoneHint: "Zastosowanie zablokuje dostęp do każdej bazy.",
+ mcpDatabaseLoaded: "Wczytano bazy widoczne dla tego konta: {count}",
+ mcpDatabaseRefresh: "Odśwież bazy danych",
+ mcpDatabaseAddSelected: "Dodaj →",
+ mcpDatabaseRemoveSelected: "← Usuń",
+ mcpDatabaseAvailable: "Niewybrane ({count})",
+ mcpDatabaseSelected: "Wybrane ({count})",
+ mcpDatabaseSearch: "Szukaj nazw baz danych",
+ mcpDatabaseSelectResults: "Zaznacz bieżące wyniki wyszukiwania ({count})",
+ mcpDatabaseBatchLevel: "Ustaw dostęp zaznaczonych ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "Zezwolić na pełny dostęp do zaznaczonych baz ({count})? Ochrona połączenia tylko do odczytu i środowiska produkcyjnego nadal obowiązuje.",
+ mcpDatabaseNotDiscovered: "Nie znaleziono podczas tego wykrywania",
+ mcpDatabaseShowMore: "Pokaż więcej (wyświetlono {shown}/{total})",
+ mcpDatabaseSaveHint: "Zapisuje tylko zakres baz i ich indywidualne uprawnienia dla tego połączenia. Pozostałe zmiany robocze pozostają.",
+ mcpDatabaseApply: "Zastosuj dostęp do baz danych",
+ mcpAccessTreePickDatabases: "Wybierz bazy danych",
+ mcpAccessTreePickerTitle: "Bazy danych: {name}",
+ mcpAccessTreeLoadingDatabases: "Ładowanie baz danych…",
+ mcpAccessTreeLoadDatabasesFailed: "Nie udało się wczytać baz: {error}. Nadal możesz dodać nazwy ręcznie.",
+ mcpAccessTreeManualDatabase: "Dodaj nazwę bazy danych",
+ mcpAccessTreeNoMatch: "Brak pasujących zasobów",
+ mcpAccessTreeEmpty: "Brak połączeń",
+ mcpAccessTreeFootnote: "Priorytet: baza > połączenie > najbliższa grupa > grupa nadrzędna > globalne domyślne. Dodatkowo zawsze obowiązuje ochrona tylko do odczytu, ochrona produkcji i uprawnienia konta bazy danych.",
+ mcpAccessTreeNacosNamespace: "Przestrzeń nazw",
+ mcpPluginScopeAll: "Wszystkie ({title})",
+ mcpPluginScopeSelected: "Wybrane ({count})",
+ mcpPluginScopeNone: "Brak: {title}",
+ mcpPluginScopeAdd: "Dodaj: {title}",
+ mcpPluginScopeLoad: "Odczytaj z wtyczki",
+ mcpPluginToolsMode: "Udostępnianie narzędzi wtyczek na zewnątrz",
+ mcpPluginToolsModeDescription: "Wybierz sposób udostępniania autoryzowanych narzędzi wtyczek klientom MCP. Kliknij Zastosuj poniżej, aby zapisać zmiany.",
+ mcpPluginToolsModeAuto: "Automatycznie (zgodność)",
+ mcpPluginToolsModeFlat: "Wyświetl bezpośrednio (domyślnie)",
+ mcpPluginToolsModeLazy: "Wykrywanie na żądanie",
+ mcpPluginToolsModeFlatDescription: "Wyświetl każde autoryzowane narzędzie wtyczki, aby klient mógł je wywołać bezpośrednio.",
+ mcpPluginToolsModeLazyDescription: "Udostępnia wspólne narzędzia wykrywania i wywoływania wtyczek, pobierając szczegóły w razie potrzeby. Włącz Wykrywanie i wywoływanie wtyczek w kategorii wspólnej DBX.",
+ mcpPluginToolsModeAutoDescription: "Zachowuje dotychczasowe działanie: wyświetla bezpośrednio do 40 narzędzi wtyczek łącznie, a powyżej używa wykrywania na żądanie.",
+ mcpBrowser: {
+ viewMode: "Tryb widoku",
+ viewManage: "Zarządzanie kategoriami",
+ viewOverview: "Przegląd globalny",
+ overviewSummary: "Zestawy: {toolsets} · narzędzia: {total} · włączone: {enabled}",
+ overviewPluginsHint: "Przejrzyj narzędzia wtyczek i uprawnienia. Otwórz wtyczkę, aby zobaczyć szczegóły.",
+ overviewOpenDetails: "Pokaż szczegóły",
+ expandCategory: "Rozwiń kategorię",
+ collapseCategory: "Zwiń kategorię",
+ builtin: "Wbudowane możliwości",
+ plugins: "Rozszerzenia wtyczek",
+ advanced: "Ustawienia zaawansowane",
+ navigation: "Kategorie możliwości",
+ searchPlaceholder: "Szukaj kategorii, możliwości, wtyczek lub narzędzi…",
+ clearSearch: "Wyczyść wyszukiwanie",
+ searchResults: "Wyniki wyszukiwania",
+ categoryCount: "Zestawy narzędzi: {count}",
+ summary: "Zestawy: {toolsets} · narzędzia: {total} · włączone: {enabled}",
+ enableCategory: "Włącz wszystkie w tej kategorii",
+ disableCategory: "Wyłącz wszystkie w tej kategorii",
+ draftHint: "Zastosuj zestaw w jego szczegółach lub użyj przycisku Zastosuj poniżej, aby zapisać wszystkie oczekujące zmiany.",
+ batchChanged: "Zmieniono narzędzia kategorii. Kliknij Zastosuj, aby zapisać",
+ coverageHint: "Pasujące połączenia liczone są według typu, a nie rzeczywistego zakresu autoryzacji.",
+ uncovered: "Połączenia bez obsługi narzędzi wbudowanych: {count}",
+ viewDetails: "Pokaż szczegóły",
+ emptyEnabled: "W tej kategorii nie ma włączonych narzędzi. Wyłącz „Tylko włączone”, aby je skonfigurować.",
+ retry: "Ponów",
+ enabledToolCount: "Włączone: {enabled}/{total}",
+ partialEnabled: "Częściowo włączone",
+ coverageConnections: "Dotyczy połączeń: {count}",
+ coveragePartialConnections: "Częściowo obsługiwane: {count}",
+ noMatchingConnections: "Brak pasujących połączeń",
+ resourceScopes: "Zakresy zasobów",
+ pluginImmediate: "Zmiany zapisują się od razu, niezależnie od przycisków Zastosuj / Anuluj poniżej",
+ pluginSaving: "Zapisywanie…",
+ pluginSaved: "Zapisano",
+ pluginOnlyEnabledEmpty: "Brak włączonych narzędzi. Wyłącz „Tylko włączone”, aby je zobaczyć.",
+ pluginUnavailable: "Ta wtyczka nie jest już dostępna. Odśwież listę wtyczek",
+ resourceKind: {
+ database: "Baza danych",
+ dbIndex: "Logiczna baza danych",
+ topic: "Temat",
+ queue: "Kolejka",
+ org: "Organizacja",
+ namespace: "Przestrzeń nazw",
+ },
+ category: {
+ database: {
+ title: "Bazy danych",
+ description: "Wysyłaj zapytania, zarządzaj sesjami i transakcjami, przeglądaj struktury obiektów i wykonuj polecenia Redis.",
+ },
+ nacos: {
+ title: "Nacos",
+ description: "Zarządzaj konfiguracjami, usługami i instancjami.",
+ },
+ consul: {
+ title: "Consul",
+ description: "Zarządzaj wpisami KV, wykrywaj usługi i sprawdzaj ich stan.",
+ },
+ mq: {
+ title: "Kolejki wiadomości",
+ description: "Odczytuj i wysyłaj wiadomości.",
+ },
+ salesforce: {
+ title: "Salesforce",
+ description: "Sprawdzaj tożsamość i pracuj z danymi.",
+ },
+ dbx: {
+ title: "Wspólne DBX",
+ description: "Możliwości wspólne dla produktów: wykrywanie połączeń, integracja z obszarem roboczym, zarządzanie połączeniami oraz wykrywanie i wywoływanie wtyczek.",
+ },
+ other: {
+ title: "Inne możliwości",
+ description: "Przeglądaj i konfiguruj zestawy bez przypisanej kategorii.",
+ },
+ },
+ },
+ mcpCapabilitiesTitle: "Możliwości MCP",
+ mcpCapabilitiesFilterLabel: "Filtr możliwości",
+ mcpCapabilitiesFilterAll: "Wszystkie",
+ mcpCapabilitiesFilterBuiltin: "Wbudowane",
+ mcpCapabilitiesFilterPlugin: "Wtyczki",
+ mcpCapabilitiesOnlyEnabled: "Tylko włączone",
+ mcpCapabilitiesDescription: "Wbudowane narzędzia MCP pogrupowane według zastosowań. Wyłączenie grupy blokuje jej narzędzia na serwerze, nawet gdy klient je pamięta. Każda grupa podaje obsługiwane typy baz danych.",
+ mcpCapabilitiesLoading: "Ładowanie możliwości MCP…",
+ mcpCapabilitiesLoadFailed: "Nie udało się wczytać możliwości MCP: {error}",
+ mcpCapabilitiesSearchPlaceholder: "Szukaj możliwości lub narzędzi",
+ mcpCapabilitiesSearchEmpty: "Brak pasujących możliwości",
+ mcpToolsetToolCount: "Narzędzia: {enabled}/{total}",
+ mcpAccessLevelClassified: "Dla każdego wywołania",
+ mcpCoverageTypes: "Typy baz danych: {count}",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Niezwiązane z połączeniem",
+ mcpCoverageUsableConnections: "Używane przez Twoje połączenia: {count}",
+ mcpCoverageNoUsableConnections: "Żadne z Twoich połączeń tego nie używa",
+ mcpCoveragePartialConnections: "Połączenia obsługujące tylko część narzędzi: {count}",
+ mcpCoverageUncoveredConnections: "Połączenia bez narzędzi MCP ({count}): {names}",
+ mcpCoverageSearchPlaceholder: "Szukaj typów baz danych",
+ mcpCoverageSearchEmpty: "Brak pasujących typów baz danych",
+ mcpCoverageLegend: "Pokazane są tylko obsługiwane typy. Wyróżnione pasują do Twoich połączeń; * oznacza, że część narzędzi grupy nie obsługuje tego typu (najedź, aby zobaczyć szczegóły).",
+ mcpCoverageTypeUnsupportedTool: "Nieobsługiwane przez {tool}",
+ mcpCoverageCategoryOther: "Inne",
+ mcpCoveragePartialTool: "{tool} obsługuje {count} z {total}",
+ mcpToolDetailSkippedConnections: "Niedostępne dla: {names}",
+ mcpToolDetailCoverage: "Obsługiwane typy baz ({count})",
+ mcpToolDetailParameterDefault: "domyślnie: {value}",
+ mcpToolDetailParameterDescription: "Opis",
+ mcpToolDetailParameterRequiredNo: "Nie",
+ mcpToolDetailParameterRequiredYes: "Tak",
+ mcpToolDetailParameterRequired: "Wymagane",
+ mcpToolDetailParameterType: "Typ",
+ mcpToolDetailParameterName: "Nazwa",
+ mcpToolDetailNoParameters: "Brak parametrów",
+ mcpToolDetailParameters: "Parametry",
+ mcpToolDetailDescription: "Opis dla modelu",
+ mcpToolDetailAccessClassified: "Klasyfikacja przy każdym wywołaniu (odczyt, zapis lub wysokie ryzyko zależnie od instrukcji)",
+ mcpToolDetailAccess: "Poziom dostępu",
+ mcpToolDetailSummary: "Podsumowanie",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "Twoje połączenia, które nie mogą tego używać: {count}",
+ mcpToolsetDetailTools: "Narzędzia",
+ mcpToolsetDetailCoverage: "Obsługa",
+ mcpToolsetApply: "Zastosuj ten zestaw narzędzi",
+ mcpToolsetApplying: "Stosowanie…",
+ mcpToolsetPending: "Niezastosowane zmiany narzędzi: {count}",
+ mcpToolsetApplied: "Zastosowano bieżącą konfigurację",
+ mcpToolsetCloseKeepsDraft: "Zamknięcie zachowuje zmiany. Możesz je też zastosować w Ustawieniach.",
+ mcpToolsetApplyFailed: "Nie udało się zastosować: {error}. Zmiany zachowano; spróbuj ponownie.",
+ mcpToolsetApplyUnavailable: "Ustawienia narzędzi są niedostępne. Poczekaj na zakończenie ładowania lub ponów próbę.",
+ mcpToolsetDetailClose: "Zamknij",
+ mcpPluginToolEntriesTitle: "Wpisy narzędzi wtyczek",
+ mcpPluginsTitle: "Wtyczki",
+ mcpPluginsDescription: "Wtyczki udostępniające narzędzia MCP. Każdą włącza się i autoryzuje jako całość; zmiany zapisują się natychmiast.",
+ mcpPluginsRefresh: "Odśwież",
+ mcpPluginsLoading: "Ładowanie narzędzi wtyczek…",
+ mcpPluginsLoadFailed: "Nie udało się wczytać narzędzi wtyczek: {error}",
+ mcpPluginsEmpty: "Żadna zainstalowana wtyczka nie udostępnia narzędzi MCP.",
+ mcpPluginSaveFailed: "Nie udało się zapisać {name}: {message}",
+ mcpPluginAuthorClosed: "Autor nie udostępnił narzędzi zewnętrznemu MCP",
+ mcpPluginDiscoveryFailed: "Nie udało się wykryć narzędzi",
+ mcpPluginToolCount: "Udostępnione narzędzia: {exposed}/{total}",
+ mcpPluginToolCountOff: "Narzędzia: {total}, wyłączone",
+ mcpPluginCeilingSummary: "Limit: {level}",
+ mcpPluginPendingTools: "Nowe narzędzia wymagające potwierdzenia: {count}",
+ mcpPluginReview: "Przejrzyj",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Nie udało się wykryć narzędzi: {error}",
+ mcpPluginCeilingTitle: "Górny limit uprawnień",
+ mcpPluginCeilingDescription: "Narzędzia powyżej limitu pozostają ukryte przed klientami MCP. Wywołania muszą także spełniać uprawnienia zasobów i reguły widoczności połączeń.",
+ mcpPluginEnableFirst: "Włącz wtyczkę, aby zmienić jej limit i narzędzia.",
+ mcpPluginDefaultToolset: "Narzędzia",
+ mcpPluginNoTools: "Ta wtyczka obecnie nie udostępnia żadnych narzędzi MCP.",
+ mcpPluginAuthorizeTitle: "Autoryzuj {name} dla MCP",
+ mcpPluginAuthorizeDescription: "Wybierz zakres uprawnień narzędzi tej wtyczki. Akceptujesz wszystkie zadeklarowane narzędzia poniżej; dodane później lub ze zwiększonym poziomem dostępu, wymagające więcej niż odczytu, ponownie poproszą o potwierdzenie.",
+ mcpPluginAuthorizeTools: "Narzędzia ({count})",
+ mcpPluginAuthorizeIncluded: "Udostępnione",
+ mcpPluginAuthorizeExcluded: "Ukryte",
+ mcpPluginAuthorizeFootnote: "Później możesz zmienić limit lub wyłączyć pojedyncze narzędzia w szczegółach wtyczki.",
+ mcpPluginAccessUndeclared: "Niezadeklarowane przez autora — nigdy nieudostępniane",
+ mcpPluginUndeclaredCount: "Narzędzia niezadeklarowane w manifeście pozostają ukryte: {count}",
+ mcpPluginUndeclaredTools: "Narzędzia bez zadeklarowanego poziomu dostępu w manifeście ({count}) nigdy nie będą udostępnione: {names}",
+ mcpPluginAuthorizeCancel: "Anuluj",
+ mcpPluginAuthorizeConfirm: "Autoryzuj",
+ mcpPluginToolEntriesHint: "Zaawansowane: dozwolone wpisy narzędzi wtyczek. dbx_*__* dopuszcza wszystkie wtyczki, dbx_<prefix>__* jedną. Przełączniki określają dostępność narzędzi; te wpisy dodają kolejny filtr.",
+ mcpPluginAllowlistBlocked: "Lista dozwolonych narzędzi MCP nie zawiera wpisu wtyczki, więc wszystkie jej narzędzia są ukryte niezależnie od przełączników.",
+ mcpPluginAllowlistAllow: "Zezwól na narzędzia wtyczek",
+ mcpPluginExposure: {
+ exposed: "Udostępnione",
+ undeclared: "Niezadeklarowane",
+ pluginDisabled: "Wtyczka wyłączona",
+ toolDisabled: "Wyłączone",
+ aboveCeiling: "Powyżej limitu",
+ pendingApproval: "Wymaga potwierdzenia",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Tylko odczyt",
+ write: "Odczyt i zapis",
+ full: "Pełny (w tym wysokie ryzyko)",
+ },
+ mcpAccessLevel: {
+ read: "Odczyt",
+ write: "Zapis",
+ full: "Wysokie ryzyko",
+ },
+ mcpToolset: {
+ coreDiscovery: {
+ title: "Wykrywanie i kontekst",
+ description: "Wyświetl połączenia i bazy oraz pobierz kontekst schematu dla modelu.",
+ },
+ sqlQuery: {
+ title: "Zapytania SQL",
+ description: "Wykonuj zapytania i skrypty. Ryzyko każdej instrukcji jest klasyfikowane przy wywołaniu.",
+ },
+ sqlSession: {
+ title: "Sesje i transakcje",
+ description: "Zachowaj sesję między wywołaniami i kontroluj transakcje.",
+ },
+ sqlSchema: {
+ title: "Obiekty schematu",
+ description: "Przeglądaj tabele, kolumny i kod procedur.",
+ },
+ redis: {
+ title: "Polecenia Redis",
+ description: "Wykonuj polecenia Redis.",
+ },
+ mq: {
+ title: "Odczyt i wysyłanie wiadomości",
+ description: "Podglądaj i wysyłaj wiadomości Kafka, RocketMQ i RabbitMQ.",
+ },
+ salesforce: {
+ title: "Tożsamość i operacje na danych",
+ description: "Sprawdź bieżącego użytkownika i zapisuj pojedyncze rekordy.",
+ },
+ workbench: {
+ title: "Obszar roboczy",
+ description: "Otwieraj tabele i pokazuj wyniki zapytań w DBX.",
+ },
+ adminConnections: {
+ title: "Zarządzanie połączeniami",
+ description: "Dodawaj, powielaj i usuwaj połączenia DBX.",
+ },
+ pluginRouter: {
+ title: "Wykrywanie i wywoływanie wtyczek",
+ description: "Wykrywaj narzędzia wtyczek na żądanie i wywołuj je przez wspólny interfejs.",
+ },
+ nacosConfig: {
+ title: "Zarządzanie konfiguracją",
+ description: "Odczytuj, wyszukuj, publikuj i usuwaj konfiguracje Nacos według przestrzeni nazw.",
+ },
+ nacosService: {
+ title: "Zarządzanie usługami",
+ description: "Wyświetlaj usługi i instancje; włączaj, wyłączaj lub zmieniaj wagi instancji.",
+ },
+ consulKv: {
+ title: "Zarządzanie KV",
+ description: "Wyświetlaj, odczytuj, zapisuj i usuwaj klucze Consul KV z porównaniem i zamianą.",
+ },
+ consulService: {
+ title: "Wykrywanie usług i stan",
+ description: "Katalog usług i węzłów, stan usług oraz tryb konserwacji.",
+ },
+ },
+ mcpToolNacosListNamespaces: "Lista przestrzeni nazw Nacos",
+ mcpToolNacosListConfigs: "Lista konfiguracji Nacos",
+ mcpToolNacosGetConfig: "Odczyt konfiguracji Nacos",
+ mcpToolNacosConfigHistory: "Historia konfiguracji Nacos",
+ mcpToolNacosPublishConfig: "Publikowanie konfiguracji Nacos",
+ mcpToolNacosDeleteConfig: "Usuwanie konfiguracji Nacos",
+ mcpToolNacosListServices: "Lista usług Nacos",
+ mcpToolNacosListInstances: "Lista instancji Nacos",
+ mcpToolNacosUpdateInstance: "Aktualizacja instancji Nacos",
+ mcpToolNacosSearchConfigs: "Wyszukiwanie konfiguracji Nacos",
+ mcpToolNacosRollbackConfig: "Przywracanie konfiguracji Nacos",
+ mcpToolNacosGetService: "Odczyt usługi Nacos",
+ mcpToolNacosRegisterInstance: "Rejestracja instancji Nacos",
+ mcpToolNacosDeregisterInstance: "Wyrejestrowanie instancji Nacos",
+ mcpToolConsulKvList: "Lista kluczy Consul KV",
+ mcpToolConsulKvGet: "Odczyt klucza Consul KV",
+ mcpToolConsulKvPut: "Zapis klucza Consul KV",
+ mcpToolConsulKvDelete: "Usuwanie klucza Consul KV",
+ mcpToolConsulListServices: "Lista usług Consul",
+ mcpToolConsulListNodes: "Lista węzłów Consul",
+ mcpToolConsulServiceHealth: "Stan usługi Consul",
+ mcpToolConsulSetMaintenance: "Tryb konserwacji Consul",
+
historyRetentionLimit: "Okres przechowywania historii zapytań",
mcpHistoryRetentionLimit: "Okres przechowywania historii MCP",
mcpHistoryRetentionDescription: "Zarządza historią wywołań MCP niezależnie od historii SQL.",
@@ -9485,7 +9868,7 @@ export default withEnglishFallback({
mcpOpenCodeConfigPath: "Globalnie w ~/.config/opencode/opencode.json lub w pliku opencode.json na poziomie projektu.",
mcpPiConfigPath: "Najpierw zainstaluj wtyczkę adaptera Pi MCP: pi install npm:pi-mcp-adapter. Następnie zapisz w ~/.pi/agent/mcp.json (globalnie) lub .mcp.json (w projekcie), uruchom /mcp, aby sprawdzić, i /reload, aby załadować w Pi.",
mcpExecutionMode: "Globalne domyślne uprawnienie MCP",
- mcpExecutionModeDescription: "Ustawia wartość domyślną, gdy nie skonfigurowano uprawnień połączenia ani bazy danych. Wartości domyślne połączenia i ustawienia bazy mogą nadpisywać to ustawienie per zakres.",
+ mcpExecutionModeDescription: "Zasoby bez własnych uprawnień używają tej wartości domyślnej. Inne uprawnienia ustaw poniżej w Kontroli dostępu.",
mcpExecutionModeReadOnly: "Tylko do odczytu",
mcpExecutionModeSafeWrite: "Odczyt/zapis danych",
mcpExecutionModeRecommended: "Zalecane",
@@ -9494,21 +9877,19 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "Zezwala na standardowy INSERT, filtrowany UPDATE/DELETE, weryfikowalne zmiany w MongoDB oraz zwykłe zapisy lub usuwanie jawnych kluczy w Redis; blokuje zmiany globalne dla tabel i struktury.",
mcpExecutionModeHighRiskWriteDescription: "Oprócz odczytu/zapisu danych zezwala na zmiany obejmujące całe tabele, DDL, TRUNCATE, czyszczenie baz i inne operacje wysokiego ryzyka. Zabezpieczenia produkcyjne i tryb tylko do odczytu połączenia nadal obowiązują.",
mcpExecutionModeHighRiskConfirm: "Pełny dostęp zezwala na modyfikacje całych tabel, DDL, TRUNCATE, czyszczenie baz i inne operacje wysokiego ryzyka. Włączyć?",
- mcpPromptHighRiskSql: "Pytaj przed wykonaniem ryzykownego SQL (tylko na komputerze; zabezpieczenia trybu tylko do odczytu i produkcji pozostają aktywne)",
mcpSqlApprovalTitle: "Zatwierdzenie ryzykownego SQL przez MCP",
mcpSqlApprovalScope: "Połączenie: {connection} · Baza danych: {database}",
mcpSqlApprovalOnce: "Tylko to żądanie",
mcpSqlApprovalHour: "Zezwól dla tej bazy na godzinę",
mcpSqlApprovalDay: "Zezwól dla tej bazy na dzień",
mcpSqlApprovalDeny: "Odmów",
- mcpCapabilityTitle: "Porównanie możliwości",
- mcpCapabilityDescription: "Oto reprezentatywne operacje; żądania, których DBX nie potrafi wiarygodnie sklasyfikować, wymagają pełnego dostępu.",
+ mcpCapabilityTitle: "Szczegóły uprawnień",
+ mcpCapabilityDescription: "Tabela opisuje poziomy dostępu; narzędzia trzeba też włączyć w Możliwościach. Niewystarczające uprawnienia powodują odmowę. Bezpieczeństwo wywołań osobno kontroluje potwierdzenia i wyjaśnia starszą autoryzację tymczasową.",
mcpCapabilityOperation: "Możliwość",
mcpCapabilityRead: "Zapytania i odczyty",
mcpCapabilityScopedMutation: "Ograniczone zmiany danych (INSERT, filtrowany UPDATE/DELETE, zapis/usuwanie jawnych kluczy)",
mcpCapabilityBroadMutation: "Aktualizacje/usuwanie obejmujące całe tabele i czyszczenie danych",
mcpCapabilitySchemaAdmin: "DDL, zmiany strukturalne i administracja wysokiego ryzyka",
- mcpCapabilityConnectionManagement: "Dodawanie/usuwanie połączeń MCP",
mcpCapabilityAllowed: "Dozwolone",
mcpCapabilityBlocked: "Zablokowane",
mcpQueryTimeout: "Limit czasu zapytania (sekundy)",
@@ -9519,6 +9900,9 @@ export default withEnglishFallback({
mcpQueryTimeoutSaveStatus_failed: "Nie udało się zapisać",
mcpCapabilityAlwaysEnforced: "Każdy tryb podlega ograniczeniom białej listy połączeń, blokadzie tylko do odczytu połączenia, zabezpieczeniom produkcyjnym i uprawnieniom konta bazy danych.",
mcpPolicySaveFailed: "Nie udało się zapisać polityki dostępu MCP: {error}",
+ mcpPolicyRetry: "Spróbuj ponownie",
+ mcpPolicyRecover: "Utwórz kopię i zresetuj uprawnienia MCP",
+ mcpPolicyRecoverConfirm: "Ta operacja natychmiast utworzy kopię uszkodzonej polityki i zresetuje uprawnienia MCP, w tym niezapisane zmiany. Wszystkie połączenia i narzędzia będą zablokowane do czasu ponownej konfiguracji. Kontynuować?",
mcpPolicyLoadFailed: "Nie udało się załadować polityki dostępu MCP: {error}",
mcpDetectionTiming: "DBX sprawdza stan automatycznie po otwarciu tej strony; użyj Sprawdź ponownie, aby odświeżyć.",
mcpNpmBoundary: "DBX sprawdza stan MCP; instalacja, aktualizacje i deinstalacja działają za pośrednictwem wykrytego środowiska npm, pnpm lub bun.",
@@ -9526,20 +9910,7 @@ export default withEnglishFallback({
mcpRefresh: "Sprawdź ponownie",
mcpGuide: "Przewodnik MCP",
mcpAuthTitle: "Autoryzacja MCP",
- mcpAuthDescription: "Przeprowadź autoryzację po kolei: ustaw globalną wartość domyślną, wybierz grupy i połączenia, ogranicz bazy danych, a następnie przejrzyj ostateczną politykę.",
- mcpAuthStepsLabel: "Kroki autoryzacji MCP",
- mcpAuthStepConnectionsTitle: "Grupy i połączenia",
- mcpAuthStepConnectionsDescription: "Wybierz, co MCP może widzieć i ustaw uprawnienia połączeń",
- mcpAuthStepDatabasesTitle: "Zakres baz danych",
- mcpAuthStepDatabasesDescription: "Ogranicz bazy danych dla poszczególnych połączeń i ustaw uprawnienia",
- mcpAuthStepOverridesTitle: "Domyślne uprawnienia",
- mcpAuthStepOverridesDescription: "Ustaw globalną wartość domyślną dla wszystkich kolejnych zakresów",
- mcpAuthStepCapabilitiesTitle: "Podsumowanie i przegląd",
- mcpAuthStepCapabilitiesDescription: "Przejrzyj uprawnienia efektywne, wybierz narzędzia i potwierdź",
- mcpAuthStepRegionLabel: "Krok {step}: {title}",
- mcpAuthPreviousStep: "Poprzedni",
- mcpAuthNextStep: "Dalej",
- mcpAuthStepProgress: "Krok {current} z {total}",
+ mcpAuthDescription: "Uprawnienia są nadpisywane kolejno: baza danych › połączenie › grupa › globalne domyślne. Węższy zakres ma wyższy priorytet.",
mcpResourceScopeTitle: "Połączenia widoczne dla MCP",
mcpResourceScopeDescription: "Wybieraj grupy dla dynamicznego pokrycia oraz pojedyncze połączenia dla precyzyjnych wyjątków.",
mcpResourceScopeModeCustom: "Zakres niestandardowy",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index b37191f8a7..1fb834cfed 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -610,6 +610,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: '"{name}" quer ler dados da conexão "{connection}". Enquanto essa conexão estiver aberta, o plugin poderá executar consultas somente leitura nela até você revogar o acesso na Central de plugins. Permitir?',
dataAccessConsentTitle: "Solicitação de acesso a dados",
+ mcpToolsBadge: "Ferramentas MCP",
+ mcpToolsBadgeHint: "This plugin provides Ferramentas MCP. Enable and authorize them in Settings → MCP → Capacidades.",
+ mcpToolsFilter: "Somente plugins com ferramentas MCP ({count})",
+ externalMcp: {
+ title: "Clientes MCP externos",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → Capacidades.",
+ notOffered: "O autor não disponibilizou as ferramentas deste plugin para clientes MCP externos.",
+ },
aiTools: {
title: "Ferramentas de IA integradas",
description: "Desativado por padrão: o assistente de IA do DBX (modo Agent) só pode usar as ferramentas deste plugin nas conexões abertas enquanto o interruptor estiver ligado. Ferramentas não somente leitura continuarão pedindo aprovação a cada chamada.",
@@ -7279,6 +7287,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "Ferramenta MCP",
+ mcpClient: "Cliente MCP",
+ mcpTransport: "Transporte MCP",
+ mcpAccess: "Acesso MCP",
+ mcpConfirmation: "Confirmação MCP",
kind: "Tipo",
operation: "Operação",
connection: "Conexão",
@@ -9605,6 +9617,303 @@ export default withEnglishFallback({
mcpInstallSuccess: "Instalação bem-sucedida",
mcpInstallFailed: "Falha na instalação",
mcpConfig: "Configuração do MCP",
+ mcpCapabilitiesFilterLabel: "Filtro de recursos",
+ mcpCapabilitiesFilterAll: "Todos",
+ mcpCapabilitiesFilterBuiltin: "Integrados",
+ mcpCapabilitiesFilterPlugin: "Extensão",
+ mcpCapabilitiesOnlyEnabled: "Mostrar apenas ativadas",
+ mcpPluginScopeLoad: "Ler do plugin",
+ mcpPluginToolsMode: "Como o DBX oferece ferramentas de plugins",
+ mcpPluginToolsModeDescription: "Escolha como o DBX oferece ferramentas autorizadas de plugins aos clientes MCP. Clique em Aplicar no rodapé para salvar.",
+ mcpPluginToolsModeAuto: "Automático (compatibilidade)",
+ mcpPluginToolsModeFlat: "Listar diretamente (padrão)",
+ mcpPluginToolsModeLazy: "Descoberta sob demanda",
+ mcpPluginToolsModeFlatDescription: "Lista cada ferramenta autorizada para que os clientes possam chamá-la diretamente.",
+ mcpPluginToolsModeLazyDescription: "Oferece ferramentas comuns de descoberta e chamada, obtendo os detalhes quando necessário. Ative a descoberta e chamada de plugins em DBX geral.",
+ mcpPluginToolsModeAutoDescription: "Mantém a alternância automática existente: lista diretamente até 40 ferramentas de plugins no total; acima disso, usa descoberta sob demanda.",
+ mcpCallSafety: "Segurança de chamadas",
+ mcpCallSafetyLegacy: "Autorização temporária legada",
+ mcpCallSafetyEnabled: "Confirmar cada chamada de alto risco",
+ mcpCallSafetyDisabled: "Sem confirmação adicional",
+ mcpCallSafetyLegacyHint: "O comportamento anterior é mantido: escrita de dados pode autorizar temporariamente algumas operações de alto risco; acesso completo não pergunta. A nova política rejeita permissões insuficientes e confirma também com acesso completo.",
+ mcpCallSafetyMigrate: "Usar a nova política",
+ mcpCallSafetyDisableLegacy: "Desativar autorização legada",
+ mcpCallSafetyConfirm: "Solicitar confirmação antes de chamadas de alto risco",
+ mcpCallSafetyHint: "Aplica-se a chamadas nativas e de plugins identificadas como de alto risco. As permissões são verificadas primeiro, inclusive com acesso completo. A confirmação nunca amplia permissões.",
+ mcpCallSafetyDesktopHint: "Requer DBX desktop e aprova apenas a chamada atual. Confirmação indisponível, negada ou expirada impede a execução. Proteções de leitura e produção continuam válidas. Clique em Aplicar para salvar.",
+ mcpToolApprovalGenericTitle: "Confirmar chamada de alto risco",
+ mcpToolApprovalPluginTitle: "Confirmar ferramenta de alto risco de {plugin}",
+ 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",
+ mcpToolApprovalTarget: "Destino",
+ mcpManagementCapabilities: "Capacidades",
+ mcpOpenCallHistory: "Ver histórico de chamadas MCP",
+ mcpAccessTreeTitle: "Controle de acesso",
+ mcpAccessTreeDescription: "Defina permissões para grupos, conexões e bancos de dados. Herdar usa a configuração superior; a permissão efetiva mostra o resultado e sua origem.",
+ mcpAccessTreeSummary: "{visible}/{total} conexões visíveis · exceções: {groups} grupos, {connections} conexões, {databases} bancos de dados",
+ mcpAccessTreeScopeLabel: "Visibilidade das conexões",
+ mcpAccessTreeScopeAll: "Todas as conexões",
+ mcpAccessTreeScopeCustom: "Somente selecionadas",
+ mcpAccessTreeSearchPlaceholder: "Pesquisar grupos, conexões ou bancos de dados",
+ mcpAccessTreeExceptionsOnly: "Mostrar apenas configurações individuais",
+ mcpAccessTreeColumnResource: "Recurso",
+ mcpAccessTreeColumnVisible: "Visível",
+ mcpAccessTreeColumnSetting: "Permissão",
+ mcpAccessTreeColumnEffective: "Efetivo",
+ mcpAccessTreeInherit: "Herdar",
+ mcpAccessTreeGroupPartiallyVisible: "Algumas conexões visíveis ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "Todas as conexões atuais visíveis ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Apenas itens filhos estão autorizados, não o grupo inteiro. Marque para permitir todo o grupo, incluindo conexões futuras.",
+ mcpAccessTreeGroupDefaultHint: "As permissões padrão do grupo se aplicam a itens filhos sem permissões próprias. Elas não alteram a visibilidade das conexões.",
+ mcpAccessTreeHidden: "Não visível para MCP",
+ mcpAccessTreeSourceGlobal: "padrão global",
+ mcpAccessTreeSourceGroup: "do grupo {group}",
+ mcpAccessTreeSourceConnection: "configuração da conexão",
+ mcpAccessTreeSourceDatabase: "configuração do banco",
+ mcpAccessTreeGroupCount: "{count} conexões",
+ mcpAccessTreeLegacy: "legado",
+ mcpAccessTreeLegacyHint: "Salvo por uma versão anterior: só pode restringir as permissões herdadas pela conexão. Escolha uma permissão novamente para convertê-la em uma configuração normal.",
+ mcpAccessTreeCoveredByGroup: "Visível through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "Alto risco allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "Bancos de dados",
+ mcpAccessTreeDatabaseScopeAll: "Todos os bancos de dados",
+ mcpAccessTreeDatabaseScopeSelected: "Selecionados ({count})",
+ mcpAccessTreeDatabaseScopeNone: "Nenhum banco de dados",
+ mcpDatabaseRemoveConfirm: "Remover os bancos selecionados também remove suas permissões específicas. Continuar?",
+ mcpDatabaseUnavailable: "As permissões dos bancos estão indisponíveis. Aguarde o carregamento ou tente novamente.",
+ mcpDatabaseConfigure: "Configurar acesso aos bancos",
+ mcpDatabaseOverrideCount: "{count} permissões específicas",
+ mcpDatabaseDialogTitle: "{name} / Acesso aos bancos",
+ mcpDatabaseDialogDescription: "Selecione bancos e suas permissões. Mover para a direita só entra em vigor após aplicar.",
+ mcpDatabaseInherited: "Permissões herdadas: {level}",
+ mcpDatabaseSavedInherited: "Há alterações pendentes nas permissões superiores. Ao aplicar apenas este escopo, as permissões salvas continuam herdadas: {level}",
+ mcpDatabaseHiddenConnection: "Esta conexão está oculta para o MCP. Aplicar permissões de bancos não expõe a conexão.",
+ mcpDatabaseAllHint: "Inclui bancos atuais e futuros usando as permissões da conexão.",
+ mcpDatabaseNoneHint: "Aplicar negará acesso a todos os bancos.",
+ mcpDatabaseLoaded: "Carregados {count} bancos visíveis para esta conta",
+ mcpDatabaseRefresh: "Atualizar lista",
+ mcpDatabaseAddSelected: "Adicionar →",
+ mcpDatabaseRemoveSelected: "← Remover",
+ mcpDatabaseAvailable: "Não selecionados ({count})",
+ mcpDatabaseSelected: "Selecionados ({count})",
+ mcpDatabaseSearch: "Pesquisar nomes de bancos",
+ mcpDatabaseSelectResults: "Selecionar resultados atuais ({count})",
+ mcpDatabaseBatchLevel: "Permissões dos marcados ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "Permitir acesso completo a {count} bancos de dados marcados? As proteções de somente leitura da conexão e do ambiente de produção continuam em vigor.",
+ mcpDatabaseNotDiscovered: "Não encontrado nesta consulta",
+ mcpDatabaseShowMore: "Mostrar mais ({shown}/{total})",
+ mcpDatabaseSaveHint: "Salva apenas o escopo e as permissões dos bancos desta conexão. Mantém as outras alterações pendentes.",
+ mcpDatabaseApply: "Aplicar permissões dos bancos",
+ mcpAccessTreePickDatabases: "Escolher bancos de dados",
+ mcpAccessTreePickerTitle: "Bancos de dados of {name}",
+ mcpAccessTreeLoadingDatabases: "Carregando bancos de dados...",
+ mcpAccessTreeLoadDatabasesFailed: "Não foi possível carregar os bancos de dados: {error}. Você ainda pode adicionar nomes manualmente.",
+ mcpAccessTreeManualDatabase: "Adicionar nome de banco de dados",
+ mcpAccessTreeNoMatch: "Nenhum recurso correspondente",
+ mcpAccessTreeEmpty: "Ainda não há conexões",
+ mcpAccessTreeFootnote: "Priority: database > connection > closest group > parent group > padrão global. Connection read-only protection, production protection and database credentials always apply on top.",
+ mcpAccessTreeNacosNamespace: "Namespace",
+ mcpPluginScopeAll: "Todos ({title})",
+ mcpPluginScopeSelected: "Selecionados ({count})",
+ mcpPluginScopeNone: "Não {title}",
+ mcpPluginScopeAdd: "Adicionar {title}",
+ mcpBrowser: {
+ viewMode: "Modo de visualização",
+ viewManage: "Gerenciamento por categoria",
+ viewOverview: "Visão geral global",
+ overviewSummary: "{toolsets} conjuntos de ferramentas · {total} ferramentas · {enabled} ativadas",
+ overviewPluginsHint: "Revise as ferramentas e autorizações do plugin. Abra um plugin para ver os detalhes.",
+ overviewOpenDetails: "Ver detalhes",
+ expandCategory: "Expandir categoria",
+ collapseCategory: "Recolher categoria",
+ builtin: "Recursos integrados",
+ plugins: "Extensões de plugins",
+ advanced: "Configurações avançadas",
+ navigation: "Categorias de recursos",
+ searchPlaceholder: "Pesquisar categorias, recursos, plugins ou ferramentas…",
+ clearSearch: "Limpar pesquisa",
+ searchResults: "Resultados da pesquisa",
+ categoryCount: "{count} conjuntos de ferramentas",
+ summary: "{toolsets} conjuntos · {total} ferramentas · {enabled} ativadas",
+ enableCategory: "Ativar toda esta categoria",
+ disableCategory: "Desativar toda esta categoria",
+ draftHint: "Aplique um conjunto nos detalhes ou use Aplicar abaixo para salvar todas as configurações pendentes.",
+ batchChanged: "Ferramentas desta categoria alteradas. Clique em Aplicar para salvar",
+ coverageHint: "As conexões compatíveis são contadas por tipo de conexão, não pelo escopo real de autorização.",
+ uncovered: "{count} conexões sem cobertura de ferramentas integradas",
+ viewDetails: "Ver detalhes",
+ emptyEnabled: "Não há ferramentas ativadas nesta categoria. Desmarque “Mostrar apenas ativadas” para configurá-las.",
+ retry: "Tentar novamente",
+ enabledToolCount: "{enabled}/{total} ativadas",
+ partialEnabled: "Parcialmente ativada",
+ coverageConnections: "Compatível com {count} conexões",
+ coveragePartialConnections: "{count} com suporte parcial",
+ noMatchingConnections: "Nenhuma conexão compatível",
+ resourceScopes: "Escopos de recursos",
+ pluginImmediate: "As alterações são salvas imediatamente, independentemente de Aplicar / Cancelar no rodapé",
+ pluginSaving: "Salvando…",
+ pluginSaved: "Salvo",
+ pluginOnlyEnabledEmpty: "Não há ferramentas ativadas. Desmarque “Mostrar apenas ativadas” para vê-las.",
+ pluginUnavailable: "Este plugin não está mais disponível. Atualize a lista de plugins",
+ resourceKind: {
+ database: "Banco de dados",
+ dbIndex: "Banco de dados lógico",
+ topic: "Tópico",
+ queue: "Fila",
+ org: "Organização",
+ namespace: "Namespace",
+ },
+ category: {
+ database: { title: "Bancos de dados", description: "Consulte dados, gerencie sessões e transações, explore estruturas de objetos e execute comandos Redis." },
+ nacos: { title: "Nacos", description: "Gerencie configurações, serviços e instâncias." },
+ consul: { title: "Consul", description: "Gerencie entradas KV, descubra serviços e veja o estado de integridade." },
+ mq: { title: "Filas de mensagens", description: "Leia e envie mensagens." },
+ salesforce: { title: "Salesforce", description: "Consulte a identidade e opere sobre dados." },
+ dbx: { title: "DBX compartilhado", description: "Recursos compartilhados entre produtos: descoberta de conexões, integração com a área de trabalho, gerenciamento de conexões e descoberta e invocação de plugins." },
+ other: { title: "Outros recursos", description: "Veja e configure conjuntos de ferramentas ainda não categorizados." },
+ },
+ },
+ mcpCapabilitiesTitle: "Capacidades do MCP",
+ mcpCapabilitiesDescription: "Integrado Ferramentas MCP grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the tipos de banco de dados it applies to.",
+ mcpCapabilitiesLoading: "Carregando capacidades do MCP...",
+ mcpCapabilitiesLoadFailed: "Failed to load Capacidades do MCP: {error}",
+ mcpCapabilitiesSearchPlaceholder: "Buscar capacidades ou ferramentas",
+ mcpCapabilitiesSearchEmpty: "Nenhuma capacidade correspondente",
+ mcpToolsetToolCount: "{enabled}/{total} ferramentas",
+ mcpAccessLevelClassified: "Por chamada",
+ mcpCoverageTypes: "{count} tipos de banco de dados",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Sem vínculo com conexão",
+ mcpCoverageUsableConnections: "Usado por {count} das suas conexões",
+ mcpCoverageNoUsableConnections: "Nenhuma das suas conexões o utiliza",
+ mcpCoveragePartialConnections: "{count} conexões oferecem suporte apenas a algumas ferramentas",
+ mcpCoverageUncoveredConnections: "{count} connections have no Ferramentas MCP yet: {names}",
+ mcpCoverageSearchPlaceholder: "Search tipos de banco de dados",
+ mcpCoverageSearchEmpty: "Não matching tipos de banco de dados",
+ mcpCoverageLegend: "Apenas os tipos compatíveis são listados. Os destacados correspondem às suas conexões; * indica que algumas ferramentas do grupo não oferecem suporte ao tipo (passe o cursor para ver detalhes).",
+ mcpCoverageTypeUnsupportedTool: "Não compatível com {tool}",
+ mcpCoverageCategoryOther: "Outro",
+ mcpCoveragePartialTool: "{tool} oferece suporte a {count} de {total}",
+ mcpToolDetailSkippedConnections: "Indisponível em: {names}",
+ mcpToolDetailCoverage: "Supported tipos de banco de dados ({count})",
+ mcpToolDetailParameterDefault: "padrão: {value}",
+ mcpToolDetailParameterDescription: "Descrição",
+ mcpToolDetailParameterRequiredNo: "Não",
+ mcpToolDetailParameterRequiredYes: "Sim",
+ mcpToolDetailParameterRequired: "Obrigatório",
+ mcpToolDetailParameterType: "Tipo",
+ mcpToolDetailParameterName: "Nome",
+ mcpToolDetailNoParameters: "Sem parâmetros",
+ mcpToolDetailParameters: "Parâmetros",
+ mcpToolDetailDescription: "Descrição para o modelo",
+ mcpToolDetailAccessClassified: "Classificado a cada chamada (leitura, escrita ou alto risco conforme a instrução)",
+ mcpToolDetailAccess: "Nível de acesso",
+ mcpToolDetailSummary: "Resumo",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "{count} das suas conexões não podem usá-lo",
+ mcpToolsetDetailTools: "Ferramentas",
+ mcpToolsetDetailCoverage: "Cobertura",
+ mcpToolsetApply: "Aplicar este conjunto",
+ mcpToolsetApplying: "Aplicando…",
+ mcpToolsetPending: "{count} alterações de ferramentas não aplicadas",
+ mcpToolsetApplied: "Configuração atual aplicada",
+ mcpToolsetCloseKeepsDraft: "Fechar mantém as alterações. Você também pode aplicá-las nas Configurações.",
+ mcpToolsetApplyFailed: "Não foi possível aplicar: {error}. As alterações foram mantidas; tente novamente.",
+ mcpToolsetApplyUnavailable: "A configuração de ferramentas está indisponível. Aguarde o carregamento ou tente novamente.",
+ mcpToolsetDetailClose: "Fechar",
+ mcpPluginToolEntriesTitle: "Entradas de ferramentas de plugins",
+ mcpPluginsTitle: "Plugins",
+ mcpPluginsDescription: "Plugins that provide Ferramentas MCP. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "Atualizar",
+ mcpPluginsLoading: "Carregando ferramentas do plugin...",
+ mcpPluginsLoadFailed: "Falha ao carregar ferramentas de plugins: {error}",
+ mcpPluginsEmpty: "Nenhum plugin instalado fornece ferramentas MCP.",
+ mcpPluginSaveFailed: "Falha ao salvar {name}: {message}",
+ mcpPluginAuthorClosed: "O autor não o disponibilizou para MCP externo",
+ mcpPluginDiscoveryFailed: "Falha ao descobrir ferramentas",
+ mcpPluginToolCount: "{exposed}/{total} ferramentas expostas",
+ mcpPluginToolCountOff: "{total} ferramentas, desativadas",
+ mcpPluginCeilingSummary: "Limite: {level}",
+ mcpPluginPendingTools: "{count} novas ferramentas precisam de confirmação",
+ mcpPluginReview: "Revisar",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Falha ao descobrir ferramentas: {error}",
+ mcpPluginCeilingTitle: "Limite de autorização",
+ mcpPluginCeilingDescription: "Ferramentas acima do limite permanecem ocultas para clientes MCP. As chamadas também devem respeitar as permissões dos recursos e as regras de visibilidade das conexões.",
+ mcpPluginEnableFirst: "Ative o plugin para alterar seu limite e suas ferramentas.",
+ mcpPluginDefaultToolset: "Ferramentas",
+ mcpPluginNoTools: "This plugin lists no Ferramentas MCP right now.",
+ mcpPluginAuthorizeTitle: "Autorizar {name} for MCP",
+ mcpPluginAuthorizeDescription: "Escolha o limite de permissões do plugin. Todas as ferramentas declaradas abaixo são aceitas; ferramentas adicionadas depois ou cujo nível declarado aumente pedirão nova confirmação se precisarem de mais que leitura.",
+ mcpPluginAuthorizeTools: "Ferramentas ({count})",
+ mcpPluginAuthorizeIncluded: "Exposto",
+ mcpPluginAuthorizeExcluded: "Oculta",
+ mcpPluginAuthorizeFootnote: "Depois você poderá alterar o limite ou desativar ferramentas individuais nos detalhes do plugin.",
+ mcpPluginAccessUndeclared: "Não declarado pelo autor — never exposed",
+ mcpPluginUndeclaredCount: "{count} ferramentas não estão declaradas no manifesto e permanecem ocultas",
+ mcpPluginUndeclaredTools: "{count} ferramentas não têm nível de acesso declarado no manifesto do plugin e nunca serão expostas: {names}",
+ mcpPluginAuthorizeCancel: "Cancelar",
+ mcpPluginAuthorizeConfirm: "Autorizar",
+ mcpPluginToolEntriesHint: "Avançado: entradas permitidas para ferramentas de plugins. dbx_*__* permite todas as ferramentas de plugins e dbx_<prefix>__* as de um plugin. Os controles dos plugins definem as ferramentas disponíveis; estas entradas adicionam outro filtro.",
+ mcpPluginAllowlistBlocked: "A lista de ferramentas MCP permitidas não contém entradas de plugins, por isso suas ferramentas ficam ocultas independentemente dos controles dos plugins.",
+ mcpPluginAllowlistAllow: "Permitir ferramentas do plugin",
+ mcpPluginExposure: {
+ exposed: "Exposto",
+ undeclared: "Não declarado",
+ pluginDisabled: "Plugin desativado",
+ toolDisabled: "Desativado",
+ aboveCeiling: "Acima do limite",
+ pendingApproval: "Requer confirmação",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Somente leitura",
+ write: "Leitura e gravação",
+ full: "Completo (inclui alto risco)",
+ },
+ mcpAccessLevel: {
+ read: "Leitura",
+ write: "Gravação",
+ full: "Alto risco",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "Descoberta e contexto", description: "Listar conexões e bancos de dados e obter o contexto do esquema para o modelo." },
+ sqlQuery: { title: "Consulta SQL", description: "Executar consultas e scripts. O risco de cada instrução é classificado a cada chamada." },
+ sqlSession: { title: "Sessões e transações", description: "Manter uma sessão entre chamadas e controlar transações." },
+ sqlSchema: { title: "Objetos do esquema", description: "Navegar por tabelas, colunas e código-fonte de rotinas." },
+ redis: { title: "Comandos Redis", description: "Executar comandos Redis." },
+ mq: { title: "Leitura e envio de mensagens", description: "Ler e enviar mensagens de Kafka, RocketMQ e RabbitMQ." },
+ salesforce: { title: "Identidade e operações de dados", description: "Identificar o usuário atual e gravar registros individuais." },
+ workbench: { title: "Área de trabalho", description: "Abrir tabelas e mostrar resultados de consultas no DBX." },
+ adminConnections: { title: "Gerenciamento de conexões", description: "Adicionar, duplicar e remover conexões do DBX." },
+ pluginRouter: { title: "Descoberta e invocação de plugins", description: "Descobrir ferramentas de plugins sob demanda e chamá-las por um único roteador." },
+ nacosConfig: { title: "Gerenciamento de configurações", description: "Leitura, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "Gerenciamento de serviços", description: "Listar serviços e instâncias; ativar ou desativar instâncias e alterar pesos." },
+ consulKv: { title: "Gerenciamento de KV", description: "Listar, ler, gravar e excluir chaves KV do Consul com comparação e atualização (CAS)." },
+ consulService: { title: "Descoberta e integridade de serviços", description: "Catálogo de serviços e nós, saúde dos serviços e modo de manutenção." },
+ },
+ mcpToolNacosListNamespaces: "Listar namespaces do Nacos",
+ mcpToolNacosListConfigs: "Listar configurações do Nacos",
+ mcpToolNacosGetConfig: "Ler configuração do Nacos",
+ mcpToolNacosConfigHistory: "Histórico de configuração do Nacos",
+ mcpToolNacosPublishConfig: "Publicar configuração do Nacos",
+ mcpToolNacosDeleteConfig: "Excluir configuração do Nacos",
+ mcpToolNacosListServices: "Listar serviços do Nacos",
+ mcpToolNacosListInstances: "Listar instâncias do Nacos",
+ mcpToolNacosUpdateInstance: "Atualizar instância do Nacos",
+ mcpToolNacosSearchConfigs: "Buscar configurações do Nacos",
+ mcpToolNacosRollbackConfig: "Reverter configuração do Nacos",
+ mcpToolNacosGetService: "Consultar serviço do Nacos",
+ mcpToolNacosRegisterInstance: "Registrar instância do Nacos",
+ mcpToolNacosDeregisterInstance: "Cancelar registro de instância do Nacos",
+ mcpToolConsulKvList: "Listar chaves do Consul KV",
+ mcpToolConsulKvGet: "Ler chave do Consul KV",
+ mcpToolConsulKvPut: "Gravar chave do Consul KV",
+ mcpToolConsulKvDelete: "Excluir chave do Consul KV",
+ mcpToolConsulListServices: "Listar serviços do Consul",
+ mcpToolConsulListNodes: "Listar nós do Consul",
+ mcpToolConsulServiceHealth: "Saúde do serviço Consul",
+ mcpToolConsulSetMaintenance: "Modo de manutenção do Consul",
mcpConfigOptionsHint:
"O DBX controla centralmente o acesso às conexões e as permissões de execução para todos os clientes MCP. A configuração gerada contém apenas os parâmetros de execução necessários para iniciar o servidor MCP e conectá-lo a esta instância do DBX, sem variáveis de permissão ou escopo de conexão.",
mcpScopeConnection: "Conexões permitidas para MCP",
@@ -9653,7 +9962,8 @@ export default withEnglishFallback({
mcpWindsurfConfigPath: "O Windsurf pode usar ~/.codeium/windsurf/mcp_config.json.",
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json globalmente, ou opencode.json no nível do projeto.",
mcpExecutionMode: "Permissão padrão global do MCP",
- mcpExecutionModeDescription: "Define o padrão usado quando não há permissão de conexão ou banco configurada. Configurações de conexão e banco podem substituí-lo por escopo.",
+ mcpExecutionModeDescription: "Recursos sem permissão própria usam este padrão. Defina permissões diferentes no controle de acesso abaixo.",
+ mcpPermissionsDraftHint: "Alterações globais, de grupos e conexões usam Aplicar abaixo. Permissões dos bancos também podem ser aplicadas na janela. Subescopos são salvos imediatamente. Descartar rascunhos não desfaz alterações salvas.",
mcpExecutionModeReadOnly: "Somente leitura",
mcpExecutionModeSafeWrite: "Leitura e gravação de dados",
mcpExecutionModeRecommended: "Recomendado",
@@ -9662,21 +9972,21 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "Permite INSERT normal, UPDATE/DELETE com filtros efetivos, alterações MongoDB de escopo verificável e gravações Redis comuns ou exclusão de chaves explícitas; bloqueia alterações globais e estruturais.",
mcpExecutionModeHighRiskWriteDescription: "Além da leitura e gravação de dados, permite alterações na tabela inteira, DDL, TRUNCATE, limpeza do banco e outras operações de alto risco. As proteções de produção e somente leitura continuam ativas.",
mcpExecutionModeHighRiskConfirm: "O acesso completo permite alterações na tabela inteira, DDL, TRUNCATE, limpeza do banco e outras operações de alto risco. Deseja ativá-lo?",
- mcpPromptHighRiskSql: "Pedir confirmação para SQL de alto risco (apenas desktop; proteções de somente leitura e produção permanecem)",
mcpSqlApprovalTitle: "Aprovação de SQL de alto risco do MCP",
mcpSqlApprovalScope: "Conexão: {connection} · Banco de dados: {database}",
mcpSqlApprovalOnce: "Somente esta solicitação",
mcpSqlApprovalHour: "Permitir neste banco de dados por 1 hora",
mcpSqlApprovalDay: "Permitir neste banco de dados por 1 dia",
mcpSqlApprovalDeny: "Negar",
- mcpCapabilityTitle: "Comparação de recursos",
- mcpCapabilityDescription: "Estas são operações representativas; solicitações que o DBX não consegue classificar com segurança exigem acesso completo.",
+ mcpCapabilityTitle: "Detalhes de permissões",
+ mcpCapabilityDescription: "A tabela descreve permissões; habilite as ferramentas em Capacidades. Permissões insuficientes são rejeitadas. Segurança de chamadas controla a confirmação e explica a autorização legada.",
mcpCapabilityOperation: "Recurso",
mcpCapabilityRead: "Consultas e leituras",
mcpCapabilityScopedMutation: "Alterações de dados com escopo (INSERT, UPDATE/DELETE filtrados, gravação/exclusão de chaves explícitas)",
mcpCapabilityBroadMutation: "Atualizações/exclusões de tabelas inteiras e limpeza de dados",
mcpCapabilitySchemaAdmin: "DDL, alterações estruturais e administração de alto risco",
- mcpCapabilityConnectionManagement: "Adicionar/remover conexões MCP",
+ mcpCapabilityConnectionCreate: "Adicionar/duplicar conexões MCP (permissão global padrão)",
+ mcpCapabilityConnectionRemove: "Remover conexões MCP (permissão global padrão)",
mcpCapabilityAllowed: "Permitido",
mcpCapabilityBlocked: "Bloqueado",
mcpQueryTimeout: "Tempo limite de consulta (segundos)",
@@ -9684,6 +9994,9 @@ export default withEnglishFallback({
mcpQueryTimeoutInvalid: "Insira um número inteiro não negativo de segundos ou deixe vazio para herdar a configuração da conexão.",
mcpCapabilityAlwaysEnforced: "Todos os modos continuam sujeitos à lista de conexões permitidas, à proteção somente leitura, à proteção de produção e às permissões da conta do banco de dados.",
mcpPolicySaveFailed: "Falha ao salvar a política de acesso MCP: {error}",
+ mcpPolicyRetry: "Tentar novamente",
+ mcpPolicyRecover: "Fazer backup e redefinir permissões MCP",
+ mcpPolicyRecoverConfirm: "Esta ação faz uma cópia imediata da política danificada e redefine as permissões MCP, incluindo alterações não salvas. Todas as conexões e ferramentas serão bloqueadas até serem configuradas novamente. Continuar?",
mcpPolicyLoadFailed: "Falha ao carregar a política de acesso MCP: {error}",
mcpDetectionTiming: "O DBX verifica automaticamente quando esta página é aberta; use Verificar novamente para atualizar.",
mcpNpmBoundary: "O DBX apenas verifica e explica o status do MCP; a instalação e as atualizações ainda são feitas pelo npm, pnpm ou bun.",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 136956b297..de66110563 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -578,6 +578,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: "«{name}» запрашивает чтение данных подключения «{connection}». Пока подключение открыто, плагин сможет выполнять в нём запросы только на чтение, пока вы не отзовёте доступ в Центре плагинов. Разрешить?",
dataAccessConsentTitle: "Запрос доступа к данным",
+ mcpToolsBadge: "Инструменты MCP",
+ mcpToolsBadgeHint: "This plugin provides Инструменты MCP. Enable and authorize them in Settings → MCP → Возможности.",
+ mcpToolsFilter: "Только плагины с инструментами MCP ({count})",
+ externalMcp: {
+ title: "Внешние клиенты MCP",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → Возможности.",
+ notOffered: "Автор не открыл инструменты этого плагина для внешних клиентов MCP.",
+ },
aiTools: {
title: "Встроенные инструменты ИИ",
description: "По умолчанию выключено: ИИ-ассистент DBX (режим Agent) может вызывать инструменты этого плагина в открытых подключениях, только пока переключатель включён. Инструменты без признака «только чтение» по-прежнему требуют подтверждения каждого вызова.",
@@ -8658,6 +8666,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "Инструмент MCP",
+ mcpClient: "Клиент MCP",
+ mcpTransport: "Транспорт MCP",
+ mcpAccess: "Доступ MCP",
+ mcpConfirmation: "Подтверждение MCP",
kind: "Тип",
operation: "Операция",
connection: "Подключение",
@@ -11242,6 +11254,303 @@ export default withEnglishFallback({
mcpUninstallConfirm: "Удалить сервер DBX MCP? Настроенные клиенты MCP больше не смогут его запустить.",
mcpUninstallFailed: "Удаление не удалось: {error}",
mcpConfig: "Конфигурация MCP",
+ mcpCapabilitiesFilterLabel: "Фильтр возможностей",
+ mcpCapabilitiesFilterAll: "Все",
+ mcpCapabilitiesFilterBuiltin: "Встроенные",
+ mcpCapabilitiesFilterPlugin: "Плагин",
+ mcpCapabilitiesOnlyEnabled: "Показывать только включённые",
+ mcpPluginScopeLoad: "Прочитать из плагина",
+ mcpPluginToolsMode: "Предоставление инструментов плагинов клиентам",
+ mcpPluginToolsModeDescription: "Выберите, как DBX предоставляет разрешённые инструменты плагинов клиентам MCP. Для сохранения нажмите «Применить» внизу.",
+ mcpPluginToolsModeAuto: "Автоматически (совместимость)",
+ mcpPluginToolsModeFlat: "Прямой список (по умолчанию)",
+ mcpPluginToolsModeLazy: "Поиск по запросу",
+ mcpPluginToolsModeFlatDescription: "Показывает каждый разрешённый инструмент отдельно для прямого вызова клиентом.",
+ mcpPluginToolsModeLazyDescription: "Предоставляет общие инструменты поиска и вызова плагинов, получая сведения по мере необходимости. Включите поиск и вызов плагинов в общих возможностях DBX.",
+ mcpPluginToolsModeAutoDescription: "Сохраняет прежнее автоматическое переключение: прямой список при общем числе инструментов плагинов до 40, иначе поиск по запросу.",
+ mcpCallSafety: "Безопасность вызовов",
+ mcpCallSafetyLegacy: "Прежнее временное разрешение",
+ mcpCallSafetyEnabled: "Подтверждать каждый опасный вызов",
+ mcpCallSafetyDisabled: "Без дополнительного подтверждения",
+ mcpCallSafetyLegacyHint: "Сохранено прежнее поведение: запись данных позволяет временно одобрять некоторые опасные операции; полный доступ не требует подтверждения. Новая политика отклоняет недостаточные права и запрашивает подтверждение даже при полном доступе.",
+ mcpCallSafetyMigrate: "Перейти на новую политику",
+ mcpCallSafetyDisableLegacy: "Отключить прежнее разрешение",
+ mcpCallSafetyConfirm: "Запрашивать подтверждение опасных вызовов",
+ mcpCallSafetyHint: "Применяется к встроенным инструментам и плагинам, чьи вызовы определены как опасные. Сначала проверяются права. Полный доступ также требует подтверждения, которое не повышает права.",
+ mcpCallSafetyDesktopHint: "Требуется DBX для рабочего стола; одобряется только текущий вызов. При отказе, тайм-ауте или отсутствии подтверждения вызов не выполняется. Защита чтения и production сохраняется. Нажмите Применить для сохранения.",
+ mcpToolApprovalGenericTitle: "Подтвердить опасный вызов",
+ mcpToolApprovalPluginTitle: "Подтвердить инструмент высокого риска плагина {plugin}",
+ mcpToolApprovalRedisTitle: "Подтвердить опасную команду Redis",
+ mcpToolApprovalDescription: "An Клиент MCP wants to run a high-risk operation. Allow it only if you expect this call.",
+ mcpToolApprovalTool: "Инструмент",
+ mcpToolApprovalTarget: "Цель",
+ mcpManagementCapabilities: "Возможности",
+ mcpOpenCallHistory: "Просмотреть историю вызовов MCP",
+ mcpAccessTreeTitle: "Управление доступом",
+ mcpAccessTreeDescription: "Задавайте разрешения для групп, подключений и баз данных. Наследование использует настройку родителя; столбец действующих прав показывает результат и источник.",
+ mcpAccessTreeSummary: "Видимые подключения: {visible}/{total} · исключения: {groups} групп, {connections} подключений, {databases} баз данных",
+ mcpAccessTreeScopeLabel: "Видимость подключений",
+ mcpAccessTreeScopeAll: "Все подключения",
+ mcpAccessTreeScopeCustom: "Только выбранные",
+ mcpAccessTreeSearchPlaceholder: "Поиск групп, подключений или баз данных",
+ mcpAccessTreeExceptionsOnly: "Только отдельные настройки",
+ mcpAccessTreeColumnResource: "Ресурс",
+ mcpAccessTreeColumnVisible: "Видимый",
+ mcpAccessTreeColumnSetting: "Разрешение",
+ mcpAccessTreeColumnEffective: "Итоговый",
+ mcpAccessTreeInherit: "Наследовать",
+ mcpAccessTreeGroupPartiallyVisible: "Часть подключений видна ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "Все текущие подключения видны ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Разрешены только дочерние элементы, а не вся группа. Установите флажок, чтобы разрешить всю группу, включая будущие подключения.",
+ mcpAccessTreeGroupDefaultHint: "Права группы по умолчанию применяются к дочерним элементам без собственных настроек прав. Они не меняют видимость подключений.",
+ mcpAccessTreeHidden: "Не виден MCP",
+ mcpAccessTreeSourceGlobal: "глобальный параметр",
+ mcpAccessTreeSourceGroup: "из группы {group}",
+ mcpAccessTreeSourceConnection: "настройка подключения",
+ mcpAccessTreeSourceDatabase: "настройка базы данных",
+ mcpAccessTreeGroupCount: "Подключений: {count}",
+ mcpAccessTreeLegacy: "устаревшее",
+ mcpAccessTreeLegacyHint: "Сохранено старой версией: может только ограничивать унаследованные подключением права. Выберите право заново, чтобы преобразовать его в обычную настройку.",
+ mcpAccessTreeCoveredByGroup: "Видимый through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "Высокий риск allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "Базы данных",
+ mcpAccessTreeDatabaseScopeAll: "Все базы данных",
+ mcpAccessTreeDatabaseScopeSelected: "Выбрано ({count})",
+ mcpAccessTreeDatabaseScopeNone: "Нет баз данных",
+ mcpDatabaseRemoveConfirm: "Удаление выбранных баз также удалит их особые права. Продолжить?",
+ mcpDatabaseUnavailable: "Настройки доступа к базам недоступны. Дождитесь загрузки или повторите попытку.",
+ mcpDatabaseConfigure: "Настроить доступ к базам",
+ mcpDatabaseOverrideCount: "Особых правил: {count}",
+ mcpDatabaseDialogTitle: "{name} / Доступ к базам данных",
+ mcpDatabaseDialogDescription: "Выберите базы и их права. Перемещение вправо вступает в силу только после применения.",
+ mcpDatabaseInherited: "Наследуемые права: {level}",
+ mcpDatabaseSavedInherited: "В родительских правах есть несохранённые изменения. При применении только прав баз наследуются сохранённые права: {level}",
+ mcpDatabaseHiddenConnection: "Подключение сейчас скрыто от MCP. Применение прав баз не делает его видимым.",
+ mcpDatabaseAllHint: "Включает текущие и будущие базы с правами подключения.",
+ mcpDatabaseNoneHint: "После применения доступ ко всем базам будет запрещён.",
+ mcpDatabaseLoaded: "Загружено баз, видимых этой учётной записи: {count}",
+ mcpDatabaseRefresh: "Обновить список",
+ mcpDatabaseAddSelected: "Добавить →",
+ mcpDatabaseRemoveSelected: "← Удалить",
+ mcpDatabaseAvailable: "Не выбрано ({count})",
+ mcpDatabaseSelected: "Выбрано ({count})",
+ mcpDatabaseSearch: "Поиск по имени базы",
+ mcpDatabaseSelectResults: "Выбрать текущие результаты ({count})",
+ mcpDatabaseBatchLevel: "Права отмеченных баз ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "Разрешить полный доступ к {count} отмеченным базам данных? Защита подключения от записи и защита производственной среды продолжат действовать.",
+ mcpDatabaseNotDiscovered: "Не найдена при текущем запросе",
+ mcpDatabaseShowMore: "Показать ещё ({shown}/{total})",
+ mcpDatabaseSaveHint: "Сохраняет только область и права баз этого подключения. Остальные несохранённые изменения остаются.",
+ mcpDatabaseApply: "Применить права баз",
+ mcpAccessTreePickDatabases: "Выбрать базы данных",
+ mcpAccessTreePickerTitle: "Базы данных of {name}",
+ mcpAccessTreeLoadingDatabases: "Загрузка баз данных...",
+ mcpAccessTreeLoadDatabasesFailed: "Не удалось загрузить базы данных: {error}. Имена по-прежнему можно добавить вручную.",
+ mcpAccessTreeManualDatabase: "Добавить имя базы данных",
+ mcpAccessTreeNoMatch: "Нет подходящих ресурсов",
+ mcpAccessTreeEmpty: "Подключений пока нет",
+ mcpAccessTreeFootnote: "Priority: database > connection > closest group > parent group > глобальный параметр. Connection read-only protection, production protection and database credentials always apply on top.",
+ mcpAccessTreeNacosNamespace: "Пространство имён",
+ mcpPluginScopeAll: "Все ({title})",
+ mcpPluginScopeSelected: "Выбрано ({count})",
+ mcpPluginScopeNone: "Нет {title}",
+ mcpPluginScopeAdd: "Добавить: {title}",
+ mcpBrowser: {
+ viewMode: "Режим просмотра",
+ viewManage: "Управление категориями",
+ viewOverview: "Общий обзор",
+ overviewSummary: "Наборов инструментов: {toolsets} · Инструментов: {total} · Включено: {enabled}",
+ overviewPluginsHint: "Просмотрите инструменты и авторизацию плагина. Откройте плагин для подробностей.",
+ overviewOpenDetails: "Подробнее",
+ expandCategory: "Развернуть категорию",
+ collapseCategory: "Свернуть категорию",
+ builtin: "Встроенные возможности",
+ plugins: "Расширения плагинов",
+ advanced: "Расширенные настройки",
+ navigation: "Категории возможностей",
+ searchPlaceholder: "Поиск категорий, возможностей, плагинов или инструментов…",
+ clearSearch: "Очистить поиск",
+ searchResults: "Результаты поиска",
+ categoryCount: "Наборов инструментов: {count}",
+ summary: "Наборов: {toolsets} · Инструментов: {total} · Включено: {enabled}",
+ enableCategory: "Включить всю категорию",
+ disableCategory: "Отключить всю категорию",
+ draftHint: "Примените набор в его описании или нажмите «Применить» внизу, чтобы сохранить все изменения настроек.",
+ batchChanged: "Инструменты категории изменены. Нажмите «Применить», чтобы сохранить",
+ coverageHint: "Совместимые подключения считаются по типу подключения, а не по фактической области разрешений.",
+ uncovered: "Подключения без поддержки встроенными инструментами: {count}",
+ viewDetails: "Подробнее",
+ emptyEnabled: "В этой категории нет включённых инструментов. Отключите «Показывать только включённые», чтобы настроить их.",
+ retry: "Повторить",
+ enabledToolCount: "Включено: {enabled}/{total}",
+ partialEnabled: "Включено частично",
+ coverageConnections: "Поддерживаемые подключения: {count}",
+ coveragePartialConnections: "Частично поддерживаются: {count}",
+ noMatchingConnections: "Нет подходящих подключений",
+ resourceScopes: "Области ресурсов",
+ pluginImmediate: "Изменения сохраняются сразу, независимо от кнопок «Применить / Отмена» внизу",
+ pluginSaving: "Сохранение…",
+ pluginSaved: "Сохранено",
+ pluginOnlyEnabledEmpty: "Нет включённых инструментов. Отключите «Показывать только включённые», чтобы увидеть их.",
+ pluginUnavailable: "Этот плагин больше недоступен. Обновите список плагинов",
+ resourceKind: {
+ database: "База данных",
+ dbIndex: "Логическая база данных",
+ topic: "Топик",
+ queue: "Очередь",
+ org: "Организация",
+ namespace: "Пространство имён",
+ },
+ category: {
+ database: { title: "Базы данных", description: "Запросы данных, управление сеансами и транзакциями, просмотр структуры объектов и выполнение команд Redis." },
+ nacos: { title: "Nacos", description: "Управление конфигурациями, сервисами и экземплярами." },
+ consul: { title: "Consul", description: "Управление KV, обнаружение сервисов и проверка их состояния." },
+ mq: { title: "Очереди сообщений", description: "Чтение и отправка сообщений." },
+ salesforce: { title: "Salesforce", description: "Просмотр сведений о пользователе и операции с данными." },
+ dbx: { title: "Общие функции DBX", description: "Общие для продуктов возможности: обнаружение подключений, интеграция с рабочей областью, управление подключениями, обнаружение и вызов плагинов." },
+ other: { title: "Другие возможности", description: "Просмотр и настройка наборов инструментов, ещё не отнесённых к категории." },
+ },
+ },
+ mcpCapabilitiesTitle: "Возможности MCP",
+ mcpCapabilitiesDescription: "Встроенные Инструменты MCP grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the типов баз данных it applies to.",
+ mcpCapabilitiesLoading: "Загрузка возможностей MCP...",
+ mcpCapabilitiesLoadFailed: "Failed to load Возможности MCP: {error}",
+ mcpCapabilitiesSearchPlaceholder: "Поиск возможностей или инструментов",
+ mcpCapabilitiesSearchEmpty: "Подходящих возможностей нет",
+ mcpToolsetToolCount: "Инструментов: {enabled}/{total}",
+ mcpAccessLevelClassified: "Для каждого вызова",
+ mcpCoverageTypes: "{count} типов баз данных",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Не связано с подключением",
+ mcpCoverageUsableConnections: "Используется вашими подключениями: {count}",
+ mcpCoverageNoUsableConnections: "Ни одно из ваших подключений не использует этот набор",
+ mcpCoveragePartialConnections: "Только часть инструментов поддерживается подключениями: {count}",
+ mcpCoverageUncoveredConnections: "{count} connections have no Инструменты MCP yet: {names}",
+ mcpCoverageSearchPlaceholder: "Search типов баз данных",
+ mcpCoverageSearchEmpty: "Нет matching типов баз данных",
+ mcpCoverageLegend: "Показаны только поддерживаемые типы. Выделенные типы соответствуют вашим подключениям; * означает, что некоторые инструменты группы не поддерживают тип (наведите указатель для подробностей).",
+ mcpCoverageTypeUnsupportedTool: "Не поддерживается инструментом {tool}",
+ mcpCoverageCategoryOther: "Другое",
+ mcpCoveragePartialTool: "{tool}: поддерживается {count} из {total}",
+ mcpToolDetailSkippedConnections: "Недоступно для: {names}",
+ mcpToolDetailCoverage: "Supported типов баз данных ({count})",
+ mcpToolDetailParameterDefault: "по умолчанию: {value}",
+ mcpToolDetailParameterDescription: "Описание",
+ mcpToolDetailParameterRequiredNo: "Нет",
+ mcpToolDetailParameterRequiredYes: "Да",
+ mcpToolDetailParameterRequired: "Обязательно",
+ mcpToolDetailParameterType: "Тип",
+ mcpToolDetailParameterName: "Имя",
+ mcpToolDetailNoParameters: "Нет параметров",
+ mcpToolDetailParameters: "Параметры",
+ mcpToolDetailDescription: "Описание для модели",
+ mcpToolDetailAccessClassified: "Классифицируется при каждом вызове (чтение, запись или высокий риск по инструкции)",
+ mcpToolDetailAccess: "Уровень доступа",
+ mcpToolDetailSummary: "Сводка",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "Не поддерживается вашими подключениями: {count}",
+ mcpToolsetDetailTools: "Инструменты",
+ mcpToolsetDetailCoverage: "Охват",
+ mcpToolsetApply: "Применить этот набор",
+ mcpToolsetApplying: "Применение…",
+ mcpToolsetPending: "Не применено изменений инструментов: {count}",
+ mcpToolsetApplied: "Текущие настройки применены",
+ mcpToolsetCloseKeepsDraft: "При закрытии изменения остаются в черновике. Их также можно применить в настройках.",
+ mcpToolsetApplyFailed: "Не удалось применить: {error}. Изменения сохранены в черновике; повторите попытку.",
+ mcpToolsetApplyUnavailable: "Настройки инструментов сейчас недоступны. Дождитесь загрузки или повторите попытку.",
+ mcpToolsetDetailClose: "Закрыть",
+ mcpPluginToolEntriesTitle: "Плагин tool entries",
+ mcpPluginsTitle: "Плагины",
+ mcpPluginsDescription: "Плагины that provide Инструменты MCP. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "Обновить",
+ mcpPluginsLoading: "Загрузка инструментов плагина...",
+ mcpPluginsLoadFailed: "Не удалось загрузить инструменты плагинов: {error}",
+ mcpPluginsEmpty: "Установленные плагины не предоставляют инструменты MCP.",
+ mcpPluginSaveFailed: "Не удалось сохранить {name}: {message}",
+ mcpPluginAuthorClosed: "Автор не открыл доступ для внешнего MCP",
+ mcpPluginDiscoveryFailed: "Не удалось обнаружить инструменты",
+ mcpPluginToolCount: "Доступно инструментов: {exposed}/{total}",
+ mcpPluginToolCountOff: "Инструментов: {total}, отключены",
+ mcpPluginCeilingSummary: "Предел: {level}",
+ mcpPluginPendingTools: "Новые инструменты требуют подтверждения: {count}",
+ mcpPluginReview: "Проверить",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Не удалось обнаружить инструменты: {error}",
+ mcpPluginCeilingTitle: "Предел авторизации",
+ mcpPluginCeilingDescription: "Инструменты выше предела скрыты от клиентов MCP. Вызовы также должны соответствовать правам ресурсов и правилам видимости подключений.",
+ mcpPluginEnableFirst: "Включите плагин, чтобы изменить предел прав и инструменты.",
+ mcpPluginDefaultToolset: "Инструменты",
+ mcpPluginNoTools: "This plugin lists no Инструменты MCP right now.",
+ mcpPluginAuthorizeTitle: "Авторизовать {name} for MCP",
+ mcpPluginAuthorizeDescription: "Выберите предел прав плагина. Все объявленные ниже инструменты принимаются; добавленные позднее инструменты или инструменты с повышенным объявленным уровнем снова запросят подтверждение, если им нужны права выше чтения.",
+ mcpPluginAuthorizeTools: "Инструменты ({count})",
+ mcpPluginAuthorizeIncluded: "Открыт",
+ mcpPluginAuthorizeExcluded: "Скрыт",
+ mcpPluginAuthorizeFootnote: "Позже можно изменить предел прав или отключить отдельные инструменты в сведениях о плагине.",
+ mcpPluginAccessUndeclared: "Не объявлено автором — never exposed",
+ mcpPluginUndeclaredCount: "Инструменты не объявлены в манифесте и остаются скрытыми: {count}",
+ mcpPluginUndeclaredTools: "У инструментов ({count}) не объявлен уровень доступа в манифесте плагина; они никогда не будут доступны: {names}",
+ mcpPluginAuthorizeCancel: "Отмена",
+ mcpPluginAuthorizeConfirm: "Авторизовать",
+ mcpPluginToolEntriesHint: "Расширенные настройки: разрешённые записи для инструментов плагинов. dbx_*__* разрешает все инструменты плагинов, dbx_<prefix>__* — инструменты одного плагина. Переключатели плагинов определяют доступные инструменты; эти записи задают дополнительный фильтр.",
+ mcpPluginAllowlistBlocked: "В списке разрешённых инструментов MCP нет записей для плагинов, поэтому их инструменты скрыты независимо от переключателей плагинов.",
+ mcpPluginAllowlistAllow: "Разрешить инструменты плагинов",
+ mcpPluginExposure: {
+ exposed: "Открыт",
+ undeclared: "Не объявлен",
+ pluginDisabled: "Плагин выключен",
+ toolDisabled: "Выключен",
+ aboveCeiling: "Выше предела",
+ pendingApproval: "Требует подтверждения",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Только чтение",
+ write: "Чтение и запись",
+ full: "Полный (включая высокий риск)",
+ },
+ mcpAccessLevel: {
+ read: "Чтение",
+ write: "Запись",
+ full: "Высокий риск",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "Обнаружение и контекст", description: "Просмотр подключений и баз данных, получение контекста схемы для модели." },
+ sqlQuery: { title: "SQL-запрос", description: "Выполнение запросов и скриптов. Риск каждой инструкции определяется при вызове." },
+ sqlSession: { title: "Сеансы и транзакции", description: "Сохранение одной сессии между вызовами и управление транзакциями." },
+ sqlSchema: { title: "Объекты схемы", description: "Просмотр таблиц, столбцов и исходного кода процедур." },
+ redis: { title: "Команды Redis", description: "Выполнение команд Redis." },
+ mq: { title: "Чтение и отправка сообщений", description: "Чтение и отправка сообщений Kafka, RocketMQ и RabbitMQ." },
+ salesforce: { title: "Сведения о пользователе и операции с данными", description: "Определение текущего пользователя и запись отдельных записей." },
+ workbench: { title: "Рабочая область", description: "Открытие таблиц и показ результатов запросов в DBX." },
+ adminConnections: { title: "Управление подключениями", description: "Добавление, копирование и удаление подключений DBX." },
+ pluginRouter: { title: "Обнаружение и вызов плагинов", description: "Поиск инструментов плагинов по запросу и вызов через единый маршрутизатор." },
+ nacosConfig: { title: "Управление конфигурациями", description: "Чтение, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "Управление сервисами", description: "Просмотр служб и экземпляров; включение, отключение и изменение веса экземпляров." },
+ consulKv: { title: "Управление KV", description: "Просмотр, чтение, запись и удаление ключей Consul KV с проверкой и заменой (CAS)." },
+ consulService: { title: "Обнаружение и состояние сервисов", description: "Каталог служб и узлов, состояние служб и режим обслуживания." },
+ },
+ mcpToolNacosListNamespaces: "Список пространств имён Nacos",
+ mcpToolNacosListConfigs: "Список конфигураций Nacos",
+ mcpToolNacosGetConfig: "Читать конфигурацию Nacos",
+ mcpToolNacosConfigHistory: "История конфигурации Nacos",
+ mcpToolNacosPublishConfig: "Опубликовать конфигурацию Nacos",
+ mcpToolNacosDeleteConfig: "Удалить конфигурацию Nacos",
+ mcpToolNacosListServices: "Список сервисов Nacos",
+ mcpToolNacosListInstances: "Список экземпляров Nacos",
+ mcpToolNacosUpdateInstance: "Обновить экземпляр Nacos",
+ mcpToolNacosSearchConfigs: "Поиск конфигураций Nacos",
+ mcpToolNacosRollbackConfig: "Откат конфигурации Nacos",
+ mcpToolNacosGetService: "Просмотр службы Nacos",
+ mcpToolNacosRegisterInstance: "Регистрация экземпляра Nacos",
+ mcpToolNacosDeregisterInstance: "Отмена регистрации экземпляра Nacos",
+ mcpToolConsulKvList: "Список ключей Consul KV",
+ mcpToolConsulKvGet: "Читать ключ Consul KV",
+ mcpToolConsulKvPut: "Записать ключ Consul KV",
+ mcpToolConsulKvDelete: "Удалить ключ Consul KV",
+ mcpToolConsulListServices: "Список сервисов Consul",
+ mcpToolConsulListNodes: "Список узлов Consul",
+ mcpToolConsulServiceHealth: "Состояние сервиса Consul",
+ mcpToolConsulSetMaintenance: "Режим обслуживания Consul",
mcpConfigOptionsHint:
"DBX централизованно управляет доступом к подключениям и разрешениями на выполнение для каждого клиента MCP. Созданные конфигурации содержат только параметры среды выполнения, необходимые для запуска сервера MCP и подключения к этому экземпляру DBX, без переменных разрешений или области подключений.",
mcpScopeConnection: "Подключения, разрешённые для MCP",
@@ -11291,7 +11600,8 @@ export default withEnglishFallback({
mcpOpenCodeConfigPath: "~/.config/opencode/opencode.json глобально или opencode.json на уровне проекта.",
mcpPiConfigPath: "Сначала установите плагин адаптера Pi MCP: pi install npm:pi-mcp-adapter. Затем сохраните в ~/.pi/agent/mcp.json (глобально) или .mcp.json (проект), выполните /mcp для проверки и /reload, чтобы применить в Pi.",
mcpExecutionMode: "Глобальное разрешение MCP по умолчанию",
- mcpExecutionModeDescription: "Задаёт значение по умолчанию, используемое, когда разрешение для подключения или базы данных не настроено. Значения по умолчанию для подключений и параметры баз данных могут переопределять его по области.",
+ mcpExecutionModeDescription: "Ресурсы без собственных разрешений используют это значение по умолчанию. Другие разрешения можно задать в разделе управления доступом ниже.",
+ mcpPermissionsDraftHint: "Глобальные права, группы и подключения сохраняются кнопкой «Применить» внизу. Права баз можно применить в их диалоге. Подобласти сохраняются сразу. Отмена черновиков не отменяет сохранённые изменения.",
mcpExecutionModeReadOnly: "Только чтение",
mcpExecutionModeSafeWrite: "Чтение/запись данных",
mcpExecutionModeRecommended: "Рекомендуется",
@@ -11300,21 +11610,21 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "Разрешает обычные INSERT, UPDATE/DELETE с фильтром, проверяемо ограниченные изменения MongoDB и обычные записи Redis или удаление по явному ключу; блокирует изменения всей таблицы и структурные изменения.",
mcpExecutionModeHighRiskWriteDescription: "Помимо чтения/записи данных разрешает изменения всей таблицы, DDL, TRUNCATE, очистку базы данных и другие операции высокого риска. Защита продакшена и подключений только для чтения по-прежнему действует.",
mcpExecutionModeHighRiskConfirm: "Полный доступ разрешает изменения всей таблицы, DDL, TRUNCATE, очистку базы данных и другие операции высокого риска. Включить его?",
- mcpPromptHighRiskSql: "Запрашивать подтверждение для SQL высокого риска (только настольная версия; защита от записи и для рабочих баз сохраняется)",
mcpSqlApprovalTitle: "Подтверждение SQL высокого риска для MCP",
mcpSqlApprovalScope: "Подключение: {connection} · База данных: {database}",
mcpSqlApprovalOnce: "Только этот запрос",
mcpSqlApprovalHour: "Разрешить для этой базы на 1 час",
mcpSqlApprovalDay: "Разрешить для этой базы на 1 день",
mcpSqlApprovalDeny: "Отклонить",
- mcpCapabilityTitle: "Сравнение возможностей",
- mcpCapabilityDescription: "Это типовые операции; запросы, которые DBX не может надёжно классифицировать, требуют полного доступа.",
+ mcpCapabilityTitle: "Описание разрешений",
+ mcpCapabilityDescription: "Таблица описывает права; инструменты также нужно включить в Возможностях. Недостаточные права отклоняются. Безопасность вызовов отдельно управляет подтверждениями и описывает прежние разрешения.",
mcpCapabilityOperation: "Возможность",
mcpCapabilityRead: "Запросы и чтение",
mcpCapabilityScopedMutation: "Ограниченные изменения данных (INSERT, UPDATE/DELETE с фильтром, запись/удаление по явному ключу)",
mcpCapabilityBroadMutation: "Обновление/удаление всей таблицы и очистка данных",
mcpCapabilitySchemaAdmin: "DDL, структурные изменения и администрирование высокого риска",
- mcpCapabilityConnectionManagement: "Добавление/удаление подключений MCP",
+ mcpCapabilityConnectionCreate: "Добавление/копирование подключений MCP (глобальное разрешение по умолчанию)",
+ mcpCapabilityConnectionRemove: "Удаление подключений MCP (глобальное разрешение по умолчанию)",
mcpCapabilityAllowed: "Разрешено",
mcpCapabilityBlocked: "Заблокировано",
mcpQueryTimeout: "Тайм-аут запроса (секунды)",
@@ -11325,6 +11635,9 @@ export default withEnglishFallback({
mcpQueryTimeoutSaveStatus_failed: "Не удалось сохранить",
mcpCapabilityAlwaysEnforced: "Каждый режим по-прежнему подчиняется списку разрешённых подключений, защите подключения только для чтения, защите продакшена и разрешениям учётной записи базы данных.",
mcpPolicySaveFailed: "Не удалось сохранить политику доступа MCP: {error}",
+ mcpPolicyRetry: "Повторить",
+ mcpPolicyRecover: "Создать резервную копию и сбросить разрешения MCP",
+ mcpPolicyRecoverConfirm: "Будет немедленно создана резервная копия повреждённой политики и выполнен сброс разрешений MCP, включая несохранённые изменения. Все подключения и инструменты будут заблокированы до повторной настройки. Продолжить?",
mcpPolicyLoadFailed: "Не удалось загрузить политику доступа MCP: {error}",
mcpDetectionTiming: "DBX проверяет автоматически при открытии этой страницы; нажмите «Проверить снова», чтобы обновить.",
mcpNpmBoundary: "DBX проверяет состояние MCP; установка, обновление и удаление выполняются через обнаруженную среду выполнения npm, pnpm или bun.",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 0b4c9a8c74..ad00edb67d 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -666,6 +666,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: '"{name}" ต้องการอ่านข้อมูลจากการเชื่อมต่อ "{connection}" ขณะที่การเชื่อมต่อนี้เปิดอยู่ Plugin จะเรียกใช้ Query แบบอ่านอย่างเดียวกับการเชื่อมต่อนี้ได้จนกว่าคุณจะเพิกถอนสิทธิ์ใน Plugin Center อนุญาตหรือไม่?',
dataAccessConsentTitle: "คำขอเข้าถึงข้อมูล",
+ mcpToolsBadge: "เครื่องมือ MCP",
+ mcpToolsBadgeHint: "This plugin provides เครื่องมือ MCP. Enable and authorize them in Settings → MCP → ความสามารถ.",
+ mcpToolsFilter: "Only plugins with เครื่องมือ MCP ({count})",
+ externalMcp: {
+ title: "Client MCP ภายนอก",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → ความสามารถ.",
+ notOffered: "ผู้เขียนยังไม่ได้เปิดเครื่องมือของปลั๊กอินนี้ให้ไคลเอนต์ MCP ภายนอกใช้งาน",
+ },
aiTools: {
title: "เครื่องมือ AI ในตัว",
description: "ปิดไว้เป็นค่าเริ่มต้น: ผู้ช่วย AI ของ DBX (โหมด Agent) เรียกใช้เครื่องมือของ Plugin นี้กับการเชื่อมต่อที่เปิดอยู่ได้เฉพาะเมื่อเปิดสวิตช์นี้ เครื่องมือที่ไม่ได้ประกาศว่าอ่านอย่างเดียวจะขออนุมัติจากคุณก่อนการเรียกใช้ทุกครั้ง",
@@ -8990,6 +8998,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "MCP Tool",
+ mcpClient: "Client MCP",
+ mcpTransport: "การรับส่ง MCP",
+ mcpAccess: "สิทธิ์เข้าถึง MCP",
+ mcpConfirmation: "การยืนยัน MCP",
kind: "ชนิด",
operation: "Operation",
connection: "การเชื่อมต่อ",
@@ -11615,6 +11627,303 @@ export default withEnglishFallback({
mcpUninstallConfirm: "ถอนการติดตั้ง DBX MCP Server หรือไม่ Client MCP ที่กำหนดค่าจะไม่สามารถเริ่มใช้งานได้อีก",
mcpUninstallFailed: "ถอนการติดตั้งไม่สำเร็จ: {error}",
mcpConfig: "การกำหนดค่า MCP",
+ mcpCapabilitiesFilterLabel: "ตัวกรองความสามารถ",
+ mcpCapabilitiesFilterAll: "ทั้งหมด",
+ mcpCapabilitiesFilterBuiltin: "ในตัว",
+ mcpCapabilitiesFilterPlugin: "ปลั๊กอิน",
+ mcpCapabilitiesOnlyEnabled: "แสดงเฉพาะที่เปิดใช้",
+ mcpPluginScopeLoad: "อ่านจากปลั๊กอิน",
+ mcpPluginToolsMode: "วิธีให้บริการเครื่องมือปลั๊กอินแก่ภายนอก",
+ mcpPluginToolsModeDescription: "เลือกวิธีที่ DBX ให้บริการเครื่องมือปลั๊กอินที่ได้รับอนุญาตแก่ไคลเอนต์ MCP คลิกนำไปใช้ด้านล่างเพื่อบันทึกการเปลี่ยนแปลง",
+ mcpPluginToolsModeAuto: "อัตโนมัติ (โหมดความเข้ากันได้)",
+ mcpPluginToolsModeFlat: "แสดงโดยตรง (ค่าเริ่มต้น)",
+ mcpPluginToolsModeLazy: "ค้นหาเมื่อร้องขอ",
+ mcpPluginToolsModeFlatDescription: "แสดงเครื่องมือปลั๊กอินที่ได้รับอนุญาตแต่ละรายการเพื่อให้ไคลเอนต์เรียกใช้ได้โดยตรง",
+ mcpPluginToolsModeLazyDescription: "ให้บริการเครื่องมือค้นหาและเรียกใช้ปลั๊กอินร่วมกัน โดยดึงรายละเอียดเมื่อต้องการใช้งาน เปิดการค้นหาและเรียกใช้ปลั๊กอินใน DBX ทั่วไป",
+ mcpPluginToolsModeAutoDescription: "คงพฤติกรรมอัตโนมัติเดิม: แสดงโดยตรงเมื่อมีเครื่องมือปลั๊กอินรวมไม่เกิน 40 รายการ หากมากกว่านั้นจะใช้การค้นหาเมื่อต้องการ",
+ mcpCallSafety: "ความปลอดภัยในการเรียกใช้",
+ mcpCallSafetyLegacy: "การอนุญาตชั่วคราวแบบเดิม",
+ mcpCallSafetyEnabled: "ยืนยันทุกการเรียกใช้ที่เสี่ยงสูง",
+ mcpCallSafetyDisabled: "ไม่ขอการยืนยันเพิ่มเติม",
+ mcpCallSafetyLegacyHint: "คงพฤติกรรมเดิมไว้: สิทธิ์เขียนข้อมูลอนุญาตงานเสี่ยงสูงบางอย่างชั่วคราวหลังยืนยัน ส่วนสิทธิ์เต็มไม่ถาม นโยบายใหม่ปฏิเสธเมื่อสิทธิ์ไม่พอ และขอยืนยันงานเสี่ยงสูงแม้มีสิทธิ์เต็ม",
+ mcpCallSafetyMigrate: "ใช้นโยบายการยืนยันใหม่",
+ mcpCallSafetyDisableLegacy: "ปิดการอนุญาตแบบเดิม",
+ mcpCallSafetyConfirm: "ขอผู้ใช้ยืนยันก่อนเรียกใช้เครื่องมือที่เสี่ยงสูง",
+ mcpCallSafetyHint: "ใช้กับการเรียกใช้เครื่องมือในตัวและปลั๊กอินที่ระบุว่าเสี่ยงสูง ตรวจสิทธิ์ก่อน รวมถึงสิทธิ์เต็ม การยืนยันไม่เพิ่มสิทธิ์",
+ mcpCallSafetyDesktopHint: "ต้องใช้ DBX เดสก์ท็อปและอนุมัติเฉพาะการเรียกใช้ปัจจุบัน หากยืนยันไม่ได้ ปฏิเสธ หรือหมดเวลา จะไม่ทำงาน การป้องกันอ่านอย่างเดียวและระบบจริงยังมีผล กดนำไปใช้เพื่อบันทึก",
+ mcpToolApprovalGenericTitle: "ยืนยันการเรียกใช้ที่เสี่ยงสูง",
+ mcpToolApprovalPluginTitle: "ยืนยันเครื่องมือความเสี่ยงสูงของ {plugin}",
+ mcpToolApprovalRedisTitle: "ยืนยันคำสั่ง Redis ที่อันตราย",
+ mcpToolApprovalDescription: "An Client MCP wants to run a high-risk operation. Allow it only if you expect this call.",
+ mcpToolApprovalTool: "เครื่องมือ",
+ mcpToolApprovalTarget: "เป้าหมาย",
+ mcpManagementCapabilities: "ความสามารถ",
+ mcpOpenCallHistory: "ดูประวัติการเรียก MCP",
+ mcpAccessTreeTitle: "การควบคุมการเข้าถึง",
+ mcpAccessTreeDescription: "กำหนดสิทธิ์ให้กลุ่ม การเชื่อมต่อ และฐานข้อมูล การสืบทอดใช้ค่าจากระดับบน คอลัมน์สิทธิ์ที่มีผลแสดงสิทธิ์สุดท้ายและที่มา",
+ mcpAccessTreeSummary: "มองเห็นการเชื่อมต่อ {visible}/{total} รายการ · การตั้งค่าเฉพาะ: {groups} กลุ่ม, {connections} การเชื่อมต่อ, {databases} ฐานข้อมูล",
+ mcpAccessTreeScopeLabel: "การมองเห็นการเชื่อมต่อ",
+ mcpAccessTreeScopeAll: "การเชื่อมต่อทั้งหมด",
+ mcpAccessTreeScopeCustom: "เฉพาะที่เลือก",
+ mcpAccessTreeSearchPlaceholder: "ค้นหากลุ่ม การเชื่อมต่อ หรือฐานข้อมูล",
+ mcpAccessTreeExceptionsOnly: "แสดงเฉพาะการตั้งค่าแยก",
+ mcpAccessTreeColumnResource: "ทรัพยากร",
+ mcpAccessTreeColumnVisible: "มองเห็น",
+ mcpAccessTreeColumnSetting: "สิทธิ์",
+ mcpAccessTreeColumnEffective: "มีผล",
+ mcpAccessTreeInherit: "สืบทอด",
+ mcpAccessTreeGroupPartiallyVisible: "มองเห็นบางการเชื่อมต่อ ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "มองเห็นทุกการเชื่อมต่อปัจจุบัน ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "อนุญาตเฉพาะรายการย่อย ยังไม่ได้อนุญาตทั้งกลุ่ม ติ๊กเพื่ออนุญาตทั้งกลุ่ม รวมถึงการเชื่อมต่อที่จะเพิ่มในอนาคต",
+ mcpAccessTreeGroupDefaultHint: "สิทธิ์เริ่มต้นของกลุ่มใช้กับรายการย่อยที่ไม่ได้ตั้งค่าสิทธิ์แยกไว้ โดยไม่เปลี่ยนขอบเขตการมองเห็นการเชื่อมต่อ",
+ mcpAccessTreeHidden: "MCP มองไม่เห็น",
+ mcpAccessTreeSourceGlobal: "ค่าเริ่มต้นส่วนกลาง",
+ mcpAccessTreeSourceGroup: "จากกลุ่ม {group}",
+ mcpAccessTreeSourceConnection: "การตั้งค่าการเชื่อมต่อ",
+ mcpAccessTreeSourceDatabase: "การตั้งค่าฐานข้อมูล",
+ mcpAccessTreeGroupCount: "{count} การเชื่อมต่อ",
+ mcpAccessTreeLegacy: "รูปแบบเดิม",
+ mcpAccessTreeLegacyHint: "บันทึกโดยเวอร์ชันเก่า: จำกัดสิทธิ์ที่การเชื่อมต่อสืบทอดได้เท่านั้น เลือกสิทธิ์อีกครั้งเพื่อเปลี่ยนเป็นการตั้งค่าปกติ",
+ mcpAccessTreeCoveredByGroup: "มองเห็น through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "ความเสี่ยงสูง allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "ฐานข้อมูล",
+ mcpAccessTreeDatabaseScopeAll: "ฐานข้อมูลทั้งหมด",
+ mcpAccessTreeDatabaseScopeSelected: "เลือกแล้ว ({count})",
+ mcpAccessTreeDatabaseScopeNone: "ไม่มีฐานข้อมูล",
+ mcpDatabaseRemoveConfirm: "การนำฐานข้อมูลที่เลือกออกจะลบสิทธิ์เฉพาะของฐานข้อมูลเหล่านั้นด้วย ต้องการดำเนินการต่อหรือไม่?",
+ mcpDatabaseUnavailable: "การตั้งค่าสิทธิ์ฐานข้อมูลยังไม่พร้อมใช้งาน โปรดรอให้โหลดเสร็จหรือลองอีกครั้ง",
+ mcpDatabaseConfigure: "ตั้งค่าสิทธิ์ฐานข้อมูล",
+ mcpDatabaseOverrideCount: "สิทธิ์เฉพาะ {count} รายการ",
+ mcpDatabaseDialogTitle: "{name} / สิทธิ์เข้าถึงฐานข้อมูล",
+ mcpDatabaseDialogDescription: "เลือกฐานข้อมูลและกำหนดสิทธิ์ การย้ายไปด้านขวาจะมีผลเมื่อกดใช้เท่านั้น",
+ mcpDatabaseInherited: "สิทธิ์ที่สืบทอด: {level}",
+ mcpDatabaseSavedInherited: "สิทธิ์ระดับบนมีการเปลี่ยนแปลงที่ยังไม่ใช้ การใช้เฉพาะสิทธิ์ฐานข้อมูลจะยังสืบทอดสิทธิ์ที่บันทึกไว้: {level}",
+ mcpDatabaseHiddenConnection: "การเชื่อมต่อนี้ถูกซ่อนจาก MCP การใช้สิทธิ์ฐานข้อมูลจะไม่เปิดเผยการเชื่อมต่อ",
+ mcpDatabaseAllHint: "รวมฐานข้อมูลปัจจุบันและที่จะเพิ่มในอนาคต โดยใช้สิทธิ์ของการเชื่อมต่อ",
+ mcpDatabaseNoneHint: "เมื่อใช้ จะไม่อนุญาตให้เข้าถึงฐานข้อมูลใด ๆ",
+ mcpDatabaseLoaded: "โหลดฐานข้อมูลที่บัญชีนี้มองเห็นแล้ว {count} รายการ",
+ mcpDatabaseRefresh: "รีเฟรชรายการ",
+ mcpDatabaseAddSelected: "เพิ่ม →",
+ mcpDatabaseRemoveSelected: "← นำออก",
+ mcpDatabaseAvailable: "ยังไม่เลือก ({count})",
+ mcpDatabaseSelected: "เลือกแล้ว ({count})",
+ mcpDatabaseSearch: "ค้นหาชื่อฐานข้อมูล",
+ mcpDatabaseSelectResults: "เลือกผลการค้นหาปัจจุบัน ({count})",
+ mcpDatabaseBatchLevel: "ตั้งค่าสิทธิ์รายการที่ติ๊ก ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "อนุญาตให้เข้าถึงฐานข้อมูลที่ติ๊กไว้ {count} รายการได้อย่างเต็มรูปแบบหรือไม่? การป้องกันแบบอ่านอย่างเดียวของการเชื่อมต่อและการป้องกันระบบใช้งานจริงยังคงมีผล",
+ mcpDatabaseNotDiscovered: "ไม่พบในรายการครั้งนี้",
+ mcpDatabaseShowMore: "แสดงเพิ่มเติม ({shown}/{total})",
+ mcpDatabaseSaveHint: "บันทึกเฉพาะขอบเขตและสิทธิ์ฐานข้อมูลของการเชื่อมต่อนี้ โดยเก็บการเปลี่ยนแปลงอื่นที่ยังไม่บันทึกไว้",
+ mcpDatabaseApply: "ใช้สิทธิ์ฐานข้อมูล",
+ mcpAccessTreePickDatabases: "เลือกฐานข้อมูล",
+ mcpAccessTreePickerTitle: "ฐานข้อมูล of {name}",
+ mcpAccessTreeLoadingDatabases: "กำลังโหลดฐานข้อมูล…",
+ mcpAccessTreeLoadDatabasesFailed: "โหลดฐานข้อมูลไม่สำเร็จ: {error} คุณยังเพิ่มชื่อด้วยตนเองได้",
+ mcpAccessTreeManualDatabase: "เพิ่มชื่อฐานข้อมูล",
+ mcpAccessTreeNoMatch: "ไม่พบทรัพยากรที่ตรงกัน",
+ mcpAccessTreeEmpty: "ยังไม่มีการเชื่อมต่อ",
+ mcpAccessTreeFootnote: "ลำดับความสำคัญ: ฐานข้อมูล > การเชื่อมต่อ > กลุ่มที่ใกล้ที่สุด > กลุ่มแม่ > ค่าเริ่มต้นส่วนกลาง การป้องกันแบบอ่านอย่างเดียว การป้องกันระบบจริง และสิทธิ์บัญชีฐานข้อมูลยังคงมีผลเสมอ",
+ mcpAccessTreeNacosNamespace: "เนมสเปซ",
+ mcpPluginScopeAll: "ทั้งหมด ({title})",
+ mcpPluginScopeSelected: "เลือกแล้ว ({count})",
+ mcpPluginScopeNone: "ไม่ {title}",
+ mcpPluginScopeAdd: "เพิ่ม {title}",
+ mcpBrowser: {
+ viewMode: "โหมดการดู",
+ viewManage: "การจัดการหมวดหมู่",
+ viewOverview: "ภาพรวมทั้งหมด",
+ overviewSummary: "{toolsets} ชุดเครื่องมือ · {total} เครื่องมือ · เปิดใช้ {enabled} รายการ",
+ overviewPluginsHint: "ตรวจสอบเครื่องมือและการอนุญาตของปลั๊กอิน เปิดปลั๊กอินเพื่อดูรายละเอียด",
+ overviewOpenDetails: "ดูรายละเอียด",
+ expandCategory: "ขยายหมวดหมู่",
+ collapseCategory: "ยุบหมวดหมู่",
+ builtin: "ความสามารถในตัว",
+ plugins: "ส่วนขยายปลั๊กอิน",
+ advanced: "การตั้งค่าขั้นสูง",
+ navigation: "หมวดหมู่ความสามารถ",
+ searchPlaceholder: "ค้นหาหมวดหมู่ ความสามารถ ปลั๊กอิน หรือเครื่องมือ…",
+ clearSearch: "ล้างการค้นหา",
+ searchResults: "ผลการค้นหา",
+ categoryCount: "ชุดเครื่องมือ {count} ชุด",
+ summary: "{toolsets} ชุดเครื่องมือ · {total} เครื่องมือ · เปิดใช้ {enabled} รายการ",
+ enableCategory: "เปิดใช้ทั้งหมดในหมวดนี้",
+ disableCategory: "ปิดใช้ทั้งหมดในหมวดนี้",
+ draftHint: "ใช้การเปลี่ยนแปลงกับชุดเครื่องมือในหน้ารายละเอียด หรือกดใช้ด้านล่างเพื่อบันทึกการตั้งค่าที่ค้างอยู่ทั้งหมด",
+ batchChanged: "แก้ไขเครื่องมือในหมวดนี้แล้ว คลิก “นำไปใช้” เพื่อบันทึก",
+ coverageHint: "นับการเชื่อมต่อที่รองรับตามประเภทการเชื่อมต่อ ไม่ใช่ขอบเขตสิทธิ์ที่ได้รับจริง",
+ uncovered: "การเชื่อมต่อ {count} รายการยังไม่มีเครื่องมือในตัวรองรับ",
+ viewDetails: "ดูรายละเอียด",
+ emptyEnabled: "ไม่มีเครื่องมือที่เปิดใช้ในหมวดนี้ ปิด “แสดงเฉพาะที่เปิดใช้” เพื่อตั้งค่า",
+ retry: "ลองอีกครั้ง",
+ enabledToolCount: "เปิดใช้ {enabled}/{total}",
+ partialEnabled: "เปิดใช้บางส่วน",
+ coverageConnections: "รองรับการเชื่อมต่อ {count} รายการ",
+ coveragePartialConnections: "รองรับบางส่วน {count} รายการ",
+ noMatchingConnections: "ไม่มีการเชื่อมต่อที่รองรับ",
+ resourceScopes: "ขอบเขตทรัพยากร",
+ pluginImmediate: "การเปลี่ยนแปลงจะบันทึกทันที โดยไม่ขึ้นกับ “นำไปใช้ / ยกเลิก” ด้านล่าง",
+ pluginSaving: "กำลังบันทึก…",
+ pluginSaved: "บันทึกแล้ว",
+ pluginOnlyEnabledEmpty: "ไม่มีเครื่องมือที่เปิดใช้ ปิด “แสดงเฉพาะที่เปิดใช้” เพื่อดูทั้งหมด",
+ pluginUnavailable: "ปลั๊กอินนี้ไม่พร้อมใช้งานแล้ว โปรดรีเฟรชรายการปลั๊กอิน",
+ resourceKind: {
+ database: "ฐานข้อมูล",
+ dbIndex: "ฐานข้อมูลเชิงตรรกะ",
+ topic: "หัวข้อ",
+ queue: "คิว",
+ org: "องค์กร",
+ namespace: "เนมสเปซ",
+ },
+ category: {
+ database: { title: "ฐานข้อมูล", description: "สืบค้นข้อมูล จัดการเซสชันและธุรกรรม ดูโครงสร้างออบเจ็กต์ และเรียกใช้คำสั่ง Redis" },
+ nacos: { title: "Nacos", description: "จัดการการกำหนดค่า บริการ และอินสแตนซ์" },
+ consul: { title: "Consul", description: "จัดการรายการ KV ค้นหาบริการ และดูสถานะความพร้อมใช้งาน" },
+ mq: { title: "คิวข้อความ", description: "อ่านและส่งข้อความ" },
+ salesforce: { title: "Salesforce", description: "ค้นหาข้อมูลตัวตนและดำเนินการกับข้อมูล" },
+ dbx: { title: "DBX ส่วนกลาง", description: "ความสามารถที่ใช้ร่วมกันข้ามผลิตภัณฑ์: ค้นหาการเชื่อมต่อ เชื่อมกับพื้นที่ทำงาน จัดการการเชื่อมต่อ รวมถึงค้นหาและเรียกใช้ปลั๊กอิน" },
+ other: { title: "ความสามารถอื่น ๆ", description: "ดูและตั้งค่าชุดเครื่องมือที่ยังไม่ได้จัดหมวดหมู่" },
+ },
+ },
+ mcpCapabilitiesTitle: "ความสามารถของ MCP",
+ mcpCapabilitiesDescription: "ในตัว เครื่องมือ MCP grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the database types it applies to.",
+ mcpCapabilitiesLoading: "กำลังโหลดความสามารถ MCP…",
+ mcpCapabilitiesLoadFailed: "Failed to load ความสามารถของ MCP: {error}",
+ mcpCapabilitiesSearchPlaceholder: "ค้นหาความสามารถหรือเครื่องมือ",
+ mcpCapabilitiesSearchEmpty: "ไม่พบความสามารถที่ตรงกัน",
+ mcpToolsetToolCount: "{enabled}/{total} เครื่องมือ",
+ mcpAccessLevelClassified: "ต่อการเรียก",
+ mcpCoverageTypes: "ฐานข้อมูล {count} ประเภท",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "ไม่ผูกกับการเชื่อมต่อ",
+ mcpCoverageUsableConnections: "ใช้ได้กับการเชื่อมต่อของคุณ {count} รายการ",
+ mcpCoverageNoUsableConnections: "ไม่มีการเชื่อมต่อของคุณที่ใช้งานได้",
+ mcpCoveragePartialConnections: "การเชื่อมต่อ {count} รายการรองรับเพียงบางเครื่องมือ",
+ mcpCoverageUncoveredConnections: "{count} connections have no เครื่องมือ MCP yet: {names}",
+ mcpCoverageSearchPlaceholder: "ค้นหาประเภทฐานข้อมูล",
+ mcpCoverageSearchEmpty: "ไม่ matching database types",
+ mcpCoverageLegend: "แสดงเฉพาะประเภทที่รองรับ ประเภทที่เน้นตรงกับการเชื่อมต่อของคุณ; * หมายถึงบางเครื่องมือในกลุ่มไม่รองรับประเภทนั้น (ชี้เมาส์เพื่อดูรายละเอียด)",
+ mcpCoverageTypeUnsupportedTool: "{tool} ไม่รองรับ",
+ mcpCoverageCategoryOther: "อื่น ๆ",
+ mcpCoveragePartialTool: "{tool} รองรับ {count} จาก {total}",
+ mcpToolDetailSkippedConnections: "ใช้งานไม่ได้กับ: {names}",
+ mcpToolDetailCoverage: "ประเภทฐานข้อมูลที่รองรับ ({count})",
+ mcpToolDetailParameterDefault: "ค่าเริ่มต้น: {value}",
+ mcpToolDetailParameterDescription: "คำอธิบาย",
+ mcpToolDetailParameterRequiredNo: "ไม่",
+ mcpToolDetailParameterRequiredYes: "ใช่",
+ mcpToolDetailParameterRequired: "จำเป็น",
+ mcpToolDetailParameterType: "ประเภท",
+ mcpToolDetailParameterName: "ชื่อ",
+ mcpToolDetailNoParameters: "ไม่มีพารามิเตอร์",
+ mcpToolDetailParameters: "พารามิเตอร์",
+ mcpToolDetailDescription: "คำอธิบายสำหรับโมเดล",
+ mcpToolDetailAccessClassified: "จำแนกในแต่ละการเรียก (อ่าน เขียน หรือความเสี่ยงสูงตามคำสั่ง)",
+ mcpToolDetailAccess: "ระดับการเข้าถึง",
+ mcpToolDetailSummary: "สรุป",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "การเชื่อมต่อของคุณ {count} รายการไม่สามารถใช้งานได้",
+ mcpToolsetDetailTools: "เครื่องมือ",
+ mcpToolsetDetailCoverage: "ขอบเขตที่รองรับ",
+ mcpToolsetApply: "ใช้การเปลี่ยนแปลงกับชุดนี้",
+ mcpToolsetApplying: "กำลังใช้การเปลี่ยนแปลง…",
+ mcpToolsetPending: "การเปลี่ยนแปลงเครื่องมือ {count} รายการยังไม่มีผล",
+ mcpToolsetApplied: "การตั้งค่าปัจจุบันมีผลแล้ว",
+ mcpToolsetCloseKeepsDraft: "เมื่อปิด การเปลี่ยนแปลงจะยังอยู่ คุณสามารถใช้การเปลี่ยนแปลงจากหน้าการตั้งค่าได้เช่นกัน",
+ mcpToolsetApplyFailed: "ใช้การเปลี่ยนแปลงไม่สำเร็จ: {error} การเปลี่ยนแปลงยังอยู่ โปรดลองอีกครั้ง",
+ mcpToolsetApplyUnavailable: "ยังตั้งค่าเครื่องมือไม่ได้ โปรดรอให้โหลดเสร็จหรือลองอีกครั้ง",
+ mcpToolsetDetailClose: "ปิด",
+ mcpPluginToolEntriesTitle: "ปลั๊กอิน tool entries",
+ mcpPluginsTitle: "ปลั๊กอิน",
+ mcpPluginsDescription: "ปลั๊กอิน that provide เครื่องมือ MCP. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "รีเฟรช",
+ mcpPluginsLoading: "กำลังโหลดเครื่องมือปลั๊กอิน…",
+ mcpPluginsLoadFailed: "โหลดเครื่องมือปลั๊กอินไม่สำเร็จ: {error}",
+ mcpPluginsEmpty: "ไม่มีปลั๊กอินที่ติดตั้งให้เครื่องมือ MCP",
+ mcpPluginSaveFailed: "บันทึก {name} ไม่สำเร็จ: {message}",
+ mcpPluginAuthorClosed: "ผู้เขียนยังไม่ได้เปิดให้ MCP ภายนอกใช้งาน",
+ mcpPluginDiscoveryFailed: "ค้นหาเครื่องมือล้มเหลว",
+ mcpPluginToolCount: "เปิดเผยเครื่องมือ {exposed}/{total} รายการ",
+ mcpPluginToolCountOff: "{total} เครื่องมือ ปิดอยู่",
+ mcpPluginCeilingSummary: "เพดานสิทธิ์: {level}",
+ mcpPluginPendingTools: "เครื่องมือใหม่ {count} รายการต้องยืนยัน",
+ mcpPluginReview: "ตรวจสอบ",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "ค้นหาเครื่องมือล้มเหลว: {error}",
+ mcpPluginCeilingTitle: "ขีดจำกัดการอนุญาต",
+ mcpPluginCeilingDescription: "เครื่องมือที่เกินเพดานสิทธิ์จะไม่แสดงต่อไคลเอนต์ MCP การเรียกจริงยังต้องเป็นไปตามสิทธิ์ของทรัพยากรและกฎการมองเห็นการเชื่อมต่อ",
+ mcpPluginEnableFirst: "เปิดปลั๊กอินก่อนเพื่อเปลี่ยนเพดานสิทธิ์และเครื่องมือ",
+ mcpPluginDefaultToolset: "เครื่องมือ",
+ mcpPluginNoTools: "This plugin lists no เครื่องมือ MCP right now.",
+ mcpPluginAuthorizeTitle: "อนุญาต {name} for MCP",
+ mcpPluginAuthorizeDescription: "เลือกเพดานสิทธิ์ของปลั๊กอิน เครื่องมือที่ประกาศด้านล่างทั้งหมดจะได้รับการยอมรับ เครื่องมือที่เพิ่มภายหลังหรือมีระดับสิทธิ์ที่ประกาศสูงขึ้นจะขอยืนยันอีกครั้งหากต้องการสิทธิ์มากกว่าการอ่าน",
+ mcpPluginAuthorizeTools: "เครื่องมือ ({count})",
+ mcpPluginAuthorizeIncluded: "เปิดเผย",
+ mcpPluginAuthorizeExcluded: "ซ่อน",
+ mcpPluginAuthorizeFootnote: "คุณสามารถเปลี่ยนเพดานสิทธิ์หรือปิดเครื่องมือแต่ละรายการได้ภายหลังในรายละเอียดปลั๊กอิน",
+ mcpPluginAccessUndeclared: "ไม่ได้ประกาศ by the author — never exposed",
+ mcpPluginUndeclaredCount: "เครื่องมือ {count} รายการไม่ได้ประกาศใน manifest และยังคงถูกซ่อน",
+ mcpPluginUndeclaredTools: "เครื่องมือ {count} รายการไม่ได้ประกาศระดับการเข้าถึงใน manifest ของปลั๊กอินและจะไม่เปิดเผย: {names}",
+ mcpPluginAuthorizeCancel: "ยกเลิก",
+ mcpPluginAuthorizeConfirm: "อนุญาต",
+ mcpPluginToolEntriesHint: "ขั้นสูง: รายการอนุญาตสำหรับเครื่องมือปลั๊กอิน dbx_*__* อนุญาตเครื่องมือปลั๊กอินทั้งหมด และ dbx_<prefix>__* อนุญาตปลั๊กอินหนึ่งตัว สวิตช์ปลั๊กอินกำหนดเครื่องมือที่พร้อมใช้งาน ส่วนรายการนี้เป็นตัวกรองเพิ่มเติม",
+ mcpPluginAllowlistBlocked: "รายการเครื่องมือ MCP ที่อนุญาตไม่มีรายการปลั๊กอิน เครื่องมือปลั๊กอินทั้งหมดจึงถูกซ่อนไม่ว่าสวิตช์ปลั๊กอินจะเป็นอย่างไร",
+ mcpPluginAllowlistAllow: "อนุญาตเครื่องมือปลั๊กอิน",
+ mcpPluginExposure: {
+ exposed: "เปิดเผย",
+ undeclared: "ไม่ได้ประกาศ",
+ pluginDisabled: "ปิดปลั๊กอิน",
+ toolDisabled: "ปิดอยู่",
+ aboveCeiling: "เกินขีดจำกัด",
+ pendingApproval: "ต้องยืนยัน",
+ },
+ mcpPluginCeilingLevel: {
+ read: "อ่านอย่างเดียว",
+ write: "อ่านและเขียน",
+ full: "เต็มรูปแบบ (รวมความเสี่ยงสูง)",
+ },
+ mcpAccessLevel: {
+ read: "อ่าน",
+ write: "เขียน",
+ full: "ความเสี่ยงสูง",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "การค้นหาและบริบท", description: "แสดงรายการการเชื่อมต่อและฐานข้อมูล พร้อมดึงบริบทสคีมาสำหรับโมเดล" },
+ sqlQuery: { title: "คิวรี SQL", description: "เรียกใช้คิวรีและสคริปต์ โดยจำแนกความเสี่ยงของแต่ละคำสั่งในแต่ละครั้งที่เรียก" },
+ sqlSession: { title: "เซสชันและธุรกรรม", description: "คงเซสชันระหว่างการเรียกและควบคุมธุรกรรม" },
+ sqlSchema: { title: "ออบเจ็กต์สคีมา", description: "เรียกดูตาราง คอลัมน์ และซอร์สโค้ดของรูทีน" },
+ redis: { title: "คำสั่ง Redis", description: "เรียกใช้คำสั่ง Redis" },
+ mq: { title: "การอ่านและส่งข้อความ", description: "อ่านและส่งข้อความ Kafka, RocketMQ และ RabbitMQ" },
+ salesforce: { title: "ข้อมูลตัวตนและการดำเนินการกับข้อมูล", description: "ระบุผู้ใช้ปัจจุบันและเขียนระเบียนทีละรายการ" },
+ workbench: { title: "เวิร์กเบนช์", description: "เปิดตารางและแสดงผลคิวรีภายใน DBX" },
+ adminConnections: { title: "การจัดการการเชื่อมต่อ", description: "เพิ่ม ทำสำเนา และลบการเชื่อมต่อ DBX" },
+ pluginRouter: { title: "การค้นหาและเรียกใช้ปลั๊กอิน", description: "ค้นหาเครื่องมือปลั๊กอินเมื่อต้องการและเรียกผ่านตัวกำหนดเส้นทางเดียว" },
+ nacosConfig: { title: "การจัดการการกำหนดค่า", description: "อ่าน, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "การจัดการบริการ", description: "แสดงบริการและอินสแตนซ์ เปิดหรือปิดสถานะออนไลน์ของอินสแตนซ์และเปลี่ยนน้ำหนัก" },
+ consulKv: { title: "การจัดการ KV", description: "แสดง อ่าน เขียน และลบคีย์ Consul KV ด้วยการเปรียบเทียบแล้วปรับค่า (CAS)" },
+ consulService: { title: "การค้นหาบริการและสถานะ", description: "แค็ตตาล็อกบริการและโหนด สถานะบริการ และโหมดบำรุงรักษา" },
+ },
+ mcpToolNacosListNamespaces: "แสดงเนมสเปซ Nacos",
+ mcpToolNacosListConfigs: "แสดงการตั้งค่า Nacos",
+ mcpToolNacosGetConfig: "อ่าน Nacos config",
+ mcpToolNacosConfigHistory: "ประวัติการตั้งค่า Nacos",
+ mcpToolNacosPublishConfig: "เผยแพร่การตั้งค่า Nacos",
+ mcpToolNacosDeleteConfig: "ลบการตั้งค่า Nacos",
+ mcpToolNacosListServices: "แสดงบริการ Nacos",
+ mcpToolNacosListInstances: "แสดงอินสแตนซ์ Nacos",
+ mcpToolNacosUpdateInstance: "อัปเดตอินสแตนซ์ Nacos",
+ mcpToolNacosSearchConfigs: "ค้นหาการตั้งค่า Nacos",
+ mcpToolNacosRollbackConfig: "ย้อนกลับการตั้งค่า Nacos",
+ mcpToolNacosGetService: "ดูบริการ Nacos",
+ mcpToolNacosRegisterInstance: "ลงทะเบียนอินสแตนซ์ Nacos",
+ mcpToolNacosDeregisterInstance: "ยกเลิกการลงทะเบียนอินสแตนซ์ Nacos",
+ mcpToolConsulKvList: "แสดงคีย์ Consul KV",
+ mcpToolConsulKvGet: "อ่าน Consul KV key",
+ mcpToolConsulKvPut: "เขียน Consul KV key",
+ mcpToolConsulKvDelete: "ลบคีย์ Consul KV",
+ mcpToolConsulListServices: "แสดงบริการ Consul",
+ mcpToolConsulListNodes: "แสดงโหนด Consul",
+ mcpToolConsulServiceHealth: "สถานะบริการ Consul",
+ mcpToolConsulSetMaintenance: "โหมดบำรุงรักษา Consul",
mcpConfigOptionsHint: "DBX ควบคุมการเข้าถึงการเชื่อมต่อและสิทธิ์การเรียกใช้ของ Client MCP ทุกตัวจากศูนย์กลาง Config ที่สร้างขึ้นมีเฉพาะการตั้งค่า Runtime ที่จำเป็นต่อการเริ่ม MCP Server และเชื่อมต่อ DBX Instance นี้ โดยไม่มีตัวแปรสิทธิ์หรือขอบเขตการเชื่อมต่อ",
mcpScopeConnection: "การเชื่อมต่อที่อนุญาตสำหรับ MCP",
mcpScopeConnectionDescription: "DBX เปิดเผยเฉพาะการเชื่อมต่อที่เลือกให้ MCP การเปลี่ยนแปลงมีผลกับ Client MCP ทุกตัว",
@@ -11663,7 +11972,8 @@ export default withEnglishFallback({
mcpOpenCodeConfigPath: "ใช้ ~/.config/opencode/opencode.json แบบรวมหรือ opencode.json ระดับโปรเจกต์",
mcpPiConfigPath: "ติดตั้ง Plugin Pi MCP adapter ก่อน: pi install npm:pi-mcp-adapter จากนั้นบันทึกเป็น ~/.pi/agent/mcp.json (รวม) หรือ .mcp.json (โปรเจกต์) ใช้ /mcp เพื่อตรวจสอบ และ /reload เพื่อโหลดใน Pi",
mcpExecutionMode: "สิทธิ์เริ่มต้น MCP แบบรวม",
- mcpExecutionModeDescription: "กำหนดค่าเริ่มต้นเมื่อยังไม่ได้ตั้งค่าสิทธิ์การเชื่อมต่อหรือฐานข้อมูล ค่าเริ่มต้นของการเชื่อมต่อและการตั้งค่าฐานข้อมูลสามารถแทนที่ได้ตามขอบเขต",
+ mcpExecutionModeDescription: "ทรัพยากรที่ไม่ได้กำหนดสิทธิ์เฉพาะจะใช้ค่าเริ่มต้นนี้ กำหนดสิทธิ์ที่แตกต่างได้ในการควบคุมการเข้าถึงด้านล่าง",
+ mcpPermissionsDraftHint: "การเปลี่ยนแปลงส่วนกลาง กลุ่ม และการเชื่อมต่อใช้ปุ่มใช้ด้านล่าง สิทธิ์ฐานข้อมูลใช้ได้จากหน้าต่างของตนเองด้วย ขอบเขตย่อยจะบันทึกทันที การทิ้งฉบับร่างไม่ยกเลิกการเปลี่ยนแปลงที่บันทึกแล้ว",
mcpExecutionModeReadOnly: "อ่านอย่างเดียว",
mcpExecutionModeSafeWrite: "อ่าน/เขียนข้อมูล",
mcpExecutionModeRecommended: "แนะนำ",
@@ -11672,21 +11982,21 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "อนุญาต INSERT ปกติ UPDATE/DELETE ที่มีตัวกรอง การเปลี่ยนแปลง MongoDB ที่จำกัดขอบเขตและตรวจสอบได้ และการเขียน Redis ปกติหรือการลบด้วย Key ที่ระบุ บล็อกการเปลี่ยนแปลงทั้งตารางและโครงสร้าง",
mcpExecutionModeHighRiskWriteDescription: "นอกจากอ่าน/เขียนข้อมูลแล้ว ยังอนุญาตการเปลี่ยนแปลงทั้งตาราง DDL TRUNCATE การล้างฐานข้อมูล และการดำเนินการเสี่ยงสูงอื่น ๆ การป้องกัน Production และการอ่านอย่างเดียวของการเชื่อมต่อยังมีผล",
mcpExecutionModeHighRiskConfirm: "การเข้าถึงเต็มรูปแบบอนุญาตการเปลี่ยนแปลงทั้งตาราง DDL TRUNCATE การล้างฐานข้อมูล และการดำเนินการเสี่ยงสูงอื่น ๆ เปิดใช้หรือไม่",
- mcpPromptHighRiskSql: "ถามก่อน SQL เสี่ยงสูง (เฉพาะ Desktop; การป้องกันอ่านอย่างเดียวและ Production ยังมีผล)",
mcpSqlApprovalTitle: "การอนุมัติ SQL เสี่ยงสูงของ MCP",
mcpSqlApprovalScope: "การเชื่อมต่อ: {connection} · ฐานข้อมูล: {database}",
mcpSqlApprovalOnce: "คำขอนี้เท่านั้น",
mcpSqlApprovalHour: "อนุญาตบนฐานข้อมูลนี้เป็นเวลา 1 ชั่วโมง",
mcpSqlApprovalDay: "อนุญาตบนฐานข้อมูลนี้เป็นเวลา 1 วัน",
mcpSqlApprovalDeny: "ปฏิเสธ",
- mcpCapabilityTitle: "การเปรียบเทียบความสามารถ",
- mcpCapabilityDescription: "นี่คือการดำเนินการตัวอย่าง คำขอที่ DBX จัดประเภทได้ไม่แน่นอนต้องใช้การเข้าถึงเต็มรูปแบบ",
+ mcpCapabilityTitle: "คำอธิบายสิทธิ์",
+ mcpCapabilityDescription: "ตารางอธิบายสิทธิ์ เครื่องมือต้องเปิดในความสามารถด้วย สิทธิ์ไม่พอจะถูกปฏิเสธ ความปลอดภัยในการเรียกใช้ควบคุมการยืนยันแยกต่างหากและอธิบายการอนุญาตแบบเดิม",
mcpCapabilityOperation: "ความสามารถ",
mcpCapabilityRead: "Query และการอ่าน",
mcpCapabilityScopedMutation: "การเปลี่ยนแปลงข้อมูลตามขอบเขต (INSERT, UPDATE/DELETE ที่มีตัวกรอง, การเขียน/ลบด้วย Key ที่ระบุ)",
mcpCapabilityBroadMutation: "การอัปเดต/ลบทั้งตารางและการล้างข้อมูล",
mcpCapabilitySchemaAdmin: "DDL การเปลี่ยนแปลงโครงสร้าง และการดูแลระบบเสี่ยงสูง",
- mcpCapabilityConnectionManagement: "เพิ่ม/นำการเชื่อมต่อ MCP ออก",
+ mcpCapabilityConnectionCreate: "เพิ่ม/ทำสำเนาการเชื่อมต่อ MCP (สิทธิ์เริ่มต้นส่วนกลาง)",
+ mcpCapabilityConnectionRemove: "ลบการเชื่อมต่อ MCP (สิทธิ์เริ่มต้นส่วนกลาง)",
mcpCapabilityAllowed: "อนุญาต",
mcpCapabilityBlocked: "ถูกบล็อก",
mcpQueryTimeout: "Timeout ของ Query (วินาที)",
@@ -11697,6 +12007,9 @@ export default withEnglishFallback({
mcpQueryTimeoutSaveStatus_failed: "บันทึกไม่สำเร็จ",
mcpCapabilityAlwaysEnforced: "ทุกโหมดยังอยู่ภายใต้ Allowlist การเชื่อมต่อ การป้องกันอ่านอย่างเดียวของการเชื่อมต่อ การป้องกัน Production และสิทธิ์บัญชีฐานข้อมูล",
mcpPolicySaveFailed: "บันทึกนโยบายการเข้าถึง MCP ไม่สำเร็จ: {error}",
+ mcpPolicyRetry: "ลองอีกครั้ง",
+ mcpPolicyRecover: "สำรองข้อมูลและรีเซ็ตสิทธิ์ MCP",
+ mcpPolicyRecoverConfirm: "การดำเนินการนี้จะสำรองนโยบายที่เสียหายทันทีและรีเซ็ตสิทธิ์ MCP รวมถึงการเปลี่ยนแปลงสิทธิ์ที่ยังไม่ได้บันทึก การเชื่อมต่อและเครื่องมือทั้งหมดจะถูกบล็อกจนกว่าจะกำหนดค่าใหม่ ต้องการดำเนินการต่อหรือไม่?",
mcpPolicyLoadFailed: "โหลดนโยบายการเข้าถึง MCP ไม่สำเร็จ: {error}",
mcpDetectionTiming: "DBX ตรวจสอบอัตโนมัติเมื่อเปิดหน้านี้ ใช้ตรวจสอบอีกครั้งเพื่อรีเฟรช",
mcpNpmBoundary: "DBX ตรวจสอบสถานะ MCP การติดตั้ง อัปเกรด และถอนการติดตั้งทำงานผ่าน Runtime npm, pnpm หรือ bun ที่ตรวจพบ",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 6a490a61db..0d30609b9f 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -84,6 +84,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: '"{name}", "{connection}" bağlantısındaki verileri okumak istiyor. Bu bağlantı açık olduğu sürece eklenti, Eklenti Merkezi\'nden erişimi iptal edene kadar bağlantıda salt okunur sorgular çalıştırabilir. İzin verilsin mi?',
dataAccessConsentTitle: "Veri Erişim İsteği",
+ mcpToolsBadge: "MCP araçları",
+ mcpToolsBadgeHint: "This plugin provides MCP araçları. Enable and authorize them in Settings → MCP → Yetenekler.",
+ mcpToolsFilter: "Only plugins with MCP araçları ({count})",
+ externalMcp: {
+ title: "Harici MCP istemcileri",
+ offered: "The author lets this plugin's tools reach external MCP clients (Claude Code, Cursor, …). Turn it on and choose how far its tools may go in Settings → MCP → Yetenekler.",
+ notOffered: "Yazar bu eklentinin araçlarını harici MCP istemcilerine açmamış.",
+ },
aiTools: {
title: "Yerleşik yapay zekâ araçları",
description: "Varsayılan olarak kapalıdır: DBX yapay zekâ asistanı (Agent modu), yalnızca bu düğme açıkken açık eklenti bağlantılarında bu eklentinin araçlarını çağırabilir. Salt okunur olmayan araçlar her çağrıda onay ister.",
@@ -6114,6 +6122,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "MCP aracı",
+ mcpClient: "MCP istemcisi",
+ mcpTransport: "MCP aktarımı",
+ mcpAccess: "MCP erişimi",
+ mcpConfirmation: "MCP onayı",
kind: "Tür",
operation: "İşlem",
connection: "Bağlantı",
@@ -8521,6 +8533,303 @@ export default withEnglishFallback({
mcpUninstallConfirm: "DBX MCP Sunucusu kaldırılsın mı? Yapılandırılmış MCP istemcileri artık başlatamayacak.",
mcpUninstallFailed: "Kaldırma başarısız: {error}",
mcpConfig: "MCP yapılandırması",
+ mcpCapabilitiesFilterLabel: "Yetenek filtresi",
+ mcpCapabilitiesFilterAll: "Tümü",
+ mcpCapabilitiesFilterBuiltin: "Yerleşik",
+ mcpCapabilitiesFilterPlugin: "Eklenti",
+ mcpCapabilitiesOnlyEnabled: "Yalnızca etkinleri göster",
+ mcpPluginScopeLoad: "Eklentiden oku",
+ mcpPluginToolsMode: "Eklenti araçlarını dış istemcilere sunma",
+ mcpPluginToolsModeDescription: "DBX’in yetkili eklenti araçlarını MCP istemcilerine nasıl sunacağını seçin. Kaydetmek için alttaki Uygula düğmesine tıklayın.",
+ mcpPluginToolsModeAuto: "Otomatik (uyumluluk)",
+ mcpPluginToolsModeFlat: "Doğrudan listele (varsayılan)",
+ mcpPluginToolsModeLazy: "İsteğe bağlı keşif",
+ mcpPluginToolsModeFlatDescription: "İstemcilerin doğrudan çağırabilmesi için yetkili eklenti araçlarını tek tek listeler.",
+ mcpPluginToolsModeLazyDescription: "Ortak eklenti keşif ve çağrı araçları sunar, ayrıntıları gerektiğinde alır. DBX genel bölümünde eklenti keşfi ve çağrısını etkinleştirin.",
+ mcpPluginToolsModeAutoDescription: "Mevcut otomatik davranışı korur: toplam eklenti aracı sayısı 40 veya altındaysa doğrudan listeler, daha fazlaysa isteğe bağlı keşif kullanır.",
+ mcpCallSafety: "Çağrı güvenliği",
+ mcpCallSafetyLegacy: "Eski geçici yetkilendirme",
+ mcpCallSafetyEnabled: "Her yüksek riskli çağrıyı onayla",
+ mcpCallSafetyDisabled: "Ek onay yok",
+ mcpCallSafetyLegacyHint: "Eski davranış korunur: veri yazma bazı yüksek riskli işlemlere geçici onay verebilir; tam erişim onay istemez. Yeni ilke yetersiz izinleri reddeder ve tam erişimde de onay ister.",
+ mcpCallSafetyMigrate: "Yeni onay ilkesini kullan",
+ mcpCallSafetyDisableLegacy: "Eski yetkilendirmeyi kapat",
+ mcpCallSafetyConfirm: "Yüksek riskli araç çağrılarından önce onay iste",
+ mcpCallSafetyHint: "Yüksek riskli olarak belirlenen yerleşik ve eklenti çağrılarına uygulanır. Önce izinler denetlenir; tam erişim de bu ilkeye uyar. Onay izinleri yükseltmez.",
+ mcpCallSafetyDesktopHint: "DBX masaüstü gerekir ve yalnızca mevcut çağrı onaylanır. Onay alınamazsa, reddedilirse veya süresi dolarsa çalıştırılmaz. Salt okunur ve üretim korumaları sürer. Kaydetmek için Uygula seçeneğine basın.",
+ mcpToolApprovalGenericTitle: "Yüksek riskli çağrıyı onayla",
+ mcpToolApprovalPluginTitle: "{plugin} yüksek riskli aracını onayla",
+ 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ç",
+ mcpToolApprovalTarget: "Hedef",
+ mcpManagementCapabilities: "Yetenekler",
+ mcpOpenCallHistory: "MCP çağrı geçmişini görüntüle",
+ mcpAccessTreeTitle: "Erişim denetimi",
+ mcpAccessTreeDescription: "Gruplar, bağlantılar ve veritabanları için izinleri ayarlayın. Devralma üst ayarı kullanır; geçerli izin sütunu sonucu ve kaynağını gösterir.",
+ mcpAccessTreeSummary: "{visible}/{total} bağlantı görünür · istisnalar: {groups} grup, {connections} bağlantı, {databases} veritabanı",
+ mcpAccessTreeScopeLabel: "Bağlantı görünürlüğü",
+ mcpAccessTreeScopeAll: "Tüm bağlantılar",
+ mcpAccessTreeScopeCustom: "Yalnızca seçilenler",
+ mcpAccessTreeSearchPlaceholder: "Grup, bağlantı veya veritabanı ara",
+ mcpAccessTreeExceptionsOnly: "Yalnızca ayrı ayarları göster",
+ mcpAccessTreeColumnResource: "Kaynak",
+ mcpAccessTreeColumnVisible: "Görünür",
+ mcpAccessTreeColumnSetting: "İzin",
+ mcpAccessTreeColumnEffective: "Etkin",
+ mcpAccessTreeInherit: "Devral",
+ mcpAccessTreeGroupPartiallyVisible: "Bazı bağlantılar görünür ({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "Mevcut bağlantıların tümü görünür ({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "Yalnızca alt öğeler yetkilendirilmiştir, grubun tamamı değil. Gelecekteki bağlantılar dahil tüm gruba izin vermek için işaretleyin.",
+ mcpAccessTreeGroupDefaultHint: "Grup varsayılan izinleri, kendi izin ayarı olmayan alt öğelere uygulanır. Bağlantı görünürlüğünü değiştirmez.",
+ mcpAccessTreeHidden: "MCP tarafından görünmez",
+ mcpAccessTreeSourceGlobal: "genel varsayılan",
+ mcpAccessTreeSourceGroup: "{group} grubundan",
+ mcpAccessTreeSourceConnection: "bağlantı ayarı",
+ mcpAccessTreeSourceDatabase: "veritabanı ayarı",
+ mcpAccessTreeGroupCount: "{count} bağlantı",
+ mcpAccessTreeLegacy: "eski biçim",
+ mcpAccessTreeLegacyHint: "Eski bir sürüm tarafından kaydedildi: yalnızca bağlantının devraldığı izinleri daraltabilir. Normal bir ayara dönüştürmek için izni yeniden seçin.",
+ mcpAccessTreeCoveredByGroup: "Görünür through a selected parent group",
+ mcpAccessTreeHighRiskConfirm: "Yüksek risk allows DDL, DROP, TRUNCATE and unconditional writes on this resource. Continue?",
+ mcpAccessTreeDatabases: "Veritabanları",
+ mcpAccessTreeDatabaseScopeAll: "Tüm veritabanları",
+ mcpAccessTreeDatabaseScopeSelected: "Seçilen ({count})",
+ mcpAccessTreeDatabaseScopeNone: "Veritabanı yok",
+ mcpDatabaseRemoveConfirm: "Seçili veritabanlarını kaldırmak özel izinlerini de kaldırır. Devam edilsin mi?",
+ mcpDatabaseUnavailable: "Veritabanı izin ayarları kullanılamıyor. Yüklemenin bitmesini bekleyin veya yeniden deneyin.",
+ mcpDatabaseConfigure: "Veritabanı erişimini yapılandır",
+ mcpDatabaseOverrideCount: "{count} özel izin",
+ mcpDatabaseDialogTitle: "{name} / Veritabanı erişimi",
+ mcpDatabaseDialogDescription: "Veritabanlarını ve izinlerini seçin. Sağa taşıma yalnızca uygulandıktan sonra geçerli olur.",
+ mcpDatabaseInherited: "Devralınan izin: {level}",
+ mcpDatabaseSavedInherited: "Üst izinlerde bekleyen değişiklikler var. Yalnızca veritabanı erişimini uygulamak kayıtlı izinleri devralır: {level}",
+ mcpDatabaseHiddenConnection: "Bu bağlantı şu anda MCP’den gizli. Veritabanı izinlerini uygulamak bağlantıyı görünür yapmaz.",
+ mcpDatabaseAllHint: "Mevcut ve gelecekteki veritabanları bağlantı izinlerini kullanır.",
+ mcpDatabaseNoneHint: "Uygulandığında tüm veritabanlarına erişim reddedilir.",
+ mcpDatabaseLoaded: "Bu hesaba görünür {count} veritabanı yüklendi",
+ mcpDatabaseRefresh: "Listeyi yenile",
+ mcpDatabaseAddSelected: "Ekle →",
+ mcpDatabaseRemoveSelected: "← Kaldır",
+ mcpDatabaseAvailable: "Seçilmemiş ({count})",
+ mcpDatabaseSelected: "Seçili ({count})",
+ mcpDatabaseSearch: "Veritabanı adı ara",
+ mcpDatabaseSelectResults: "Geçerli arama sonuçlarını seç ({count})",
+ mcpDatabaseBatchLevel: "İşaretlenenlerin izinleri ({count})",
+ mcpDatabaseBatchHighRiskConfirm: "İşaretlenen {count} veritabanına tam erişim verilsin mi? Bağlantının salt okunur ayarı ve üretim ortamı korumaları geçerli kalır.",
+ mcpDatabaseNotDiscovered: "Bu sorguda bulunamadı",
+ mcpDatabaseShowMore: "Daha fazla göster ({shown}/{total})",
+ mcpDatabaseSaveHint: "Yalnızca bu bağlantının veritabanı kapsamını ve izinlerini kaydeder. Diğer taslaklar korunur.",
+ mcpDatabaseApply: "Veritabanı izinlerini uygula",
+ mcpAccessTreePickDatabases: "Veritabanlarını seç",
+ mcpAccessTreePickerTitle: "Veritabanları of {name}",
+ mcpAccessTreeLoadingDatabases: "Veritabanları yükleniyor...",
+ mcpAccessTreeLoadDatabasesFailed: "Veritabanları yüklenemedi: {error}. Adları yine de elle ekleyebilirsiniz.",
+ mcpAccessTreeManualDatabase: "Veritabanı adı ekle",
+ mcpAccessTreeNoMatch: "Eşleşen kaynak yok",
+ mcpAccessTreeEmpty: "Henüz bağlantı yok",
+ mcpAccessTreeFootnote: "Öncelik: veritabanı > bağlantı > en yakın grup > üst grup > genel varsayılan. Bağlantının salt okunur koruması, üretim koruması ve veritabanı hesabı izinleri her zaman geçerlidir.",
+ mcpAccessTreeNacosNamespace: "Ad alanı",
+ mcpPluginScopeAll: "Tümü ({title})",
+ mcpPluginScopeSelected: "Seçilen ({count})",
+ mcpPluginScopeNone: "Hayır {title}",
+ mcpPluginScopeAdd: "{title} ekle",
+ mcpBrowser: {
+ viewMode: "Görünüm modu",
+ viewManage: "Kategori yönetimi",
+ viewOverview: "Genel bakış",
+ overviewSummary: "{toolsets} araç kümesi · {total} araç · {enabled} etkin",
+ overviewPluginsHint: "Eklenti araçlarını ve yetkilendirmeyi inceleyin. Ayrıntılar için eklentiyi açın.",
+ overviewOpenDetails: "Ayrıntıları görüntüle",
+ expandCategory: "Kategoriyi genişlet",
+ collapseCategory: "Kategoriyi daralt",
+ builtin: "Yerleşik yetenekler",
+ plugins: "Eklenti uzantıları",
+ advanced: "Gelişmiş ayarlar",
+ navigation: "Yetenek kategorileri",
+ searchPlaceholder: "Kategori, yetenek, eklenti veya araç ara…",
+ clearSearch: "Aramayı temizle",
+ searchResults: "Arama sonuçları",
+ categoryCount: "{count} araç kümesi",
+ summary: "{toolsets} araç kümesi · {total} araç · {enabled} etkin",
+ enableCategory: "Bu kategorinin tümünü etkinleştir",
+ disableCategory: "Bu kategorinin tümünü devre dışı bırak",
+ draftHint: "Ayrıntılardan bir araç kümesini uygulayın veya bekleyen tüm ayarları kaydetmek için alttaki Uygula düğmesini kullanın.",
+ batchChanged: "Bu kategorideki araçlar değiştirildi. Kaydetmek için Uygula düğmesine tıklayın",
+ coverageHint: "Uygun bağlantılar bağlantı türüne göre sayılır; gerçek yetki kapsamını göstermez.",
+ uncovered: "{count} bağlantı için yerleşik araç desteği yok",
+ viewDetails: "Ayrıntıları görüntüle",
+ emptyEnabled: "Bu kategoride etkin araç yok. Yapılandırmak için “Yalnızca etkinleri göster” seçeneğini kapatın.",
+ retry: "Yeniden dene",
+ enabledToolCount: "{enabled}/{total} etkin",
+ partialEnabled: "Kısmen etkin",
+ coverageConnections: "{count} bağlantıda kullanılabilir",
+ coveragePartialConnections: "{count} bağlantı kısmen destekleniyor",
+ noMatchingConnections: "Uygun bağlantı yok",
+ resourceScopes: "Kaynak kapsamları",
+ pluginImmediate: "Değişiklikler hemen kaydedilir; alttaki Uygula / İptal düğmelerinden etkilenmez",
+ pluginSaving: "Kaydediliyor…",
+ pluginSaved: "Kaydedildi",
+ pluginOnlyEnabledEmpty: "Etkin araç yok. Görmek için “Yalnızca etkinleri göster” seçeneğini kapatın.",
+ pluginUnavailable: "Bu eklenti artık kullanılamıyor. Eklenti listesini yenileyin",
+ resourceKind: {
+ database: "Veritabanı",
+ dbIndex: "Mantıksal veritabanı",
+ topic: "Konu",
+ queue: "Kuyruk",
+ org: "Kuruluş",
+ namespace: "Ad alanı",
+ },
+ category: {
+ database: { title: "Veritabanları", description: "Verileri sorgulayın, oturum ve işlemleri yönetin, nesne yapılarını inceleyin ve Redis komutlarını çalıştırın." },
+ nacos: { title: "Nacos", description: "Yapılandırmaları, hizmetleri ve örnekleri yönetin." },
+ consul: { title: "Consul", description: "KV kayıtlarını yönetin, hizmetleri keşfedin ve sağlık durumlarını görüntüleyin." },
+ mq: { title: "Mesaj kuyrukları", description: "Mesajları okuyun ve gönderin." },
+ salesforce: { title: "Salesforce", description: "Kimlik bilgilerini sorgulayın ve veriler üzerinde işlem yapın." },
+ dbx: { title: "DBX ortak", description: "Ürünler arasında paylaşılan yetenekler: bağlantı keşfi, çalışma alanı entegrasyonu, bağlantı yönetimi ve eklenti keşfi ile çağırma." },
+ other: { title: "Diğer yetenekler", description: "Henüz sınıflandırılmamış araç kümelerini görüntüleyin ve yapılandırın." },
+ },
+ },
+ mcpCapabilitiesTitle: "MCP yetenekleri",
+ mcpCapabilitiesDescription: "Yerleşik MCP araçları grouped by scenario. Turning a group off rejects its tools on the server even if a client cached them. Each group lists the database types it applies to.",
+ mcpCapabilitiesLoading: "MCP yetenekleri yükleniyor...",
+ mcpCapabilitiesLoadFailed: "Failed to load MCP yetenekleri: {error}",
+ mcpCapabilitiesSearchPlaceholder: "Yetenek veya araç ara",
+ mcpCapabilitiesSearchEmpty: "Eşleşen yetenek yok",
+ mcpToolsetToolCount: "{enabled}/{total} araç",
+ mcpAccessLevelClassified: "Çağrı başına",
+ mcpCoverageTypes: "{count} veritabanı türü",
+ mcpCoverageToolTypes: "{tools}: {count}",
+ mcpCoverageNotBound: "Bir bağlantıya bağlı değil",
+ mcpCoverageUsableConnections: "{count} bağlantınızda kullanılabilir",
+ mcpCoverageNoUsableConnections: "Bağlantılarınızın hiçbiri bunu kullanmıyor",
+ mcpCoveragePartialConnections: "{count} bağlantı yalnızca bazı araçları destekliyor",
+ mcpCoverageUncoveredConnections: "{count} connections have no MCP araçları yet: {names}",
+ mcpCoverageSearchPlaceholder: "Veritabanı türü ara",
+ mcpCoverageSearchEmpty: "Hayır matching database types",
+ mcpCoverageLegend: "Yalnızca desteklenen türler listelenir. Vurgulanan türler bağlantılarınızla eşleşir; * gruptaki bazı araçların türü desteklemediğini belirtir (ayrıntılar için üzerine gelin).",
+ mcpCoverageTypeUnsupportedTool: "{tool} tarafından desteklenmiyor",
+ mcpCoverageCategoryOther: "Diğer",
+ mcpCoveragePartialTool: "{tool}, {total} türün {count} tanesini destekliyor",
+ mcpToolDetailSkippedConnections: "Kullanılamaz: {names}",
+ mcpToolDetailCoverage: "Desteklenen veritabanı türleri ({count})",
+ mcpToolDetailParameterDefault: "varsayılan: {value}",
+ mcpToolDetailParameterDescription: "Açıklama",
+ mcpToolDetailParameterRequiredNo: "Hayır",
+ mcpToolDetailParameterRequiredYes: "Evet",
+ mcpToolDetailParameterRequired: "Zorunlu",
+ mcpToolDetailParameterType: "Tür",
+ mcpToolDetailParameterName: "Ad",
+ mcpToolDetailNoParameters: "Parametre yok",
+ mcpToolDetailParameters: "Parametreler",
+ mcpToolDetailDescription: "Modele sunulan açıklama",
+ mcpToolDetailAccessClassified: "Her çağrıda sınıflandırılır (ifadeye göre okuma, yazma veya yüksek risk)",
+ mcpToolDetailAccess: "Erişim düzeyi",
+ mcpToolDetailSummary: "Özet",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "{count} bağlantınız bunu kullanamaz",
+ mcpToolsetDetailTools: "Araçlar",
+ mcpToolsetDetailCoverage: "Kapsam",
+ mcpToolsetApply: "Bu araç kümesini uygula",
+ mcpToolsetApplying: "Uygulanıyor…",
+ mcpToolsetPending: "Henüz uygulanmamış {count} araç değişikliği",
+ mcpToolsetApplied: "Geçerli yapılandırma uygulandı",
+ mcpToolsetCloseKeepsDraft: "Kapatmak değişiklikleri korur. Ayarlar sayfasından da uygulayabilirsiniz.",
+ mcpToolsetApplyFailed: "Uygulanamadı: {error}. Değişiklikler korundu; yeniden deneyin.",
+ mcpToolsetApplyUnavailable: "Araç ayarları kullanılamıyor. Yüklemenin tamamlanmasını bekleyin veya yeniden deneyin.",
+ mcpToolsetDetailClose: "Kapat",
+ mcpPluginToolEntriesTitle: "Eklenti tool entries",
+ mcpPluginsTitle: "Eklentiler",
+ mcpPluginsDescription: "Eklentiler that provide MCP araçları. Each plugin is switched and authorized as a whole; changes save immediately.",
+ mcpPluginsRefresh: "Yenile",
+ mcpPluginsLoading: "Eklenti araçları yükleniyor...",
+ mcpPluginsLoadFailed: "Eklenti araçları yüklenemedi: {error}",
+ mcpPluginsEmpty: "Yüklü eklentiler MCP aracı sağlamıyor.",
+ mcpPluginSaveFailed: "{name} kaydedilemedi: {message}",
+ mcpPluginAuthorClosed: "Yazar harici MCP erişimini açmamış",
+ mcpPluginDiscoveryFailed: "Araç keşfi başarısız",
+ mcpPluginToolCount: "{exposed}/{total} araç sunuluyor",
+ mcpPluginToolCountOff: "{total} araç, kapalı",
+ mcpPluginCeilingSummary: "Üst sınır: {level}",
+ mcpPluginPendingTools: "{count} yeni araç onay bekliyor",
+ mcpPluginReview: "İncele",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "Araç keşfi başarısız: {error}",
+ mcpPluginCeilingTitle: "Yetkilendirme sınırı",
+ mcpPluginCeilingDescription: "Üst sınırı aşan araçlar MCP istemcilerinden gizli kalır. Çağrılar ayrıca kaynak izinlerine ve bağlantı görünürlüğü kurallarına uymalıdır.",
+ mcpPluginEnableFirst: "Üst sınırı ve araçları değiştirmek için eklentiyi açın.",
+ mcpPluginDefaultToolset: "Araçlar",
+ mcpPluginNoTools: "This plugin lists no MCP araçları right now.",
+ mcpPluginAuthorizeTitle: "Yetkilendir {name} for MCP",
+ mcpPluginAuthorizeDescription: "Eklentinin izin üst sınırını seçin. Aşağıda bildirilen tüm araçlar kabul edilir; daha sonra eklenen veya bildirilen düzeyi yükselen araçlar, okumadan daha fazla izin gerektiriyorsa yeniden onay ister.",
+ mcpPluginAuthorizeTools: "Araçlar ({count})",
+ mcpPluginAuthorizeIncluded: "Açık",
+ mcpPluginAuthorizeExcluded: "Gizli",
+ mcpPluginAuthorizeFootnote: "Daha sonra eklenti ayrıntılarında üst sınırı değiştirebilir veya tek tek araçları kapatabilirsiniz.",
+ mcpPluginAccessUndeclared: "Tanımlanmamış by the author — never exposed",
+ mcpPluginUndeclaredCount: "{count} araç manifestte bildirilmediği için gizli kalır",
+ mcpPluginUndeclaredTools: "{count} araç için eklenti manifestinde erişim düzeyi bildirilmemiştir ve bu araçlar hiçbir zaman sunulmaz: {names}",
+ mcpPluginAuthorizeCancel: "İptal",
+ mcpPluginAuthorizeConfirm: "Yetkilendir",
+ mcpPluginToolEntriesHint: "Gelişmiş: eklenti araçları için izin listesi kayıtları. dbx_*__* tüm eklenti araçlarına, dbx_<prefix>__* tek bir eklentiye izin verir. Eklenti anahtarları kullanılabilir araçları belirler; bu kayıtlar ek bir filtre oluşturur.",
+ mcpPluginAllowlistBlocked: "MCP araç izin listesinde eklenti kaydı yok; bu nedenle eklenti anahtarlarının durumundan bağımsız olarak tüm eklenti araçları gizlenir.",
+ mcpPluginAllowlistAllow: "Eklenti araçlarına izin ver",
+ mcpPluginExposure: {
+ exposed: "Açık",
+ undeclared: "Tanımlanmamış",
+ pluginDisabled: "Eklenti kapalı",
+ toolDisabled: "Kapatıldı",
+ aboveCeiling: "Sınırın üzerinde",
+ pendingApproval: "Onay gerekiyor",
+ },
+ mcpPluginCeilingLevel: {
+ read: "Salt okunur",
+ write: "Okuma ve yazma",
+ full: "Tam (yüksek risk dahil)",
+ },
+ mcpAccessLevel: {
+ read: "Okuma",
+ write: "Yazma",
+ full: "Yüksek risk",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "Keşif ve bağlam", description: "Bağlantıları ve veritabanlarını listeleyin, model için şema bağlamını alın." },
+ sqlQuery: { title: "SQL sorgusu", description: "Sorguları ve betikleri çalıştırın. Her ifadenin riski her çağrıda sınıflandırılır." },
+ sqlSession: { title: "Oturumlar ve işlemler", description: "Çağrılar arasında aynı oturumu koruyun ve işlemleri yönetin." },
+ sqlSchema: { title: "Şema nesneleri", description: "Tabloları, sütunları ve rutin kaynak kodunu inceleyin." },
+ redis: { title: "Redis komutları", description: "Redis komutlarını çalıştırın." },
+ mq: { title: "Mesaj okuma ve gönderme", description: "Kafka, RocketMQ ve RabbitMQ mesajlarını okuyun ve gönderin." },
+ salesforce: { title: "Kimlik sorgulama ve veri işlemleri", description: "Geçerli kullanıcıyı belirleyin ve tekil kayıtları yazın." },
+ workbench: { title: "Çalışma alanı", description: "DBX içinde tabloları açın ve sorgu sonuçlarını gösterin." },
+ adminConnections: { title: "Bağlantı yönetimi", description: "DBX bağlantılarını ekleyin, çoğaltın ve kaldırın." },
+ pluginRouter: { title: "Eklenti keşfi ve çağırma", description: "Eklenti araçlarını gerektiğinde keşfedin ve tek bir yönlendirici üzerinden çağırın." },
+ nacosConfig: { title: "Yapılandırma yönetimi", description: "Okuma, search, publish and delete Nacos configurations by namespace." },
+ nacosService: { title: "Hizmet yönetimi", description: "Hizmetleri ve örnekleri listeleyin; örnekleri çevrimiçi veya çevrimdışı yapın ve ağırlıklarını değiştirin." },
+ consulKv: { title: "KV yönetimi", description: "Karşılaştır ve değiştir (CAS) ile Consul KV anahtarlarını listeleyin, okuyun, yazın ve silin." },
+ consulService: { title: "Hizmet keşfi ve sağlık", description: "Hizmet ve düğüm kataloğu, hizmet sağlığı ve bakım modu." },
+ },
+ mcpToolNacosListNamespaces: "Nacos ad alanlarını listele",
+ mcpToolNacosListConfigs: "Nacos yapılandırmalarını listele",
+ mcpToolNacosGetConfig: "Okuma Nacos config",
+ mcpToolNacosConfigHistory: "Nacos yapılandırma geçmişi",
+ mcpToolNacosPublishConfig: "Nacos yapılandırmasını yayımla",
+ mcpToolNacosDeleteConfig: "Nacos yapılandırmasını sil",
+ mcpToolNacosListServices: "Nacos hizmetlerini listele",
+ mcpToolNacosListInstances: "Nacos örneklerini listele",
+ mcpToolNacosUpdateInstance: "Nacos örneğini güncelle",
+ mcpToolNacosSearchConfigs: "Nacos yapılandırmalarını ara",
+ mcpToolNacosRollbackConfig: "Nacos yapılandırmasını geri al",
+ mcpToolNacosGetService: "Nacos hizmetini görüntüle",
+ mcpToolNacosRegisterInstance: "Nacos örneğini kaydet",
+ mcpToolNacosDeregisterInstance: "Nacos örneğinin kaydını kaldır",
+ mcpToolConsulKvList: "Consul KV anahtarlarını listele",
+ mcpToolConsulKvGet: "Okuma Consul KV key",
+ mcpToolConsulKvPut: "Yazma Consul KV key",
+ mcpToolConsulKvDelete: "Consul KV anahtarını sil",
+ mcpToolConsulListServices: "Consul hizmetlerini listele",
+ mcpToolConsulListNodes: "Consul düğümlerini listele",
+ mcpToolConsulServiceHealth: "Consul hizmet sağlığı",
+ mcpToolConsulSetMaintenance: "Consul bakım modu",
mcpConfigOptionsHint:
"DBX, her MCP istemcisi için bağlantı erişimini ve yürütme yetkilerini merkezî olarak denetler. Üretilen yapılandırmalar yalnızca MCP sunucusunu başlatmak ve bu DBX örneğine bağlanmak için gereken çalışma zamanı ayarlarını içerir; yetki veya bağlantı kapsamı değişkeni içermez.",
mcpScopeConnection: "MCP için izin verilen bağlantılar",
@@ -8571,7 +8880,8 @@ export default withEnglishFallback({
mcpOpenCodeConfigPath: "Genel olarak ~/.config/opencode/opencode.json ya da proje düzeyinde opencode.json.",
mcpPiConfigPath: "Önce Pi MCP bağdaştırıcı eklentisini kurun: pi install npm:pi-mcp-adapter. Ardından ~/.pi/agent/mcp.json (genel) ya da .mcp.json (proje) dosyasına kaydedin, doğrulamak için /mcp, Pi'de yüklemek için /reload çalıştırın.",
mcpExecutionMode: "MCP genel varsayılan yetkisi",
- mcpExecutionModeDescription: "Bağlantı veya veritabanı yetkisi yapılandırılmadığında kullanılan varsayılanı belirler. Bağlantı varsayılanları ve veritabanı ayarları bunu kapsama göre geçersiz kılabilir.",
+ mcpExecutionModeDescription: "Kendi izni olmayan kaynaklar bu varsayılanı kullanır. Farklı izinleri aşağıdaki erişim denetiminde ayarlayın.",
+ mcpPermissionsDraftHint: "Genel, grup ve bağlantı değişiklikleri alttaki Uygula ile kaydedilir. Veritabanı izinleri kendi penceresinde de uygulanabilir. Alt kapsamlar hemen kaydedilir. Taslakları atmak kayıtlı değişiklikleri geri almaz.",
mcpExecutionModeReadOnly: "Salt okunur",
mcpExecutionModeSafeWrite: "Veri okuma/yazma",
mcpExecutionModeRecommended: "Önerilen",
@@ -8580,14 +8890,15 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "Normal INSERT, filtrelenmiş UPDATE/DELETE, kapsamı doğrulanabilir MongoDB değişiklikleri ve sıradan Redis yazmaları ya da açık anahtar silmelerine izin verir; tablo genelindeki ve yapısal değişiklikleri engeller.",
mcpExecutionModeHighRiskWriteDescription: "Veri okuma/yazmaya ek olarak tablo genelinde değişikliklere, DDL'e, TRUNCATE'e, veritabanı temizlemeye ve diğer yüksek riskli işlemlere izin verir. Üretim ve bağlantı salt okunur korumaları yine geçerlidir.",
mcpExecutionModeHighRiskConfirm: "Tam erişim; tablo genelinde değişikliklere, DDL'e, TRUNCATE'e, veritabanı temizlemeye ve diğer yüksek riskli işlemlere izin verir. Etkinleştirilsin mi?",
- mcpCapabilityTitle: "Yetenek karşılaştırması",
- mcpCapabilityDescription: "Bunlar örnek işlemlerdir; DBX'in güvenilir biçimde sınıflandıramadığı istekler tam erişim gerektirir.",
+ mcpCapabilityTitle: "İzin açıklamaları",
+ mcpCapabilityDescription: "Tablo erişim düzeylerini açıklar; araçlar Yetenekler altında da etkinleştirilmelidir. Yetersiz izinler reddedilir. Çağrı güvenliği onayı ayrı yönetir ve eski yetkilendirmeyi açıklar.",
mcpCapabilityOperation: "Yetenek",
mcpCapabilityRead: "Sorgular ve okumalar",
mcpCapabilityScopedMutation: "Kapsamlı veri değişiklikleri (INSERT, filtrelenmiş UPDATE/DELETE, açık anahtarla yazma/silme)",
mcpCapabilityBroadMutation: "Tablo genelinde güncelleme/silme ve veri temizleme",
mcpCapabilitySchemaAdmin: "DDL, yapısal değişiklikler ve yüksek riskli yönetim",
- mcpCapabilityConnectionManagement: "MCP bağlantısı ekle/kaldır",
+ mcpCapabilityConnectionCreate: "MCP bağlantısı ekle/çoğalt (genel varsayılan izin)",
+ mcpCapabilityConnectionRemove: "MCP bağlantısını sil (genel varsayılan izin)",
mcpCapabilityAllowed: "İzin verilen",
mcpCapabilityBlocked: "Engellendi",
mcpQueryTimeout: "Sorgu zaman aşımı (saniye)",
@@ -8595,6 +8906,9 @@ export default withEnglishFallback({
mcpQueryTimeoutInvalid: "Saniye cinsinden negatif olmayan bir tam sayı girin ya da bağlantı ayarını devralmak için boş bırakın.",
mcpCapabilityAlwaysEnforced: "Her mod; bağlantı izin listesine, bağlantı salt okunur korumasına, üretim korumasına ve veritabanı hesabı yetkilerine tabidir.",
mcpPolicySaveFailed: "MCP erişim politikası kaydedilemedi: {error}",
+ mcpPolicyRetry: "Yeniden dene",
+ mcpPolicyRecover: "MCP izinlerini yedekle ve sıfırla",
+ mcpPolicyRecoverConfirm: "Bu işlem hasarlı ilkeyi hemen yedekler ve kaydedilmemiş değişiklikler dahil MCP izinlerini sıfırlar. Yeniden yapılandırılana kadar tüm bağlantılar ve araçlar engellenir. Devam edilsin mi?",
mcpPolicyLoadFailed: "MCP erişim politikası yüklenemedi: {error}",
mcpDetectionTiming: "DBX bu sayfa açıldığında otomatik denetim yapar; yenilemek için Yeniden denetle'yi kullanın.",
mcpNpmBoundary: "DBX, MCP durumunu denetler; kurulum, yükseltme ve kaldırma işlemleri algılanan npm, pnpm ya da bun çalışma zamanı üzerinden yürür.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index ff6f6a18db..b5332ca883 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -750,6 +750,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: "「{name}」请求读取连接「{connection}」中的数据。在该连接打开期间,插件可以对它执行只读查询,直到你在插件中心撤销授权。是否允许?",
dataAccessConsentTitle: "数据访问请求",
+ mcpToolsBadge: "MCP 工具",
+ mcpToolsBadgeHint: "该插件提供 MCP 工具,可在「设置 → MCP → 能力」中启用并授权。",
+ mcpToolsFilter: "仅显示提供 MCP 工具的插件({count})",
+ externalMcp: {
+ title: "外部 MCP 客户端",
+ offered: "插件作者允许其工具接入外部 MCP 客户端(Claude Code、Cursor 等)。请到「设置 → MCP → 能力」开启并选择授权上限。",
+ notOffered: "插件作者未开放该插件的工具给外部 MCP 客户端。",
+ },
aiTools: {
title: "内置 AI 工具",
description: "默认关闭:仅在此开关开启期间,DBX AI 助手(Agent 模式)才能在你已打开的该插件连接上调用其工具。未声明为只读的工具每次调用前仍会请求你确认,工具输出会发送给你配置的 AI 模型。",
@@ -8405,6 +8413,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "MCP 工具",
+ mcpClient: "MCP 客户端",
+ mcpTransport: "MCP 传输",
+ mcpAccess: "MCP 权限",
+ mcpConfirmation: "MCP 确认",
kind: "类型",
operation: "操作",
connection: "连接",
@@ -11141,7 +11153,8 @@ export default withEnglishFallback({
mcpOpenCodeConfigPath: "全局 ~/.config/opencode/opencode.json,项目级 opencode.json。",
mcpPiConfigPath: "先安装 Pi MCP 适配器插件:pi install npm:pi-mcp-adapter。然后保存到 ~/.pi/agent/mcp.json(全局)或 .mcp.json(项目),在 Pi 中运行 /mcp 确认、/reload 生效。",
mcpExecutionMode: "MCP 全局默认权限",
- mcpExecutionModeDescription: "设置未配置连接或单库权限时使用的默认级别。连接默认和单库设置可按范围覆盖此默认值。",
+ mcpExecutionModeDescription: "未单独设置权限的资源使用此默认值;需要不同权限时,在下方访问控制中设置。",
+ mcpPermissionsDraftHint: "全局默认权限及分组、连接设置需点击底部“应用”生效;库权限也可在弹窗中单独应用。命名空间等子范围设置会立即保存。已保存的修改不受放弃草稿影响。",
mcpExecutionModeReadOnly: "只读",
mcpExecutionModeSafeWrite: "数据读写",
mcpExecutionModeRecommended: "推荐",
@@ -11150,21 +11163,37 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "允许普通 INSERT、带有效条件的 UPDATE/DELETE、MongoDB 范围可验证的变更,以及 Redis 普通写入和明确键删除;阻止全表修改和结构变更。",
mcpExecutionModeHighRiskWriteDescription: "在数据读写基础上允许全表修改、DDL、TRUNCATE、清库及其他高风险操作;生产库和连接只读保护仍然生效。",
mcpExecutionModeHighRiskConfirm: "完全访问允许全表修改、DDL、TRUNCATE、清库及其他高风险操作。确定要启用吗?",
- mcpPromptHighRiskSql: "高风险 SQL 请求人工确认(仅桌面端;只读和生产库保护不变)",
+ mcpCallSafety: "调用安全",
+ mcpCallSafetyLegacy: "旧版临时授权",
+ mcpCallSafetyEnabled: "高危调用逐次确认",
+ mcpCallSafetyDisabled: "不额外确认",
+ mcpCallSafetyLegacyHint: "当前保留旧版行为:数据读写权限可经确认临时执行部分高危操作,完全访问不询问。切换新策略后,权限不足将直接拒绝,完全访问的高危调用也须逐次确认。",
+ mcpCallSafetyMigrate: "改用新的确认策略",
+ mcpCallSafetyDisableLegacy: "关闭旧版临时授权",
+ mcpCallSafetyConfirm: "高危工具调用执行前,请求人工确认",
+ mcpCallSafetyHint: "覆盖内置和插件中被识别为高危的调用。先校验权限,再请求确认;完全访问也遵循此策略,确认不会提升权限。",
+ mcpCallSafetyDesktopHint: "确认仅在 DBX 桌面端进行,每次仅批准当前调用;无法确认、拒绝或超时均不执行。连接只读和生产保护始终有效。修改后点击“应用”生效。",
+ mcpToolApprovalGenericTitle: "确认高危工具调用",
mcpSqlApprovalTitle: "MCP 高风险 SQL 授权",
+ mcpToolApprovalPluginTitle: "确认 {plugin} 的高危工具",
+ mcpToolApprovalRedisTitle: "确认高危 Redis 命令",
+ mcpToolApprovalDescription: "MCP 客户端请求执行一个高危操作。只有在你预期这次调用时才允许。",
+ mcpToolApprovalTool: "工具",
+ mcpToolApprovalTarget: "目标",
mcpSqlApprovalScope: "连接:{connection} · 数据库:{database}",
mcpSqlApprovalOnce: "仅本次",
mcpSqlApprovalHour: "允许此库 1 小时",
mcpSqlApprovalDay: "允许此库 1 天",
mcpSqlApprovalDeny: "拒绝",
- mcpCapabilityTitle: "权限能力对照",
- mcpCapabilityDescription: "以下为典型操作;无法可靠分类的请求需要完全访问。",
+ mcpCapabilityTitle: "权限说明",
+ mcpCapabilityDescription: "下表说明权限级别;工具仍需在“能力”页面开启。权限不足直接拒绝,人工确认由独立的“调用安全”控制;旧版临时授权行为在该区域单独说明。",
mcpCapabilityOperation: "能力",
mcpCapabilityRead: "查询与读取",
mcpCapabilityScopedMutation: "范围可控的数据变更(INSERT、有效条件 UPDATE/DELETE、明确键写入/删除)",
mcpCapabilityBroadMutation: "全表更新/删除与清空数据",
mcpCapabilitySchemaAdmin: "DDL、结构变更与高风险管理命令",
- mcpCapabilityConnectionManagement: "MCP 连接添加/删除",
+ mcpCapabilityConnectionCreate: "MCP 连接添加/复制(全局默认权限)",
+ mcpCapabilityConnectionRemove: "MCP 连接删除(全局默认权限)",
mcpCapabilityAllowed: "允许",
mcpCapabilityBlocked: "禁止",
mcpQueryTimeout: "查询超时(秒)",
@@ -11175,6 +11204,9 @@ export default withEnglishFallback({
mcpQueryTimeoutSaveStatus_failed: "保存失败",
mcpCapabilityAlwaysEnforced: "所有模式仍受连接允许范围、连接只读、生产库保护和数据库账号权限约束。",
mcpPolicySaveFailed: "保存 MCP 访问策略失败:{error}",
+ mcpPolicyRetry: "重试",
+ mcpPolicyRecover: "备份并重置 MCP 权限",
+ mcpPolicyRecoverConfirm: "这会立即备份损坏的策略并重置 MCP 权限,同时清除未保存的权限修改。所有连接和工具将被禁用,直到你重新配置。是否继续?",
mcpPolicyLoadFailed: "加载 MCP 访问策略失败:{error}",
mcpDetectionTiming: "打开此页时会自动检测,点击重新检查可刷新。",
mcpNpmBoundary: "DBX 负责检查 MCP 状态;安装、升级和卸载由检测到的 npm、pnpm 或 bun 运行环境执行。",
@@ -11265,6 +11297,265 @@ export default withEnglishFallback({
mcpDatabaseEmptyHint: "点击“加载资源列表”获取数据库列表,或手工添加允许的数据库。",
mcpManagementAccess: "接入方式",
mcpManagementPermissions: "权限管理",
+ mcpManagementCapabilities: "能力",
+ mcpOpenCallHistory: "查看 MCP 调用记录",
+ mcpAccessTreeTitle: "访问控制",
+ mcpAccessTreeDescription: "为分组、连接和数据库单独设置权限。选择“继承”时使用上级设置,“生效”列显示最终权限及来源。",
+ mcpAccessTreeSummary: "可见连接 {visible}/{total} · 例外:{groups} 个分组、{connections} 个连接、{databases} 个库",
+ mcpAccessTreeScopeLabel: "连接可见范围",
+ mcpAccessTreeScopeAll: "全部连接",
+ mcpAccessTreeScopeCustom: "仅选中的",
+ mcpAccessTreeSearchPlaceholder: "搜索分组、连接或库",
+ mcpAccessTreeExceptionsOnly: "仅显示单独设置",
+ mcpAccessTreeColumnResource: "资源",
+ mcpAccessTreeColumnVisible: "可见",
+ mcpAccessTreeColumnSetting: "权限",
+ mcpAccessTreeColumnEffective: "生效",
+ mcpAccessTreeInherit: "继承",
+ mcpAccessTreeGroupPartiallyVisible: "部分连接可见({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "当前连接均可见({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "仅子项已获授权,尚未开放整个分组。勾选将开放整组,包含以后新增的连接。",
+ mcpAccessTreeGroupDefaultHint: "分组默认权限仅供未单独设置权限的子项继承,不改变连接的可见范围。",
+ mcpAccessTreeHidden: "对 MCP 不可见",
+ mcpAccessTreeSourceGlobal: "全局默认",
+ mcpAccessTreeSourceGroup: "来自分组 {group}",
+ mcpAccessTreeSourceConnection: "连接设置",
+ mcpAccessTreeSourceDatabase: "库设置",
+ mcpAccessTreeGroupCount: "{count} 个连接",
+ mcpAccessTreeLegacy: "旧规则",
+ mcpAccessTreeLegacyHint: "由旧版本保存:只能收紧连接继承到的权限。重新选择一次权限即可变成普通设置。",
+ mcpAccessTreeCoveredByGroup: "已通过选中的上级分组可见",
+ mcpAccessTreeHighRiskConfirm: "高危权限允许在该资源上执行 DDL、DROP、TRUNCATE 和无条件的增删改。确定继续吗?",
+ mcpAccessTreeDatabases: "库范围",
+ mcpAccessTreeDatabaseScopeAll: "全部库",
+ mcpAccessTreeDatabaseScopeSelected: "指定库({count})",
+ mcpAccessTreeDatabaseScopeNone: "不开放任何库",
+ mcpDatabaseRemoveConfirm: "移除所选库也会删除这些库的独立权限,是否继续?",
+ mcpDatabaseUnavailable: "库权限配置暂不可用,请等待加载完成或重试。",
+ mcpDatabaseConfigure: "配置库权限",
+ mcpDatabaseOverrideCount: "{count} 项独立权限",
+ mcpDatabaseDialogTitle: "{name} / 库访问权限",
+ mcpDatabaseDialogDescription: "选择允许访问的库,并为每个库设置权限。移入右侧后,应用才会生效。",
+ mcpDatabaseInherited: "继承权限:{level}",
+ mcpDatabaseSavedInherited: "上级权限有未应用修改。仅应用库权限后,仍继承当前已保存权限:{level}",
+ mcpDatabaseHiddenConnection: "该连接当前对 MCP 不可见。应用库权限不会同时开放连接。",
+ mcpDatabaseAllHint: "包含当前及以后新增的库,统一使用连接权限。",
+ mcpDatabaseNoneHint: "应用后不允许访问任何库。",
+ mcpDatabaseLoaded: "已获取 {count} 个库(当前账号可见)",
+ mcpDatabaseRefresh: "刷新库列表",
+ mcpDatabaseAddSelected: "添加 →",
+ mcpDatabaseRemoveSelected: "← 移除",
+ mcpDatabaseAvailable: "未选择({count})",
+ mcpDatabaseSelected: "已选择({count})",
+ mcpDatabaseSearch: "搜索库名",
+ mcpDatabaseSelectResults: "选择当前搜索结果({count})",
+ mcpDatabaseBatchLevel: "批量设置权限({count})",
+ mcpDatabaseBatchHighRiskConfirm: "确认为勾选的 {count} 个库设置完全访问吗?连接只读与生产库保护仍会生效。",
+ mcpDatabaseNotDiscovered: "未在本次列表中发现",
+ mcpDatabaseShowMore: "显示更多(已显示 {shown}/{total})",
+ mcpDatabaseSaveHint: "仅保存本连接的库范围和单库权限;其他未保存修改保留。",
+ mcpDatabaseApply: "应用本连接库权限",
+ mcpAccessTreePickDatabases: "选择库",
+ mcpAccessTreePickerTitle: "{name} 的库",
+ mcpAccessTreeLoadingDatabases: "正在加载库列表...",
+ mcpAccessTreeLoadDatabasesFailed: "无法加载库列表:{error}。仍可手动添加库名。",
+ mcpAccessTreeManualDatabase: "手动添加库名",
+ mcpAccessTreeNoMatch: "没有匹配的资源",
+ mcpAccessTreeEmpty: "还没有连接",
+ mcpAccessTreeFootnote: "优先级:库 > 连接 > 最近的分组 > 上级分组 > 全局默认。连接只读保护、生产保护和数据库账号权限始终在此之上生效。",
+ mcpAccessTreeNacosNamespace: "命名空间",
+ mcpPluginScopeAll: "全部({title})",
+ mcpPluginScopeSelected: "指定({count})",
+ mcpPluginScopeNone: "不开放任何{title}",
+ mcpPluginScopeAdd: "添加{title}",
+ mcpPluginScopeLoad: "从插件读取",
+ mcpPluginToolsMode: "插件工具对外提供方式",
+ mcpPluginToolsModeDescription: "设置 DBX 如何向 MCP 客户端提供已授权的插件工具。更改后点击底部“应用”生效。",
+ mcpPluginToolsModeAuto: "自动(兼容模式)",
+ mcpPluginToolsModeFlat: "直接列出(默认)",
+ mcpPluginToolsModeLazy: "按需发现",
+ mcpPluginToolsModeFlatDescription: "将已授权的插件工具逐个列出,客户端可直接调用。",
+ mcpPluginToolsModeLazyDescription: "提供统一的插件查询与调用入口,使用时再获取具体工具信息。需开启“DBX 通用 → 插件发现与调用”。",
+ mcpPluginToolsModeAutoDescription: "保留原有自动切换行为:插件工具总数不超过 40 个时直接列出,更多时使用按需发现。",
+ mcpBrowser: {
+ viewMode: "查看方式",
+ viewManage: "分类管理",
+ viewOverview: "全局总览",
+ overviewSummary: "{toolsets} 个工具集 · {total} 个工具 · 已开启 {enabled} 个",
+ overviewPluginsHint: "按插件查看工具与授权状态,点击进入详情配置。",
+ overviewOpenDetails: "查看详情",
+ expandCategory: "展开分类",
+ collapseCategory: "收起分类",
+ builtin: "内置能力",
+ plugins: "插件扩展",
+ advanced: "高级配置",
+ navigation: "能力分类",
+ searchPlaceholder: "搜索分类、能力、插件或工具…",
+ clearSearch: "清空搜索",
+ searchResults: "搜索结果",
+ categoryCount: "{count} 个工具集",
+ summary: "{toolsets} 个工具集 · {total} 个工具 · 已开启 {enabled} 个",
+ enableCategory: "本分类全部开启",
+ disableCategory: "本分类全部关闭",
+ draftHint: "可在详情中应用当前工具集,或点击底部“应用”保存全部待应用设置。",
+ batchChanged: "已修改本分类工具,点击“应用”生效",
+ coverageHint: "适用连接按连接类型统计,不代表实际授权范围。",
+ uncovered: "{count} 个连接暂无内置工具覆盖",
+ viewDetails: "查看详情",
+ emptyEnabled: "本分类没有已开启的工具,可取消“仅显示已开启”继续配置。",
+ retry: "重试",
+ enabledToolCount: "已开启 {enabled}/{total}",
+ partialEnabled: "部分开启",
+ coverageConnections: "适用于 {count} 个连接",
+ coveragePartialConnections: "部分支持 {count} 个",
+ noMatchingConnections: "暂无适用连接",
+ resourceScopes: "资源范围",
+ pluginImmediate: "更改立即保存,不受底部“应用 / 取消”影响",
+ pluginSaving: "正在保存…",
+ pluginSaved: "已保存",
+ pluginOnlyEnabledEmpty: "没有已开启的工具,可取消“仅显示已开启”查看。",
+ pluginUnavailable: "此插件已不可用,请刷新插件列表",
+ resourceKind: {
+ database: "数据库",
+ dbIndex: "逻辑库",
+ topic: "主题",
+ queue: "队列",
+ org: "组织",
+ namespace: "命名空间",
+ },
+ category: {
+ database: { title: "数据库", description: "查询数据、管理会话与事务、浏览对象结构和执行 Redis 命令。" },
+ nacos: { title: "Nacos", description: "管理配置、服务与实例。" },
+ consul: { title: "Consul", description: "管理 KV、发现服务并查看健康状态。" },
+ mq: { title: "消息队列", description: "读取与发送消息。" },
+ salesforce: { title: "Salesforce", description: "查询身份并操作数据。" },
+ dbx: { title: "DBX 通用", description: "此处包含跨产品共享能力:连接发现、工作台联动、连接管理以及插件发现与调用。" },
+ other: { title: "其他能力", description: "尚未归入分类的工具集,可在此查看与配置。" },
+ },
+ },
+ mcpCapabilitiesTitle: "MCP 能力",
+ mcpCapabilitiesFilterLabel: "能力筛选",
+ mcpCapabilitiesFilterAll: "全部",
+ mcpCapabilitiesFilterBuiltin: "内置",
+ mcpCapabilitiesFilterPlugin: "插件",
+ mcpCapabilitiesOnlyEnabled: "仅显示已开启",
+ mcpCapabilitiesDescription: "内置 MCP 工具按场景分组。关闭某组后,客户端即使缓存了工具定义也会被服务端拒绝。每组都标明了适用的数据库类型。",
+ mcpCapabilitiesLoading: "正在加载 MCP 能力...",
+ mcpCapabilitiesLoadFailed: "加载 MCP 能力失败:{error}",
+ mcpCapabilitiesSearchPlaceholder: "搜索能力或工具",
+ mcpCapabilitiesSearchEmpty: "没有匹配的能力",
+ mcpToolsetToolCount: "{enabled}/{total} 个工具",
+ mcpAccessLevelClassified: "逐次判定",
+ mcpCoverageTypes: "适用 {count} 种数据库",
+ mcpCoverageToolTypes: "{tools}:{count} 种",
+ mcpCoverageNotBound: "不绑定连接",
+ mcpCoverageUsableConnections: "你有 {count} 个连接会用到",
+ mcpCoverageNoUsableConnections: "你的连接都用不到",
+ mcpCoveragePartialConnections: "{count} 个连接只支持其中部分工具",
+ mcpCoverageUncoveredConnections: "有 {count} 个连接的类型暂无 MCP 工具:{names}",
+ mcpCoverageSearchPlaceholder: "搜索数据库类型",
+ mcpCoverageSearchEmpty: "没有匹配的数据库类型",
+ mcpCoverageLegend: "只列出支持的类型。高亮的是你已有连接的类型;带 * 表示本组有部分工具不支持该类型,悬停可查看详情。",
+ mcpCoverageTypeUnsupportedTool: "{tool} 不支持",
+ mcpCoverageCategoryOther: "其他",
+ mcpCoveragePartialTool: "{tool} 仅支持其中 {count}/{total} 种",
+ mcpToolDetailSkippedConnections: "以下连接不支持:{names}",
+ mcpToolDetailCoverage: "支持的数据库类型({count})",
+ mcpToolDetailParameterDefault: "默认:{value}",
+ mcpToolDetailParameterDescription: "说明",
+ mcpToolDetailParameterRequiredNo: "否",
+ mcpToolDetailParameterRequiredYes: "是",
+ mcpToolDetailParameterRequired: "必填",
+ mcpToolDetailParameterType: "类型",
+ mcpToolDetailParameterName: "参数名",
+ mcpToolDetailNoParameters: "无参数",
+ mcpToolDetailParameters: "参数",
+ mcpToolDetailDescription: "给模型的说明",
+ mcpToolDetailAccessClassified: "逐次判定(按语句判为读、写或高危)",
+ mcpToolDetailAccess: "权限级别",
+ mcpToolDetailSummary: "说明",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "你有 {count} 个连接用不了",
+ mcpToolsetDetailTools: "工具",
+ mcpToolsetDetailCoverage: "覆盖范围",
+ mcpToolsetApply: "应用本工具集",
+ mcpToolsetApplying: "应用中…",
+ mcpToolsetPending: "{count} 项工具修改尚未应用",
+ mcpToolsetApplied: "当前配置已应用",
+ mcpToolsetCloseKeepsDraft: "关闭后保留修改,也可在设置页统一应用。",
+ mcpToolsetApplyFailed: "应用失败:{error}。修改已保留,请重试。",
+ mcpToolsetApplyUnavailable: "工具配置暂不可用,请等待加载完成或重试。",
+ mcpToolsetDetailClose: "关闭",
+ mcpPluginToolEntriesTitle: "插件工具条目",
+ mcpPluginsTitle: "插件",
+ mcpPluginsDescription: "提供 MCP 工具的插件。每个插件整体开关和授权,修改立即保存。",
+ mcpPluginsRefresh: "刷新",
+ mcpPluginsLoading: "正在加载插件工具...",
+ mcpPluginsLoadFailed: "加载插件工具失败:{error}",
+ mcpPluginsEmpty: "已安装的插件中没有提供 MCP 工具的。",
+ mcpPluginSaveFailed: "保存 {name} 失败:{message}",
+ mcpPluginAuthorClosed: "插件作者未开放外部 MCP",
+ mcpPluginDiscoveryFailed: "工具发现失败",
+ mcpPluginToolCount: "已开放 {exposed}/{total} 个工具",
+ mcpPluginToolCountOff: "{total} 个工具,未开启",
+ mcpPluginCeilingSummary: "上限:{level}",
+ mcpPluginPendingTools: "{count} 个新工具待确认",
+ mcpPluginReview: "去确认",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "工具发现失败:{error}",
+ mcpPluginCeilingTitle: "授权上限",
+ mcpPluginCeilingDescription: "超过上限的工具不会出现在 MCP 客户端中。实际调用还须满足资源权限和连接可见范围的限制。",
+ mcpPluginEnableFirst: "开启插件后才能修改上限和工具。",
+ mcpPluginDefaultToolset: "工具",
+ mcpPluginNoTools: "该插件当前没有提供 MCP 工具。",
+ mcpPluginAuthorizeTitle: "授权 {name} 接入 MCP",
+ mcpPluginAuthorizeDescription: "选择这个插件的工具最多能做到什么程度。下方已声明的工具会全部记为已确认;以后新增的工具,或声明级别升高的工具,如果需要读以上权限,会再次请你确认。",
+ mcpPluginAuthorizeTools: "工具({count})",
+ mcpPluginAuthorizeIncluded: "开放",
+ mcpPluginAuthorizeExcluded: "隐藏",
+ mcpPluginAuthorizeFootnote: "之后可以在插件详情里调整上限,或单独关闭某个工具。",
+ mcpPluginAccessUndeclared: "作者未声明 —— 不会开放",
+ mcpPluginUndeclaredCount: "{count} 个工具未在 manifest 中声明,不会开放",
+ mcpPluginUndeclaredTools: "{count} 个工具未在插件 manifest 中声明权限级别,不会开放:{names}",
+ mcpPluginAuthorizeCancel: "取消",
+ mcpPluginAuthorizeConfirm: "授权",
+ mcpPluginToolEntriesHint: "高级:插件工具的白名单条目。dbx_*__* 放行所有插件工具,dbx_<前缀>__* 放行单个插件。插件开关决定有哪些工具,这里的条目是额外的一层过滤。",
+ mcpPluginAllowlistBlocked: "MCP 工具白名单里没有插件条目,无论插件开关如何,插件工具都不会出现。",
+ mcpPluginAllowlistAllow: "放行插件工具",
+ mcpPluginExposure: {
+ exposed: "已开放",
+ undeclared: "未声明",
+ pluginDisabled: "插件未开启",
+ toolDisabled: "已关闭",
+ aboveCeiling: "超过上限",
+ pendingApproval: "待确认",
+ },
+ mcpPluginCeilingLevel: {
+ read: "只读",
+ write: "读写",
+ full: "完全(含高危)",
+ },
+ mcpAccessLevel: {
+ read: "读",
+ write: "写",
+ full: "高危",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "发现与上下文", description: "列出连接和数据库,为模型获取 Schema 上下文。" },
+ sqlQuery: { title: "SQL 查询", description: "执行查询和脚本,每条语句的风险逐次判定。" },
+ sqlSession: { title: "会话与事务", description: "跨调用固定会话,并控制事务。" },
+ sqlSchema: { title: "对象结构", description: "浏览表、字段和存储过程源码。" },
+ redis: { title: "Redis 命令", description: "执行 Redis 命令。" },
+ mq: { title: "消息读取与发送", description: "读取和发送 Kafka、RocketMQ、RabbitMQ 消息。" },
+ salesforce: { title: "身份查询与数据操作", description: "识别当前用户,写入单条记录。" },
+ workbench: { title: "工作台联动", description: "在 DBX 中打开表、展示查询结果。" },
+ adminConnections: { title: "连接管理", description: "新增、复制和删除 DBX 连接。" },
+ pluginRouter: { title: "插件发现与调用", description: "按需发现插件工具,并通过统一入口调用。" },
+ nacosConfig: { title: "配置管理", description: "按命名空间读取、搜索、发布和删除 Nacos 配置。" },
+ nacosService: { title: "服务管理", description: "列出服务和实例,上下线实例或调整权重。" },
+ consulKv: { title: "KV 管理", description: "列出、读取、写入和删除 Consul KV,支持 CAS。" },
+ consulService: { title: "服务发现与健康", description: "目录服务和节点、服务健康、维护模式。" },
+ },
mcpTransportLabel: "接入类型",
mcpRuntimeSettings: "运行参数",
mcpTransportLocalStdio: "本地 stdio",
@@ -11374,6 +11665,28 @@ export default withEnglishFallback({
mcpToolPluginList: "插件目录",
mcpToolPluginTools: "插件工具清单",
mcpToolPluginCall: "调用插件工具",
+ mcpToolNacosListNamespaces: "列出 Nacos 命名空间",
+ mcpToolNacosListConfigs: "列出 Nacos 配置",
+ mcpToolNacosGetConfig: "读取 Nacos 配置",
+ mcpToolNacosConfigHistory: "Nacos 配置历史",
+ mcpToolNacosPublishConfig: "发布 Nacos 配置",
+ mcpToolNacosDeleteConfig: "删除 Nacos 配置",
+ mcpToolNacosListServices: "列出 Nacos 服务",
+ mcpToolNacosListInstances: "列出 Nacos 实例",
+ mcpToolNacosUpdateInstance: "修改 Nacos 实例",
+ mcpToolNacosSearchConfigs: "搜索 Nacos 配置",
+ mcpToolNacosRollbackConfig: "回滚 Nacos 配置",
+ mcpToolNacosGetService: "查看 Nacos 服务",
+ mcpToolNacosRegisterInstance: "注册 Nacos 实例",
+ mcpToolNacosDeregisterInstance: "注销 Nacos 实例",
+ mcpToolConsulKvList: "列出 Consul KV",
+ mcpToolConsulKvGet: "读取 Consul KV",
+ mcpToolConsulKvPut: "写入 Consul KV",
+ mcpToolConsulKvDelete: "删除 Consul KV",
+ mcpToolConsulListServices: "列出 Consul 服务",
+ mcpToolConsulListNodes: "列出 Consul 节点",
+ mcpToolConsulServiceHealth: "Consul 服务健康",
+ mcpToolConsulSetMaintenance: "Consul 维护模式",
supportInfoTitle: "支持信息",
supportInfoDescription: "提交 issue 或寻求帮助时,可复制这些环境信息。",
supportInfoCopy: "复制支持信息",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 24c41167df..8a676c8ea9 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -590,6 +590,14 @@ export default withEnglishFallback({
pluginPlatform: {
dataAccessConsent: "「{name}」請求讀取連線「{connection}」中的資料。在該連線開啟期間,外掛可以對它執行唯讀查詢,直到你在外掛中心撤銷授權。是否允許?",
dataAccessConsentTitle: "資料存取請求",
+ mcpToolsBadge: "MCP 工具",
+ mcpToolsBadgeHint: "該外掛提供 MCP 工具,可在「設定 → MCP → 能力」中啟用並授權。",
+ mcpToolsFilter: "僅顯示提供 MCP 工具的外掛({count})",
+ externalMcp: {
+ title: "外部 MCP 用戶端",
+ offered: "外掛作者允許其工具接入外部 MCP 用戶端(Claude Code、Cursor 等)。請到「設定 → MCP → 能力」開啟並選擇授權上限。",
+ notOffered: "外掛作者未開放該外掛的工具給外部 MCP 用戶端。",
+ },
aiTools: {
title: "內建 AI 工具",
description: "預設關閉:僅在此開關開啟期間,DBX AI 助理(Agent 模式)才能在你已開啟的此外掛連線上呼叫其工具。未宣告為唯讀的工具每次呼叫前仍會請求你確認,工具輸出會傳送給你設定的 AI 模型。",
@@ -6386,6 +6394,10 @@ export default withEnglishFallback({
},
detail: {
mcpTool: "MCP 工具",
+ mcpClient: "MCP 用戶端",
+ mcpTransport: "MCP 傳輸",
+ mcpAccess: "MCP 權限",
+ mcpConfirmation: "MCP 確認",
kind: "類型",
operation: "操作",
connection: "連線",
@@ -8806,7 +8818,8 @@ export default withEnglishFallback({
mcpWindsurfConfigPath: "Windsurf 可放在 ~/.codeium/windsurf/mcp_config.json。",
mcpOpenCodeConfigPath: "全域 ~/.config/opencode/opencode.json,專案級 opencode.json。",
mcpExecutionMode: "MCP 全域預設權限",
- mcpExecutionModeDescription: "設定未配置連線或單一資料庫權限時使用的預設等級。連線預設與單庫設定可依範圍覆蓋此預設值。",
+ mcpExecutionModeDescription: "未單獨設定權限的資源使用此預設值;需要不同權限時,在下方存取控制中設定。",
+ mcpPermissionsDraftHint: "全域預設權限及群組、連線設定需點擊底部「套用」生效;資料庫權限也可在對話框中個別套用。命名空間等子範圍設定會立即儲存。放棄草稿不會撤銷已儲存修改。",
mcpExecutionModeReadOnly: "唯讀",
mcpExecutionModeSafeWrite: "資料讀寫",
mcpExecutionModeRecommended: "推薦",
@@ -8815,21 +8828,37 @@ export default withEnglishFallback({
mcpExecutionModeSafeWriteDescription: "允許一般 INSERT、帶有效條件的 UPDATE/DELETE、MongoDB 可驗證範圍的變更,以及 Redis 一般寫入和明確鍵刪除;阻止全表修改與結構變更。",
mcpExecutionModeHighRiskWriteDescription: "在資料讀寫基礎上允許全表修改、DDL、TRUNCATE、清空資料庫及其他高風險操作;生產庫與連線唯讀保護仍然生效。",
mcpExecutionModeHighRiskConfirm: "完整存取允許全表修改、DDL、TRUNCATE、清空資料庫及其他高風險操作。確定要啟用嗎?",
- mcpPromptHighRiskSql: "高風險 SQL 請求人工確認(僅桌面版;唯讀與正式環境保護維持不變)",
+ mcpCallSafety: "呼叫安全",
+ mcpCallSafetyLegacy: "舊版臨時授權",
+ mcpCallSafetyEnabled: "高風險呼叫逐次確認",
+ mcpCallSafetyDisabled: "不額外確認",
+ mcpCallSafetyLegacyHint: "目前保留舊版行為:資料讀寫權限可經確認臨時執行部分高風險操作,完整存取不詢問。切換新策略後,權限不足會直接拒絕,完整存取的高風險呼叫也須逐次確認。",
+ mcpCallSafetyMigrate: "改用新的確認策略",
+ mcpCallSafetyDisableLegacy: "關閉舊版臨時授權",
+ mcpCallSafetyConfirm: "高風險工具呼叫執行前,請求人工確認",
+ mcpCallSafetyHint: "涵蓋內建與外掛中辨識為高風險的呼叫。先檢查權限,再請求確認;完整存取也遵循此策略,確認不會提升權限。",
+ mcpCallSafetyDesktopHint: "確認僅在 DBX 桌面端進行,每次只批准目前呼叫;無法確認、拒絕或逾時均不執行。連線唯讀與正式環境保護始終有效。修改後點選「套用」生效。",
+ mcpToolApprovalGenericTitle: "確認高風險工具呼叫",
mcpSqlApprovalTitle: "MCP 高風險 SQL 核准",
+ mcpToolApprovalPluginTitle: "確認 {plugin} 的高危工具",
+ mcpToolApprovalRedisTitle: "確認高危 Redis 命令",
+ mcpToolApprovalDescription: "MCP 用戶端請求執行一個高危操作。只有在你預期這次呼叫時才允許。",
+ mcpToolApprovalTool: "工具",
+ mcpToolApprovalTarget: "目標",
mcpSqlApprovalScope: "連線:{connection} · 資料庫:{database}",
mcpSqlApprovalOnce: "僅本次請求",
mcpSqlApprovalHour: "允許此資料庫 1 小時",
mcpSqlApprovalDay: "允許此資料庫 1 天",
mcpSqlApprovalDeny: "拒絕",
- mcpCapabilityTitle: "權限能力對照",
- mcpCapabilityDescription: "以下為典型操作;無法可靠分類的請求需要完整存取。",
+ mcpCapabilityTitle: "權限說明",
+ mcpCapabilityDescription: "下表說明權限等級;工具仍須在「能力」頁面啟用。權限不足直接拒絕,人工確認由獨立的「呼叫安全」控制;舊版臨時授權行為在該區域單獨說明。",
mcpCapabilityOperation: "能力",
mcpCapabilityRead: "查詢與讀取",
mcpCapabilityScopedMutation: "範圍可控的資料變更(INSERT、有效條件 UPDATE/DELETE、明確鍵寫入/刪除)",
mcpCapabilityBroadMutation: "全表更新/刪除與清空資料",
mcpCapabilitySchemaAdmin: "DDL、結構變更與高風險管理命令",
- mcpCapabilityConnectionManagement: "MCP 連線新增/刪除",
+ mcpCapabilityConnectionCreate: "MCP 連線新增/複製(全域預設權限)",
+ mcpCapabilityConnectionRemove: "MCP 連線刪除(全域預設權限)",
mcpCapabilityAllowed: "允許",
mcpCapabilityBlocked: "禁止",
mcpQueryTimeout: "查詢逾時(秒)",
@@ -8837,6 +8866,9 @@ export default withEnglishFallback({
mcpQueryTimeoutInvalid: "請輸入非負整數秒數,或留空以繼承連線設定。",
mcpCapabilityAlwaysEnforced: "所有模式仍受連線允許範圍、連線唯讀、生產庫保護和資料庫帳號權限約束。",
mcpPolicySaveFailed: "儲存 MCP 存取策略失敗:{error}",
+ mcpPolicyRetry: "重試",
+ mcpPolicyRecover: "備份並重設 MCP 權限",
+ mcpPolicyRecoverConfirm: "這會立即備份損壞的策略並重設 MCP 權限,同時清除未儲存的權限修改。所有連線和工具將被停用,直到你重新設定。是否繼續?",
mcpPolicyLoadFailed: "載入 MCP 存取策略失敗:{error}",
mcpDetectionTiming: "打開此頁時會自動檢測,點擊重新檢查可刷新。",
mcpNpmBoundary: "DBX 只檢測和提示 MCP 狀態;安裝與升級仍由 npm、pnpm 或 bun 完成。",
@@ -8927,6 +8959,265 @@ export default withEnglishFallback({
mcpDatabaseEmptyHint: "點擊「載入資源清單」取得資料庫清單,或手動新增允許的資料庫。",
mcpManagementAccess: "接入方式",
mcpManagementPermissions: "權限管理",
+ mcpManagementCapabilities: "能力",
+ mcpOpenCallHistory: "檢視 MCP 呼叫記錄",
+ mcpAccessTreeTitle: "存取控制",
+ mcpAccessTreeDescription: "為群組、連線和資料庫單獨設定權限。選擇「繼承」時使用上級設定,「生效」欄顯示最終權限及來源。",
+ mcpAccessTreeSummary: "可見連線 {visible}/{total} · 例外:{groups} 個分組、{connections} 個連線、{databases} 個資料庫",
+ mcpAccessTreeScopeLabel: "連線可見範圍",
+ mcpAccessTreeScopeAll: "全部連線",
+ mcpAccessTreeScopeCustom: "僅選取的",
+ mcpAccessTreeSearchPlaceholder: "搜尋分組、連線或資料庫",
+ mcpAccessTreeExceptionsOnly: "僅顯示單獨設定",
+ mcpAccessTreeColumnResource: "資源",
+ mcpAccessTreeColumnVisible: "可見",
+ mcpAccessTreeColumnSetting: "權限",
+ mcpAccessTreeColumnEffective: "生效",
+ mcpAccessTreeInherit: "繼承",
+ mcpAccessTreeGroupPartiallyVisible: "部分連線可見({visible}/{total})",
+ mcpAccessTreeGroupCurrentVisible: "目前連線皆可見({visible}/{total})",
+ mcpAccessTreeGroupChildrenOnlyHint: "僅子項已獲授權,尚未開放整個群組。勾選將開放整組,包含以後新增的連線。",
+ mcpAccessTreeGroupDefaultHint: "群組預設權限僅供未單獨設定權限的子項繼承,不改變連線的可見範圍。",
+ mcpAccessTreeHidden: "對 MCP 不可見",
+ mcpAccessTreeSourceGlobal: "全域預設",
+ mcpAccessTreeSourceGroup: "來自分組 {group}",
+ mcpAccessTreeSourceConnection: "連線設定",
+ mcpAccessTreeSourceDatabase: "資料庫設定",
+ mcpAccessTreeGroupCount: "{count} 個連線",
+ mcpAccessTreeLegacy: "舊規則",
+ mcpAccessTreeLegacyHint: "由舊版本儲存:只能收緊連線繼承到的權限。重新選擇一次權限即可變成一般設定。",
+ mcpAccessTreeCoveredByGroup: "已透過選取的上層分組可見",
+ mcpAccessTreeHighRiskConfirm: "高危權限允許在該資源上執行 DDL、DROP、TRUNCATE 和無條件的增刪改。確定繼續嗎?",
+ mcpAccessTreeDatabases: "資料庫範圍",
+ mcpAccessTreeDatabaseScopeAll: "全部資料庫",
+ mcpAccessTreeDatabaseScopeSelected: "指定資料庫({count})",
+ mcpAccessTreeDatabaseScopeNone: "不開放任何資料庫",
+ mcpDatabaseRemoveConfirm: "移除所選資料庫也會刪除其個別權限,是否繼續?",
+ mcpDatabaseUnavailable: "資料庫權限設定暫時無法使用,請等待載入完成或重試。",
+ mcpDatabaseConfigure: "設定資料庫權限",
+ mcpDatabaseOverrideCount: "{count} 項獨立權限",
+ mcpDatabaseDialogTitle: "{name} / 資料庫存取權限",
+ mcpDatabaseDialogDescription: "選擇允許存取的資料庫,並分別設定權限。移至右側後,套用才會生效。",
+ mcpDatabaseInherited: "繼承權限:{level}",
+ mcpDatabaseSavedInherited: "上層權限有未套用的修改。僅套用資料庫權限後,仍繼承目前已儲存的權限:{level}",
+ mcpDatabaseHiddenConnection: "此連線目前對 MCP 不可見。套用資料庫權限不會同時開放連線。",
+ mcpDatabaseAllHint: "包含目前及日後新增的資料庫,統一使用連線權限。",
+ mcpDatabaseNoneHint: "套用後不允許存取任何資料庫。",
+ mcpDatabaseLoaded: "已取得 {count} 個資料庫(目前帳號可見)",
+ mcpDatabaseRefresh: "重新整理清單",
+ mcpDatabaseAddSelected: "新增 →",
+ mcpDatabaseRemoveSelected: "← 移除",
+ mcpDatabaseAvailable: "未選擇({count})",
+ mcpDatabaseSelected: "已選擇({count})",
+ mcpDatabaseSearch: "搜尋資料庫名稱",
+ mcpDatabaseSelectResults: "選擇目前搜尋結果({count})",
+ mcpDatabaseBatchLevel: "批次設定權限({count})",
+ mcpDatabaseBatchHighRiskConfirm: "確認為勾選的 {count} 個資料庫設定完整存取嗎?連線唯讀與正式環境資料庫保護仍會生效。",
+ mcpDatabaseNotDiscovered: "未在本次清單中找到",
+ mcpDatabaseShowMore: "顯示更多(已顯示 {shown}/{total})",
+ mcpDatabaseSaveHint: "僅儲存此連線的資料庫範圍及個別權限;保留其他未儲存修改。",
+ mcpDatabaseApply: "套用此連線資料庫權限",
+ mcpAccessTreePickDatabases: "選擇資料庫",
+ mcpAccessTreePickerTitle: "{name} 的資料庫",
+ mcpAccessTreeLoadingDatabases: "正在載入資料庫清單...",
+ mcpAccessTreeLoadDatabasesFailed: "無法載入資料庫清單:{error}。仍可手動新增資料庫名稱。",
+ mcpAccessTreeManualDatabase: "手動新增資料庫名稱",
+ mcpAccessTreeNoMatch: "沒有符合的資源",
+ mcpAccessTreeEmpty: "還沒有連線",
+ mcpAccessTreeFootnote: "優先順序:資料庫 > 連線 > 最近的分組 > 上層分組 > 全域預設。連線唯讀保護、正式環境保護和資料庫帳號權限始終在此之上生效。",
+ mcpAccessTreeNacosNamespace: "命名空間",
+ mcpPluginScopeAll: "全部({title})",
+ mcpPluginScopeSelected: "指定({count})",
+ mcpPluginScopeNone: "不開放任何{title}",
+ mcpPluginScopeAdd: "新增{title}",
+ mcpPluginScopeLoad: "從外掛讀取",
+ mcpPluginToolsMode: "外掛工具對外提供方式",
+ mcpPluginToolsModeDescription: "設定 DBX 如何向 MCP 用戶端提供已授權的外掛工具。變更後點擊底部「套用」生效。",
+ mcpPluginToolsModeAuto: "自動(相容模式)",
+ mcpPluginToolsModeFlat: "直接列出(預設)",
+ mcpPluginToolsModeLazy: "按需探索",
+ mcpPluginToolsModeFlatDescription: "逐一列出已授權的外掛工具,供用戶端直接呼叫。",
+ mcpPluginToolsModeLazyDescription: "提供統一的外掛查詢與呼叫入口,使用時再取得具體工具資訊。需啟用「DBX 通用 → 外掛探索與呼叫」。",
+ mcpPluginToolsModeAutoDescription: "保留原有自動切換行為:外掛工具總數不超過 40 個時直接列出,更多時使用按需探索。",
+ mcpBrowser: {
+ viewMode: "檢視方式",
+ viewManage: "分類管理",
+ viewOverview: "全域總覽",
+ overviewSummary: "{toolsets} 個工具集 · {total} 個工具 · 已啟用 {enabled} 個",
+ overviewPluginsHint: "依外掛檢視工具與授權狀態,點擊進入詳細設定。",
+ overviewOpenDetails: "檢視詳細資料",
+ expandCategory: "展開分類",
+ collapseCategory: "收合分類",
+ builtin: "內建能力",
+ plugins: "外掛擴充",
+ advanced: "進階設定",
+ navigation: "能力分類",
+ searchPlaceholder: "搜尋分類、能力、外掛或工具…",
+ clearSearch: "清除搜尋",
+ searchResults: "搜尋結果",
+ categoryCount: "{count} 個工具集",
+ summary: "{toolsets} 個工具集 · {total} 個工具 · 已開啟 {enabled} 個",
+ enableCategory: "開啟本分類全部工具",
+ disableCategory: "關閉本分類全部工具",
+ draftHint: "可在詳細資料中套用目前工具組,或點擊底部「套用」儲存所有待套用設定。",
+ batchChanged: "已修改本分類工具,點選「套用」生效",
+ coverageHint: "適用連線依連線類型統計,不代表實際授權範圍。",
+ uncovered: "{count} 個連線尚無內建工具涵蓋",
+ viewDetails: "檢視詳情",
+ emptyEnabled: "本分類沒有已開啟的工具,可取消「僅顯示已開啟」繼續設定。",
+ retry: "重試",
+ enabledToolCount: "已開啟 {enabled}/{total}",
+ partialEnabled: "部分開啟",
+ coverageConnections: "適用於 {count} 個連線",
+ coveragePartialConnections: "部分支援 {count} 個",
+ noMatchingConnections: "暫無適用連線",
+ resourceScopes: "資源範圍",
+ pluginImmediate: "變更會立即儲存,不受底部「套用 / 取消」影響",
+ pluginSaving: "正在儲存…",
+ pluginSaved: "已儲存",
+ pluginOnlyEnabledEmpty: "沒有已開啟的工具,可取消「僅顯示已開啟」檢視。",
+ pluginUnavailable: "此外掛已無法使用,請重新整理外掛清單",
+ resourceKind: {
+ database: "資料庫",
+ dbIndex: "邏輯資料庫",
+ topic: "主題",
+ queue: "佇列",
+ org: "組織",
+ namespace: "命名空間",
+ },
+ category: {
+ database: { title: "資料庫", description: "查詢資料、管理工作階段與交易、瀏覽物件結構及執行 Redis 命令。" },
+ nacos: { title: "Nacos", description: "管理設定、服務與實例。" },
+ consul: { title: "Consul", description: "管理 KV、探索服務及檢視健康狀態。" },
+ mq: { title: "訊息佇列", description: "讀取與傳送訊息。" },
+ salesforce: { title: "Salesforce", description: "查詢身分及操作資料。" },
+ dbx: { title: "DBX 通用", description: "此處包含跨產品共用能力:連線探索、工作台連動、連線管理及外掛探索與呼叫。" },
+ other: { title: "其他能力", description: "尚未歸類的工具集,可在此檢視與設定。" },
+ },
+ },
+ mcpCapabilitiesTitle: "MCP 能力",
+ mcpCapabilitiesFilterLabel: "能力篩選",
+ mcpCapabilitiesFilterAll: "全部",
+ mcpCapabilitiesFilterBuiltin: "內建",
+ mcpCapabilitiesFilterPlugin: "外掛",
+ mcpCapabilitiesOnlyEnabled: "僅顯示已開啟",
+ mcpCapabilitiesDescription: "內建 MCP 工具依情境分組。關閉某組後,用戶端即使快取了工具定義也會被伺服器拒絕。每組都標明了適用的資料庫類型。",
+ mcpCapabilitiesLoading: "正在載入 MCP 能力...",
+ mcpCapabilitiesLoadFailed: "載入 MCP 能力失敗:{error}",
+ mcpCapabilitiesSearchPlaceholder: "搜尋能力或工具",
+ mcpCapabilitiesSearchEmpty: "沒有符合的能力",
+ mcpToolsetToolCount: "{enabled}/{total} 個工具",
+ mcpAccessLevelClassified: "逐次判定",
+ mcpCoverageTypes: "適用 {count} 種資料庫",
+ mcpCoverageToolTypes: "{tools}:{count} 種",
+ mcpCoverageNotBound: "不綁定連線",
+ mcpCoverageUsableConnections: "你有 {count} 個連線會用到",
+ mcpCoverageNoUsableConnections: "你的連線都用不到",
+ mcpCoveragePartialConnections: "{count} 個連線只支援其中部分工具",
+ mcpCoverageUncoveredConnections: "有 {count} 個連線的類型暫無 MCP 工具:{names}",
+ mcpCoverageSearchPlaceholder: "搜尋資料庫類型",
+ mcpCoverageSearchEmpty: "沒有符合的資料庫類型",
+ mcpCoverageLegend: "只列出支援的類型。醒目標示的是你已有連線的類型;帶 * 表示本組有部分工具不支援該類型,懸停可查看詳情。",
+ mcpCoverageTypeUnsupportedTool: "{tool} 不支援",
+ mcpCoverageCategoryOther: "其他",
+ mcpCoveragePartialTool: "{tool} 僅支援其中 {count}/{total} 種",
+ mcpToolDetailSkippedConnections: "以下連線不支援:{names}",
+ mcpToolDetailCoverage: "支援的資料庫類型({count})",
+ mcpToolDetailParameterDefault: "預設:{value}",
+ mcpToolDetailParameterDescription: "說明",
+ mcpToolDetailParameterRequiredNo: "否",
+ mcpToolDetailParameterRequiredYes: "是",
+ mcpToolDetailParameterRequired: "必填",
+ mcpToolDetailParameterType: "類型",
+ mcpToolDetailParameterName: "參數名",
+ mcpToolDetailNoParameters: "無參數",
+ mcpToolDetailParameters: "參數",
+ mcpToolDetailDescription: "給模型的說明",
+ mcpToolDetailAccessClassified: "逐次判定(依語句判為讀、寫或高危)",
+ mcpToolDetailAccess: "權限級別",
+ mcpToolDetailSummary: "說明",
+ mcpToolDetailId: "ID",
+ mcpToolSkippedConnections: "你有 {count} 個連線用不了",
+ mcpToolsetDetailTools: "工具",
+ mcpToolsetDetailCoverage: "涵蓋範圍",
+ mcpToolsetApply: "套用此工具組",
+ mcpToolsetApplying: "套用中…",
+ mcpToolsetPending: "{count} 項工具修改尚未套用",
+ mcpToolsetApplied: "目前設定已套用",
+ mcpToolsetCloseKeepsDraft: "關閉後保留修改,也可在設定頁統一套用。",
+ mcpToolsetApplyFailed: "套用失敗:{error}。修改已保留,請重試。",
+ mcpToolsetApplyUnavailable: "工具設定暫時無法使用,請等待載入完成或重試。",
+ mcpToolsetDetailClose: "關閉",
+ mcpPluginToolEntriesTitle: "外掛工具條目",
+ mcpPluginsTitle: "外掛",
+ mcpPluginsDescription: "提供 MCP 工具的外掛。每個外掛整體開關和授權,修改立即儲存。",
+ mcpPluginsRefresh: "重新整理",
+ mcpPluginsLoading: "正在載入外掛工具...",
+ mcpPluginsLoadFailed: "載入外掛工具失敗:{error}",
+ mcpPluginsEmpty: "已安裝的外掛中沒有提供 MCP 工具的。",
+ mcpPluginSaveFailed: "儲存 {name} 失敗:{message}",
+ mcpPluginAuthorClosed: "外掛作者未開放外部 MCP",
+ mcpPluginDiscoveryFailed: "工具探索失敗",
+ mcpPluginToolCount: "已開放 {exposed}/{total} 個工具",
+ mcpPluginToolCountOff: "{total} 個工具,未開啟",
+ mcpPluginCeilingSummary: "上限:{level}",
+ mcpPluginPendingTools: "{count} 個新工具待確認",
+ mcpPluginReview: "去確認",
+ mcpPluginDetailDescription: "{id} · v{version}",
+ mcpPluginDiscoveryError: "工具探索失敗:{error}",
+ mcpPluginCeilingTitle: "授權上限",
+ mcpPluginCeilingDescription: "超過上限的工具不會出現在 MCP 用戶端中。實際呼叫還須符合資源權限及連線可見範圍的限制。",
+ mcpPluginEnableFirst: "開啟外掛後才能修改上限和工具。",
+ mcpPluginDefaultToolset: "工具",
+ mcpPluginNoTools: "該外掛目前沒有提供 MCP 工具。",
+ mcpPluginAuthorizeTitle: "授權 {name} 接入 MCP",
+ mcpPluginAuthorizeDescription: "選擇這個外掛的工具最多能做到什麼程度。下方已宣告的工具會全部記為已確認;以後新增的工具,或宣告級別升高的工具,如果需要讀以上權限,會再次請你確認。",
+ mcpPluginAuthorizeTools: "工具({count})",
+ mcpPluginAuthorizeIncluded: "開放",
+ mcpPluginAuthorizeExcluded: "隱藏",
+ mcpPluginAuthorizeFootnote: "之後可以在外掛詳情裡調整上限,或單獨關閉某個工具。",
+ mcpPluginAccessUndeclared: "作者未宣告 —— 不會開放",
+ mcpPluginUndeclaredCount: "{count} 個工具未在 manifest 中宣告,不會開放",
+ mcpPluginUndeclaredTools: "{count} 個工具未在外掛 manifest 中宣告權限級別,不會開放:{names}",
+ mcpPluginAuthorizeCancel: "取消",
+ mcpPluginAuthorizeConfirm: "授權",
+ mcpPluginToolEntriesHint: "進階:外掛工具的白名單條目。dbx_*__* 放行所有外掛工具,dbx_<前綴>__* 放行單一外掛。外掛開關決定有哪些工具,這裡的條目是額外的一層過濾。",
+ mcpPluginAllowlistBlocked: "MCP 工具白名單裡沒有外掛條目,無論外掛開關如何,外掛工具都不會出現。",
+ mcpPluginAllowlistAllow: "放行外掛工具",
+ mcpPluginExposure: {
+ exposed: "已開放",
+ undeclared: "未宣告",
+ pluginDisabled: "外掛未開啟",
+ toolDisabled: "已關閉",
+ aboveCeiling: "超過上限",
+ pendingApproval: "待確認",
+ },
+ mcpPluginCeilingLevel: {
+ read: "唯讀",
+ write: "讀寫",
+ full: "完全(含高危)",
+ },
+ mcpAccessLevel: {
+ read: "讀",
+ write: "寫",
+ full: "高危",
+ },
+ mcpToolset: {
+ coreDiscovery: { title: "探索與上下文", description: "列出連線和資料庫,為模型取得 Schema 上下文。" },
+ sqlQuery: { title: "SQL 查詢", description: "執行查詢和指令碼,每條語句的風險逐次判定。" },
+ sqlSession: { title: "工作階段與交易", description: "跨呼叫固定工作階段,並控制交易。" },
+ sqlSchema: { title: "物件結構", description: "瀏覽資料表、欄位和預存程序原始碼。" },
+ redis: { title: "Redis 命令", description: "執行 Redis 命令。" },
+ mq: { title: "訊息讀取與傳送", description: "讀取和傳送 Kafka、RocketMQ、RabbitMQ 訊息。" },
+ salesforce: { title: "身分查詢與資料操作", description: "識別目前使用者,寫入單筆記錄。" },
+ workbench: { title: "工作台聯動", description: "在 DBX 中開啟資料表、顯示查詢結果。" },
+ adminConnections: { title: "連線管理", description: "新增、複製和刪除 DBX 連線。" },
+ pluginRouter: { title: "外掛探索與呼叫", description: "按需探索外掛工具,並透過統一入口呼叫。" },
+ nacosConfig: { title: "設定管理", description: "依命名空間讀取、搜尋、發布和刪除 Nacos 設定。" },
+ nacosService: { title: "服務管理", description: "列出服務和實例,上下線實例或調整權重。" },
+ consulKv: { title: "KV 管理", description: "列出、讀取、寫入和刪除 Consul KV,支援 CAS。" },
+ consulService: { title: "服務探索與健康狀態", description: "目錄服務和節點、服務健康、維護模式。" },
+ },
mcpTransportLabel: "接入類型",
mcpRuntimeSettings: "執行參數",
mcpTransportLocalStdio: "本機 stdio",
@@ -9036,6 +9327,28 @@ export default withEnglishFallback({
mcpToolPluginList: "Plugin catalog",
mcpToolPluginTools: "Plugin tool listing",
mcpToolPluginCall: "Call plugin tools",
+ mcpToolNacosListNamespaces: "列出 Nacos 命名空間",
+ mcpToolNacosListConfigs: "列出 Nacos 設定",
+ mcpToolNacosGetConfig: "讀取 Nacos 設定",
+ mcpToolNacosConfigHistory: "Nacos 設定歷史",
+ mcpToolNacosPublishConfig: "發布 Nacos 設定",
+ mcpToolNacosDeleteConfig: "刪除 Nacos 設定",
+ mcpToolNacosListServices: "列出 Nacos 服務",
+ mcpToolNacosListInstances: "列出 Nacos 實例",
+ mcpToolNacosUpdateInstance: "修改 Nacos 實例",
+ mcpToolNacosSearchConfigs: "搜尋 Nacos 設定",
+ mcpToolNacosRollbackConfig: "回復 Nacos 設定",
+ mcpToolNacosGetService: "檢視 Nacos 服務",
+ mcpToolNacosRegisterInstance: "註冊 Nacos 執行個體",
+ mcpToolNacosDeregisterInstance: "取消註冊 Nacos 執行個體",
+ mcpToolConsulKvList: "列出 Consul KV",
+ mcpToolConsulKvGet: "讀取 Consul KV",
+ mcpToolConsulKvPut: "寫入 Consul KV",
+ mcpToolConsulKvDelete: "刪除 Consul KV",
+ mcpToolConsulListServices: "列出 Consul 服務",
+ mcpToolConsulListNodes: "列出 Consul 節點",
+ mcpToolConsulServiceHealth: "Consul 服務健康",
+ mcpToolConsulSetMaintenance: "Consul 維護模式",
updateDownloadSource: "更新下載來源",
updateDownloadSourceDescription: "選擇應用程式內更新安裝程式的下載來源。建議使用官方來源;CNB 在中國大陸網路環境下可能更快。",
updateDownloadSourceOfficial: "官方來源(建議)",
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpAccessTree.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpAccessTree.spec.ts
new file mode 100644
index 0000000000..aaadf95983
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpAccessTree.spec.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it } from "vitest";
+
+import type { McpConnectionPolicy, McpGlobalPolicy } from "@/lib/backend/tauri";
+import type { ConnectionConfig, SidebarLayout } from "@/types/database";
+import { buildMcpAccessTreeRows, countMcpTreeExceptions, mcpTreeRowHasException, type McpTreeConnectionRow, type McpTreeDatabaseRow, type McpTreeGroupRow } from "@/lib/mcp/mcpAccessTree";
+
+function connection(id: string, dbType = "mysql"): ConnectionConfig {
+ return { id, name: `${id}-name`, db_type: dbType, host: "127.0.0.1", port: 3306, username: "u", password: "" } as ConnectionConfig;
+}
+
+const layout: SidebarLayout = {
+ groups: [
+ { id: "prod", name: "Production", collapsed: false },
+ { id: "eu", name: "EU", collapsed: false },
+ ] as SidebarLayout["groups"],
+ order: [
+ {
+ type: "group",
+ id: "prod",
+ children: [
+ { type: "group", id: "eu", children: [{ type: "connection", id: "c1" }] },
+ { type: "connection", id: "c2" },
+ ],
+ },
+ { type: "connection", id: "c3" },
+ ],
+};
+
+const connections = [connection("c1"), connection("c2"), connection("c3"), connection("orphan")];
+
+function rule(patch: Partial<McpConnectionPolicy> & { connectionId: string }): McpConnectionPolicy {
+ return { readOnly: false, allowDangerousSql: false, executionModeConfigured: false, executionModePolicyVersion: 1, databaseScope: "all", allowedDatabases: [], databasePolicies: [], allowSalesforceDml: false, ...patch };
+}
+
+function policy(patch: Partial<McpGlobalPolicy> = {}) {
+ return { readOnly: true, allowDangerousSql: false, allowedConnectionIds: null, allowedGroupIds: [], connectionPolicies: [], groupPolicies: [], ...patch };
+}
+
+const expandAll = { expandedGroupIds: new Set(["prod", "eu"]), expandedConnectionIds: new Set(["c1", "c2", "c3"]) };
+
+function rowsBy(rows: ReturnType<typeof buildMcpAccessTreeRows>) {
+ return Object.fromEntries(rows.map((row) => [row.key, row]));
+}
+
+describe("MCP access tree", () => {
+ it("lists sidebar order with orphans at the root and respects collapsed groups", () => {
+ const collapsed = buildMcpAccessTreeRows(policy(), layout, connections, { expandedGroupIds: new Set(), expandedConnectionIds: new Set() });
+ expect(collapsed.map((row) => row.key)).toEqual(["group:prod", "connection:c3", "connection:orphan"]);
+ const expanded = buildMcpAccessTreeRows(policy(), layout, connections, expandAll);
+ expect(expanded.map((row) => [row.key, row.depth])).toEqual([
+ ["group:prod", 0],
+ ["group:eu", 1],
+ ["connection:c1", 2],
+ ["connection:c2", 1],
+ ["connection:c3", 0],
+ ["connection:orphan", 0],
+ ]);
+ expect((expanded[0] as McpTreeGroupRow).connectionCount).toBe(2);
+ });
+
+ it("resolves database > connection > closest group > ancestor group > global", () => {
+ const rows = rowsBy(
+ buildMcpAccessTreeRows(
+ policy({
+ groupPolicies: [
+ { groupId: "prod", readOnly: false, allowDangerousSql: false },
+ { groupId: "eu", readOnly: false, allowDangerousSql: true },
+ ],
+ connectionPolicies: [rule({ connectionId: "c2", executionModeConfigured: true, readOnly: true }), rule({ connectionId: "c1", databaseScope: "selected", allowedDatabases: ["billing", "ops"], databasePolicies: [{ databaseName: "billing", readOnly: true, allowDangerousSql: false }] })],
+ }),
+ layout,
+ connections,
+ expandAll,
+ ),
+ );
+ expect(rows["group:eu"]).toMatchObject({ effective: "high_risk_write", source: { kind: "group", groupId: "eu" } });
+ expect(rows["connection:c1"]).toMatchObject({ effective: "high_risk_write", source: { kind: "group", groupId: "eu", groupName: "EU" }, setting: "inherit", databaseCount: 2 });
+ expect(rows["database:c1:billing"]).toMatchObject({ effective: "read_only", source: { kind: "database" }, setting: "read_only" });
+ expect((rows["database:c1:ops"] as McpTreeDatabaseRow).effective).toBe("high_risk_write");
+ expect(rows["connection:c2"]).toMatchObject({ effective: "read_only", source: { kind: "connection" } });
+ expect(rows["connection:c3"]).toMatchObject({ effective: "read_only", source: { kind: "global" } });
+ });
+
+ it("treats legacy connection rules as ceilings", () => {
+ const rows = rowsBy(buildMcpAccessTreeRows(policy({ readOnly: false, allowDangerousSql: false, connectionPolicies: [rule({ connectionId: "c3", executionModeConfigured: true, allowDangerousSql: true, executionModePolicyVersion: null })] }), layout, connections, expandAll));
+ const c3 = rows["connection:c3"] as McpTreeConnectionRow;
+ expect(c3.legacy).toBe(true);
+ expect(c3.effective).toBe("safe_write");
+ });
+
+ it("derives visibility from a custom connection scope", () => {
+ const rows = rowsBy(buildMcpAccessTreeRows(policy({ allowedConnectionIds: ["c3"], allowedGroupIds: ["eu"] }), layout, connections, expandAll));
+ expect(rows["group:prod"]).toMatchObject({ visible: false, visibleConnectionCount: 1, connectionCount: 2 });
+ expect(rows["group:eu"]).toMatchObject({ visible: true, selected: true });
+ expect(rows["connection:c1"]).toMatchObject({ visible: true, selected: false, coveredBy: "eu" });
+ expect(rows["connection:c2"].visible).toBe(false);
+ expect(rows["connection:c3"]).toMatchObject({ visible: true, selected: true, coveredBy: null });
+ expect(rows["connection:orphan"].visible).toBe(false);
+ });
+
+ it.each([
+ { allowedConnectionIds: ["c1"], allowedGroupIds: [], visible: 1 },
+ { allowedConnectionIds: ["c1", "c2"], allowedGroupIds: [], visible: 2 },
+ { allowedConnectionIds: [], allowedGroupIds: ["eu"], visible: 1 },
+ { allowedConnectionIds: ["c1", "c1", "missing"], allowedGroupIds: ["eu"], visible: 1 },
+ { allowedConnectionIds: [], allowedGroupIds: [], visible: 0 },
+ ])("aggregates visible descendants without granting the parent: %j", ({ allowedConnectionIds, allowedGroupIds, visible }) => {
+ const fields = policy({ allowedConnectionIds, allowedGroupIds });
+ const before = JSON.stringify(fields);
+ const collapsed = { expandedGroupIds: new Set<string>(), expandedConnectionIds: new Set<string>() };
+ for (const options of [collapsed, expandAll, { ...collapsed, query: "c2-name" }]) {
+ const rows = rowsBy(buildMcpAccessTreeRows(fields, layout, connections, options));
+ expect(rows["group:prod"]).toMatchObject({ visible: false, selected: false, coveredBy: null, visibleConnectionCount: visible, connectionCount: 2 });
+ }
+ expect(JSON.stringify(fields)).toBe(before);
+ });
+
+ it("keeps full descendant counts when only one permission exception matches the filter", () => {
+ const fields = policy({ allowedConnectionIds: ["c1"], connectionPolicies: [rule({ connectionId: "c2", executionModeConfigured: true })] });
+ const rows = rowsBy(buildMcpAccessTreeRows(fields, layout, connections, { ...expandAll, exceptionsOnly: true }));
+ expect(rows["group:prod"]).toMatchObject({ visible: false, connectionCount: 2, visibleConnectionCount: 1 });
+ expect(rows["connection:c1"]).toBeUndefined();
+ expect(rows["connection:c2"].visible).toBe(false);
+ });
+
+ it.each([policy(), policy({ allowedConnectionIds: [], allowedGroupIds: ["prod"] })])("counts global and ancestor grants without treating empty groups as partial", (fields) => {
+ const withEmpty: SidebarLayout = { groups: [...layout.groups, { id: "empty", name: "Empty", collapsed: false }], order: [...layout.order, { type: "group", id: "empty", children: [] }] };
+ const rows = rowsBy(buildMcpAccessTreeRows(fields, withEmpty, connections, expandAll));
+ expect(rows["group:prod"]).toMatchObject({ visible: true, visibleConnectionCount: 2, connectionCount: 2 });
+ expect(rows["group:eu"]).toMatchObject({ visible: true, visibleConnectionCount: 1, connectionCount: 1 });
+ expect(rows["group:empty"]).toMatchObject({ visibleConnectionCount: 0, connectionCount: 0 });
+ });
+
+ it("applies group defaults to individually visible children without widening visibility", () => {
+ const fields = policy({ allowedConnectionIds: ["c1"], groupPolicies: [{ groupId: "prod", readOnly: false, allowDangerousSql: false }] });
+ const rows = rowsBy(buildMcpAccessTreeRows(fields, layout, connections, expandAll));
+ expect(rows["group:prod"]).toMatchObject({ selected: false, visibleConnectionCount: 1, setting: "safe_write" });
+ expect(rows["connection:c1"]).toMatchObject({ visible: true, effective: "safe_write", source: { kind: "group", groupId: "prod" } });
+ expect(rows["connection:c2"].visible).toBe(false);
+ });
+
+ it("filters by text keeping ancestors and by exceptions only", () => {
+ const searched = buildMcpAccessTreeRows(policy(), layout, connections, { expandedGroupIds: new Set(), expandedConnectionIds: new Set(), query: "c1-name" });
+ expect(searched.map((row) => row.key)).toEqual(["group:prod", "group:eu", "connection:c1"]);
+ const exceptions = buildMcpAccessTreeRows(policy({ connectionPolicies: [rule({ connectionId: "c2", allowSalesforceDml: true })] }), layout, connections, { ...expandAll, exceptionsOnly: true });
+ expect(exceptions.map((row) => row.key)).toEqual(["group:prod", "connection:c2"]);
+ });
+
+ it("counts exceptions and flags rows with their own settings", () => {
+ const fields = policy({
+ groupPolicies: [{ groupId: "prod", readOnly: true, allowDangerousSql: false }],
+ connectionPolicies: [rule({ connectionId: "c1", databaseScope: "selected", allowedDatabases: ["a"], databasePolicies: [{ databaseName: "a", readOnly: true, allowDangerousSql: false }] }), rule({ connectionId: "c2" })],
+ });
+ expect(countMcpTreeExceptions(fields)).toEqual({ groups: 1, connections: 1, databases: 1 });
+ const rows = rowsBy(buildMcpAccessTreeRows(fields, layout, connections, expandAll));
+ expect(mcpTreeRowHasException(rows["connection:c1"])).toBe(true);
+ expect(mcpTreeRowHasException(rows["connection:c2"])).toBe(false);
+ });
+ it("reveals nested exceptions even when their groups and connections are collapsed", () => {
+ const fields = policy({ connectionPolicies: [rule({ connectionId: "c1", databaseScope: "selected", allowedDatabases: ["app"], databasePolicies: [{ databaseName: "app", readOnly: false, allowDangerousSql: false }] })] });
+ const collapsed = { expandedGroupIds: new Set<string>(), expandedConnectionIds: new Set<string>() };
+ const rows = buildMcpAccessTreeRows(fields, layout, connections, { ...collapsed, exceptionsOnly: true });
+ expect(rows.map((row) => row.key)).toEqual(["group:prod", "group:eu", "connection:c1", "database:c1:app"]);
+ expect(buildMcpAccessTreeRows(fields, layout, connections, collapsed).map((row) => row.key)).toEqual(["group:prod", "connection:c3", "connection:orphan"]);
+ });
+
+ it("keeps legacy database ceilings when the connection itself inherits", () => {
+ const rows = rowsBy(
+ buildMcpAccessTreeRows(
+ policy({ connectionPolicies: [rule({ connectionId: "c1", executionModeConfigured: false, executionModePolicyVersion: null, databaseScope: "selected", allowedDatabases: ["app"], databasePolicies: [{ databaseName: "app", readOnly: false, allowDangerousSql: true }] })] }),
+ layout,
+ connections,
+ expandAll,
+ ),
+ );
+ expect(rows["database:c1:app"].effective).toBe("read_only");
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpCallHistory.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpCallHistory.spec.ts
new file mode 100644
index 0000000000..f94cfd0f9e
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpCallHistory.spec.ts
@@ -0,0 +1,45 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it, vi } from "vitest";
+
+import { MCP_CALL_HISTORY_OPEN_EVENT, openMcpCallHistory } from "@/lib/mcp/mcpCallHistory";
+
+const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
+const historySource = readFileSync(new URL("../../../components/editor/QueryHistory.vue", import.meta.url), "utf8");
+const settingsSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
+
+describe("MCP call history entry point", () => {
+ it("dispatches the open event", () => {
+ const target = new EventTarget();
+ vi.stubGlobal("window", target);
+ const listener = vi.fn();
+ target.addEventListener(MCP_CALL_HISTORY_OPEN_EVENT, listener);
+ openMcpCallHistory();
+ vi.unstubAllGlobals();
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+
+ it("carries a resource filter when opened from the access tree", () => {
+ const target = new EventTarget();
+ vi.stubGlobal("window", target);
+ const listener = vi.fn();
+ target.addEventListener(MCP_CALL_HISTORY_OPEN_EVENT, listener);
+ openMcpCallHistory({ connectionId: "c1", database: "analytics" });
+ vi.unstubAllGlobals();
+ expect((listener.mock.calls[0][0] as CustomEvent).detail).toEqual({ connectionId: "c1", database: "analytics" });
+ });
+
+ it("is wired from settings to the app shell to the history panel", () => {
+ // The settings handler defers navigation until the close guard allows it.
+ expect(settingsSource).toContain('@click="requestMcpCallHistory()"');
+ expect(appSource).toContain("window.addEventListener(MCP_CALL_HISTORY_OPEN_EVENT, openMcpCallHistory)");
+ expect(appSource).toContain(':mcp-request="mcpHistoryRequest"');
+ expect(appSource).toContain('@mcp-request-handled="mcpHistoryRequest = null"');
+ expect(historySource).toContain("() => props.mcpRequest");
+ expect(historySource).toContain("applyMcpResource");
+ });
+
+ it("shows the recorded MCP client in the history detail", () => {
+ expect(historySource).toContain('t("history.detail.mcpClient")');
+ expect(historySource).toContain("function mcpClientLabel(entry: HistoryEntry)");
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpCapabilitySearch.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpCapabilitySearch.spec.ts
new file mode 100644
index 0000000000..71ef939e02
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpCapabilitySearch.spec.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+import { searchMcpCapabilities } from "@/lib/mcp/mcpCapabilitySearch";
+import type { McpToolCatalog, PluginMcpView } from "@/types/mcpCatalog";
+
+const messages: Record<string, string> = {
+ "settings.mcpBrowser.category.nacos.title": "Nacos",
+ "settings.mcpToolset.nacosConfig.title": "配置管理",
+ "settings.mcpToolset.nacosConfig.description": "发布与查询配置",
+ "settings.mcpToolNacosListConfigs": "列出配置",
+};
+const t = (key: string) => messages[key] ?? key;
+const catalog: McpToolCatalog = {
+ toolsets: [
+ {
+ id: "nacos.config",
+ provider: "builtin:nacos",
+ resourceKinds: ["namespace"],
+ scopeKinds: ["namespace"],
+ tools: [
+ { name: "dbx_nacos_list_configs", description: "List configurations", access: "read", accessMode: "static", coverageKind: "types", databaseTypes: ["nacos"], parameters: [] },
+ { name: "dbx_nacos_publish_config", description: "Publish configuration", access: "write", accessMode: "static", coverageKind: "types", databaseTypes: ["nacos"], parameters: [] },
+ ],
+ },
+ ],
+};
+const plugin: PluginMcpView = {
+ pluginId: "nacos-extension",
+ pluginName: "Nacos",
+ version: "1",
+ authorAllowsExternal: true,
+ hasSavedGrant: true,
+ grant: { external: true, ceiling: "read", approvedTools: {}, disabledTools: ["dbx_ext__disabled"] },
+ toolsets: [{ id: "admin", title: "扩展管理", description: "Operations" }],
+ tools: [
+ { name: "dbx_ext__pending", access: "write", exposure: "pendingApproval", toolset: "admin", description: "Pending write", parameters: [] },
+ { name: "dbx_ext__ceiling", access: "full", exposure: "aboveCeiling", toolset: "admin", description: "Above ceiling", parameters: [] },
+ { name: "dbx_ext__disabled", access: "read", exposure: "toolDisabled", toolset: "admin", description: "Disabled", parameters: [] },
+ ],
+ discoveryError: null,
+};
+const search = (query: string, overrides: Partial<Parameters<typeof searchMcpCapabilities>[0]> = {}) => searchMcpCapabilities({ query, catalog, plugins: [plugin], allowedToolNames: null, onlyEnabled: false, t, ...overrides });
+
+describe("capability search", () => {
+ it("keeps a same-named builtin category and plugin separate, with source and paths", () => {
+ const groups = search("NaCoS");
+ expect(groups.map((group) => [group.id, group.source])).toEqual([
+ ["nacos", "builtin"],
+ ["plugin:nacos-extension", "plugin"],
+ ]);
+ expect(groups[0].items[0]).toMatchObject({ path: "Nacos / 配置管理", toolsetId: "nacos.config" });
+ expect(groups[1].items[0]).toMatchObject({ pluginId: "nacos-extension" });
+ });
+
+ it("finds localized toolset titles, tool IDs, plugin IDs and plugin toolsets", () => {
+ expect(search("配置管理")[0].items[0].toolsetId).toBe("nacos.config");
+ expect(search("dbx_nacos_publish_config")[0].items[0]).toMatchObject({ toolsetId: "nacos.config", toolName: "dbx_nacos_publish_config" });
+ expect(search("nacos-extension")[0].items[0].pluginId).toBe("nacos-extension");
+ expect(search("扩展管理")[0].items).toHaveLength(3);
+ expect(search("dbx_ext__pending")[0].items[0]).toMatchObject({ pluginId: "nacos-extension", toolName: "dbx_ext__pending" });
+ });
+
+ it("filters by configuration rather than runtime exposure and retains enabled plugins with errors", () => {
+ expect(search("dbx_ext__", { onlyEnabled: true })[0].items.map((item) => item.toolName)).toEqual(["dbx_ext__pending", "dbx_ext__ceiling"]);
+ expect(search("Nacos", { onlyEnabled: true, allowedToolNames: [] }).map((group) => group.source)).toEqual(["plugin"]);
+ const errorPlugin = { ...plugin, tools: [], discoveryError: "Unavailable" };
+ expect(search("Nacos", { catalog: null, plugins: [errorPlugin], onlyEnabled: true })[0].items).toHaveLength(1);
+ expect(search("Nacos", { catalog: null, plugins: [{ ...plugin, grant: { ...plugin.grant, external: false } }], onlyEnabled: true })).toEqual([]);
+ });
+
+ it("only returns enabled matching builtin tools and safely handles partial catalog availability", () => {
+ expect(search("dbx_nacos_publish_config", { onlyEnabled: true, allowedToolNames: ["dbx_nacos_list_configs"] })).toEqual([]);
+ expect(search("nacos", { plugins: null }).every((group) => group.source === "builtin")).toBe(true);
+ expect(search("dbx_ext__pending", { catalog: null })[0].source).toBe("plugin");
+ expect(search(" ")).toEqual([]);
+ expect(search("no-such-tool")).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpCapabilityViewLocales.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpCapabilityViewLocales.spec.ts
new file mode 100644
index 0000000000..54d0045179
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpCapabilityViewLocales.spec.ts
@@ -0,0 +1,32 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+const supportedLocales = ["az", "en", "es", "id", "it", "ja", "ko", "pt-BR", "ru", "th", "tr", "zh-CN", "zh-TW"];
+const viewKeys = [
+ "viewMode",
+ "viewManage",
+ "viewOverview",
+ "overviewSummary",
+ "overviewPluginsHint",
+ "overviewOpenDetails",
+ "expandCategory",
+ "collapseCategory",
+ "mcpPluginToolsMode",
+ "mcpPluginToolsModeDescription",
+ "mcpPluginToolsModeFlat",
+ "mcpPluginToolsModeLazy",
+ "mcpPluginToolsModeAuto",
+ "mcpPluginToolsModeFlatDescription",
+ "mcpPluginToolsModeLazyDescription",
+ "mcpPluginToolsModeAutoDescription",
+];
+
+describe("MCP capability view translations", () => {
+ it("defines every view label in every supported locale", () => {
+ for (const locale of supportedLocales) {
+ const source = readFileSync(new URL(`../../../i18n/locales/${locale}.ts`, import.meta.url), "utf8");
+ for (const key of viewKeys) expect(source, `${locale}.${key}`).toMatch(new RegExp(`\\b${key}: "[^"\\n]+"`));
+ expect(source, `${locale}.overviewSummary placeholders`).toMatch(/overviewSummary: "[^"]*\{toolsets\}[^"]*\{total\}[^"]*\{enabled\}/);
+ }
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpDatabaseAccess.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpDatabaseAccess.spec.ts
new file mode 100644
index 0000000000..f32f66924c
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpDatabaseAccess.spec.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+import { normalizeMcpGlobalPolicy } from "@/stores/settingsStore";
+import { databaseAccess, databaseAccessEqual, editableDatabaseAccess, mergeDatabaseAccess } from "@/lib/mcp/mcpDatabaseAccess";
+import type { ConnectionConfig, SidebarLayout } from "@/types/database";
+
+const connections = [{ id: "c1", name: "DB", db_type: "mysql" }] as ConnectionConfig[];
+const layout: SidebarLayout = { groups: [], order: [] };
+const rule = {
+ connectionId: "c1",
+ readOnly: false,
+ allowDangerousSql: true,
+ executionModeConfigured: true,
+ executionModePolicyVersion: null,
+ databaseScope: "selected" as const,
+ allowedDatabases: ["a"],
+ databasePolicies: [{ databaseName: "a", readOnly: false, allowDangerousSql: true }],
+ allowSalesforceDml: false,
+};
+
+describe("database permission patches", () => {
+ it("represents legacy database ceilings at their effective permission without mutating the stored rule", () => {
+ const policy = normalizeMcpGlobalPolicy({ readOnly: true, connectionPolicies: [rule] });
+ const edited = editableDatabaseAccess(policy, "c1", layout, connections);
+ expect(edited.databasePolicies).toEqual([{ databaseName: "a", readOnly: true, allowDangerousSql: false }]);
+ const merged = mergeDatabaseAccess(policy, "c1", edited, layout, connections);
+ expect(merged[0]).toMatchObject({ readOnly: true, allowDangerousSql: false, executionModePolicyVersion: 1, databasePolicies: edited.databasePolicies });
+ expect(policy.connectionPolicies[0].allowDangerousSql).toBe(true);
+ });
+ it("retains inherited connection permission semantics while applying a database override", () => {
+ const policy = normalizeMcpGlobalPolicy({ readOnly: true, connectionPolicies: [{ ...rule, executionModeConfigured: false, executionModePolicyVersion: 1 }] });
+ const merged = mergeDatabaseAccess(policy, "c1", { databaseScope: "selected", allowedDatabases: ["a", "b"], databasePolicies: [{ databaseName: "b", readOnly: false, allowDangerousSql: false }] }, layout, connections);
+ expect(merged[0].executionModeConfigured).toBe(false);
+ expect(merged[0].databasePolicies[0].databaseName).toBe("b");
+ });
+ it("clears removed database overrides and compares membership independently of ordering", () => {
+ const value = { databaseScope: "selected" as const, allowedDatabases: ["b", "a", "b"], databasePolicies: [{ databaseName: "removed", readOnly: true, allowDangerousSql: false }] };
+ expect(databaseAccess(value)).toEqual({ databaseScope: "selected", allowedDatabases: ["a", "b"], databasePolicies: [] });
+ expect(databaseAccessEqual(value, { databaseScope: "selected", allowedDatabases: ["a", "b"], databasePolicies: [] })).toBe(true);
+ expect(databaseAccessEqual(value, databaseAccess())).toBe(false);
+ });
+ it("removes an empty connection rule when restoring all databases without changing other connections", () => {
+ const policy = normalizeMcpGlobalPolicy({
+ connectionPolicies: [
+ { ...rule, executionModeConfigured: false, executionModePolicyVersion: 1 },
+ { ...rule, connectionId: "other" },
+ ],
+ });
+ const merged = mergeDatabaseAccess(policy, "c1", databaseAccess(), layout, connections);
+ expect(merged).toEqual([policy.connectionPolicies[1]]);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpPermissionLocales.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpPermissionLocales.spec.ts
new file mode 100644
index 0000000000..51941221ea
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpPermissionLocales.spec.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it, vi } from "vitest";
+import i18nSource from "@/i18n/index.ts?raw";
+
+// Check each locale's own messages so English fallback cannot hide missing translations.
+vi.mock("@/i18n/locales/fallback", () => ({ withEnglishFallback: (messages: Record<string, unknown>) => messages }));
+
+const supportedLocales = [...i18nSource.match(/const supportedLocales: Locale\[\] = \[([^\]]+)\]/)![1].matchAll(/"([^"]+)"/g)].map((match) => match[1]);
+const locales = import.meta.glob<{ default: { settings: Record<string, unknown>; history: { detail: Record<string, unknown> } } }>("../../../i18n/locales/*.ts");
+const keys = [
+ "mcpDatabaseConfigure",
+ "mcpDatabaseApply",
+ "mcpDatabaseSaveHint",
+ "mcpDatabaseSavedInherited",
+ "mcpDatabaseSelectResults",
+ "mcpDatabaseBatchLevel",
+ "mcpDatabaseBatchHighRiskConfirm",
+ "mcpDatabaseShowMore",
+ "mcpDatabaseRemoveConfirm",
+ "mcpExecutionModeDescription",
+ "mcpPermissionsDraftHint",
+ "mcpCallSafety",
+ "mcpCallSafetyLegacy",
+ "mcpCallSafetyEnabled",
+ "mcpCallSafetyDisabled",
+ "mcpCallSafetyLegacyHint",
+ "mcpCallSafetyMigrate",
+ "mcpCallSafetyDisableLegacy",
+ "mcpCallSafetyConfirm",
+ "mcpCallSafetyHint",
+ "mcpCallSafetyDesktopHint",
+ "mcpToolApprovalGenericTitle",
+ "mcpCapabilityTitle",
+ "mcpCapabilityDescription",
+ "mcpCapabilityConnectionCreate",
+ "mcpCapabilityConnectionRemove",
+ "mcpAccessTreeDescription",
+ "mcpAccessTreeExceptionsOnly",
+ "mcpToolsetDetailTools",
+ "mcpToolsetDetailCoverage",
+ "mcpToolsetDetailClose",
+];
+
+function mcpMessages(value: unknown, prefix = ""): Record<string, string> {
+ if (typeof value === "string") return /^(settings\.mcp|history\.detail\.mcp|pluginPlatform\.(mcpTools|externalMcp))/.test(prefix) ? { [prefix]: value } : {};
+ if (!value || typeof value !== "object") return {};
+ return Object.assign({}, ...Object.entries(value).map(([key, child]) => mcpMessages(child, prefix ? `${prefix}.${key}` : key)));
+}
+
+const placeholders = (message: string) => [...message.matchAll(/\{([\w]+)\}/g)].map((match) => match[1]).sort();
+// New capability/access-control messages must be translated explicitly. Older
+// installation and SQL-approval labels still use the supported English fallback.
+const requiresOwnTranslation = (key: string) =>
+ /^(settings\.mcp(?:AccessLevel|AccessTree|Database(?:Configure|Apply|SaveHint|SavedInherited|SelectResults|Batch|ShowMore|RemoveConfirm)|Browser|Capabilities|Confirmation|Coverage|ManagementCapabilities$|OpenCallHistory$|PermissionsDraftHint$|Plugin|Tool(?:Approval|Consul|Detail|Nacos|SkippedConnections)|Toolset)|history\.detail\.mcp(?:Client|Transport|Access|Confirmation)$|pluginPlatform\.(?:mcpTools|externalMcp))/.test(
+ key,
+ );
+
+describe("MCP permission text", () => {
+ it.each(supportedLocales)("translates new MCP labels and preserves all interpolation parameters in %s", async (locale) => {
+ const english = mcpMessages((await locales["../../../i18n/locales/en.ts"]()).default);
+ const messages = (await locales[`../../../i18n/locales/${locale}.ts`]()).default;
+ const own = mcpMessages(messages);
+ expect(Object.keys(own).filter(requiresOwnTranslation).sort(), locale).toEqual(Object.keys(english).filter(requiresOwnTranslation).sort());
+ const { withEnglishFallback } = await vi.importActual<typeof import("@/i18n/locales/fallback")>("@/i18n/locales/fallback");
+ const translated = mcpMessages(withEnglishFallback(messages));
+ expect(Object.keys(translated).sort(), locale).toEqual(Object.keys(english).sort());
+ for (const [key, message] of Object.entries(english)) {
+ // Legacy sentence fragments may intentionally be empty (e.g. Korean
+ // puts the entire listener hint after its interpolated host).
+ expect(translated[key], `${locale}.${key}`).toEqual(requiresOwnTranslation(key) ? expect.stringMatching(/\S/) : expect.any(String));
+ expect(placeholders(translated[key]), `${locale}.${key}`).toEqual(placeholders(message));
+ }
+ if (locale !== "en") {
+ for (const key of [
+ "settings.mcpToolNacosSearchConfigs",
+ "settings.mcpToolNacosRollbackConfig",
+ "settings.mcpToolNacosGetService",
+ "settings.mcpToolNacosRegisterInstance",
+ "settings.mcpToolNacosDeregisterInstance",
+ "settings.mcpAccessTreeLegacyHint",
+ "settings.mcpPluginAuthorizeDescription",
+ ]) {
+ expect(own[key], `${locale}.${key} must not be an English placeholder`).not.toBe(english[key]);
+ }
+ }
+ });
+
+ it.each(supportedLocales)("provides permission explanations and removes retired presets in %s", async (locale) => {
+ const {
+ default: { settings, history },
+ } = await locales[`../../../i18n/locales/${locale}.ts`]();
+ for (const key of keys) expect(settings[key], `${locale}.${key}`).toEqual(expect.stringMatching(/\S/));
+ for (const key of ["mcpTransport", "mcpAccess", "mcpConfirmation"]) expect(history.detail[key], `${locale}.history.detail.${key}`).toEqual(expect.stringMatching(/\S/));
+ expect((settings.mcpBrowser as Record<string, unknown>).pluginImmediate, `${locale}.mcpBrowser.pluginImmediate`).toEqual(expect.stringMatching(/\S/));
+ expect(settings).not.toHaveProperty("mcpPreset");
+ expect(settings).not.toHaveProperty("mcpPresetTitle");
+ expect(settings).not.toHaveProperty("mcpAuthStepCapabilitiesTitle");
+ expect(settings).not.toHaveProperty("mcpAuthStepCapabilitiesDescription");
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
index ed83e77aa0..08f51e54b3 100644
--- a/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
@@ -44,7 +44,8 @@ describe("MCP execution permission selection", () => {
{ labelKey: "settings.mcpCapabilityScopedMutation", read_only: false, safe_write: true, high_risk_write: true },
{ labelKey: "settings.mcpCapabilityBroadMutation", read_only: false, safe_write: false, high_risk_write: true },
{ labelKey: "settings.mcpCapabilitySchemaAdmin", read_only: false, safe_write: false, high_risk_write: true },
- { labelKey: "settings.mcpCapabilityConnectionManagement", read_only: false, safe_write: true, high_risk_write: true },
+ { labelKey: "settings.mcpCapabilityConnectionCreate", read_only: false, safe_write: true, high_risk_write: true },
+ { labelKey: "settings.mcpCapabilityConnectionRemove", read_only: false, safe_write: false, high_risk_write: true },
]);
});
});
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpToolCatalog.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpToolCatalog.spec.ts
new file mode 100644
index 0000000000..f365ced960
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpToolCatalog.spec.ts
@@ -0,0 +1,209 @@
+import { describe, expect, it } from "vitest";
+
+import type { McpToolCatalog, McpToolCatalogToolset } from "@/types/mcpCatalog";
+import { MCP_PLUGIN_TOOLS_WILDCARD } from "@/lib/mcp/mcpPolicySelection";
+import {
+ groupMcpDatabaseTypesByCategory,
+ mcpCoverageByCategory,
+ mcpCoverageCategory,
+ mcpToolLabelKey,
+ mcpToolsetScopeKinds,
+ mcpToolsetAccessLevels,
+ mcpToolsetMessageKey,
+ mcpToolsetState,
+ mcpToolsetsForDatabaseType,
+ mcpUncoveredConnections,
+ setMcpToolsetEnabled,
+ summarizeMcpToolsetCoverage,
+ MCP_CAPABILITY_CATEGORIES,
+ mcpCapabilityCategories,
+ mcpCapabilityCategoryId,
+ setMcpCategoryEnabled,
+ setMcpToolsEnabled,
+ mergeMcpToolsetSelection,
+} from "@/lib/mcp/mcpToolCatalog";
+
+const schema: McpToolCatalogToolset = {
+ id: "sql.schema",
+ provider: "builtin:sql",
+ resourceKinds: ["database"],
+ scopeKind: "database",
+ scopeKinds: ["database"],
+ tools: [
+ { name: "dbx_list_tables", access: "read", accessMode: "static", coverageKind: "capability", databaseTypes: ["mysql", "postgres", "sqlite"], description: "", parameters: [] },
+ { name: "dbx_get_routine_source", access: "read", accessMode: "static", coverageKind: "capability", databaseTypes: ["mysql", "postgres"], description: "", parameters: [] },
+ ],
+};
+
+const query: McpToolCatalogToolset = {
+ id: "sql.query",
+ provider: "builtin:sql",
+ resourceKinds: ["database"],
+ scopeKind: "database",
+ scopeKinds: ["database"],
+ tools: [{ name: "dbx_execute_query", access: "full", accessMode: "classified", coverageKind: "capability", databaseTypes: ["mysql", "postgres", "sqlite", "redis"], description: "", parameters: [] }],
+};
+
+const admin: McpToolCatalogToolset = {
+ id: "admin.connections",
+ provider: "builtin:admin",
+ resourceKinds: [],
+ scopeKinds: [],
+ tools: [
+ { name: "dbx_add_connection", access: "write", accessMode: "static", coverageKind: "none", databaseTypes: [], description: "", parameters: [] },
+ { name: "dbx_remove_connection", access: "full", accessMode: "static", coverageKind: "none", databaseTypes: [], description: "", parameters: [] },
+ ],
+};
+
+const catalog: McpToolCatalog = { toolsets: [query, schema, admin] };
+
+const connections = [
+ { id: "c1", name: "local-mysql", dbType: "mysql" as const },
+ { id: "c2", name: "notes", dbType: "sqlite" as const },
+ { id: "c3", name: "dev-nacos", dbType: "nacos" as const },
+];
+
+describe("MCP toolset switches", () => {
+ it("keeps allow-all unrestricted when the selected toolset has no effective change", () => {
+ expect(mergeMcpToolsetSelection(null, ["dbx_list_tables", "dbx_get_routine_source"], schema, catalog)).toBeNull();
+ });
+
+ it("exposes provider resource scope metadata", () => {
+ expect(mcpToolsetScopeKinds(schema)).toEqual(["database"]);
+ expect(schema.scopeKind).toBe("database");
+ expect(mcpToolsetScopeKinds(admin)).toEqual([]);
+ expect(admin.scopeKind).toBeUndefined();
+ });
+ it("derives on/off/partial from the flat allowlist", () => {
+ expect(mcpToolsetState(null, schema)).toBe("on");
+ expect(mcpToolsetState(["dbx_list_tables"], schema)).toBe("partial");
+ expect(mcpToolsetState([], schema)).toBe("off");
+ });
+
+ it("materializes allow-all with the plugin wildcard before switching a toolset off", () => {
+ const next = setMcpToolsetEnabled(null, schema, false, catalog);
+ expect(next).toContain(MCP_PLUGIN_TOOLS_WILDCARD);
+ expect(next).toContain("dbx_execute_query");
+ expect(next).not.toContain("dbx_list_tables");
+ expect(next).not.toContain("dbx_get_routine_source");
+ expect(next).toHaveLength(catalog.toolsets.flatMap((toolset) => toolset.tools).length - schema.tools.length + 1);
+ });
+
+ it("switches every tool of a toolset on without touching custom entries", () => {
+ expect(setMcpToolsetEnabled(["dbx_ssh__*"], schema, true, catalog)).toEqual(["dbx_ssh__*", "dbx_list_tables", "dbx_get_routine_source"]);
+ });
+
+ it("badges classified tools as reaching write and high-risk levels", () => {
+ expect(mcpToolsetAccessLevels(query)).toEqual(["read", "write", "full"]);
+ expect(mcpToolsetAccessLevels(schema)).toEqual(["read"]);
+ expect(mcpToolsetAccessLevels(admin)).toEqual(["read", "write", "full"]);
+ });
+
+ it("maps toolset ids to camelCase message keys and tools to existing labels", () => {
+ expect(mcpToolsetMessageKey("admin.connections", "title")).toBe("settings.mcpToolset.adminConnections.title");
+ expect(mcpToolsetMessageKey("redis", "description")).toBe("settings.mcpToolset.redis.description");
+ expect(mcpToolLabelKey("dbx_list_tables")).toBe("settings.mcpToolListTables");
+ expect(mcpToolLabelKey("dbx_unknown")).toBeUndefined();
+ });
+});
+
+describe("MCP capability categories", () => {
+ function toolset(id: string, names: string[]): McpToolCatalogToolset {
+ return { ...schema, id, tools: names.map((name) => ({ ...schema.tools[0], name })) };
+ }
+ const complete: McpToolCatalog = {
+ toolsets: [query, schema, toolset("nacos.config", ["nacos_read", "nacos_write"]), toolset("consul.service", ["consul_services"]), toolset("core.discovery", ["dbx_list_connections"]), toolset("plugin.router", ["plugin_discover"]), toolset("future.toolset", ["new_runtime_tool"])],
+ };
+
+ it("assigns every known group once and keeps unknown groups accessible", () => {
+ const configuredIds = MCP_CAPABILITY_CATEGORIES.flatMap((category) => [...category.toolsetIds]);
+ expect(new Set(configuredIds).size).toBe(configuredIds.length);
+ const groups = mcpCapabilityCategories(complete);
+ expect(groups.map((group) => group.id)).toEqual(["database", "nacos", "consul", "mq", "salesforce", "dbx", "other"]);
+ expect(
+ groups
+ .flatMap((group) => group.toolsets)
+ .map((group) => group.id)
+ .sort(),
+ ).toEqual(complete.toolsets.map((group) => group.id).sort());
+ expect(groups.at(-1)?.toolsets[0].id).toBe("future.toolset");
+ expect(mcpCapabilityCategoryId("redis")).toBe("database");
+ expect(mcpCapabilityCategoryId("core.discovery")).toBe("dbx");
+ expect(mcpCapabilityCategories(catalog).map((group) => group.id)).not.toContain("other");
+ });
+
+ it("disables database tools without removing other products, shared discovery, future tools or plugins", () => {
+ const next = setMcpCategoryEnabled(null, complete, "database", false);
+ expect(next).toEqual(["nacos_read", "nacos_write", "consul_services", "dbx_list_connections", "plugin_discover", "new_runtime_tool", MCP_PLUGIN_TOOLS_WILDCARD]);
+ expect(complete.toolsets[0].tools[0].name).toBe("dbx_execute_query");
+ });
+
+ it("uses the complete category even when only some tools are enabled or visible", () => {
+ const current = ["nacos_read", "dbx_ssh__*", "dbx_custom__tool", "custom_name"];
+ const all = setMcpCategoryEnabled(current, complete, "nacos", true);
+ expect(all).toEqual([...current, "nacos_write"]);
+ expect(setMcpCategoryEnabled(all, complete, "nacos", false)).toEqual(current.slice(1));
+ expect(current).toEqual(["nacos_read", "dbx_ssh__*", "dbx_custom__tool", "custom_name"]);
+ });
+
+ it("materializes a single tool and toolset from the same full runtime catalog", () => {
+ const single = setMcpToolsEnabled(null, complete, ["dbx_list_tables"], false);
+ const group = setMcpToolsetEnabled(null, schema, false, complete);
+ for (const names of [single, group]) {
+ expect(names).toContain("new_runtime_tool");
+ expect(names).toContain(MCP_PLUGIN_TOOLS_WILDCARD);
+ expect(names).not.toContain("dbx_list_tables");
+ }
+ expect(single).toContain("dbx_get_routine_source");
+ expect(group).not.toContain("dbx_get_routine_source");
+ });
+});
+
+describe("MCP coverage summaries", () => {
+ it("counts usable connections and flags connections only some tools support", () => {
+ const summary = summarizeMcpToolsetCoverage(schema, connections);
+ expect(summary.typeCount).toBe(3);
+ expect(summary.usableConnections.map((connection) => connection.id)).toEqual(["c1", "c2"]);
+ expect(summary.partialConnections).toEqual([{ connection: connections[1], unsupportedTools: [schema.tools[1]] }]);
+ expect(summary.distinctToolCounts.map(({ tools, typeCount }) => [tools.map((tool) => tool.name), typeCount])).toEqual([
+ [["dbx_list_tables"], 3],
+ [["dbx_get_routine_source"], 2],
+ ]);
+ });
+
+ it("collapses identical tool coverage into one summary and skips connection-less tools", () => {
+ expect(summarizeMcpToolsetCoverage(query, connections).distinctToolCounts).toEqual([]);
+ expect(summarizeMcpToolsetCoverage(admin, connections)).toMatchObject({ typeCount: 0, usableConnections: [], partialConnections: [] });
+ });
+
+ it("lists connections no built-in toolset reaches", () => {
+ expect(mcpUncoveredConnections(catalog, connections).map((connection) => connection.name)).toEqual(["dev-nacos"]);
+ });
+
+ it("groups coverage by connection picker categories and marks per-tool support", () => {
+ expect(mcpCoverageCategory("mysql")).toBe("sql");
+ expect(mcpCoverageCategory("sqlite")).toBe("lightweight");
+ // Only types some tool in the set supports appear — no unsupported entries.
+ const rows = mcpCoverageByCategory(schema);
+ expect(rows.map((row) => row.category)).toEqual(["sql", "lightweight"]);
+ const lightweight = rows.find((row) => row.category === "lightweight")!;
+ expect(lightweight.types).toEqual(["sqlite"]);
+ expect(lightweight.tools.map((entry) => [entry.tool.name, [...entry.supported]])).toEqual([
+ ["dbx_list_tables", ["sqlite"]],
+ ["dbx_get_routine_source", []],
+ ]);
+ });
+
+ it("groups a single tool's supported types by category without unsupported entries", () => {
+ expect(groupMcpDatabaseTypesByCategory(["sqlite", "postgres", "mysql", "sqlite"])).toEqual([
+ { category: "sql", titleKey: "connection.databaseCategorySql", types: ["mysql", "postgres"] },
+ { category: "lightweight", titleKey: "connection.databaseCategoryLightweight", types: ["sqlite"] },
+ ]);
+ expect(groupMcpDatabaseTypesByCategory([])).toEqual([]);
+ });
+
+ it("finds the toolsets a connection type can use", () => {
+ expect(mcpToolsetsForDatabaseType(catalog, "sqlite").map((toolset) => toolset.id)).toEqual(["sql.query", "sql.schema"]);
+ expect(mcpToolsetsForDatabaseType(catalog, "nacos")).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/mcp/pluginMcpGrant.spec.ts b/apps/desktop/src/lib/__tests__/mcp/pluginMcpGrant.spec.ts
new file mode 100644
index 0000000000..7154fb6f85
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/mcp/pluginMcpGrant.spec.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "vitest";
+
+import type { PluginMcpToolView, PluginMcpView } from "@/types/mcpCatalog";
+import {
+ pluginMcpAccessLevels,
+ pluginMcpAuthorizedGrant,
+ pluginMcpDefaultCeiling,
+ pluginMcpEnabled,
+ pluginMcpExposedCount,
+ pluginMcpHighestLevel,
+ pluginMcpLevelAtMost,
+ pluginMcpNeedsAuthorization,
+ pluginMcpPendingTools,
+ pluginMcpSetCeiling,
+ pluginMcpSetEnabled,
+ pluginMcpSetToolEnabled,
+ pluginMcpToolsByToolset,
+ pluginMcpUndeclaredTools,
+} from "@/lib/mcp/pluginMcpGrant";
+
+function tool(name: string, access: PluginMcpToolView["access"], exposure: PluginMcpToolView["exposure"] = "exposed", toolset = "default"): PluginMcpToolView {
+ return { name, description: "", toolset, access, exposure, parameters: [] };
+}
+
+function view(patch: Partial<PluginMcpView> = {}): PluginMcpView {
+ return {
+ pluginId: "io.dbx.ssh",
+ pluginName: "Terminal",
+ version: "1.4.0",
+ authorAllowsExternal: true,
+ hasSavedGrant: true,
+ grant: { external: true, ceiling: "write", approvedTools: { list_dir: "read", upload: "write" }, disabledTools: [] },
+ toolsets: [
+ { id: "files", title: "Files", description: null },
+ { id: "default", title: null, description: null },
+ ],
+ tools: [tool("list_dir", "read", "exposed", "files"), tool("upload", "write", "exposed", "files"), tool("exec", "full", "aboveCeiling")],
+ discoveryError: null,
+ ...patch,
+ };
+}
+
+describe("plugin MCP grant helpers", () => {
+ it("orders access levels and finds the highest", () => {
+ expect(pluginMcpLevelAtMost("read", "write")).toBe(true);
+ expect(pluginMcpLevelAtMost("full", "write")).toBe(false);
+ expect(pluginMcpHighestLevel(view().tools)).toBe("full");
+ expect(pluginMcpHighestLevel([])).toBe("read");
+ expect(pluginMcpAccessLevels(view().tools)).toEqual(["read", "write", "full"]);
+ });
+
+ it("ignores undeclared tools for levels and the default ceiling", () => {
+ const tools = [tool("list_dir", "read"), { ...tool("raw", "full", "undeclared"), access: null }];
+ expect(pluginMcpHighestLevel(tools)).toBe("read");
+ expect(pluginMcpAccessLevels(tools)).toEqual(["read"]);
+ expect(pluginMcpUndeclaredTools(tools).map((entry) => entry.name)).toEqual(["raw"]);
+ });
+
+ it("caps the offered default ceiling at write", () => {
+ expect(pluginMcpDefaultCeiling(view())).toBe("write");
+ expect(pluginMcpDefaultCeiling(view({ tools: [tool("a", "read")] }))).toBe("read");
+ });
+
+ it("needs authorization for never-saved, switched-off, or pending plugins only", () => {
+ expect(pluginMcpNeedsAuthorization(view())).toBe(false);
+ expect(pluginMcpNeedsAuthorization(view({ hasSavedGrant: false }))).toBe(true);
+ expect(pluginMcpNeedsAuthorization(view({ grant: { ...view().grant, external: false } }))).toBe(true);
+ expect(pluginMcpNeedsAuthorization(view({ tools: [tool("new_tool", "write", "pendingApproval")] }))).toBe(true);
+ });
+
+ it("derives enabled state from the author opt-in and the grant", () => {
+ expect(pluginMcpEnabled(view())).toBe(true);
+ expect(pluginMcpEnabled(view({ authorAllowsExternal: false }))).toBe(false);
+ expect(pluginMcpExposedCount(view())).toBe(2);
+ expect(pluginMcpPendingTools(view({ tools: [tool("x", "write", "pendingApproval")] })).map((entry) => entry.name)).toEqual(["x"]);
+ });
+
+ it("builds the authorized grant, keeping per-tool opt-outs only for reviewed plugins", () => {
+ const reviewed = view({ grant: { external: false, ceiling: "read", approvedTools: { list_dir: "read" }, disabledTools: ["upload"] } });
+ expect(pluginMcpAuthorizedGrant(reviewed, "full")).toEqual({ external: true, ceiling: "full", approvedTools: { list_dir: "read" }, disabledTools: ["upload"] });
+ expect(pluginMcpAuthorizedGrant(view({ hasSavedGrant: false, grant: { ...reviewed.grant } }), "write").disabledTools).toEqual([]);
+ });
+
+ it("edits switch, ceiling and per-tool opt-outs immutably", () => {
+ const grant = view().grant;
+ expect(pluginMcpSetEnabled(grant, false).external).toBe(false);
+ expect(pluginMcpSetCeiling(grant, "full").ceiling).toBe("full");
+ const off = pluginMcpSetToolEnabled(grant, "upload", false);
+ expect(off.disabledTools).toEqual(["upload"]);
+ expect(pluginMcpSetToolEnabled(off, "upload", true).disabledTools).toEqual([]);
+ expect(grant.disabledTools).toEqual([]);
+ });
+
+ it("groups tools by toolset in declaration order and skips empty groups", () => {
+ expect(pluginMcpToolsByToolset(view()).map((group) => [group.id, group.tools.map((entry) => entry.name)])).toEqual([
+ ["files", ["list_dir", "upload"]],
+ ["default", ["exec"]],
+ ]);
+ expect(pluginMcpToolsByToolset(view({ tools: [tool("a", "read")] })).map((group) => group.id)).toEqual(["default"]);
+ });
+});
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index ebf98d5622..f9c1b42fe9 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -432,6 +432,14 @@ export const loadDesktopSettings = forward("loadDesktopSettings");
export const saveDesktopSettings = forward("saveDesktopSettings");
export const loadMcpGlobalPolicy = forward("loadMcpGlobalPolicy");
export const saveMcpGlobalPolicy = forward("saveMcpGlobalPolicy");
+export const loadMcpToolCatalog = forward("loadMcpToolCatalog");
+export const listPluginMcpViews = forward("listPluginMcpViews");
+export const loadMcpAccessPolicy = forward("loadMcpAccessPolicy");
+export const resetInvalidMcpAccessPolicy = forward("resetInvalidMcpAccessPolicy");
+export const setMcpPluginScopeRule = forward("setMcpPluginScopeRule");
+export const loadPluginMcpView = forward("loadPluginMcpView");
+export const listMcpPluginScopes = forward("listMcpPluginScopes");
+export const savePluginMcpGrant = forward("savePluginMcpGrant");
export const loadMaxAgentTurns = forward("loadMaxAgentTurns");
export const loadSqlFileUploadMaxBytes = forward("loadSqlFileUploadMaxBytes");
export const saveSqlFileUploadMaxMb = forward("saveSqlFileUploadMaxMb");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 60ef51f330..a785f7b28f 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -5,6 +5,7 @@ import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRest
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
import type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
+import type { McpAccessPolicy, McpAccessRule, McpSubScopeMode, McpToolCatalog, PluginMcpGrant, PluginMcpView } from "@/types/mcpCatalog";
import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";
import type { NativeJobContext, NativeJobDetails, NativeJobList, NativeJobListRequest, NativeJobRequest, NativeJobOperationStatus, NativeJobPreparedPlan, NativeJobRef, NativeJobReferenceCatalog, NativeJobReferenceListRequest } from "@/lib/database/nativeJobs";
import type { PlDebugBootstrap, PlDebugSessionRef, PlDebugStartIntent, PlDebugOperationRequest, PlDebugReadRequest, PlDebugReceipt, PlDebugSnapshot } from "@/lib/debug/plDebugProtocol";
@@ -2570,6 +2571,50 @@ export async function loadMcpGlobalPolicy(): Promise<McpGlobalPolicy> {
return get("/api/app-settings/mcp-policy");
}
+export async function loadMcpToolCatalog(): Promise<McpToolCatalog> {
+ return get("/api/app-settings/mcp-tool-catalog");
+}
+
+export async function loadMcpAccessPolicy(): Promise<McpAccessPolicy> {
+ return get("/api/app-settings/mcp-access-policy");
+}
+
+export async function resetInvalidMcpAccessPolicy(): Promise<void> {
+ return post("/api/app-settings/mcp-access-policy/recover", {});
+}
+
+export async function setMcpPluginScopeRule(connectionId: string, kind: string, value: string | null, rule: McpAccessRule | null, subScope: McpSubScopeMode | null): Promise<McpAccessPolicy> {
+ const res = await fetch(apiUrl("/api/app-settings/mcp-access-policy/plugin-scope"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ connectionId, kind, value, rule, subScope }),
+ });
+ if (!res.ok) throw await backendResponseError(res);
+ return res.json();
+}
+
+export async function listPluginMcpViews(): Promise<PluginMcpView[]> {
+ return get("/api/app-settings/plugin-mcp");
+}
+
+export async function loadPluginMcpView(pluginId: string): Promise<PluginMcpView> {
+ return post("/api/app-settings/plugin-mcp/view", { pluginId });
+}
+
+export async function listMcpPluginScopes(pluginId: string, connectionId: string): Promise<{ values: string[] }> {
+ return post("/api/app-settings/plugin-mcp/scopes", { pluginId, connectionId });
+}
+
+export async function savePluginMcpGrant(pluginId: string, grant: PluginMcpGrant, approveCurrent: boolean): Promise<PluginMcpView> {
+ const res = await fetch(apiUrl("/api/app-settings/plugin-mcp/grant"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ pluginId, grant, approveCurrent }),
+ });
+ if (!res.ok) throw await backendResponseError(res);
+ return res.json();
+}
+
export async function saveMcpGlobalPolicy(policy: Omit<McpGlobalPolicy, "configured">): Promise<void> {
const res = await fetch(apiUrl("/api/app-settings/mcp-policy"), {
method: "PUT",
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 8b269824a8..0cadad8309 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -7,6 +7,7 @@ import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRest
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
import type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
+import type { McpAccessPolicy, McpAccessRule, McpSubScopeMode, McpToolCatalog, PluginMcpGrant, PluginMcpView } from "@/types/mcpCatalog";
import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";
import type { NativeJobContext, NativeJobDetails, NativeJobList, NativeJobListRequest, NativeJobRequest, NativeJobOperationStatus, NativeJobPreparedPlan, NativeJobRef, NativeJobReferenceCatalog, NativeJobReferenceListRequest } from "@/lib/database/nativeJobs";
import { functionDiffsToWire, functionInfoFromWire, schemaDiffPreparationFromWire, schemaDiffPreparationToWire, type FunctionInfoWire, type SchemaDiffPreparationWire } from "./functionInfoTransport";
@@ -409,6 +410,7 @@ export interface McpGlobalPolicy {
readOnly: boolean;
allowDangerousSql: boolean;
promptHighRiskSql: boolean;
+ callConfirmation?: "off" | "full" | "high_risk" | null;
allowedConnectionIds: string[] | null;
allowedGroupIds: string[];
allowedToolNames: string[] | null;
@@ -416,6 +418,7 @@ export interface McpGlobalPolicy {
groupPolicies: McpGroupPolicy[];
configured: boolean;
queryTimeoutSecs: number | null;
+ pluginToolsMode: "auto" | "flat" | "lazy";
}
export interface McpGroupPolicy {
@@ -974,6 +977,38 @@ export async function saveMcpGlobalPolicy(policy: Omit<McpGlobalPolicy, "configu
return invoke("save_mcp_global_policy", { policy });
}
+export async function loadMcpToolCatalog(): Promise<McpToolCatalog> {
+ return invoke("load_mcp_tool_catalog");
+}
+
+export async function loadMcpAccessPolicy(): Promise<McpAccessPolicy> {
+ return invoke("load_mcp_access_policy");
+}
+
+export async function resetInvalidMcpAccessPolicy(): Promise<void> {
+ return invoke("reset_invalid_mcp_access_policy");
+}
+
+export async function setMcpPluginScopeRule(connectionId: string, kind: string, value: string | null, rule: McpAccessRule | null, subScope: McpSubScopeMode | null): Promise<McpAccessPolicy> {
+ return invoke("set_mcp_plugin_scope_rule", { connectionId, kind, value, rule, subScope });
+}
+
+export async function listPluginMcpViews(): Promise<PluginMcpView[]> {
+ return invoke("list_plugin_mcp_views");
+}
+
+export async function loadPluginMcpView(pluginId: string): Promise<PluginMcpView> {
+ return invoke("load_plugin_mcp_view", { pluginId });
+}
+
+export async function listMcpPluginScopes(pluginId: string, connectionId: string): Promise<{ values: string[] }> {
+ return invoke("list_mcp_plugin_scopes", { pluginId, connectionId });
+}
+
+export async function savePluginMcpGrant(pluginId: string, grant: PluginMcpGrant, approveCurrent: boolean): Promise<PluginMcpView> {
+ return invoke("save_plugin_mcp_grant", { pluginId, grant, approveCurrent });
+}
+
export interface McpHttpServerSettings {
enabled: boolean;
host: string;
diff --git a/apps/desktop/src/lib/mcp/mcpAccessTree.ts b/apps/desktop/src/lib/mcp/mcpAccessTree.ts
new file mode 100644
index 0000000000..494bf35ca3
--- /dev/null
+++ b/apps/desktop/src/lib/mcp/mcpAccessTree.ts
@@ -0,0 +1,324 @@
+import type { McpConnectionPolicy, McpGlobalPolicy, McpGroupPolicy } from "@/lib/backend/tauri";
+import type { ConnectionConfig, SidebarLayout, SidebarOrderEntry } from "@/types/database";
+
+/**
+ * View model of the MCP access-control tree: the sidebar's groups and
+ * connections, plus the databases a connection has rules for, each with its
+ * own setting, its effective level and where that level comes from. Pure, so
+ * the inheritance rules can be tested without the settings dialog; the
+ * component only renders rows and forwards edits.
+ *
+ * Inheritance (mirrors `dbx_core::mcp_access` and the v1 server rules):
+ * database > connection > closest group > ancestor group > global default.
+ */
+
+export type McpTreeLevel = "read_only" | "safe_write" | "high_risk_write";
+export type McpTreeSetting = McpTreeLevel | "inherit";
+export type McpTreeVisibility = "visible" | "hidden";
+
+export type McpTreeSource = { kind: "global" } | { kind: "group"; groupId: string; groupName: string } | { kind: "connection" } | { kind: "database" };
+
+interface McpTreeRowBase {
+ key: string;
+ depth: number;
+ /** The resource is admitted directly or through a group/global scope. */
+ visible: boolean;
+ effective: McpTreeLevel;
+ source: McpTreeSource;
+ setting: McpTreeSetting;
+}
+
+export interface McpTreeGroupRow extends McpTreeRowBase {
+ type: "group";
+ id: string;
+ name: string;
+ pathIds: string[];
+ /** Explicitly selected under a custom connection scope. */
+ selected: boolean;
+ /** Admitted by a selected ancestor group. */
+ coveredBy: string | null;
+ connectionCount: number;
+ /** Actual visible descendants, including individually selected connections. */
+ visibleConnectionCount: number;
+ childCount: number;
+}
+
+export interface McpTreeConnectionRow extends McpTreeRowBase {
+ type: "connection";
+ id: string;
+ connection: ConnectionConfig;
+ pathIds: string[];
+ selected: boolean;
+ coveredBy: string | null;
+ databaseScope: McpConnectionPolicy["databaseScope"];
+ /** Databases with a rule (listed under a `selected` scope). */
+ databaseCount: number;
+ /** Rule saved before connection rules carried a version (a ceiling, not an override). */
+ legacy: boolean;
+ salesforceDml: boolean;
+}
+
+export interface McpTreeDatabaseRow extends McpTreeRowBase {
+ type: "database";
+ connectionId: string;
+ database: string;
+}
+
+export type McpTreeRow = McpTreeGroupRow | McpTreeConnectionRow | McpTreeDatabaseRow;
+
+type ScopeFields = Pick<McpGlobalPolicy, "readOnly" | "allowDangerousSql" | "allowedConnectionIds" | "allowedGroupIds" | "connectionPolicies" | "groupPolicies">;
+
+const RANK: Record<McpTreeLevel, number> = { read_only: 0, safe_write: 1, high_risk_write: 2 };
+
+export function mcpTreeLevelFromFlags(readOnly: boolean, allowDangerousSql: boolean): McpTreeLevel {
+ if (readOnly) return "read_only";
+ return allowDangerousSql ? "high_risk_write" : "safe_write";
+}
+
+function stricter(left: McpTreeLevel, right: McpTreeLevel): McpTreeLevel {
+ return RANK[left] <= RANK[right] ? left : right;
+}
+
+function groupSetting(policy: McpGroupPolicy | undefined): McpTreeSetting {
+ return policy ? mcpTreeLevelFromFlags(policy.readOnly, policy.allowDangerousSql) : "inherit";
+}
+
+function connectionSetting(policy: McpConnectionPolicy | undefined): McpTreeSetting {
+ if (!policy || !policy.executionModeConfigured) return "inherit";
+ return mcpTreeLevelFromFlags(policy.readOnly, policy.allowDangerousSql);
+}
+
+interface TreeGroupNode {
+ type: "group";
+ id: string;
+ name: string;
+ pathIds: string[];
+ children: TreeNode[];
+}
+
+interface TreeConnectionNode {
+ type: "connection";
+ connection: ConnectionConfig;
+ pathIds: string[];
+}
+
+type TreeNode = TreeGroupNode | TreeConnectionNode;
+
+function entryChildren(entry: Extract<SidebarOrderEntry, { type: "group" }>): SidebarOrderEntry[] {
+ return entry.children ?? entry.connectionIds?.map((id) => ({ type: "connection" as const, id })) ?? [];
+}
+
+/** Sidebar order as a tree; connections missing from the layout are appended at the root. */
+export function buildMcpResourceTree(layout: SidebarLayout, connections: readonly ConnectionConfig[]): TreeNode[] {
+ const byId = new Map(connections.map((connection) => [connection.id, connection]));
+ const groupNames = new Map(layout.groups.map((group) => [group.id, group.name]));
+ const seenConnections = new Set<string>();
+ const seenGroups = new Set<string>();
+ const build = (entries: SidebarOrderEntry[], pathIds: string[]): TreeNode[] =>
+ entries.flatMap((entry): TreeNode[] => {
+ if (entry.type === "connection") {
+ const connection = byId.get(entry.id);
+ if (!connection || seenConnections.has(entry.id)) return [];
+ seenConnections.add(entry.id);
+ return [{ type: "connection", connection, pathIds }];
+ }
+ const name = groupNames.get(entry.id);
+ if (!name || seenGroups.has(entry.id)) return [];
+ seenGroups.add(entry.id);
+ const nextPath = [...pathIds, entry.id];
+ return [{ type: "group", id: entry.id, name, pathIds: nextPath, children: build(entryChildren(entry), nextPath) }];
+ });
+ const nodes = build(layout.order, []);
+ for (const connection of connections) {
+ if (!seenConnections.has(connection.id)) nodes.push({ type: "connection", connection, pathIds: [] });
+ }
+ return nodes;
+}
+
+export interface McpAccessTreeOptions {
+ /** Group ids whose children are shown. */
+ expandedGroupIds: ReadonlySet<string>;
+ /** Connection ids whose database rows are shown. */
+ expandedConnectionIds: ReadonlySet<string>;
+ /** Free-text filter; matching rows keep their ancestors and are expanded. */
+ query?: string;
+ /** Only rows that carry a setting (and their ancestors). */
+ exceptionsOnly?: boolean;
+ /** Connections with immediately saved product/plugin scope rules. */
+ scopeExceptionIds?: ReadonlySet<string>;
+}
+
+/** Flattens the tree into rows in display order, with effective levels resolved. */
+export function buildMcpAccessTreeRows(policy: ScopeFields, layout: SidebarLayout, connections: readonly ConnectionConfig[], options: McpAccessTreeOptions): McpTreeRow[] {
+ const globalLevel = mcpTreeLevelFromFlags(policy.readOnly, policy.allowDangerousSql);
+ const groupPolicies = new Map(policy.groupPolicies.map((rule) => [rule.groupId, rule]));
+ const connectionPolicies = new Map(policy.connectionPolicies.map((rule) => [rule.connectionId, rule]));
+ const customScope = policy.allowedConnectionIds !== null;
+ const selectedGroups = new Set(policy.allowedGroupIds);
+ const selectedConnections = new Set(policy.allowedConnectionIds ?? []);
+ const groupNames = new Map(layout.groups.map((group) => [group.id, group.name]));
+ const query = options.query?.trim().toLocaleLowerCase() ?? "";
+
+ const inherited = (pathIds: string[]): { level: McpTreeLevel; source: McpTreeSource } => {
+ let result: { level: McpTreeLevel; source: McpTreeSource } = { level: globalLevel, source: { kind: "global" } };
+ for (const groupId of pathIds) {
+ const setting = groupSetting(groupPolicies.get(groupId));
+ if (setting !== "inherit") result = { level: setting, source: { kind: "group", groupId, groupName: groupNames.get(groupId) ?? groupId } };
+ }
+ return result;
+ };
+ const coveringGroup = (pathIds: string[]) => [...pathIds].reverse().find((id) => selectedGroups.has(id)) ?? null;
+ const connectionVisible = (node: TreeConnectionNode) => !customScope || selectedConnections.has(node.connection.id) || coveringGroup(node.pathIds) !== null;
+
+ // Summarize the complete tree before expanding or filtering rows. A group's
+ // grant includes future connections, whereas individually visible children do
+ // not: keep this aggregate separate from the group's own `visible` flag.
+ const tree = buildMcpResourceTree(layout, connections);
+ const groupCounts = new Map<string, { total: number; visible: number }>();
+ const summarize = (nodes: TreeNode[]): { total: number; visible: number } => {
+ const counts = { total: 0, visible: 0 };
+ for (const node of nodes) {
+ if (node.type === "connection") {
+ counts.total++;
+ if (connectionVisible(node)) counts.visible++;
+ } else {
+ const children = summarize(node.children);
+ groupCounts.set(node.id, children);
+ counts.total += children.total;
+ counts.visible += children.visible;
+ }
+ }
+ return counts;
+ };
+ summarize(tree);
+
+ const connectionRows = (node: TreeConnectionNode, depth: number): McpTreeRow[] => {
+ const { connection } = node;
+ const rule = connectionPolicies.get(connection.id);
+ const setting = connectionSetting(rule);
+ const legacy = Boolean(rule && rule.executionModePolicyVersion !== 1);
+ const parent = inherited(node.pathIds);
+ let effective = parent.level;
+ let source = parent.source;
+ if (setting !== "inherit") {
+ // Legacy rules are ceilings: never wider than what the connection inherits.
+ effective = legacy ? stricter(setting, parent.level) : setting;
+ source = { kind: "connection" };
+ }
+ const coveredBy = coveringGroup(node.pathIds);
+ const selected = selectedConnections.has(connection.id);
+ const visible = connectionVisible(node);
+ const databaseScope = rule?.databaseScope ?? "all";
+ const databases = databaseScope === "selected" ? (rule?.allowedDatabases ?? []) : [];
+ const row: McpTreeConnectionRow = {
+ type: "connection",
+ key: `connection:${connection.id}`,
+ id: connection.id,
+ connection,
+ pathIds: node.pathIds,
+ depth,
+ visible,
+ effective,
+ source,
+ setting,
+ selected,
+ coveredBy,
+ databaseScope,
+ databaseCount: databases.length,
+ legacy,
+ salesforceDml: Boolean(rule?.allowSalesforceDml && !rule.readOnly),
+ };
+ if (!options.expandedConnectionIds.has(connection.id) && !query && !options.exceptionsOnly) return [row];
+ const databaseRows = databases.map((database): McpTreeDatabaseRow => {
+ const databaseRule = rule?.databasePolicies.find((item) => item.databaseName === database);
+ const databaseSetting: McpTreeSetting = databaseRule ? mcpTreeLevelFromFlags(databaseRule.readOnly, databaseRule.allowDangerousSql) : "inherit";
+ const databaseEffective = databaseSetting === "inherit" ? effective : legacy ? stricter(databaseSetting, effective) : databaseSetting;
+ return {
+ type: "database",
+ key: `database:${connection.id}:${database}`,
+ connectionId: connection.id,
+ database,
+ depth: depth + 1,
+ visible,
+ effective: databaseEffective,
+ source: databaseSetting === "inherit" ? source : { kind: "database" },
+ setting: databaseSetting,
+ };
+ });
+ return [row, ...databaseRows];
+ };
+
+ const visit = (nodes: TreeNode[], depth: number): McpTreeRow[] =>
+ nodes.flatMap((node): McpTreeRow[] => {
+ if (node.type === "connection") return connectionRows(node, depth);
+ const setting = groupSetting(groupPolicies.get(node.id));
+ const parent = inherited(node.pathIds.slice(0, -1));
+ const coveredBy = coveringGroup(node.pathIds.slice(0, -1));
+ const selected = selectedGroups.has(node.id);
+ const counts = groupCounts.get(node.id)!;
+ const row: McpTreeGroupRow = {
+ type: "group",
+ key: `group:${node.id}`,
+ id: node.id,
+ name: node.name,
+ pathIds: node.pathIds,
+ depth,
+ visible: !customScope || selected || coveredBy !== null,
+ effective: setting === "inherit" ? parent.level : setting,
+ source: setting === "inherit" ? parent.source : { kind: "group", groupId: node.id, groupName: node.name },
+ setting,
+ selected,
+ coveredBy,
+ connectionCount: counts.total,
+ visibleConnectionCount: counts.visible,
+ childCount: node.children.length,
+ };
+ if (!options.expandedGroupIds.has(node.id) && !query && !options.exceptionsOnly) return [row];
+ return [row, ...visit(node.children, depth + 1)];
+ });
+
+ let rows = visit(tree, 0);
+ if (query) rows = keepMatchingWithAncestors(rows, (row) => mcpTreeRowText(row).includes(query));
+ if (options.exceptionsOnly) rows = keepMatchingWithAncestors(rows, (row) => mcpTreeRowHasException(row) || (row.type === "connection" && Boolean(options.scopeExceptionIds?.has(row.id))));
+ return rows;
+}
+
+export function mcpTreeRowText(row: McpTreeRow): string {
+ if (row.type === "group") return row.name.toLocaleLowerCase();
+ if (row.type === "database") return row.database.toLocaleLowerCase();
+ const { connection } = row;
+ return [connection.name, connection.db_type, connection.host, connection.database].filter(Boolean).join(" ").toLocaleLowerCase();
+}
+
+/** A row carries its own setting (not merely inherited). */
+export function mcpTreeRowHasException(row: McpTreeRow): boolean {
+ if (row.setting !== "inherit") return true;
+ if (row.type === "connection") return row.databaseScope !== "all" || row.salesforceDml;
+ return false;
+}
+
+/** Keeps matching rows plus every ancestor row (by depth), preserving order. */
+function keepMatchingWithAncestors(rows: McpTreeRow[], matches: (row: McpTreeRow) => boolean): McpTreeRow[] {
+ const keep = new Set<number>();
+ rows.forEach((row, index) => {
+ if (!matches(row)) return;
+ keep.add(index);
+ let depth = row.depth;
+ for (let parent = index - 1; parent >= 0 && depth > 0; parent -= 1) {
+ if (rows[parent].depth < depth) {
+ keep.add(parent);
+ depth = rows[parent].depth;
+ }
+ }
+ });
+ return rows.filter((_, index) => keep.has(index));
+}
+
+/** Number of rows with their own settings, for the summary line. */
+export function countMcpTreeExceptions(policy: ScopeFields, scopeExceptionIds: ReadonlySet<string> = new Set()): { groups: number; connections: number; databases: number } {
+ return {
+ groups: policy.groupPolicies.length,
+ connections: new Set([...scopeExceptionIds, ...policy.connectionPolicies.filter((rule) => rule.executionModeConfigured || rule.databaseScope !== "all" || rule.allowSalesforceDml).map((rule) => rule.connectionId)]).size,
+ databases: policy.connectionPolicies.reduce((total, rule) => total + rule.databasePolicies.length, 0),
+ };
+}
diff --git a/apps/desktop/src/lib/mcp/mcpCallHistory.ts b/apps/desktop/src/lib/mcp/mcpCallHistory.ts
new file mode 100644
index 0000000000..815c8c0439
--- /dev/null
+++ b/apps/desktop/src/lib/mcp/mcpCallHistory.ts
@@ -0,0 +1,18 @@
+/**
+ * Opening the MCP call history from outside the history panel (Settings → MCP).
+ * The app shell retains the request until the lazy history panel consumes it.
+ */
+export const MCP_CALL_HISTORY_OPEN_EVENT = "dbx:open-mcp-call-history";
+
+export interface McpCallHistoryResource {
+ connectionId?: string;
+ database?: string;
+}
+
+export interface McpCallHistoryRequest {
+ resource?: McpCallHistoryResource;
+}
+
+export function openMcpCallHistory(resource?: McpCallHistoryResource): void {
+ window.dispatchEvent(new CustomEvent(MCP_CALL_HISTORY_OPEN_EVENT, { detail: resource }));
+}
diff --git a/apps/desktop/src/lib/mcp/mcpCapabilitySearch.ts b/apps/desktop/src/lib/mcp/mcpCapabilitySearch.ts
new file mode 100644
index 0000000000..65791d1e62
--- /dev/null
+++ b/apps/desktop/src/lib/mcp/mcpCapabilitySearch.ts
@@ -0,0 +1,92 @@
+import type { McpToolCatalog, PluginMcpView } from "@/types/mcpCatalog";
+import { mcpCapabilityCategories, mcpToolAllowed, mcpToolLabelKey, mcpToolsetMessageKey, type McpCapabilityCategoryId } from "./mcpToolCatalog";
+import { pluginMcpEnabled } from "./pluginMcpGrant";
+
+export interface McpCapabilitySearchItem {
+ key: string;
+ title: string;
+ path: string;
+ toolsetId?: string;
+ toolName?: string;
+ pluginId?: string;
+}
+
+export interface McpCapabilitySearchGroup {
+ id: string;
+ title: string;
+ source: "builtin" | "plugin";
+ items: McpCapabilitySearchItem[];
+}
+
+type Translate = (key: string) => string;
+
+export interface McpCapabilityBrowserState {
+ selected: McpCapabilityCategoryId | `plugin:${string}` | "advanced";
+ search: string;
+ onlyEnabled: boolean;
+ viewMode: McpCapabilityViewMode;
+}
+
+export type McpCapabilityViewMode = "manage" | "overview";
+
+export type McpCapabilityNavigationTarget = { kind: "tool"; toolName: string } | { kind: "advanced" };
+
+export interface McpCapabilityNavigator {
+ revealSearchTarget(target?: McpCapabilityNavigationTarget): void;
+}
+
+export function initialMcpCapabilityBrowserState(): McpCapabilityBrowserState {
+ return { selected: "database", search: "", onlyEnabled: false, viewMode: "manage" };
+}
+
+export function mcpCategoryTitle(id: McpCapabilityCategoryId, t: Translate): string {
+ return t(`settings.mcpBrowser.category.${id}.title`);
+}
+
+export function mcpToolsetTitle(id: string, t: Translate): string {
+ const key = mcpToolsetMessageKey(id, "title");
+ const title = t(key);
+ return title === key ? id : title;
+}
+
+/** Search the full catalogs, keeping navigation and saved authorization independent. */
+export function searchMcpCapabilities(options: { query: string; catalog: McpToolCatalog | null; plugins: readonly PluginMcpView[] | null; allowedToolNames: readonly string[] | null; onlyEnabled: boolean; t: Translate }): McpCapabilitySearchGroup[] {
+ const { query, catalog, plugins, allowedToolNames, onlyEnabled, t } = options;
+ const needle = query.trim().toLocaleLowerCase();
+ if (!needle) return [];
+ const matches = (...values: Array<string | null | undefined>) => values.some((value) => value?.toLocaleLowerCase().includes(needle));
+ const results: McpCapabilitySearchGroup[] = [];
+ for (const category of mcpCapabilityCategories(catalog)) {
+ const title = mcpCategoryTitle(category.id, t);
+ const categoryMatch = matches(title, category.id);
+ const items: McpCapabilitySearchItem[] = [];
+ for (const toolset of category.toolsets) {
+ const tools = toolset.tools.filter((tool) => !onlyEnabled || mcpToolAllowed(allowedToolNames, tool.name));
+ if (onlyEnabled && !tools.length) continue;
+ const toolsetTitle = mcpToolsetTitle(toolset.id, t);
+ const path = `${title} / ${toolsetTitle}`;
+ if (categoryMatch || matches(toolset.id, toolsetTitle, t(mcpToolsetMessageKey(toolset.id, "description")))) {
+ items.push({ key: toolset.id, title: toolsetTitle, path, toolsetId: toolset.id });
+ }
+ for (const tool of tools) {
+ const labelKey = mcpToolLabelKey(tool.name);
+ const label = labelKey ? t(labelKey) : tool.name;
+ if (matches(tool.name, label, tool.description)) items.push({ key: `${toolset.id}/${tool.name}`, title: label, path, toolsetId: toolset.id, toolName: tool.name });
+ }
+ }
+ if (items.length) results.push({ id: category.id, title, source: "builtin", items });
+ }
+ for (const plugin of plugins ?? []) {
+ if (onlyEnabled && !pluginMcpEnabled(plugin)) continue;
+ const items: McpCapabilitySearchItem[] = [];
+ if (matches(plugin.pluginName, plugin.pluginId)) items.push({ key: plugin.pluginId, title: plugin.pluginName, path: plugin.pluginId, pluginId: plugin.pluginId });
+ for (const tool of plugin.tools) {
+ if (onlyEnabled && (tool.access === null || plugin.grant.disabledTools.includes(tool.name))) continue;
+ const group = plugin.toolsets.find((toolset) => toolset.id === tool.toolset);
+ if (!matches(tool.name, tool.description, group?.title, group?.id, group?.description)) continue;
+ items.push({ key: `${plugin.pluginId}/${tool.name}`, title: tool.name, path: `${plugin.pluginName} / ${group?.title ?? t("settings.mcpPluginDefaultToolset")}`, pluginId: plugin.pluginId, toolName: tool.name });
+ }
+ if (items.length) results.push({ id: `plugin:${plugin.pluginId}`, title: plugin.pluginName, source: "plugin", items });
+ }
+ return results;
+}
diff --git a/apps/desktop/src/lib/mcp/mcpDatabaseAccess.ts b/apps/desktop/src/lib/mcp/mcpDatabaseAccess.ts
new file mode 100644
index 0000000000..829aefc8d6
--- /dev/null
+++ b/apps/desktop/src/lib/mcp/mcpDatabaseAccess.ts
@@ -0,0 +1,71 @@
+import type { McpConnectionPolicy, McpGlobalPolicy } from "@/lib/backend/tauri";
+import type { ConnectionConfig, SidebarLayout } from "@/types/database";
+import { buildMcpAccessTreeRows, type McpTreeConnectionRow } from "./mcpAccessTree";
+
+export type McpDatabaseAccess = Pick<McpConnectionPolicy, "databaseScope" | "allowedDatabases" | "databasePolicies">;
+export type McpDatabaseAccessPolicy = Pick<McpGlobalPolicy, "readOnly" | "allowDangerousSql" | "allowedConnectionIds" | "allowedGroupIds" | "connectionPolicies" | "groupPolicies">;
+
+export function databaseAccess(rule?: McpDatabaseAccess): McpDatabaseAccess {
+ const databaseScope = rule?.databaseScope ?? "all";
+ const allowedDatabases = databaseScope === "selected" ? [...new Set(rule?.allowedDatabases ?? [])].sort() : [];
+ const databasePolicies = (rule?.databasePolicies ?? [])
+ .filter((entry) => allowedDatabases.includes(entry.databaseName))
+ .map((entry) => ({ ...entry }))
+ .sort((a, b) => a.databaseName.localeCompare(b.databaseName));
+ return { databaseScope, allowedDatabases, databasePolicies };
+}
+
+export function databaseAccessEqual(left?: McpDatabaseAccess, right?: McpDatabaseAccess): boolean {
+ return JSON.stringify(databaseAccess(left)) === JSON.stringify(databaseAccess(right));
+}
+
+export function databaseConnectionRow(policy: McpDatabaseAccessPolicy, id: string, layout: SidebarLayout, connections: readonly ConnectionConfig[]): McpTreeConnectionRow | undefined {
+ return buildMcpAccessTreeRows(policy, layout, connections, { expandedGroupIds: new Set(layout.groups.map((group) => group.id)), expandedConnectionIds: new Set() }).find((row): row is McpTreeConnectionRow => row.type === "connection" && row.id === id);
+}
+
+/** Show legacy ceilings as their effective values before editing individual overrides. */
+export function editableDatabaseAccess(policy: McpDatabaseAccessPolicy, id: string, layout: SidebarLayout, connections: readonly ConnectionConfig[]): McpDatabaseAccess {
+ const rule = policy.connectionPolicies.find((entry) => entry.connectionId === id);
+ const access = databaseAccess(rule);
+ if (!rule || rule.executionModePolicyVersion === 1) return access;
+ const rows = buildMcpAccessTreeRows(policy, layout, connections, { expandedGroupIds: new Set(layout.groups.map((group) => group.id)), expandedConnectionIds: new Set([id]) });
+ access.databasePolicies = access.databasePolicies.map((entry) => {
+ const row = rows.find((item) => item.type === "database" && item.connectionId === id && item.database === entry.databaseName);
+ return row ? { ...entry, readOnly: row.effective === "read_only", allowDangerousSql: row.effective === "high_risk_write" } : entry;
+ });
+ return access;
+}
+
+/** Patch only one connection's database fields, preserving all unrelated settings. */
+export function mergeDatabaseAccess(policy: McpDatabaseAccessPolicy, id: string, access: McpDatabaseAccess, layout: SidebarLayout, connections: readonly ConnectionConfig[]): McpConnectionPolicy[] {
+ const existing = policy.connectionPolicies.find((entry) => entry.connectionId === id);
+ const next: McpConnectionPolicy = {
+ connectionId: id,
+ readOnly: false,
+ allowDangerousSql: false,
+ executionModeConfigured: false,
+ executionModePolicyVersion: 1,
+ allowSalesforceDml: false,
+ ...existing,
+ ...databaseAccess(access),
+ };
+ if (existing && existing.executionModePolicyVersion !== 1) {
+ // Upgrading a legacy ceiling must retain the effective *saved* connection
+ // permission, never an unrelated pending global/group/connection edit.
+ const row = databaseConnectionRow(policy, id, layout, connections);
+ if (!row) throw new Error("Connection is unavailable");
+ next.readOnly = row.effective === "read_only";
+ next.allowDangerousSql = row.effective === "high_risk_write";
+ next.executionModeConfigured = true;
+ next.executionModePolicyVersion = 1;
+ next.allowSalesforceDml = next.allowSalesforceDml && !next.readOnly;
+ }
+ const rules = [...policy.connectionPolicies];
+ const index = rules.findIndex((entry) => entry.connectionId === id);
+ const meaningful = next.executionModeConfigured || next.databaseScope !== "all" || next.databasePolicies.length > 0 || next.allowSalesforceDml;
+ if (index >= 0) {
+ if (meaningful) rules[index] = next;
+ else rules.splice(index, 1);
+ } else if (meaningful) rules.push(next);
+ return rules.sort((left, right) => left.connectionId.localeCompare(right.connectionId));
+}
diff --git a/apps/desktop/src/lib/mcp/mcpPolicySelection.ts b/apps/desktop/src/lib/mcp/mcpPolicySelection.ts
index 1bd10c37f5..46b31becfc 100644
--- a/apps/desktop/src/lib/mcp/mcpPolicySelection.ts
+++ b/apps/desktop/src/lib/mcp/mcpPolicySelection.ts
@@ -18,7 +18,8 @@ export const MCP_CAPABILITY_ROWS: readonly McpCapabilityRow[] = [
{ labelKey: "settings.mcpCapabilityScopedMutation", read_only: false, safe_write: true, high_risk_write: true },
{ labelKey: "settings.mcpCapabilityBroadMutation", read_only: false, safe_write: false, high_risk_write: true },
{ labelKey: "settings.mcpCapabilitySchemaAdmin", read_only: false, safe_write: false, high_risk_write: true },
- { labelKey: "settings.mcpCapabilityConnectionManagement", read_only: false, safe_write: true, high_risk_write: true },
+ { labelKey: "settings.mcpCapabilityConnectionCreate", read_only: false, safe_write: true, high_risk_write: true },
+ { labelKey: "settings.mcpCapabilityConnectionRemove", read_only: false, safe_write: false, high_risk_write: true },
];
export const MCP_TOOL_OPTIONS = [
@@ -40,6 +41,28 @@ export const MCP_TOOL_OPTIONS = [
{ name: "dbx_salesforce_current_user", labelKey: "settings.mcpToolSalesforceCurrentUser" },
{ name: "dbx_salesforce_prepare_write", labelKey: "settings.mcpToolSalesforcePrepareWrite" },
{ name: "dbx_salesforce_apply_write", labelKey: "settings.mcpToolSalesforceApplyWrite" },
+ { name: "dbx_nacos_list_namespaces", labelKey: "settings.mcpToolNacosListNamespaces" },
+ { name: "dbx_nacos_list_configs", labelKey: "settings.mcpToolNacosListConfigs" },
+ { name: "dbx_nacos_search_configs", labelKey: "settings.mcpToolNacosSearchConfigs" },
+ { name: "dbx_nacos_get_config", labelKey: "settings.mcpToolNacosGetConfig" },
+ { name: "dbx_nacos_config_history", labelKey: "settings.mcpToolNacosConfigHistory" },
+ { name: "dbx_nacos_publish_config", labelKey: "settings.mcpToolNacosPublishConfig" },
+ { name: "dbx_nacos_rollback_config", labelKey: "settings.mcpToolNacosRollbackConfig" },
+ { name: "dbx_nacos_delete_config", labelKey: "settings.mcpToolNacosDeleteConfig" },
+ { name: "dbx_nacos_list_services", labelKey: "settings.mcpToolNacosListServices" },
+ { name: "dbx_nacos_get_service", labelKey: "settings.mcpToolNacosGetService" },
+ { name: "dbx_nacos_list_instances", labelKey: "settings.mcpToolNacosListInstances" },
+ { name: "dbx_nacos_update_instance", labelKey: "settings.mcpToolNacosUpdateInstance" },
+ { name: "dbx_nacos_register_instance", labelKey: "settings.mcpToolNacosRegisterInstance" },
+ { name: "dbx_nacos_deregister_instance", labelKey: "settings.mcpToolNacosDeregisterInstance" },
+ { name: "dbx_consul_kv_list", labelKey: "settings.mcpToolConsulKvList" },
+ { name: "dbx_consul_kv_get", labelKey: "settings.mcpToolConsulKvGet" },
+ { name: "dbx_consul_kv_put", labelKey: "settings.mcpToolConsulKvPut" },
+ { name: "dbx_consul_kv_delete", labelKey: "settings.mcpToolConsulKvDelete" },
+ { name: "dbx_consul_list_services", labelKey: "settings.mcpToolConsulListServices" },
+ { name: "dbx_consul_list_nodes", labelKey: "settings.mcpToolConsulListNodes" },
+ { name: "dbx_consul_service_health", labelKey: "settings.mcpToolConsulServiceHealth" },
+ { name: "dbx_consul_set_maintenance", labelKey: "settings.mcpToolConsulSetMaintenance" },
{ name: "dbx_peek_messages", labelKey: "settings.mcpToolPeekMessages" },
{ name: "dbx_send_message", labelKey: "settings.mcpToolSendMessage" },
{ name: "dbx_add_connection", labelKey: "settings.mcpToolAddConnection" },
diff --git a/apps/desktop/src/lib/mcp/mcpToolCatalog.ts b/apps/desktop/src/lib/mcp/mcpToolCatalog.ts
new file mode 100644
index 0000000000..803f177002
--- /dev/null
+++ b/apps/desktop/src/lib/mcp/mcpToolCatalog.ts
@@ -0,0 +1,233 @@
+import type { DatabaseType } from "@/types/database";
+import type { McpAccessLevel, McpToolCatalog, McpToolCatalogTool, McpToolCatalogToolset } from "@/types/mcpCatalog";
+import { CONNECTION_PICKER_OPTIONS } from "@/types/generated/connectionProfiles";
+import { AGENT_DRIVER_CATEGORY_MAP, DRIVER_CATEGORIES, type DriverCategoryKey } from "@/lib/connection/driver-category-definitions";
+import { databaseManifestEntry } from "@/lib/database/databaseDriverManifest";
+import { MCP_PLUGIN_TOOLS_WILDCARD, MCP_TOOL_OPTIONS } from "@/lib/mcp/mcpPolicySelection";
+
+/**
+ * View-model helpers for the MCP capability tab. The catalog itself comes from
+ * the backend (`dbx_core::mcp_catalog`); everything here is pure so the tab
+ * stays a thin renderer. Tool permissions are still the flat
+ * `allowedToolNames` allowlist — a toolset switch only edits that list.
+ */
+
+export const MCP_ACCESS_LEVELS: readonly McpAccessLevel[] = ["read", "write", "full"];
+
+/** Product navigation is presentation metadata, independent of policy scopes. */
+export const MCP_CAPABILITY_CATEGORIES = [
+ { id: "database", toolsetIds: ["sql.query", "sql.session", "sql.schema", "redis"] },
+ { id: "nacos", toolsetIds: ["nacos.config", "nacos.service"] },
+ { id: "consul", toolsetIds: ["consul.kv", "consul.service"] },
+ { id: "mq", toolsetIds: ["mq"] },
+ { id: "salesforce", toolsetIds: ["salesforce"] },
+ { id: "dbx", toolsetIds: ["core.discovery", "workbench", "admin.connections", "plugin.router"] },
+] as const;
+
+export type McpCapabilityCategoryId = (typeof MCP_CAPABILITY_CATEGORIES)[number]["id"] | "other";
+
+export function mcpCapabilityCategoryId(toolsetId: string): McpCapabilityCategoryId {
+ return MCP_CAPABILITY_CATEGORIES.find((category) => (category.toolsetIds as readonly string[]).includes(toolsetId))?.id ?? "other";
+}
+
+export function mcpCapabilityCategories(catalog: McpToolCatalog | null): Array<{ id: McpCapabilityCategoryId; toolsets: McpToolCatalogToolset[] }> {
+ const toolsets = catalog?.toolsets ?? [];
+ const categories = MCP_CAPABILITY_CATEGORIES.map((category) => ({
+ id: category.id as McpCapabilityCategoryId,
+ toolsets: category.toolsetIds.flatMap((id) => toolsets.filter((toolset) => toolset.id === id)),
+ }));
+ const other = toolsets.filter((toolset) => mcpCapabilityCategoryId(toolset.id) === "other");
+ if (other.length) categories.push({ id: "other", toolsets: other });
+ return categories;
+}
+
+/** i18n keys for toolset titles and descriptions, keyed by catalog toolset id. */
+export function mcpToolsetMessageKey(toolsetId: string, part: "title" | "description"): string {
+ const key = toolsetId.replace(/\.(\w)/g, (_, letter: string) => letter.toUpperCase());
+ return `settings.mcpToolset.${key}.${part}`;
+}
+
+/** Label key for one tool, reusing the per-tool labels of the static option list. */
+export function mcpToolLabelKey(toolName: string): string | undefined {
+ return MCP_TOOL_OPTIONS.find((tool) => tool.name === toolName)?.labelKey;
+}
+
+export function mcpToolAllowed(allowedToolNames: readonly string[] | null, toolName: string): boolean {
+ return allowedToolNames === null || allowedToolNames.includes(toolName);
+}
+
+export type McpToolsetState = "on" | "off" | "partial";
+
+export function mcpToolsetState(allowedToolNames: readonly string[] | null, toolset: McpToolCatalogToolset): McpToolsetState {
+ const enabled = toolset.tools.filter((tool) => mcpToolAllowed(allowedToolNames, tool.name)).length;
+ if (enabled === 0) return "off";
+ return enabled === toolset.tools.length ? "on" : "partial";
+}
+
+/**
+ * Turns every tool of a toolset on or off. Materializing the null ("all")
+ * allowlist seeds the plugin wildcard, exactly like the single-tool toggle, so
+ * switching a built-in toolset never silently strips discovered plugin tools.
+ */
+export function setMcpToolsEnabled(allowedToolNames: readonly string[] | null, catalog: McpToolCatalog, toolNames: readonly string[], enabled: boolean): string[] {
+ // Use the complete runtime catalog: a newer server can advertise tools that
+ // this frontend's static label list does not know yet.
+ const selected = new Set<string>(allowedToolNames === null ? [...catalog.toolsets.flatMap((toolset) => toolset.tools.map((tool) => tool.name)), MCP_PLUGIN_TOOLS_WILDCARD] : allowedToolNames);
+ for (const name of toolNames) {
+ if (enabled) selected.add(name);
+ else selected.delete(name);
+ }
+ return [...selected];
+}
+
+export function setMcpToolsetEnabled(allowedToolNames: readonly string[] | null, toolset: McpToolCatalogToolset, enabled: boolean, catalog: McpToolCatalog): string[] {
+ return setMcpToolsEnabled(
+ allowedToolNames,
+ catalog,
+ toolset.tools.map((tool) => tool.name),
+ enabled,
+ );
+}
+
+/** Copy only this toolset's switches into a saved allowlist, preserving all other entries. */
+export function mergeMcpToolsetSelection(saved: readonly string[] | null, draft: readonly string[] | null, toolset: McpToolCatalogToolset, catalog: McpToolCatalog): string[] | null {
+ let merged = saved === null ? null : [...saved];
+ for (const tool of toolset.tools) {
+ const enabled = mcpToolAllowed(draft, tool.name);
+ if (mcpToolAllowed(merged, tool.name) !== enabled) merged = setMcpToolsEnabled(merged, catalog, [tool.name], enabled);
+ }
+ return merged;
+}
+
+export function setMcpCategoryEnabled(allowedToolNames: readonly string[] | null, catalog: McpToolCatalog, categoryId: McpCapabilityCategoryId, enabled: boolean): string[] {
+ const names = catalog.toolsets.filter((toolset) => mcpCapabilityCategoryId(toolset.id) === categoryId).flatMap((toolset) => toolset.tools.map((tool) => tool.name));
+ return setMcpToolsEnabled(allowedToolNames, catalog, names, enabled);
+}
+
+/** Access levels present in a toolset, in Read → Full order (badge row). */
+export function mcpToolsetAccessLevels(toolset: McpToolCatalogToolset): McpAccessLevel[] {
+ const levels = new Set<McpAccessLevel>();
+ for (const tool of toolset.tools) {
+ levels.add("read");
+ if (tool.accessMode === "classified" || tool.access !== "read") levels.add("write");
+ if (tool.access === "full") levels.add("full");
+ }
+ return MCP_ACCESS_LEVELS.filter((level) => levels.has(level));
+}
+
+/** Whether the toolset is bound to connections at all (connection-less toolsets have no coverage). */
+export function mcpToolsetHasCoverage(toolset: McpToolCatalogToolset): boolean {
+ return toolset.tools.some((tool) => tool.coverageKind !== "none");
+}
+
+/** Stable resource scope ids supplied by the backend descriptor. */
+export function mcpToolsetScopeKinds(toolset: McpToolCatalogToolset): string[] {
+ return toolset.resourceKinds;
+}
+
+/** Union of connection types the toolset reaches. */
+export function mcpToolsetDatabaseTypes(toolset: McpToolCatalogToolset): Set<DatabaseType> {
+ return new Set(toolset.tools.flatMap((tool) => tool.databaseTypes));
+}
+
+export interface McpCoverageConnection {
+ id: string;
+ name: string;
+ dbType: DatabaseType;
+}
+
+export interface McpToolsetCoverageSummary {
+ /** Distinct connection types any tool in the set reaches. */
+ typeCount: number;
+ /** Per distinct coverage, the number of types (only when tools differ). */
+ distinctToolCounts: Array<{ tools: McpToolCatalogTool[]; typeCount: number }>;
+ /** User connections at least one tool in the set reaches. */
+ usableConnections: McpCoverageConnection[];
+ /** User connections the set reaches only partially: some tools skip their type. */
+ partialConnections: Array<{ connection: McpCoverageConnection; unsupportedTools: McpToolCatalogTool[] }>;
+}
+
+function coverageKey(tool: McpToolCatalogTool): string {
+ return tool.databaseTypes.join(",");
+}
+
+export function summarizeMcpToolsetCoverage(toolset: McpToolCatalogToolset, connections: readonly McpCoverageConnection[]): McpToolsetCoverageSummary {
+ const bound = toolset.tools.filter((tool) => tool.coverageKind !== "none");
+ const types = new Set(bound.flatMap((tool) => tool.databaseTypes));
+ const groups = new Map<string, McpToolCatalogTool[]>();
+ for (const tool of bound) groups.set(coverageKey(tool), [...(groups.get(coverageKey(tool)) ?? []), tool]);
+ const distinctToolCounts = groups.size > 1 ? [...groups.values()].map((tools) => ({ tools, typeCount: tools[0].databaseTypes.length })).sort((left, right) => right.typeCount - left.typeCount) : [];
+ const usableConnections = connections.filter((connection) => types.has(connection.dbType));
+ const partialConnections = usableConnections.map((connection) => ({ connection, unsupportedTools: bound.filter((tool) => !tool.databaseTypes.includes(connection.dbType)) })).filter((entry) => entry.unsupportedTools.length > 0);
+ return { typeCount: types.size, distinctToolCounts, usableConnections, partialConnections };
+}
+
+/** Connections no built-in toolset reaches (types MCP does not support yet). */
+export function mcpUncoveredConnections(catalog: McpToolCatalog, connections: readonly McpCoverageConnection[]): McpCoverageConnection[] {
+ const covered = new Set(catalog.toolsets.flatMap((toolset) => toolset.tools.flatMap((tool) => tool.databaseTypes)));
+ return connections.filter((connection) => !covered.has(connection.dbType));
+}
+
+export type McpCoverageCategory = DriverCategoryKey | "other";
+
+const PICKER_CATEGORY_BY_TYPE = new Map<string, DriverCategoryKey>();
+for (const option of CONNECTION_PICKER_OPTIONS) {
+ const type = option.value;
+ if (!PICKER_CATEGORY_BY_TYPE.has(type)) PICKER_CATEGORY_BY_TYPE.set(type, option.category as DriverCategoryKey);
+}
+
+export function mcpCoverageCategory(dbType: DatabaseType): McpCoverageCategory {
+ return PICKER_CATEGORY_BY_TYPE.get(dbType) ?? AGENT_DRIVER_CATEGORY_MAP[dbType] ?? "other";
+}
+
+export function mcpDatabaseTypeLabel(dbType: DatabaseType): string {
+ return databaseManifestEntry(dbType)?.label ?? dbType;
+}
+
+export interface McpCoverageCategoryRow {
+ category: McpCoverageCategory;
+ titleKey: string;
+ /** Supported types of this category, sorted by label. */
+ types: DatabaseType[];
+ /** Per tool: which of `types` it supports. */
+ tools: Array<{ tool: McpToolCatalogTool; supported: Set<DatabaseType> }>;
+}
+
+const COVERAGE_CATEGORIES: Array<{ key: McpCoverageCategory; titleKey: string }> = [...DRIVER_CATEGORIES.map(({ key, titleKey }) => ({ key, titleKey })), { key: "other", titleKey: "settings.mcpCoverageCategoryOther" }];
+
+/** Groups connection types by the connection-picker categories users already know. */
+export function groupMcpDatabaseTypesByCategory(types: Iterable<DatabaseType>): Array<{ category: McpCoverageCategory; titleKey: string; types: DatabaseType[] }> {
+ const rows = new Map<McpCoverageCategory, DatabaseType[]>();
+ for (const type of new Set(types)) {
+ const category = mcpCoverageCategory(type);
+ rows.set(category, [...(rows.get(category) ?? []), type]);
+ }
+ return COVERAGE_CATEGORIES.filter(({ key }) => rows.has(key)).map(({ key, titleKey }) => ({
+ category: key,
+ titleKey,
+ types: (rows.get(key) ?? []).sort((left, right) => mcpDatabaseTypeLabel(left).localeCompare(mcpDatabaseTypeLabel(right))),
+ }));
+}
+
+/**
+ * Toolset coverage detail: only the types at least one tool in the set
+ * supports, grouped by category, with per-tool support so a type that only
+ * some tools reach can be marked.
+ */
+export function mcpCoverageByCategory(toolset: McpToolCatalogToolset): McpCoverageCategoryRow[] {
+ const bound = toolset.tools.filter((tool) => tool.coverageKind !== "none");
+ return groupMcpDatabaseTypesByCategory(mcpToolsetDatabaseTypes(toolset)).map((row) => ({
+ ...row,
+ tools: bound.map((tool) => ({ tool, supported: new Set(tool.databaseTypes.filter((type) => row.types.includes(type))) })),
+ }));
+}
+
+/** Every type any catalog tool reaches. */
+export function mcpReachableDatabaseTypes(catalog: McpToolCatalog): Set<DatabaseType> {
+ return new Set(catalog.toolsets.flatMap((toolset) => toolset.tools.flatMap((tool) => tool.databaseTypes)));
+}
+
+/** Toolsets whose tools reach this connection type (connection row hint). */
+export function mcpToolsetsForDatabaseType(catalog: McpToolCatalog, dbType: DatabaseType): McpToolCatalogToolset[] {
+ return catalog.toolsets.filter((toolset) => toolset.tools.some((tool) => tool.databaseTypes.includes(dbType)));
+}
diff --git a/apps/desktop/src/lib/mcp/pluginMcpGrant.ts b/apps/desktop/src/lib/mcp/pluginMcpGrant.ts
new file mode 100644
index 0000000000..a5aa3a3efb
--- /dev/null
+++ b/apps/desktop/src/lib/mcp/pluginMcpGrant.ts
@@ -0,0 +1,94 @@
+import type { PluginMcpAccessLevel, PluginMcpGrant, PluginMcpToolView, PluginMcpView } from "@/types/mcpCatalog";
+
+/**
+ * Pure helpers for the plugin cards of the MCP capability tab. The backend
+ * (`dbx_core::plugin_mcp`) decides exposure; these only derive display state
+ * and build the next grant to save.
+ */
+
+export const PLUGIN_MCP_ACCESS_LEVELS: readonly PluginMcpAccessLevel[] = ["read", "write", "full"];
+
+const LEVEL_RANK: Record<PluginMcpAccessLevel, number> = { read: 0, write: 1, full: 2 };
+
+export function pluginMcpLevelAtMost(level: PluginMcpAccessLevel, ceiling: PluginMcpAccessLevel): boolean {
+ return LEVEL_RANK[level] <= LEVEL_RANK[ceiling];
+}
+
+/** Tools the author declared an access level for; only these can ever be exposed. */
+export function pluginMcpDeclaredTools(tools: readonly PluginMcpToolView[]): Array<PluginMcpToolView & { access: PluginMcpAccessLevel }> {
+ return tools.filter((tool): tool is PluginMcpToolView & { access: PluginMcpAccessLevel } => tool.access !== null);
+}
+
+/** Highest declared access level among the plugin's tools (read when none). */
+export function pluginMcpHighestLevel(tools: readonly PluginMcpToolView[]): PluginMcpAccessLevel {
+ return pluginMcpDeclaredTools(tools).reduce<PluginMcpAccessLevel>((highest, tool) => (LEVEL_RANK[tool.access] > LEVEL_RANK[highest] ? tool.access : highest), "read");
+}
+
+/** Declared access levels present among the plugin's tools, in Read → Full order. */
+export function pluginMcpAccessLevels(tools: readonly PluginMcpToolView[]): PluginMcpAccessLevel[] {
+ const present = new Set(pluginMcpDeclaredTools(tools).map((tool) => tool.access));
+ return PLUGIN_MCP_ACCESS_LEVELS.filter((level) => present.has(level));
+}
+
+export function pluginMcpUndeclaredTools(tools: readonly PluginMcpToolView[]): PluginMcpToolView[] {
+ return tools.filter((tool) => tool.access === null);
+}
+
+export function pluginMcpPendingTools(view: PluginMcpView): PluginMcpToolView[] {
+ return view.tools.filter((tool) => tool.exposure === "pendingApproval");
+}
+
+export function pluginMcpExposedCount(view: PluginMcpView): number {
+ return view.tools.filter((tool) => tool.exposure === "exposed").length;
+}
+
+/** Whether the plugin card switch shows on: the user's grant, gated by the author opt-in. */
+export function pluginMcpEnabled(view: PluginMcpView): boolean {
+ return view.authorAllowsExternal && view.grant.external;
+}
+
+/**
+ * Whether turning a plugin on must go through the authorization dialog: the
+ * user never saved a grant, the saved grant is off, or tools wait for
+ * confirmation. Re-enabling an already reviewed plugin with nothing pending
+ * is a plain switch.
+ */
+export function pluginMcpNeedsAuthorization(view: PluginMcpView): boolean {
+ return !view.hasSavedGrant || !view.grant.external || pluginMcpPendingTools(view).length > 0;
+}
+
+/** Default ceiling offered in the authorization dialog: the plugin's highest level, capped at write. */
+export function pluginMcpDefaultCeiling(view: PluginMcpView): PluginMcpAccessLevel {
+ const highest = pluginMcpHighestLevel(view.tools);
+ return LEVEL_RANK[highest] > LEVEL_RANK.write ? "write" : highest;
+}
+
+/** The grant saved by the authorization dialog (paired with `approveCurrent: true`). */
+export function pluginMcpAuthorizedGrant(view: PluginMcpView, ceiling: PluginMcpAccessLevel): PluginMcpGrant {
+ return { ...view.grant, external: true, ceiling, disabledTools: view.hasSavedGrant ? [...view.grant.disabledTools] : [] };
+}
+
+export function pluginMcpSetEnabled(grant: PluginMcpGrant, enabled: boolean): PluginMcpGrant {
+ return { ...grant, external: enabled };
+}
+
+export function pluginMcpSetCeiling(grant: PluginMcpGrant, ceiling: PluginMcpAccessLevel): PluginMcpGrant {
+ return { ...grant, ceiling };
+}
+
+export function pluginMcpSetToolEnabled(grant: PluginMcpGrant, toolName: string, enabled: boolean): PluginMcpGrant {
+ const disabled = new Set(grant.disabledTools);
+ if (enabled) disabled.delete(toolName);
+ else disabled.add(toolName);
+ return { ...grant, disabledTools: [...disabled].sort() };
+}
+
+/** A mutable copy of the grant behind a card (an unauthorized plugin carries the backend's "off" grant). */
+export function pluginMcpBaseGrant(view: PluginMcpView): PluginMcpGrant {
+ return { ...view.grant, approvedTools: { ...view.grant.approvedTools }, disabledTools: [...view.grant.disabledTools] };
+}
+
+/** Tools grouped by toolset in declaration order (the default group last). */
+export function pluginMcpToolsByToolset(view: PluginMcpView): Array<{ id: string; title: string | null; description: string | null; tools: PluginMcpToolView[] }> {
+ return view.toolsets.map((toolset) => ({ ...toolset, tools: view.tools.filter((tool) => tool.toolset === toolset.id) })).filter((group) => group.tools.length > 0);
+}
diff --git a/apps/desktop/src/lib/plugins/__tests__/pluginMcpMark.spec.ts b/apps/desktop/src/lib/plugins/__tests__/pluginMcpMark.spec.ts
new file mode 100644
index 0000000000..faf30c3394
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/__tests__/pluginMcpMark.spec.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+
+import type { InstalledPlugin } from "@/types/database";
+import { installedPluginOffersExternalMcp, installedPluginProvidesMcpTools, marketplacePluginProvidesMcpTools } from "@/lib/plugins/pluginMcpMark";
+
+function plugin(manifest: Partial<InstalledPlugin["manifest"]>): Pick<InstalledPlugin, "manifest"> {
+ return { manifest: { id: "io.dbx.x", name: "X", version: "1.0.0", ...manifest } as InstalledPlugin["manifest"] };
+}
+
+const backend = { backend: { executable: "bin/x" } };
+
+describe("plugin MCP mark", () => {
+ it("is carried by plugins with a backend and an mcp contribution", () => {
+ expect(installedPluginProvidesMcpTools(plugin({ entrypoints: backend, contributions: [{ type: "mcp", id: "x.mcp" }] }))).toBe(true);
+ expect(installedPluginProvidesMcpTools(plugin({ entrypoints: backend, contributions: [] }))).toBe(false);
+ expect(installedPluginProvidesMcpTools(plugin({ contributions: [{ type: "mcp", id: "x.mcp" }] }))).toBe(false);
+ expect(installedPluginProvidesMcpTools(plugin({}))).toBe(false);
+ });
+
+ it("separates the mark from the author's external opt-in", () => {
+ const marked = plugin({ entrypoints: backend, contributions: [{ type: "mcp", id: "x.mcp" }] });
+ expect(installedPluginOffersExternalMcp(marked)).toBe(false);
+ expect(installedPluginOffersExternalMcp(plugin({ entrypoints: backend, contributions: [{ type: "mcp", id: "x.mcp", external_tools: true }] }))).toBe(true);
+ });
+
+ it("reads the store listing flag", () => {
+ expect(marketplacePluginProvidesMcpTools({ mcpTools: true })).toBe(true);
+ expect(marketplacePluginProvidesMcpTools({})).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/lib/plugins/pluginMcpMark.ts b/apps/desktop/src/lib/plugins/pluginMcpMark.ts
new file mode 100644
index 0000000000..34a63120b8
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginMcpMark.ts
@@ -0,0 +1,26 @@
+import type { InstalledPlugin, PluginMarketplacePlugin, PluginMcpContribution } from "@/types/database";
+
+/**
+ * The "provides MCP tools" mark. A plugin carries it when its manifest has a
+ * backend plus an `mcp` contribution (mirrors
+ * `PluginManifest::provides_mcp_tools` in the plugin runtime). Only marked
+ * plugins appear in Settings → MCP → Capabilities; unmarked plugins have no MCP
+ * surface. Store listings carry the same mark as `mcpTools` so it shows
+ * before install.
+ */
+export function pluginMcpContribution(plugin: Pick<InstalledPlugin, "manifest">): PluginMcpContribution | undefined {
+ return (plugin.manifest.contributions || []).find((contribution): contribution is PluginMcpContribution => contribution.type === "mcp");
+}
+
+export function installedPluginProvidesMcpTools(plugin: Pick<InstalledPlugin, "manifest">): boolean {
+ return Boolean(plugin.manifest.entrypoints?.backend) && pluginMcpContribution(plugin) !== undefined;
+}
+
+/** The author lets the tools reach external MCP clients (the MCP card's switch can be turned on). */
+export function installedPluginOffersExternalMcp(plugin: Pick<InstalledPlugin, "manifest">): boolean {
+ return installedPluginProvidesMcpTools(plugin) && pluginMcpContribution(plugin)?.external_tools === true;
+}
+
+export function marketplacePluginProvidesMcpTools(plugin: Pick<PluginMarketplacePlugin, "mcpTools">): boolean {
+ return plugin.mcpTools === true;
+}
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsSearchCoverage.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsSearchCoverage.spec.ts
index 5a1ba11fe2..0237a48531 100644
--- a/apps/desktop/src/lib/settings/__tests__/settingsSearchCoverage.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/settingsSearchCoverage.spec.ts
@@ -64,6 +64,8 @@ const auditedNonLiteralLabels: Record<string, string> = {
"t(`settings.${titleKey}`)": "Formatter rule titles derived from the SFC below",
"t(`settings.${titleKey}`) t(`settings.sqlFormatterRule_${value}`)": "Formatter rule titles and enum labels derived from the SFC below",
database: "User-owned database names must never enter the static search index",
+ name: "Discovered database names in McpDatabaseAccessDialog are user data",
+ value: "Discovered plugin scope values in McpPluginScopeEditor are user data",
Authentication: "Static AI protocol alias tested below",
Endpoint: "Static AI protocol alias tested below",
API: "Static AI protocol alias tested below",
@@ -159,7 +161,14 @@ describe("settings search template coverage", () => {
});
it("follows nested settings forms, including backup and authorization fields", () => {
expect([...controls.keys()]).toEqual(
- expect.arrayContaining(["components/backup/DatabaseBackupConfigFields.vue", "components/connection/TunnelProfileManager.vue", "components/settings/McpAuthorizationTabs.vue", "components/editor/SqlFormatterSettingsPanel.vue", "components/grid/DataGridTypeColorSchemeDialog.vue"]),
+ expect.arrayContaining([
+ "components/backup/DatabaseBackupConfigFields.vue",
+ "components/connection/TunnelProfileManager.vue",
+ "components/settings/McpAccessTree.vue",
+ "components/settings/McpCapabilityBrowser.vue",
+ "components/editor/SqlFormatterSettingsPanel.vue",
+ "components/grid/DataGridTypeColorSchemeDialog.vue",
+ ]),
);
});
for (const [file, keys] of controls) {
@@ -207,14 +216,14 @@ describe("settings search localization coverage", () => {
const entries = resolveSettingsSearchEntries(definitions, { isWeb, visibleCategories: new Set(categories) }, (key) => String(messageAt(messages, key) ?? key), categoryLabels);
for (const key of ["mcpResourceScopeTitle", "mcpScopeModeAll", "mcpResourceScopeModeCustom"]) {
const results = searchSettings(entries, String(messageAt(messages, `settings.${key}`)), locale, Infinity);
- expect(results).toEqual(expect.arrayContaining([expect.objectContaining({ targetId: "mcp-connections", route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "connections" } })]));
+ expect(results).toEqual(expect.arrayContaining([expect.objectContaining({ targetId: "mcp-connections", route: { mcpManagementTab: "permissions" } })]));
}
for (const key of ["mcpDatabaseScopeAriaLabel", "mcpDatabaseScopeAllTitle", "mcpDatabaseScopeSelectedTitle", "mcpDatabaseScopeNoneTitle"]) {
const results = searchSettings(entries, String(messageAt(messages, `settings.${key}`)), locale, Infinity);
- expect(results).toEqual(expect.arrayContaining([expect.objectContaining({ targetId: "mcp-databases", route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "databases" } })]));
+ expect(results).toEqual(expect.arrayContaining([expect.objectContaining({ targetId: "mcp-connections", route: { mcpManagementTab: "permissions" } })]));
}
for (const query of [locale === "zh-CN" ? "通配符" : "wildcard", "dbx_ssh__*"]) {
- expect(searchSettings(entries, query, locale, Infinity)).toEqual(expect.arrayContaining([expect.objectContaining({ targetId: "mcp-capabilities", route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "capabilities" } })]));
+ expect(searchSettings(entries, query, locale, Infinity)).toEqual(expect.arrayContaining([expect.objectContaining({ targetId: "mcp-capabilities", route: { mcpManagementTab: "capabilities", mcpCapabilityTarget: { kind: "advanced" } } })]));
}
}
});
diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts
index 909767e92a..a5f84b769e 100644
--- a/apps/desktop/src/lib/settings/settingsSearch.ts
+++ b/apps/desktop/src/lib/settings/settingsSearch.ts
@@ -2,6 +2,7 @@ import { getPlatform } from "@/lib/backend/platform";
import { SQL_VARIABLE_SYNTAX_KEYS, SQL_VARIABLE_SYNTAX_TOKENS } from "@/lib/sql/sqlVariableSyntax";
import { APP_CUSTOM_UI_COLOR_DEFS } from "@/lib/app/appTheme";
import { MCP_TOOL_OPTIONS, MCP_EXECUTION_MODE_COLUMNS } from "@/lib/mcp/mcpPolicySelection";
+import type { McpCapabilityNavigationTarget } from "@/lib/mcp/mcpCapabilitySearch";
export type SettingsCategory = "editor" | "formatter" | "appearance" | "navigation" | "data" | "backups" | "tunnels" | "shortcuts" | "snippets" | "sync" | "ai" | "mcp" | "updates" | "security" | "about";
@@ -56,9 +57,9 @@ export interface SettingsSearchEntry {
export interface SettingsSearchRoute {
syncMethodTab?: "webdav" | "snippet" | "local";
- mcpManagementTab?: "access" | "permissions";
+ mcpManagementTab?: "access" | "permissions" | "capabilities";
mcpTransportTab?: "stdio" | "http";
- mcpAuthorizationTab?: "overrides" | "connections" | "databases" | "capabilities";
+ mcpCapabilityTarget?: McpCapabilityNavigationTarget;
formatterMode?: "form" | "json";
}
@@ -715,7 +716,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
titleKey: "settings.mcpExecutionMode",
descriptionKey: "settings.mcpExecutionModeDescription",
targetId: "mcp-overrides",
- route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "overrides" },
+ route: { mcpManagementTab: "permissions" },
keywordKeys: MCP_EXECUTION_MODE_COLUMNS.map((mode) => mode.labelKey),
},
{ id: "mcp-config", category: "mcp", titleKey: "settings.mcpConfig", targetId: "mcp-client-config", route: { mcpManagementTab: "access", mcpTransportTab: "stdio" } },
@@ -866,18 +867,22 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{
id: "mcp-prompt-high-risk-sql",
category: "mcp",
- titleKey: "settings.mcpPromptHighRiskSql",
- targetId: "mcp-overrides",
- route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "overrides" },
- keywordKeys: ["settings.mcpExecutionModeDescription", "settings.mcpPermissionGlobalDefaultHint", "settings.mcpCapabilityTitle", "settings.mcpCapabilityDescription", "settings.mcpCapabilityOperation", "settings.mcpCapabilityAlwaysEnforced"],
+ titleKey: "settings.mcpCallSafety",
+ targetId: "mcp-call-safety",
+ route: { mcpManagementTab: "permissions" },
+ keywordKeys: ["settings.mcpCallSafetyConfirm", "settings.mcpExecutionModeDescription", "settings.mcpPermissionGlobalDefaultHint", "settings.mcpCapabilityTitle", "settings.mcpCapabilityDescription", "settings.mcpCapabilityOperation", "settings.mcpCapabilityAlwaysEnforced"],
},
{
id: "mcp-auth-tab-connections-title",
category: "mcp",
titleKey: "settings.mcpAuthTabConnectionsTitle",
targetId: "mcp-connections",
- route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "connections" },
+ route: { mcpManagementTab: "permissions" },
keywordKeys: [
+ "settings.mcpAccessTreeScopeLabel",
+ "settings.mcpAccessTreeExceptionsOnly",
+ "settings.mcpAccessTreeColumnVisible",
+ "settings.mcpAccessTreeColumnSetting",
"settings.mcpConnectionPolicyAllowSalesforceDml",
"settings.mcpConnectionPolicyInherit",
"settings.mcpConnectionPolicyReadOnly",
@@ -892,13 +897,18 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
id: "mcp-auth-tab-databases-title",
category: "mcp",
titleKey: "settings.mcpAuthTabDatabasesTitle",
- targetId: "mcp-databases",
- route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "databases" },
+ targetId: "mcp-connections",
+ route: { mcpManagementTab: "permissions" },
keywordKeys: [
"settings.mcpConnectionPolicyInherit",
"settings.mcpConnectionPolicyReadOnly",
"settings.mcpConnectionPolicySafeWrite",
"settings.mcpConnectionPolicyHighRiskWrite",
+ "settings.mcpAccessTreeDatabases",
+ "settings.mcpDatabaseSearch",
+ "settings.mcpDatabaseSelectResults",
+ "settings.mcpDatabaseBatchLevel",
+ "settings.mcpAccessTreeManualDatabase",
"settings.mcpDatabaseScopeTitle",
"settings.mcpDatabaseScopeDescription",
"settings.mcpDatabaseScopeAriaLabel",
@@ -915,13 +925,28 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
category: "mcp",
titleKey: "settings.mcpToolPermissionsTitle",
descriptionKey: "settings.mcpToolPermissionsDescription",
- keywordKeys: ["settings.mcpToolCustomPlaceholder", "settings.mcpToolCustomHint"],
+ keywordKeys: ["settings.mcpBrowser.searchPlaceholder", "settings.mcpCapabilitiesOnlyEnabled", "settings.mcpBrowser.navigation", "settings.mcpCapabilitiesFilterLabel", "settings.mcpBrowser.builtin", "settings.mcpBrowser.plugins"],
+ targetId: "mcp-capabilities",
+ route: { mcpManagementTab: "capabilities" },
+ },
+ {
+ id: "mcp-custom-tool-entries",
+ category: "mcp",
+ titleKey: "settings.mcpPluginToolEntriesTitle",
+ keywordKeys: ["settings.mcpToolCustomPlaceholder", "settings.mcpToolCustomHint", "settings.mcpPluginToolEntriesHint"],
targetId: "mcp-capabilities",
- route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "capabilities" },
+ route: { mcpManagementTab: "capabilities", mcpCapabilityTarget: { kind: "advanced" } },
},
- { id: "mcp-permission-preview-title", category: "mcp", titleKey: "settings.mcpPermissionPreviewTitle", targetId: "mcp-capabilities", route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "capabilities" } },
+ { id: "mcp-permission-preview-title", category: "mcp", titleKey: "settings.mcpAccessTreeTitle", targetId: "mcp-connections", route: { mcpManagementTab: "permissions" } },
{ id: "backups-background-worker", category: "backups", titleKey: "databaseBackup.backgroundWorker", targetId: "backups", visible: desktopOnly },
- ...MCP_TOOL_OPTIONS.map((tool): SettingsSearchDefinition => ({ id: `mcp-tool-${tool.name}`, category: "mcp", titleKey: tool.labelKey, targetId: "mcp-capabilities", route: { mcpManagementTab: "permissions", mcpAuthorizationTab: "capabilities" } })),
+ ...MCP_TOOL_OPTIONS.map((tool): SettingsSearchDefinition => ({
+ id: `mcp-tool-${tool.name}`,
+ category: "mcp",
+ titleKey: tool.labelKey,
+ keywordTexts: [tool.name],
+ targetId: "mcp-capabilities",
+ route: { mcpManagementTab: "capabilities", mcpCapabilityTarget: { kind: "tool", toolName: tool.name } },
+ })),
];
export function resolveSettingsSearchEntries(definitions: readonly SettingsSearchDefinition[], context: SettingsSearchContext, translate: Translate, categoryLabels: Readonly<Record<SettingsCategory, string>>): SettingsSearchEntry[] {
diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
index 74422d6722..bd615c8f32 100644
--- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
+++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
@@ -1026,9 +1026,20 @@ describe("normalizeMcpGlobalPolicy", () => {
groupPolicies: [],
configured: false,
queryTimeoutSecs: null,
+ pluginToolsMode: "flat",
});
});
+ it.each(["auto", "flat", "lazy"] as const)("preserves the saved %s plugin tool mode", (pluginToolsMode) => {
+ expect(normalizeMcpGlobalPolicy({ configured: true, pluginToolsMode }).pluginToolsMode).toBe(pluginToolsMode);
+ });
+
+ it("distinguishes a missing mode in legacy saved policies from a fresh configuration", () => {
+ expect(normalizeMcpGlobalPolicy({ configured: true }).pluginToolsMode).toBe("auto");
+ expect(normalizeMcpGlobalPolicy({ configured: false }).pluginToolsMode).toBe("flat");
+ expect(normalizeMcpGlobalPolicy(null).pluginToolsMode).toBe("flat");
+ });
+
it("normalizes and deduplicates an explicit connection allowlist", () => {
expect(
normalizeMcpGlobalPolicy({
@@ -1048,6 +1059,7 @@ describe("normalizeMcpGlobalPolicy", () => {
groupPolicies: [],
configured: true,
queryTimeoutSecs: null,
+ pluginToolsMode: "auto",
});
});
@@ -1056,6 +1068,9 @@ describe("normalizeMcpGlobalPolicy", () => {
});
it("enables high-risk SQL prompts only when explicitly configured", () => {
+ expect(normalizeMcpGlobalPolicy({ promptHighRiskSql: true, callConfirmation: "high_risk" })).toMatchObject({ promptHighRiskSql: false, callConfirmation: "high_risk" });
+ expect(normalizeMcpGlobalPolicy({ promptHighRiskSql: true, callConfirmation: "off" }).promptHighRiskSql).toBe(false);
+ expect(normalizeMcpGlobalPolicy({ promptHighRiskSql: false, callConfirmation: "full" }).promptHighRiskSql).toBe(true);
expect(normalizeMcpGlobalPolicy({ promptHighRiskSql: true }).promptHighRiskSql).toBe(true);
expect(normalizeMcpGlobalPolicy({ promptHighRiskSql: "true" } as any).promptHighRiskSql).toBe(false);
});
@@ -1664,6 +1679,7 @@ describe("settingsStore MCP policy persistence", () => {
groupPolicies: [],
configured: true,
queryTimeoutSecs: null,
+ pluginToolsMode: "auto",
};
store.mcpGlobalPolicy = previous;
@@ -1682,6 +1698,7 @@ describe("settingsStore MCP policy persistence", () => {
groupPolicies: [],
configured: true,
queryTimeoutSecs: null,
+ pluginToolsMode: "auto",
});
rejectSave(new Error("save failed"));
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index 257ffeadc5..a51459a9ce 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -107,7 +107,9 @@ export interface DesktopSettings {
export interface McpGlobalPolicy {
readOnly: boolean;
allowDangerousSql: boolean;
+ /** Legacy temporary elevation; new confirmation never reuses this flag. */
promptHighRiskSql: boolean;
+ callConfirmation?: "off" | "full" | "high_risk" | null;
allowedConnectionIds: string[] | null;
allowedGroupIds: string[];
allowedToolNames: string[] | null;
@@ -116,6 +118,7 @@ export interface McpGlobalPolicy {
configured: boolean;
/** MCP query timeout override in seconds. null/undefined = inherit the connection; 0 = no limit. */
queryTimeoutSecs: number | null;
+ pluginToolsMode: "auto" | "flat" | "lazy";
}
export interface McpGroupPolicy {
@@ -198,6 +201,7 @@ export const DEFAULT_MCP_GLOBAL_POLICY: McpGlobalPolicy = {
groupPolicies: [],
configured: false,
queryTimeoutSecs: null,
+ pluginToolsMode: "flat",
};
export function normalizeMcpGlobalPolicy(policy: Partial<McpGlobalPolicy> | null | undefined): McpGlobalPolicy {
@@ -262,7 +266,8 @@ export function normalizeMcpGlobalPolicy(policy: Partial<McpGlobalPolicy> | null
return {
readOnly: policy?.readOnly === true,
allowDangerousSql: policy?.allowDangerousSql === true,
- promptHighRiskSql: policy?.promptHighRiskSql === true,
+ promptHighRiskSql: policy?.callConfirmation === "full" || (!policy?.callConfirmation && policy?.promptHighRiskSql === true),
+ ...(policy?.callConfirmation === "high_risk" ? { callConfirmation: "high_risk" as const } : {}),
allowedConnectionIds,
allowedGroupIds,
allowedToolNames,
@@ -270,6 +275,9 @@ export function normalizeMcpGlobalPolicy(policy: Partial<McpGlobalPolicy> | null
groupPolicies,
configured: policy?.configured === true,
queryTimeoutSecs,
+ // A saved policy without this field used automatic discovery before the
+ // default changed. Preserve it; only new configurations start in flat mode.
+ pluginToolsMode: policy?.pluginToolsMode === "auto" || policy?.pluginToolsMode === "flat" || policy?.pluginToolsMode === "lazy" ? policy.pluginToolsMode : policy?.configured ? "auto" : "flat",
};
}
@@ -2687,12 +2695,14 @@ export const useSettingsStore = defineStore("settings", () => {
readOnly: next.readOnly,
allowDangerousSql: next.allowDangerousSql,
promptHighRiskSql: next.promptHighRiskSql,
+ ...(next.callConfirmation ? { callConfirmation: next.callConfirmation } : {}),
allowedConnectionIds: next.allowedConnectionIds,
allowedGroupIds: next.allowedGroupIds,
allowedToolNames: next.allowedToolNames,
connectionPolicies: next.connectionPolicies,
groupPolicies: next.groupPolicies,
queryTimeoutSecs: next.queryTimeoutSecs,
+ pluginToolsMode: next.pluginToolsMode,
});
} catch (error) {
mcpGlobalPolicy.value = previous;
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 0493b50f6b..4e73bdee21 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -739,6 +739,12 @@ export interface PluginMcpContribution {
description?: string;
ai_tools?: boolean;
external_tools?: boolean;
+ /** Optional grouping of the plugin's tools for the MCP settings UI. */
+ toolsets?: Array<{ id: string; title: string; description?: string }>;
+ /** Optional per-tool declarations keyed by tool name. */
+ tools?: Record<string, { toolset?: string; access?: "read" | "write" | "full" }>;
+ /** Optional sub-scope below a connection (e.g. a Kubernetes namespace). */
+ scope?: { kind: string; title: string; argument: string; list_method?: string };
}
/**
@@ -887,6 +893,8 @@ export interface PluginMarketplacePlugin {
icon?: string;
tags: string[];
permissions: string[];
+ /** The plugin provides MCP tools (manifest declares an `mcp` contribution). */
+ mcpTools?: boolean;
source?: string;
homepage?: string;
license?: string;
diff --git a/apps/desktop/src/types/mcpCatalog.ts b/apps/desktop/src/types/mcpCatalog.ts
new file mode 100644
index 0000000000..1357947c9d
--- /dev/null
+++ b/apps/desktop/src/types/mcpCatalog.ts
@@ -0,0 +1,105 @@
+import type { DatabaseType } from "@/types/database";
+
+/** Mirrors `dbx_core::mcp_catalog` — the built-in MCP tool descriptor catalog. */
+export type McpAccessLevel = "read" | "write" | "full";
+export type McpAccessMode = "static" | "classified";
+export type McpCoverageKind = "none" | "allConnections" | "capability" | "types";
+
+export interface McpToolParameter {
+ name: string;
+ /** Display type such as `string`, `integer`, `string[]` or `latest | earliest | offset`. */
+ valueType: string;
+ required: boolean;
+ default?: unknown;
+ description: string;
+}
+
+export interface McpToolCatalogTool {
+ name: string;
+ access: McpAccessLevel;
+ accessMode: McpAccessMode;
+ coverageKind: McpCoverageKind;
+ /** Applicable connection types; empty when `coverageKind` is `none`. */
+ databaseTypes: DatabaseType[];
+ /** Description the MCP server advertises to clients (English, for the model). */
+ description: string;
+ parameters: McpToolParameter[];
+}
+
+export interface McpToolCatalogToolset {
+ id: string;
+ provider: string;
+ resourceKinds: string[];
+ scopeKind?: string;
+ /** Resource scope ids declared by the provider (database, namespace, ...). */
+ scopeKinds: string[];
+ tools: McpToolCatalogTool[];
+}
+
+export interface McpToolCatalog {
+ toolsets: McpToolCatalogToolset[];
+}
+
+/** Mirrors `dbx_core::storage::PluginMcpAccessLevel`. */
+export type PluginMcpAccessLevel = "read" | "write" | "full";
+
+/** Mirrors `dbx_core::storage::PluginMcpGrant` — the user's external MCP decision for one plugin. */
+export interface PluginMcpGrant {
+ external: boolean;
+ ceiling: PluginMcpAccessLevel;
+ /** Accepted tools with the access level each had when accepted. */
+ approvedTools: Record<string, PluginMcpAccessLevel>;
+ disabledTools: string[];
+}
+
+export type PluginToolExposure = "exposed" | "undeclared" | "pluginDisabled" | "toolDisabled" | "aboveCeiling" | "pendingApproval";
+
+export interface PluginMcpToolView {
+ name: string;
+ description: string;
+ toolset: string;
+ /** Declared access level; `null` when the manifest does not declare the tool (never exposed). */
+ access: PluginMcpAccessLevel | null;
+ exposure: PluginToolExposure;
+ parameters: McpToolParameter[];
+}
+
+export interface PluginMcpToolsetView {
+ id: string;
+ /** Declared title; `null` for the default group. */
+ title: string | null;
+ description: string | null;
+}
+
+/** Mirrors `dbx_core::plugin_mcp::PluginMcpView` — one plugin card. */
+export interface PluginMcpView {
+ pluginId: string;
+ pluginName: string;
+ version: string;
+ authorAllowsExternal: boolean;
+ hasSavedGrant: boolean;
+ grant: PluginMcpGrant;
+ toolsets: PluginMcpToolsetView[];
+ tools: PluginMcpToolView[];
+ discoveryError: string | null;
+}
+
+/** Mirrors `dbx_core::mcp_access` — the v2 access policy (plugin sub-scope rules live only here). */
+export type McpAccessLevelV2 = "none" | "read" | "write" | "full";
+export type McpSubScopeMode = "all" | "selected" | "none";
+export type McpRuleTarget = { kind: "group"; id: string } | { kind: "connection"; id: string } | { kind: "scope"; connectionId: string; scope: string; value: string };
+
+export interface McpAccessRule {
+ access?: McpAccessLevelV2;
+ ceiling?: McpAccessLevelV2;
+ visible?: boolean;
+ subScope?: McpSubScopeMode;
+ subScopeKind?: string;
+ toolsetCeilings?: Record<string, McpAccessLevelV2>;
+}
+
+export interface McpAccessPolicy {
+ version: number;
+ defaultAccess: McpAccessLevelV2;
+ rules: Array<{ target: McpRuleTarget } & McpAccessRule>;
+}
diff --git a/crates/dbx-core/src/admin/consul/catalog.rs b/crates/dbx-core/src/admin/consul/catalog.rs
index 6af8657907..8f94345ef6 100644
--- a/crates/dbx-core/src/admin/consul/catalog.rs
+++ b/crates/dbx-core/src/admin/consul/catalog.rs
@@ -36,9 +36,9 @@ pub struct ConsulCatalogNode {
pub address: String,
#[serde(default)]
pub datacenter: String,
- #[serde(default)]
+ #[serde(default, deserialize_with = "super::health::null_as_default")]
pub tagged_addresses: BTreeMap<String, String>,
- #[serde(default)]
+ #[serde(default, deserialize_with = "super::health::null_as_default")]
pub node_meta: BTreeMap<String, String>,
#[serde(default)]
pub create_index: u64,
diff --git a/crates/dbx-core/src/admin/consul/health.rs b/crates/dbx-core/src/admin/consul/health.rs
index 33ace473b7..0f4b2a9209 100644
--- a/crates/dbx-core/src/admin/consul/health.rs
+++ b/crates/dbx-core/src/admin/consul/health.rs
@@ -10,6 +10,14 @@ use super::catalog::{
};
use super::client::{client_for_state, ConsulClient};
+pub(super) fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
+where
+ D: serde::Deserializer<'de>,
+ T: Deserialize<'de> + Default,
+{
+ Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "PascalCase")]
pub struct ConsulHealthCheck {
@@ -29,7 +37,7 @@ pub struct ConsulHealthCheck {
pub service_id: String,
#[serde(default)]
pub service_name: String,
- #[serde(default)]
+ #[serde(default, deserialize_with = "null_as_default")]
pub service_tags: Vec<String>,
#[serde(default)]
#[serde(rename = "Type")]
@@ -70,13 +78,13 @@ pub struct ConsulHealthService {
pub id: String,
#[serde(default)]
pub service: String,
- #[serde(default)]
+ #[serde(default, deserialize_with = "null_as_default")]
pub tags: Vec<String>,
#[serde(default)]
pub address: String,
- #[serde(default)]
+ #[serde(default, deserialize_with = "null_as_default")]
pub tagged_addresses: BTreeMap<String, ConsulServiceAddress>,
- #[serde(default)]
+ #[serde(default, deserialize_with = "null_as_default")]
pub meta: BTreeMap<String, String>,
#[serde(default)]
pub port: u16,
@@ -91,7 +99,7 @@ pub struct ConsulHealthService {
pub struct ConsulServiceInstance {
pub node: ConsulCatalogNode,
pub service: ConsulHealthService,
- #[serde(default)]
+ #[serde(default, deserialize_with = "null_as_default")]
pub checks: Vec<ConsulHealthCheck>,
}
@@ -214,3 +222,23 @@ pub async fn consul_health_state_core(
) -> Result<ConsulListResponse<Vec<ConsulHealthCheck>>, String> {
client_for_state(state, connection_id).await?.health_state_checks(health_state, &options).await
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn health_response_accepts_absent_and_null_collections_without_changing_output_shape() {
+ for meta in [serde_json::json!(null), serde_json::json!({}), serde_json::json!({"env": "dev"})] {
+ let value = serde_json::json!({
+ "Node": {"NodeMeta": null, "TaggedAddresses": null},
+ "Service": {"Service": "api", "Meta": meta, "Tags": null, "TaggedAddresses": null},
+ "Checks": [{"ServiceTags": null}]
+ });
+ let parsed: ConsulServiceInstance = serde_json::from_value(value).unwrap();
+ assert!(serde_json::to_value(&parsed).unwrap()["Service"]["Meta"].is_object());
+ }
+ assert!(serde_json::from_value::<ConsulHealthService>(serde_json::json!({})).unwrap().meta.is_empty());
+ assert!(serde_json::from_value::<ConsulHealthService>(serde_json::json!({"Meta": 42})).is_err());
+ }
+}
diff --git a/crates/dbx-core/src/admin/nacos/http.rs b/crates/dbx-core/src/admin/nacos/http.rs
index 15553b3510..c0a8ec9e6f 100644
--- a/crates/dbx-core/src/admin/nacos/http.rs
+++ b/crates/dbx-core/src/admin/nacos/http.rs
@@ -403,10 +403,7 @@ impl NacosOpenApiAdmin {
// tenant. Keep the explicit `public` scope in DBX (ordinary users may
// not be able to list namespaces), and translate only at the HTTP
// boundary. Naming APIs, Nacos 3 and r-nacos retain their own IDs.
- if !self.is_rnacos_compatible()
- && matches!(self.cfg.version_mode, Some(NacosVersionMode::V2))
- && (path.starts_with("/v1/cs/") || path.starts_with("/v2/cs/"))
- {
+ if !self.is_rnacos_compatible() && (path.starts_with("/v1/cs/") || path.starts_with("/v2/cs/")) {
for (key, value) in query.iter_mut().chain(form.iter_mut().flatten()) {
if key == "tenant" && value == "public" {
value.clear();
@@ -2651,6 +2648,11 @@ impl NacosAdmin for NacosOpenApiAdmin {
resp.text().await.map_err(|e| format!("Failed to read Nacos config response: {e}"))?;
// show=all → detail JSON; default GET → opaque content text.
if show_all {
+ if text.is_empty() {
+ // An empty detail response is not a config value;
+ // the plain GET can still return valid empty content.
+ continue;
+ }
if let Ok(value) = serde_json::from_str::<Value>(&text) {
return Ok(parse_config_detail(value, key.data_id, key.group, namespace));
}
@@ -3243,9 +3245,9 @@ impl NacosAdmin for NacosOpenApiAdmin {
];
push_optional(&mut params, "groupName", req.group_name);
push_optional(&mut params, "clusterName", req.cluster_name);
- if let Some(ephemeral) = req.ephemeral {
- params.push(("ephemeral".to_string(), ephemeral.to_string()));
- }
+ // Manual registrations are persistent; omission must address the
+ // same instance type. Callers can explicitly target ephemeral ones.
+ params.push(("ephemeral".to_string(), req.ephemeral.unwrap_or(false).to_string()));
self.submit_service_query_candidates(
"deregister Nacos instance",
reqwest::Method::DELETE,
@@ -4706,6 +4708,94 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn public_config_requests_use_empty_v1_tenant_and_empty_detail_falls_back() {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ for (step, body) in ["", "", "ok", "ok", "ok"].into_iter().enumerate() {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let request = read_http_request(&mut socket).await;
+ let target = request.lines().next().unwrap().split_whitespace().nth(1).unwrap();
+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();
+ let params = url.query_pairs().collect::<HashMap<_, _>>();
+ if step < 2 {
+ assert_eq!(params.get("tenant").map(|v| v.as_ref()), Some(""));
+ assert_eq!(params.contains_key("show"), step == 0);
+ } else if step == 2 {
+ assert_eq!(request_form_value(&request, "tenant"), Some(""));
+ } else {
+ assert_eq!(
+ params.get("tenant").map(|v| v.as_ref()),
+ Some(if step == 3 { "team" } else { "public" })
+ );
+ }
+ write_text_response(&mut socket, body).await;
+ }
+ });
+ let mut config = test_admin_config(format!("http://{address}"));
+ config.version_mode = Some(NacosVersionMode::V2);
+ let admin = NacosOpenApiAdmin::new(config).unwrap();
+ let item = admin
+ .get_config(NacosConfigKey { namespace: Some("public".into()), data_id: "a".into(), group: "g".into() })
+ .await
+ .unwrap();
+ assert_eq!(item.content.as_deref(), Some(""));
+ admin
+ .request(
+ reqwest::Method::POST,
+ "/v1/cs/configs",
+ vec![],
+ Some(vec![("tenant".into(), "public".into())]),
+ None,
+ )
+ .await
+ .unwrap();
+ admin
+ .request(reqwest::Method::GET, "/v1/cs/configs", vec![("tenant".into(), "team".into())], None, None)
+ .await
+ .unwrap();
+ admin
+ .request(reqwest::Method::GET, "/v3/admin/cs/config", vec![("tenant".into(), "public".into())], None, None)
+ .await
+ .unwrap();
+ server.await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn deregister_defaults_to_persistent_and_preserves_explicit_instance_type() {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ for expected in ["false", "true", "false"] {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let target = read_request_target(&mut socket).await;
+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();
+ assert_eq!(url.path(), "/v1/ns/instance");
+ assert_eq!(url.query_pairs().find(|(k, _)| k == "ephemeral").unwrap().1, expected);
+ write_text_response(&mut socket, "ok").await;
+ }
+ });
+ let mut config = test_admin_config(format!("http://{address}"));
+ config.version_mode = Some(NacosVersionMode::V2);
+ let admin = NacosOpenApiAdmin::new(config).unwrap();
+ for ephemeral in [None, Some(true), Some(false)] {
+ admin
+ .deregister_instance(NacosInstanceRef {
+ namespace: None,
+ service_name: "api".into(),
+ ip: "127.0.0.1".into(),
+ port: 8080,
+ group_name: None,
+ cluster_name: None,
+ ephemeral,
+ })
+ .await
+ .unwrap();
+ }
+ server.await.unwrap();
+ }
+
#[tokio::test]
async fn v3_namespace_list_uses_managed_namespaces_after_admin_denial() {
let api_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/crates/dbx-core/src/ai/mcp_access.rs b/crates/dbx-core/src/ai/mcp_access.rs
new file mode 100644
index 0000000000..91554c0bde
--- /dev/null
+++ b/crates/dbx-core/src/ai/mcp_access.rs
@@ -0,0 +1,1589 @@
+//! Unified MCP access model (policy v2).
+//!
+//! Every resource — global default, sidebar group, connection, sub-scope (a
+//! database today; namespaces, topics, … for product providers) — resolves to
+//! one access level: `none < read < write < full`. Rules are keyed by target
+//! and inherited from the closest configured node:
+//! sub-scope > connection > closest group > ancestor group > global default.
+//!
+//! This module is the evaluation core shared by the MCP server, the desktop
+//! bridge, the Web routes and the settings preview. It is pure: callers pass
+//! the policy plus the resource path.
+//!
+//! The persisted v1 policy (`McpGlobalPolicy`) stays the source of truth until
+//! the v2 storage lands; [`McpAccessPolicy::from_v1`] maps it losslessly and
+//! the equivalence tests below pin that every v1 decision (visibility,
+//! database scope, `(read_only, allow_dangerous_sql)`) is reproduced.
+
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+
+use crate::mcp_policy::{policy_allows_connection, McpConnectionGroupPath};
+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)]
+#[serde(rename_all = "lowercase")]
+pub enum McpPluginToolsMode {
+ Auto,
+ #[default]
+ Flat,
+ Lazy,
+}
+
+impl McpPluginToolsMode {
+ /// Preserve the behavior of saved policies written without this field.
+ /// New policies use `Default` (flat); explicit saved modes always win.
+ pub fn legacy_default() -> Self {
+ Self::Auto
+ }
+}
+
+/// Unified access level. Ordered: `None < Read < Write < Full`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum McpAccessLevel {
+ None,
+ Read,
+ Write,
+ Full,
+}
+
+impl McpAccessLevel {
+ /// v1 `(read_only, allow_dangerous_sql)` → level. Read-only wins, as in v1.
+ pub fn from_flags(read_only: bool, allow_dangerous_sql: bool) -> Self {
+ match (read_only, allow_dangerous_sql) {
+ (true, _) => Self::Read,
+ (false, false) => Self::Write,
+ (false, true) => Self::Full,
+ }
+ }
+
+ pub fn from_flags_pair((read_only, allow_dangerous_sql): (bool, bool)) -> Self {
+ Self::from_flags(read_only, allow_dangerous_sql)
+ }
+
+ /// Level → v1 flags. `None` maps to read-only; visibility carries the denial.
+ pub fn to_flags(self) -> (bool, bool) {
+ match self {
+ Self::None | Self::Read => (true, false),
+ Self::Write => (false, false),
+ Self::Full => (false, true),
+ }
+ }
+}
+
+/// When a call needs the desktop user's confirmation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum McpConfirmPolicy {
+ /// Never ask (calls above the access level are rejected, not confirmed).
+ #[default]
+ Off,
+ /// Legacy temporary elevation: Write can confirm supported Full operations;
+ /// Full itself does not prompt. Never reinterpret saved `full` as HighRisk.
+ Full,
+ /// Confirm each authorized high-risk call, including Full access.
+ #[serde(rename = "high_risk")]
+ HighRisk,
+}
+
+/// Authorization is evaluated before confirmation. Callers must also enforce
+/// visibility, tool grants, connection protections and production safeguards.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum McpCallDecision {
+ Deny,
+ Allow,
+ Confirm,
+}
+
+impl McpConfirmPolicy {
+ pub fn decide(self, actual: McpAccessLevel, required: McpAccessLevel, high_risk: bool) -> McpCallDecision {
+ if actual < required {
+ if self == Self::Full && high_risk && actual == McpAccessLevel::Write && required == McpAccessLevel::Full {
+ return McpCallDecision::Confirm;
+ }
+ return McpCallDecision::Deny;
+ }
+ if self == Self::HighRisk && high_risk {
+ McpCallDecision::Confirm
+ } else {
+ McpCallDecision::Allow
+ }
+ }
+}
+
+/// What one rule applies to.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", tag = "kind")]
+pub enum McpRuleTarget {
+ Group {
+ id: String,
+ },
+ Connection {
+ id: String,
+ },
+ /// A sub-scope below a connection; `scope` names its kind (`database`, …).
+ #[serde(rename_all = "camelCase")]
+ Scope {
+ connection_id: String,
+ scope: String,
+ value: String,
+ },
+}
+
+/// One node's settings. Every field is optional: absent means "inherit".
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpAccessRule {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub access: Option<McpAccessLevel>,
+ /// Upper bound applied after inheritance instead of an override. Only
+ /// produced by migrating legacy (unversioned) v1 rules, whose semantics
+ /// were "never wider than what the node would inherit".
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ceiling: Option<McpAccessLevel>,
+ /// Explicit visibility. With `visibility = selected`, only nodes marked
+ /// visible (directly or through an ancestor group) can be reached.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub visible: Option<bool>,
+ /// Sub-scope admission for a connection: `all` (default), `selected`
+ /// (only `Scope` rules with `visible: true`), or `none`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sub_scope: Option<McpSubScopeMode>,
+ /// Kind owned by the immediate sub-scope editor. Keeps a later v1 draft
+ /// save from replacing non-database admission with its stale database mode.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sub_scope_kind: Option<String>,
+ /// Per-toolset ceilings that can only narrow the resolved level, e.g.
+ /// `{ "salesforce.write": "read" }`.
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub toolset_ceilings: BTreeMap<String, McpAccessLevel>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum McpSubScopeMode {
+ #[default]
+ All,
+ Selected,
+ None,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum McpVisibilityMode {
+ /// Every connection is visible unless a rule hides it.
+ #[default]
+ All,
+ /// Only connections marked visible (or inside a visible group).
+ Selected,
+}
+
+/// Toolset ceiling key that replaces v1 `allow_salesforce_dml`.
+pub const SALESFORCE_WRITE_TOOLSET: &str = "salesforce.write";
+
+/// The v2 policy. Rules are kept in a target-keyed map, so one target never
+/// carries two competing rules.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpAccessPolicy {
+ pub version: u8,
+ pub default_access: McpAccessLevel,
+ #[serde(default)]
+ pub confirm: McpConfirmPolicy,
+ #[serde(default)]
+ pub visibility: McpVisibilityMode,
+ #[serde(default, with = "rule_list")]
+ pub rules: BTreeMap<McpRuleTarget, McpAccessRule>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub allowed_tool_names: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub query_timeout_secs: Option<u64>,
+ #[serde(default = "McpPluginToolsMode::legacy_default")]
+ pub plugin_tools_mode: McpPluginToolsMode,
+}
+
+/// Rules serialize as a list of `{ target, ...rule }` so the JSON stays
+/// readable (map keys cannot be objects).
+mod rule_list {
+ use super::{McpAccessRule, McpRuleTarget};
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
+ use std::collections::BTreeMap;
+
+ #[derive(Serialize, Deserialize)]
+ struct Entry {
+ target: McpRuleTarget,
+ #[serde(flatten)]
+ rule: McpAccessRule,
+ }
+
+ pub fn serialize<S: Serializer>(
+ rules: &BTreeMap<McpRuleTarget, McpAccessRule>,
+ serializer: S,
+ ) -> Result<S::Ok, S::Error> {
+ rules
+ .iter()
+ .map(|(target, rule)| Entry { target: target.clone(), rule: rule.clone() })
+ .collect::<Vec<_>>()
+ .serialize(serializer)
+ }
+
+ pub fn deserialize<'de, D: Deserializer<'de>>(
+ deserializer: D,
+ ) -> Result<BTreeMap<McpRuleTarget, McpAccessRule>, D::Error> {
+ // Duplicate targets merge to the strictest combination, mirroring v1 normalization.
+ let mut rules = BTreeMap::new();
+ for Entry { target, rule } in Vec::<Entry>::deserialize(deserializer)? {
+ rules
+ .entry(target)
+ .and_modify(|current: &mut McpAccessRule| current.merge_strictest(&rule))
+ .or_insert(rule);
+ }
+ Ok(rules)
+ }
+}
+
+impl McpAccessRule {
+ fn merge_strictest(&mut self, other: &McpAccessRule) {
+ self.access = match (self.access, other.access) {
+ (Some(left), Some(right)) => Some(left.min(right)),
+ (left, right) => left.or(right),
+ };
+ self.ceiling = match (self.ceiling, other.ceiling) {
+ (Some(left), Some(right)) => Some(left.min(right)),
+ (left, right) => left.or(right),
+ };
+ self.visible = match (self.visible, other.visible) {
+ (Some(left), Some(right)) => Some(left && right),
+ (left, right) => left.or(right),
+ };
+ self.sub_scope = match (self.sub_scope, other.sub_scope) {
+ (Some(McpSubScopeMode::None), _) | (_, Some(McpSubScopeMode::None)) => Some(McpSubScopeMode::None),
+ (Some(McpSubScopeMode::Selected), _) | (_, Some(McpSubScopeMode::Selected)) => {
+ Some(McpSubScopeMode::Selected)
+ }
+ (left, right) => left.or(right),
+ };
+ if self.sub_scope_kind.is_none() {
+ self.sub_scope_kind.clone_from(&other.sub_scope_kind);
+ }
+ for (toolset, ceiling) in &other.toolset_ceilings {
+ self.toolset_ceilings
+ .entry(toolset.clone())
+ .and_modify(|current| *current = (*current).min(*ceiling))
+ .or_insert(*ceiling);
+ }
+ }
+}
+
+impl Default for McpAccessPolicy {
+ fn default() -> Self {
+ Self {
+ version: MCP_ACCESS_POLICY_VERSION,
+ default_access: McpAccessLevel::Read,
+ confirm: McpConfirmPolicy::Off,
+ visibility: McpVisibilityMode::All,
+ rules: BTreeMap::new(),
+ allowed_tool_names: None,
+ query_timeout_secs: None,
+ plugin_tools_mode: McpPluginToolsMode::default(),
+ }
+ }
+}
+
+/// Where a resolved level came from (settings preview).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase", tag = "kind")]
+pub enum McpAccessSource {
+ Default,
+ Group { id: String },
+ Connection,
+ Scope,
+}
+
+/// The resolved access of one connection or sub-scope.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpResolvedAccess {
+ pub visible: bool,
+ pub level: McpAccessLevel,
+ pub source: McpAccessSource,
+}
+
+impl McpAccessPolicy {
+ fn rule(&self, target: &McpRuleTarget) -> Option<&McpAccessRule> {
+ self.rules.get(target)
+ }
+
+ fn connection_rule(&self, connection_id: &str) -> Option<&McpAccessRule> {
+ self.rule(&McpRuleTarget::Connection { id: connection_id.to_string() })
+ }
+
+ /// Whether a connection is reachable at all.
+ pub fn connection_visible(&self, group_ids: &[String], connection_id: &str) -> bool {
+ let connection = self.connection_rule(connection_id);
+ if connection.and_then(|rule| rule.visible) == Some(false) {
+ return false;
+ }
+ match self.visibility {
+ McpVisibilityMode::All => true,
+ McpVisibilityMode::Selected => {
+ connection.and_then(|rule| rule.visible) == Some(true)
+ || group_ids.iter().any(|group_id| {
+ self.rule(&McpRuleTarget::Group { id: group_id.clone() }).and_then(|rule| rule.visible)
+ == Some(true)
+ })
+ }
+ }
+ }
+
+ /// Connection-level access before sub-scopes: closest configured group
+ /// (root → leaf, the leaf wins), then the connection rule.
+ fn connection_access(&self, group_ids: &[String], connection_id: &str) -> (McpAccessLevel, McpAccessSource) {
+ let mut resolved = (self.default_access, McpAccessSource::Default);
+ for group_id in group_ids {
+ if let Some(level) = self.rule(&McpRuleTarget::Group { id: group_id.clone() }).and_then(|rule| rule.access)
+ {
+ resolved = (level, McpAccessSource::Group { id: group_id.clone() });
+ }
+ }
+ if let Some(rule) = self.connection_rule(connection_id) {
+ if let Some(level) = rule.access {
+ resolved = (level, McpAccessSource::Connection);
+ }
+ if let Some(ceiling) = rule.ceiling.filter(|ceiling| *ceiling < resolved.0) {
+ resolved = (ceiling, McpAccessSource::Connection);
+ }
+ }
+ resolved
+ }
+
+ /// Whether `value` of sub-scope kind `scope` is admitted below a connection.
+ pub fn sub_scope_visible(&self, connection_id: &str, scope: &str, value: &str) -> bool {
+ let target = McpRuleTarget::Scope {
+ connection_id: connection_id.to_string(),
+ scope: scope.to_string(),
+ value: value.to_string(),
+ };
+ let rule = self.rule(&target);
+ if rule.and_then(|rule| rule.visible) == Some(false) {
+ return false;
+ }
+ match self.connection_rule(connection_id).and_then(|rule| rule.sub_scope).unwrap_or_default() {
+ McpSubScopeMode::All => true,
+ McpSubScopeMode::Selected => rule.and_then(|rule| rule.visible) == Some(true),
+ McpSubScopeMode::None => false,
+ }
+ }
+
+ /// Returns the admission mode configured on a connection. Callers that
+ /// require an explicit scope argument use this to fail closed when the
+ /// connection only permits selected scopes or no scopes.
+ pub fn sub_scope_mode(&self, connection_id: &str) -> McpSubScopeMode {
+ self.connection_rule(connection_id).and_then(|rule| rule.sub_scope).unwrap_or_default()
+ }
+
+ /// 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
+ /// hides or denies one of them. Callers still enforce the connection's
+ /// minimum access level for the operation itself.
+ pub fn sub_scope_allows_all(&self, connection_id: &str, scope: &str) -> bool {
+ if self.sub_scope_mode(connection_id) != McpSubScopeMode::All {
+ return false;
+ }
+ !self.rules.iter().any(|(target, rule)| {
+ matches!(
+ target,
+ McpRuleTarget::Scope {
+ connection_id: target_connection,
+ scope: target_scope,
+ ..
+ } if target_connection == connection_id && target_scope == scope
+ ) && (rule.visible == Some(false)
+ || rule.access == Some(McpAccessLevel::None)
+ || rule.ceiling == Some(McpAccessLevel::None))
+ })
+ }
+
+ /// Resolves one connection (with `sub_scope = None`) or one sub-scope value.
+ pub fn resolve(
+ &self,
+ group_ids: &[String],
+ connection_id: &str,
+ sub_scope: Option<(&str, &str)>,
+ ) -> McpResolvedAccess {
+ let visible = self.connection_visible(group_ids, connection_id)
+ && sub_scope.is_none_or(|(scope, value)| self.sub_scope_visible(connection_id, scope, value));
+ let (mut level, mut source) = self.connection_access(group_ids, connection_id);
+ if let Some((scope, value)) = sub_scope {
+ let target = McpRuleTarget::Scope {
+ connection_id: connection_id.to_string(),
+ scope: scope.to_string(),
+ value: value.to_string(),
+ };
+ if let Some(rule) = self.rule(&target) {
+ if let Some(scoped) = rule.access {
+ level = scoped;
+ source = McpAccessSource::Scope;
+ }
+ if let Some(ceiling) = rule.ceiling.filter(|ceiling| *ceiling < level) {
+ level = ceiling;
+ source = McpAccessSource::Scope;
+ }
+ }
+ }
+ McpResolvedAccess { visible, level: if visible { level } else { McpAccessLevel::None }, source }
+ }
+
+ /// A toolset ceiling on the connection narrows the resolved level for
+ /// calls of that toolset (e.g. Salesforce writes).
+ pub fn toolset_ceiling(&self, connection_id: &str, toolset: &str) -> Option<McpAccessLevel> {
+ self.connection_rule(connection_id)
+ .and_then(|rule| rule.toolset_ceilings.get(toolset).copied())
+ // Salesforce requires a separate, explicit opt-in. Visibility and
+ // inherited write access must never manufacture that permission.
+ .or_else(|| (toolset == SALESFORCE_WRITE_TOOLSET).then_some(McpAccessLevel::Read))
+ }
+
+ /// Whether a connection carries sub-scope rules, which makes cross-scope
+ /// references (SQL naming another database) unverifiable per call.
+ pub fn has_scope_rules(&self, connection_id: &str) -> bool {
+ self.rules
+ .keys()
+ .any(|target| matches!(target, McpRuleTarget::Scope { connection_id: id, .. } if id == connection_id))
+ }
+
+ // -----------------------------------------------------------------------
+ // v1 mapping
+ // -----------------------------------------------------------------------
+
+ /// Maps a persisted v1 policy losslessly. Versioned connection and
+ /// database rules become overrides; legacy (unversioned) rules become
+ /// ceilings, preserving their "never wider than inherited" semantics.
+ pub fn from_v1(policy: &McpGlobalPolicy) -> Self {
+ let policy = policy.normalized();
+ let mut rules = BTreeMap::<McpRuleTarget, McpAccessRule>::new();
+ let visibility =
+ if policy.allowed_connection_ids.is_some() { McpVisibilityMode::Selected } else { McpVisibilityMode::All };
+ for connection_id in policy.allowed_connection_ids.iter().flatten() {
+ rules.entry(McpRuleTarget::Connection { id: connection_id.clone() }).or_default().visible = Some(true);
+ }
+ for group_id in &policy.allowed_group_ids {
+ rules.entry(McpRuleTarget::Group { id: group_id.clone() }).or_default().visible = Some(true);
+ }
+ for group in &policy.group_policies {
+ rules.entry(McpRuleTarget::Group { id: group.group_id.clone() }).or_default().access =
+ Some(McpAccessLevel::from_flags(group.read_only, group.allow_dangerous_sql));
+ }
+ for connection in &policy.connection_policies {
+ let versioned =
+ connection.execution_mode_policy_version == Some(crate::mcp_policy::MCP_EXECUTION_POLICY_VERSION);
+ let connection_level = McpAccessLevel::from_flags(connection.read_only, connection.allow_dangerous_sql);
+ {
+ let rule = rules.entry(McpRuleTarget::Connection { id: connection.connection_id.clone() }).or_default();
+ rule.sub_scope = Some(match connection.database_scope {
+ McpDatabaseScope::All => McpSubScopeMode::All,
+ McpDatabaseScope::Selected => McpSubScopeMode::Selected,
+ McpDatabaseScope::None => McpSubScopeMode::None,
+ });
+ if connection.execution_mode_configured {
+ if versioned {
+ rule.access = Some(connection_level);
+ } else {
+ rule.ceiling = Some(connection_level);
+ }
+ }
+ rule.toolset_ceilings.insert(
+ SALESFORCE_WRITE_TOOLSET.to_string(),
+ if connection.allow_salesforce_dml && !connection.read_only {
+ McpAccessLevel::Full
+ } else {
+ McpAccessLevel::Read
+ },
+ );
+ }
+ let scope_target = |database: &str| McpRuleTarget::Scope {
+ connection_id: connection.connection_id.clone(),
+ scope: "database".to_string(),
+ value: database.to_string(),
+ };
+ for database in &connection.allowed_databases {
+ rules.entry(scope_target(database)).or_default().visible = Some(true);
+ }
+ for database_policy in &connection.database_policies {
+ let level = McpAccessLevel::from_flags(database_policy.read_only, database_policy.allow_dangerous_sql);
+ let rule = rules.entry(scope_target(&database_policy.database_name)).or_default();
+ if versioned {
+ rule.access = Some(level);
+ } else {
+ rule.ceiling = Some(level);
+ }
+ }
+ }
+ Self {
+ version: MCP_ACCESS_POLICY_VERSION,
+ default_access: McpAccessLevel::from_flags(policy.read_only, policy.allow_dangerous_sql),
+ confirm: policy.confirmation_policy(),
+ visibility,
+ rules,
+ allowed_tool_names: policy.allowed_tool_names.clone(),
+ query_timeout_secs: policy.query_timeout_secs,
+ plugin_tools_mode: policy.plugin_tools_mode,
+ }
+ }
+}
+
+impl McpAccessPolicy {
+ fn projected_toolset_ceiling(&self, connection_id: &str) -> Option<McpAccessLevel> {
+ self.connection_rule(connection_id)?
+ .toolset_ceilings
+ .iter()
+ .filter(|(toolset, _)| toolset.as_str() != SALESFORCE_WRITE_TOOLSET)
+ .map(|(_, ceiling)| *ceiling)
+ .min()
+ }
+
+ /// The strictest level a connection can resolve to across any group
+ /// placement: the minimum of the default, every group level, and its
+ /// own override. Used where v1 cannot express group-relative ceilings.
+ fn strictest_connection_level(&self, connection_id: &str) -> McpAccessLevel {
+ let mut strictest = self.default_access;
+ for (target, rule) in &self.rules {
+ if let (McpRuleTarget::Group { .. }, Some(level)) = (target, rule.access) {
+ strictest = strictest.min(level);
+ }
+ }
+ if let Some(rule) = self.connection_rule(connection_id) {
+ if let Some(level) = rule.access {
+ strictest = level;
+ }
+ if let Some(ceiling) = rule.ceiling {
+ strictest = strictest.min(ceiling);
+ }
+ }
+ strictest
+ }
+
+ /// Earlier v2 snapshots represented an explicit Salesforce opt-in by an
+ /// absent ceiling. Recover it only from a saved v1 opt-in; an ambiguous
+ /// standalone or visibility-only v2 rule remains denied. Existing ceilings win.
+ pub(crate) fn restore_legacy_salesforce_opt_ins(&mut self, legacy: &McpGlobalPolicy) {
+ for connection in &legacy.connection_policies {
+ if connection.allow_salesforce_dml && !connection.read_only {
+ if let Some(rule) =
+ self.rules.get_mut(&McpRuleTarget::Connection { id: connection.connection_id.clone() })
+ {
+ // A legacy explicit connection policy always had a database
+ // admission mode. Visibility alone is not opt-in evidence.
+ if rule.sub_scope.is_some() {
+ rule.toolset_ceilings
+ .entry(SALESFORCE_WRITE_TOOLSET.to_string())
+ .or_insert(McpAccessLevel::Full);
+ }
+ }
+ }
+ }
+ }
+
+ /// Projects the v2 policy onto v1 fields for hosts that only read v1
+ /// (an older standalone `dbx-mcp`). The projection is never wider than
+ /// v2: anything v1 cannot express collapses to the stricter reading —
+ /// a `none` level hides the node, a ceiling becomes a versioned
+ /// override computed against the default, sub-scope rules for kinds
+ /// other than `database` are dropped only when they could not widen.
+ pub fn to_v1(&self) -> McpGlobalPolicy {
+ use crate::storage::{McpConnectionPolicy, McpDatabasePolicy, McpGroupPolicy};
+ let flags = |level: McpAccessLevel| level.to_flags();
+ let mut allowed_connection_ids = (self.visibility == McpVisibilityMode::Selected).then(Vec::new);
+ let mut allowed_group_ids = Vec::new();
+ let mut group_policies = Vec::new();
+ let mut connection_policies = BTreeMap::<String, McpConnectionPolicy>::new();
+ let mut hidden_connections = Vec::new();
+ let blank = |id: &str| McpConnectionPolicy {
+ connection_id: id.to_string(),
+ read_only: false,
+ allow_dangerous_sql: false,
+ execution_mode_configured: false,
+ execution_mode_policy_version: Some(crate::mcp_policy::MCP_EXECUTION_POLICY_VERSION),
+ database_scope: McpDatabaseScope::All,
+ allowed_databases: Vec::new(),
+ database_policies: Vec::new(),
+ allow_salesforce_dml: false,
+ };
+ for (target, rule) in &self.rules {
+ match target {
+ McpRuleTarget::Group { id } => {
+ if rule.visible == Some(true) && self.visibility == McpVisibilityMode::Selected {
+ allowed_group_ids.push(id.clone());
+ }
+ if let Some(level) = rule.access {
+ let (read_only, allow_dangerous_sql) = flags(level.max(McpAccessLevel::Read));
+ group_policies.push(McpGroupPolicy { group_id: id.clone(), read_only, allow_dangerous_sql });
+ }
+ }
+ McpRuleTarget::Connection { id } => {
+ if rule.visible == Some(false)
+ || rule.access == Some(McpAccessLevel::None)
+ || rule.ceiling == Some(McpAccessLevel::None)
+ {
+ hidden_connections.push(id.clone());
+ } else if rule.visible == Some(true) {
+ if let Some(ids) = allowed_connection_ids.as_mut() {
+ ids.push(id.clone());
+ }
+ }
+ let policy = connection_policies.entry(id.clone()).or_insert_with(|| blank(id));
+ // A ceiling is pinned as an override against the default:
+ // v1 overrides cannot be narrower than "inherit or tighter"
+ // unless set explicitly, so pinning is the strict reading.
+ let level = match (rule.access, rule.ceiling) {
+ (Some(access), Some(ceiling)) => Some(access.min(ceiling)),
+ (Some(access), None) => Some(access),
+ (None, Some(ceiling)) => Some(ceiling.min(self.strictest_connection_level(id))),
+ (None, None) => None,
+ };
+ // v1 has one connection-wide execution level. Projecting
+ // any toolset-specific ceiling to the strictest one keeps
+ // older hosts from widening a v2-restricted toolset.
+ let level = self.projected_toolset_ceiling(id).map_or(level, |ceiling| {
+ Some(level.unwrap_or_else(|| self.strictest_connection_level(id)).min(ceiling))
+ });
+ if level == Some(McpAccessLevel::None) && !hidden_connections.contains(id) {
+ hidden_connections.push(id.clone());
+ }
+ if let Some(level) = level {
+ (policy.read_only, policy.allow_dangerous_sql) = flags(level.max(McpAccessLevel::Read));
+ policy.execution_mode_configured = true;
+ }
+ policy.database_scope = match rule.sub_scope.unwrap_or_default() {
+ McpSubScopeMode::All => McpDatabaseScope::All,
+ McpSubScopeMode::Selected => McpDatabaseScope::Selected,
+ McpSubScopeMode::None => McpDatabaseScope::None,
+ };
+ policy.allow_salesforce_dml = rule
+ .toolset_ceilings
+ .get(SALESFORCE_WRITE_TOOLSET)
+ .is_some_and(|ceiling| *ceiling > McpAccessLevel::Read)
+ && !policy.read_only;
+ }
+ McpRuleTarget::Scope { connection_id, scope, value } => {
+ let policy =
+ connection_policies.entry(connection_id.clone()).or_insert_with(|| blank(connection_id));
+ if scope != "database" {
+ // v1 has no other sub-scope kind: deny the whole
+ // connection's sub-scopes rather than widen.
+ if rule.visible == Some(false) || rule.access.is_some() || rule.ceiling.is_some() {
+ policy.database_scope = McpDatabaseScope::None;
+ }
+ continue;
+ }
+ let hidden = rule.visible == Some(false)
+ || rule.access == Some(McpAccessLevel::None)
+ || rule.ceiling == Some(McpAccessLevel::None);
+ if rule.visible == Some(true) && !hidden {
+ policy.allowed_databases.push(value.clone());
+ }
+ // A ceiling caps whatever the database would inherit. The
+ // inherited level depends on the connection's groups,
+ // which v1 database rules cannot see, so cap it with the
+ // strictest level the connection could inherit.
+ let level = match (rule.access, rule.ceiling) {
+ (Some(access), Some(ceiling)) => Some(access.min(ceiling)),
+ (Some(access), None) => Some(access),
+ (None, Some(ceiling)) => Some(ceiling.min(self.strictest_connection_level(connection_id))),
+ (None, None) => None,
+ };
+ // v1 database overrides replace the connection level, so
+ // every override must also carry the toolset ceiling.
+ let level = level.map(|level| {
+ self.projected_toolset_ceiling(connection_id).map_or(level, |ceiling| level.min(ceiling))
+ });
+ if let Some(level) = level.filter(|_| !hidden) {
+ let (read_only, allow_dangerous_sql) = flags(level.max(McpAccessLevel::Read));
+ policy.database_policies.push(McpDatabasePolicy {
+ database_name: value.clone(),
+ read_only,
+ allow_dangerous_sql,
+ });
+ }
+ }
+ }
+ }
+ // v1 expresses per-database levels and hidden databases only under a
+ // `selected` scope; promote `all` to `selected` with every visible
+ // database listed would need the live database list, so hidden or
+ // levelled databases under `all` fall back to denying the scope.
+ for policy in connection_policies.values_mut() {
+ let has_database_rules = self.rules.iter().any(|(target, _)| {
+ matches!(target, McpRuleTarget::Scope { connection_id, scope, .. } if connection_id == &policy.connection_id && scope == "database")
+ });
+ if policy.database_scope == McpDatabaseScope::All && has_database_rules {
+ policy.database_scope = McpDatabaseScope::Selected;
+ let listed = policy.allowed_databases.clone();
+ policy.database_policies.retain(|database| listed.contains(&database.database_name));
+ }
+ }
+ for id in &hidden_connections {
+ // v1 can only hide a connection through an allowlist, which would
+ // need the full connection list here. Remove it from an existing
+ // allowlist, and otherwise lock it down: no database is reachable
+ // and every write is refused.
+ if let Some(ids) = allowed_connection_ids.as_mut() {
+ ids.retain(|candidate| candidate != id);
+ }
+ let policy = connection_policies.entry(id.clone()).or_insert_with(|| blank(id));
+ policy.read_only = true;
+ policy.allow_dangerous_sql = false;
+ policy.allow_salesforce_dml = false;
+ policy.execution_mode_configured = true;
+ policy.database_scope = McpDatabaseScope::None;
+ policy.allowed_databases.clear();
+ policy.database_policies.clear();
+ }
+ // v1 has no way to express an exclusion for one connection. A
+ // connection policy can still lock that connection down for
+ // execution, but older hosts use only the global allowlist and group
+ // visibility when enumerating and resolving connections. Switch to a
+ // strict allowlist containing only explicitly visible connection
+ // rules and drop group visibility, so the projection cannot re-expose
+ // a hidden connection through an allowed group. This may hide
+ // additional unlisted connections on a v1 host, which is the safe
+ // direction for a lossy projection.
+ let restricted_ancestors = self.default_access == McpAccessLevel::None
+ || self.rules.iter().any(|(target, rule)| {
+ matches!(target, McpRuleTarget::Group { .. })
+ && (rule.visible == Some(false)
+ || rule.access == Some(McpAccessLevel::None)
+ || rule.ceiling == Some(McpAccessLevel::None))
+ });
+ if !hidden_connections.is_empty() || restricted_ancestors {
+ let explicitly_visible = self
+ .rules
+ .iter()
+ .filter_map(|(target, rule)| match target {
+ McpRuleTarget::Connection { id }
+ if rule.visible == Some(true)
+ && !hidden_connections.contains(id)
+ && (!restricted_ancestors
+ || rule.access.is_some_and(|level| level > McpAccessLevel::None)) =>
+ {
+ Some(id.clone())
+ }
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ allowed_connection_ids = Some(explicitly_visible);
+ allowed_group_ids.clear();
+ }
+ let (read_only, allow_dangerous_sql) = flags(self.default_access.max(McpAccessLevel::Read));
+ McpGlobalPolicy {
+ read_only: read_only || self.default_access == McpAccessLevel::None,
+ allow_dangerous_sql,
+ prompt_high_risk_sql: self.confirm == McpConfirmPolicy::Full,
+ call_confirmation: (self.confirm == McpConfirmPolicy::HighRisk).then_some(self.confirm),
+ allowed_connection_ids,
+ allowed_group_ids,
+ allowed_tool_names: self.allowed_tool_names.clone(),
+ connection_policies: connection_policies.into_values().collect(),
+ group_policies,
+ query_timeout_secs: self.query_timeout_secs,
+ plugin_tools_mode: self.plugin_tools_mode,
+ }
+ .normalized()
+ }
+}
+
+/// The three answers every MCP host needs for one (connection, database)
+/// pair, computed from the v2 policy.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct McpDatabaseDecision {
+ /// The connection is reachable.
+ pub connection_visible: bool,
+ /// The database is admitted below the connection.
+ pub database_visible: bool,
+ /// v1-shaped execution flags (`read_only`, `allow_dangerous_sql`).
+ pub flags: (bool, bool),
+}
+
+impl McpAccessPolicy {
+ /// Decision for `database` on `connection_id`; an empty database name
+ /// resolves the connection level (connection-default operations).
+ pub fn decide(&self, group_ids: &[String], connection_id: &str, database: &str) -> McpDatabaseDecision {
+ let connection_visible = self.connection_visible(group_ids, connection_id);
+ let sub_scope = (!database.is_empty()).then_some(("database", database));
+ let resolved = self.resolve(group_ids, connection_id, sub_scope);
+ let database_visible = connection_visible
+ && sub_scope.is_none_or(|(scope, value)| self.sub_scope_visible(connection_id, scope, value));
+ // Flags follow the level even for hidden scopes so callers that check
+ // visibility separately still get the strict reading.
+ let level = if database_visible {
+ resolved.level
+ } else {
+ self.resolve_level_ignoring_visibility(group_ids, connection_id, sub_scope)
+ };
+ McpDatabaseDecision { connection_visible, database_visible, flags: level.max(McpAccessLevel::Read).to_flags() }
+ }
+
+ fn resolve_level_ignoring_visibility(
+ &self,
+ group_ids: &[String],
+ connection_id: &str,
+ sub_scope: Option<(&str, &str)>,
+ ) -> McpAccessLevel {
+ let mut visible_everywhere = self.clone();
+ visible_everywhere.visibility = McpVisibilityMode::All;
+ for rule in visible_everywhere.rules.values_mut() {
+ rule.visible = None;
+ rule.sub_scope = None;
+ }
+ visible_everywhere.resolve(group_ids, connection_id, sub_scope).level
+ }
+}
+
+impl McpAccessPolicy {
+ /// Carries over the rules v1 cannot express — sub-scope rules of kinds
+ /// other than `database` (plugin scopes) and the connection sub-scope
+ /// modes they rely on — from `previous` into a policy rebuilt from v1.
+ /// Lets the v1 settings form save without erasing plugin scope rules.
+ pub fn with_v2_only_rules_from(mut self, previous: &McpAccessPolicy) -> Self {
+ // Preserve the admission mode even when the user has not selected a
+ // concrete value yet. Without this pass, a connection configured as
+ // `selected` or `none` silently reverted to `all` on the next v1 save.
+ for (target, rule) in &previous.rules {
+ let McpRuleTarget::Connection { id } = target else { continue };
+ let Some(mode) = rule.sub_scope else { continue };
+ let non_database_scope = rule.sub_scope_kind.as_deref().is_some_and(|kind| kind != "database")
+ || previous.rules.keys().any(|target| matches!(target, McpRuleTarget::Scope { connection_id, scope, .. } if connection_id == id && scope != "database"));
+ if non_database_scope {
+ let connection = self.rules.entry(target.clone()).or_default();
+ connection.sub_scope = Some(mode);
+ connection.sub_scope_kind.clone_from(&rule.sub_scope_kind);
+ }
+ }
+ for (target, rule) in &previous.rules {
+ let McpRuleTarget::Connection { .. } = target else { continue };
+ if rule.toolset_ceilings.keys().all(|toolset| toolset == SALESFORCE_WRITE_TOOLSET) {
+ continue;
+ }
+ let connection = self.rules.entry(target.clone()).or_default();
+ for (toolset, ceiling) in &rule.toolset_ceilings {
+ // Salesforce DML is explicitly editable by v1.
+ if toolset == SALESFORCE_WRITE_TOOLSET {
+ continue;
+ }
+ connection
+ .toolset_ceilings
+ .entry(toolset.clone())
+ .and_modify(|current| *current = (*current).min(*ceiling))
+ .or_insert(*ceiling);
+ }
+ }
+ for (target, rule) in &previous.rules {
+ if let McpRuleTarget::Scope { scope, .. } = target {
+ if scope != "database" {
+ self.rules.insert(target.clone(), rule.clone());
+ }
+ }
+ }
+ self
+ }
+}
+
+/// Convenience: v1 visibility check expressed through the v2 resolver, used
+/// by the equivalence tests and by callers that migrate incrementally.
+pub fn v1_connection_visible(
+ policy: &McpGlobalPolicy,
+ group_path: Option<&McpConnectionGroupPath>,
+ connection_id: &str,
+) -> bool {
+ policy_allows_connection(policy, group_path, connection_id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::mcp_policy::{effective_database_execution_policy_with_groups, MCP_EXECUTION_POLICY_VERSION};
+ #[allow(unused_imports)]
+ use crate::storage::McpDatabaseScope;
+ use crate::storage::{McpConnectionPolicy, McpDatabasePolicy, McpGroupPolicy};
+
+ fn connection_rule(id: &str) -> McpConnectionPolicy {
+ McpConnectionPolicy {
+ connection_id: id.to_string(),
+ read_only: false,
+ allow_dangerous_sql: false,
+ execution_mode_configured: false,
+ execution_mode_policy_version: Some(MCP_EXECUTION_POLICY_VERSION),
+ database_scope: McpDatabaseScope::All,
+ allowed_databases: Vec::new(),
+ database_policies: Vec::new(),
+ allow_salesforce_dml: false,
+ }
+ }
+
+ #[test]
+ fn visibility_only_does_not_opt_in_to_salesforce_dml() {
+ for allowed in [None, Some(vec!["sf".to_string()])] {
+ let policy = McpGlobalPolicy { allowed_connection_ids: allowed, ..Default::default() };
+ let access = McpAccessPolicy::from_v1(&policy);
+ assert_eq!(access.toolset_ceiling("sf", SALESFORCE_WRITE_TOOLSET), Some(McpAccessLevel::Read));
+ assert!(!crate::mcp_policy::connection_allows_salesforce_dml(&access.to_v1(), "sf"));
+ }
+ for allowed in [false, true] {
+ let mut rule = connection_rule("sf");
+ rule.allow_salesforce_dml = allowed;
+ let policy = McpGlobalPolicy { connection_policies: vec![rule], ..Default::default() };
+ assert_eq!(
+ crate::mcp_policy::connection_allows_salesforce_dml(&McpAccessPolicy::from_v1(&policy).to_v1(), "sf"),
+ allowed
+ );
+ }
+ }
+
+ #[test]
+ fn legacy_salesforce_opt_in_requires_explicit_v1_evidence_and_respects_ceiling() {
+ let mut access = McpAccessPolicy::default();
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "sf".into() },
+ McpAccessRule { visible: Some(true), ..Default::default() },
+ );
+ let mut rule = connection_rule("sf");
+ let mut legacy = McpGlobalPolicy { connection_policies: vec![rule.clone()], ..Default::default() };
+ access.restore_legacy_salesforce_opt_ins(&legacy);
+ assert!(!crate::mcp_policy::connection_allows_salesforce_dml(&access.to_v1(), "sf"));
+ rule.allow_salesforce_dml = true;
+ legacy.connection_policies = vec![rule];
+ access.restore_legacy_salesforce_opt_ins(&legacy);
+ assert!(!crate::mcp_policy::connection_allows_salesforce_dml(&access.to_v1(), "sf"));
+ access.rules.get_mut(&McpRuleTarget::Connection { id: "sf".into() }).unwrap().sub_scope =
+ Some(McpSubScopeMode::All);
+ access.restore_legacy_salesforce_opt_ins(&legacy);
+ assert!(crate::mcp_policy::connection_allows_salesforce_dml(&access.to_v1(), "sf"));
+ access
+ .rules
+ .get_mut(&McpRuleTarget::Connection { id: "sf".into() })
+ .unwrap()
+ .toolset_ceilings
+ .insert(SALESFORCE_WRITE_TOOLSET.into(), McpAccessLevel::Read);
+ access.restore_legacy_salesforce_opt_ins(&legacy);
+ assert!(!crate::mcp_policy::connection_allows_salesforce_dml(&access.to_v1(), "sf"));
+ }
+
+ #[test]
+ fn removing_database_rule_reopens_databases_but_retains_plugin_admission() {
+ for mode in [McpDatabaseScope::Selected, McpDatabaseScope::None] {
+ let mut rule = connection_rule("sql");
+ rule.database_scope = mode;
+ rule.allowed_databases = vec!["one".into()];
+ let previous =
+ McpAccessPolicy::from_v1(&McpGlobalPolicy { connection_policies: vec![rule], ..Default::default() });
+ let next = McpAccessPolicy::from_v1(&McpGlobalPolicy::default()).with_v2_only_rules_from(&previous);
+ assert!(next.sub_scope_visible("sql", "database", "two"));
+ assert!(!next.rules.contains_key(&McpRuleTarget::Connection { id: "sql".into() }));
+ }
+ let mut previous = McpAccessPolicy::default();
+ previous.rules.insert(
+ McpRuleTarget::Connection { id: "plugin".into() },
+ McpAccessRule {
+ sub_scope: Some(McpSubScopeMode::None),
+ sub_scope_kind: Some("custom".into()),
+ ..Default::default()
+ },
+ );
+ let next = McpAccessPolicy::default().with_v2_only_rules_from(&previous);
+ assert!(!next.sub_scope_visible("plugin", "custom", "one"));
+ }
+
+ /// Deterministic pseudo-random generator so the equivalence sweep is reproducible.
+ struct Lcg(u64);
+ impl Lcg {
+ fn next(&mut self) -> u64 {
+ self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ self.0 >> 33
+ }
+ fn bool(&mut self) -> bool {
+ self.next().is_multiple_of(2)
+ }
+ fn pick<T: Copy>(&mut self, items: &[T]) -> T {
+ items[(self.next() as usize) % items.len()]
+ }
+ }
+
+ const CONNECTIONS: [&str; 3] = ["c1", "c2", "c3"];
+ const GROUPS: [&str; 2] = ["g-root", "g-leaf"];
+ const DATABASES: [&str; 3] = ["db_a", "db_b", "db_c"];
+
+ fn group_path(connection: &str) -> McpConnectionGroupPath {
+ match connection {
+ "c1" => McpConnectionGroupPath {
+ ids: vec!["g-root".into(), "g-leaf".into()],
+ names: vec!["Root".into(), "Leaf".into()],
+ },
+ "c2" => McpConnectionGroupPath { ids: vec!["g-root".into()], names: vec!["Root".into()] },
+ _ => McpConnectionGroupPath::default(),
+ }
+ }
+
+ fn random_policy(rng: &mut Lcg) -> McpGlobalPolicy {
+ let flags = |rng: &mut Lcg| (rng.bool(), rng.bool());
+ let (read_only, allow_dangerous_sql) = flags(rng);
+ let allowed_connection_ids =
+ rng.bool().then(|| CONNECTIONS.iter().filter(|_| rng.bool()).map(|id| id.to_string()).collect());
+ let allowed_group_ids = GROUPS.iter().filter(|_| rng.bool()).map(|id| id.to_string()).collect();
+ let mut group_policies = Vec::new();
+ for id in GROUPS {
+ if rng.bool() {
+ let (read_only, allow_dangerous_sql) = flags(rng);
+ group_policies.push(McpGroupPolicy { group_id: id.to_string(), read_only, allow_dangerous_sql });
+ }
+ }
+ let mut connection_policies = Vec::new();
+ for id in CONNECTIONS {
+ if !rng.bool() {
+ continue;
+ }
+ let mut rule = connection_rule(id);
+ (rule.read_only, rule.allow_dangerous_sql) = flags(rng);
+ rule.execution_mode_configured = rng.bool();
+ rule.execution_mode_policy_version = rng.pick(&[Some(MCP_EXECUTION_POLICY_VERSION), None]);
+ rule.database_scope =
+ rng.pick(&[McpDatabaseScope::All, McpDatabaseScope::Selected, McpDatabaseScope::None]);
+ rule.allowed_databases = DATABASES.iter().filter(|_| rng.bool()).map(|db| db.to_string()).collect();
+ for db in DATABASES {
+ if rng.bool() {
+ let (read_only, allow_dangerous_sql) = flags(rng);
+ rule.database_policies.push(McpDatabasePolicy {
+ database_name: db.to_string(),
+ read_only,
+ allow_dangerous_sql,
+ });
+ }
+ }
+ rule.allow_salesforce_dml = rng.bool();
+ connection_policies.push(rule);
+ }
+ McpGlobalPolicy {
+ read_only,
+ allow_dangerous_sql,
+ prompt_high_risk_sql: rng.bool(),
+ call_confirmation: None,
+ allowed_connection_ids,
+ allowed_group_ids,
+ allowed_tool_names: None,
+ connection_policies,
+ group_policies,
+ query_timeout_secs: None,
+ plugin_tools_mode: McpPluginToolsMode::Auto,
+ }
+ .normalized()
+ }
+
+ /// v1 database admission, mirroring the MCP server's DatabaseScope.
+ fn v1_database_visible(policy: &McpGlobalPolicy, connection: &str, database: &str) -> bool {
+ match policy.connection_policies.iter().find(|rule| rule.connection_id == connection) {
+ None => true,
+ Some(rule) => match rule.database_scope {
+ McpDatabaseScope::All => true,
+ McpDatabaseScope::Selected => rule.allowed_databases.iter().any(|allowed| allowed == database),
+ McpDatabaseScope::None => false,
+ },
+ }
+ }
+
+ #[test]
+ fn call_safety_authorizes_before_confirming_and_preserves_legacy() {
+ use McpAccessLevel::{Full, None, Read, Write};
+ use McpCallDecision::{Allow, Confirm, Deny};
+ for actual in [None, Read, Write, Full] {
+ for required in [Read, Write, Full] {
+ for high_risk in [false, true] {
+ assert_eq!(
+ McpConfirmPolicy::HighRisk.decide(actual, required, high_risk),
+ if actual < required {
+ Deny
+ } else if high_risk {
+ Confirm
+ } else {
+ Allow
+ }
+ );
+ assert_eq!(
+ McpConfirmPolicy::Off.decide(actual, required, high_risk),
+ if actual < required { Deny } else { Allow }
+ );
+ }
+ }
+ }
+ assert_eq!(McpConfirmPolicy::Full.decide(Write, Full, true), Confirm);
+ assert_eq!(McpConfirmPolicy::Full.decide(Full, Full, true), Allow);
+ assert_eq!(McpConfirmPolicy::Full.decide(Read, Full, true), Deny);
+ }
+
+ #[test]
+ fn confirmation_migration_is_explicit_and_roundtrips() {
+ for (field, old, expected) in [
+ (serde_json::Value::Null, true, McpConfirmPolicy::Full),
+ (serde_json::Value::Null, false, McpConfirmPolicy::Off),
+ (serde_json::json!("off"), true, McpConfirmPolicy::Off),
+ (serde_json::json!("high_risk"), true, McpConfirmPolicy::HighRisk),
+ ] {
+ let policy: McpGlobalPolicy = serde_json::from_value(serde_json::json!({
+ "readOnly": false, "allowDangerousSql": true,
+ "promptHighRiskSql": old, "callConfirmation": field,
+ }))
+ .unwrap();
+ let normalized = policy.normalized();
+ assert_eq!(normalized.confirmation_policy(), expected);
+ let v2 = McpAccessPolicy::from_v1(&normalized);
+ assert_eq!(v2.confirm, expected);
+ assert_eq!(v2.to_v1().normalized(), normalized);
+ assert_eq!(normalized.prompt_high_risk_sql, expected == McpConfirmPolicy::Full);
+ }
+ assert_eq!(serde_json::from_str::<McpConfirmPolicy>("\"full\"").unwrap(), McpConfirmPolicy::Full);
+ assert_eq!(McpGlobalPolicy::default().confirmation_policy(), McpConfirmPolicy::Off);
+ }
+
+ #[test]
+ fn v2_reproduces_every_v1_decision() {
+ let mut rng = Lcg(0x5eed_d8c4);
+ for case in 0..4_000 {
+ let v1 = random_policy(&mut rng);
+ let v2 = McpAccessPolicy::from_v1(&v1);
+ for connection in CONNECTIONS {
+ let path = group_path(connection);
+ let visible_v1 = policy_allows_connection(&v1, Some(&path), connection);
+ assert_eq!(
+ v2.connection_visible(&path.ids, connection),
+ visible_v1,
+ "case {case}: visibility of {connection}\nv1={v1:#?}\nv2={v2:#?}"
+ );
+ for database in DATABASES {
+ let resolved = v2.resolve(&path.ids, connection, Some(("database", database)));
+ let admitted_v1 = visible_v1 && v1_database_visible(&v1, connection, database);
+ assert_eq!(
+ resolved.visible, admitted_v1,
+ "case {case}: admission of {connection}/{database}\nv1={v1:#?}\nv2={v2:#?}"
+ );
+ if !admitted_v1 {
+ continue;
+ }
+ let flags_v1 =
+ effective_database_execution_policy_with_groups(&v1, &path.ids, connection, database);
+ assert_eq!(
+ resolved.level.to_flags(),
+ flags_v1,
+ "case {case}: level of {connection}/{database}\nv1={v1:#?}\nv2={v2:#?}"
+ );
+ }
+ let salesforce_v1 = crate::mcp_policy::connection_allows_salesforce_dml(&v1, connection);
+ let salesforce_v2 = v2
+ .toolset_ceiling(connection, SALESFORCE_WRITE_TOOLSET)
+ .is_none_or(|ceiling| ceiling > McpAccessLevel::Read)
+ && v1.connection_policies.iter().any(|rule| rule.connection_id == connection);
+ assert_eq!(salesforce_v2, salesforce_v1, "case {case}: salesforce DML of {connection}");
+ }
+ assert_eq!(v2.confirm == McpConfirmPolicy::Full, v1.prompt_high_risk_sql);
+ }
+ }
+
+ #[test]
+ fn v1_round_trip_through_v2_is_never_wider() {
+ let mut rng = Lcg(0x0b5e_55ed);
+ for case in 0..4_000 {
+ let v1 = random_policy(&mut rng);
+ let projected = McpAccessPolicy::from_v1(&v1).to_v1();
+ for connection in CONNECTIONS {
+ let path = group_path(connection);
+ let visible = policy_allows_connection(&v1, Some(&path), connection);
+ let projected_visible = policy_allows_connection(&projected, Some(&path), connection);
+ assert!(
+ !projected_visible || visible,
+ "case {case}: projection widened visibility of {connection}\nv1={v1:#?}\nprojected={projected:#?}"
+ );
+ if !projected_visible {
+ continue;
+ }
+ for database in DATABASES {
+ if !v1_database_visible(&projected, connection, database) {
+ continue;
+ }
+ assert!(
+ v1_database_visible(&v1, connection, database),
+ "case {case}: projection widened {connection}/{database}"
+ );
+ let original = McpAccessLevel::from_flags_pair(effective_database_execution_policy_with_groups(
+ &v1, &path.ids, connection, database,
+ ));
+ let after = McpAccessLevel::from_flags_pair(effective_database_execution_policy_with_groups(
+ &projected, &path.ids, connection, database,
+ ));
+ assert!(after <= original, "case {case}: projection widened level of {connection}/{database}: {after:?} > {original:?}\nv1={v1:#?}\nprojected={projected:#?}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn projection_hides_none_levels_and_unknown_scope_kinds() {
+ let mut policy = McpAccessPolicy { default_access: McpAccessLevel::Write, ..Default::default() };
+ policy.rules.insert(
+ McpRuleTarget::Connection { id: "c".into() },
+ McpAccessRule { access: Some(McpAccessLevel::None), ..Default::default() },
+ );
+ policy.rules.insert(
+ McpRuleTarget::Scope { connection_id: "k".into(), scope: "namespace".into(), value: "prod".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Read), ..Default::default() },
+ );
+ let v1 = policy.to_v1();
+ let c = v1.connection_policies.iter().find(|rule| rule.connection_id == "c").unwrap();
+ assert!(c.read_only && c.database_scope == McpDatabaseScope::None, "a none level locks the connection down");
+ assert!(!policy_allows_connection(&v1, None, "other"), "lossy v1 projection must fail closed");
+ let k = v1.connection_policies.iter().find(|rule| rule.connection_id == "k").unwrap();
+ assert_eq!(k.database_scope, McpDatabaseScope::None, "unknown sub-scope kinds deny rather than widen");
+ }
+
+ #[test]
+ fn projection_of_hidden_connection_under_all_uses_strict_allowlist() {
+ let mut policy = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ policy.rules.insert(
+ McpRuleTarget::Connection { id: "hidden".into() },
+ McpAccessRule { visible: Some(false), ..Default::default() },
+ );
+ policy.rules.insert(
+ McpRuleTarget::Connection { id: "visible".into() },
+ McpAccessRule { visible: Some(true), ..Default::default() },
+ );
+
+ let projected = policy.to_v1();
+ assert_eq!(projected.allowed_connection_ids, Some(vec!["visible".to_string()]));
+ assert!(policy_allows_connection(&projected, None, "visible"));
+ assert!(!policy_allows_connection(&projected, None, "hidden"));
+ assert!(!policy_allows_connection(&projected, None, "unlisted"));
+
+ let mut selected = policy;
+ selected.visibility = McpVisibilityMode::Selected;
+ selected.rules.insert(
+ McpRuleTarget::Group { id: "group".into() },
+ McpAccessRule { visible: Some(true), ..Default::default() },
+ );
+ let projected = selected.to_v1();
+ assert!(projected.allowed_group_ids.is_empty(), "group visibility must not bypass a hidden connection");
+ assert!(!policy_allows_connection(
+ &projected,
+ Some(&McpConnectionGroupPath { ids: vec!["group".into()], names: vec![] }),
+ "hidden"
+ ));
+ }
+
+ #[test]
+ fn projection_and_v1_save_preserve_unknown_toolset_ceilings_conservatively() {
+ let mut policy = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ let mut connection = McpAccessRule { access: Some(McpAccessLevel::Full), ..Default::default() };
+ connection.toolset_ceilings.insert("custom.write".into(), McpAccessLevel::Read);
+ policy.rules.insert(McpRuleTarget::Connection { id: "c".into() }, connection.clone());
+
+ let projected = policy.to_v1();
+ let projected = projected.connection_policies.iter().find(|rule| rule.connection_id == "c").unwrap();
+ assert!(projected.read_only, "v1 must conservatively cap the connection at read");
+ assert!(!projected.allow_dangerous_sql);
+
+ let saved = McpAccessPolicy::default().with_v2_only_rules_from(&policy);
+ assert_eq!(
+ saved.toolset_ceiling("c", "custom.write"),
+ Some(McpAccessLevel::Read),
+ "v1-backed saves must not erase v2-only ceilings"
+ );
+ }
+
+ #[test]
+ fn toolset_ceiling_projection_never_widens_inheritance_or_database_overrides() {
+ for inherited in [McpAccessLevel::Read, McpAccessLevel::Write, McpAccessLevel::Full] {
+ for ceiling in [McpAccessLevel::Read, McpAccessLevel::Write, McpAccessLevel::Full] {
+ for database in [None, Some(McpAccessLevel::Read), Some(McpAccessLevel::Full)] {
+ let mut policy = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ policy.rules.insert(
+ McpRuleTarget::Group { id: "parent".into() },
+ McpAccessRule { access: Some(inherited), ..Default::default() },
+ );
+ policy.rules.insert(
+ McpRuleTarget::Connection { id: "c".into() },
+ McpAccessRule {
+ sub_scope: Some(McpSubScopeMode::Selected),
+ toolset_ceilings: [("sql.query".into(), ceiling)].into(),
+ ..Default::default()
+ },
+ );
+ policy.rules.insert(
+ McpRuleTarget::Scope {
+ connection_id: "c".into(),
+ scope: "database".into(),
+ value: "db".into(),
+ },
+ McpAccessRule { access: database, visible: Some(true), ..Default::default() },
+ );
+ let groups = vec!["parent".into()];
+ let expected = policy.resolve(&groups, "c", Some(("database", "db"))).level.min(ceiling);
+ let projected = policy.to_v1();
+ let actual = McpAccessLevel::from_flags_pair(effective_database_execution_policy_with_groups(
+ &projected, &groups, "c", "db",
+ ));
+ assert!(actual <= expected, "{inherited:?}/{ceiling:?}/{database:?}: {actual:?} > {expected:?}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn decide_matches_v1_for_every_generated_policy() {
+ let mut rng = Lcg(0xdec1_de00);
+ for case in 0..2_000 {
+ let v1 = random_policy(&mut rng);
+ let v2 = McpAccessPolicy::from_v1(&v1);
+ for connection in CONNECTIONS {
+ let path = group_path(connection);
+ for database in DATABASES {
+ let decision = v2.decide(&path.ids, connection, database);
+ assert_eq!(
+ decision.connection_visible,
+ policy_allows_connection(&v1, Some(&path), connection),
+ "case {case}"
+ );
+ assert_eq!(
+ decision.database_visible,
+ decision.connection_visible && v1_database_visible(&v1, connection, database),
+ "case {case}"
+ );
+ assert_eq!(
+ decision.flags,
+ effective_database_execution_policy_with_groups(&v1, &path.ids, connection, database),
+ "case {case}: {connection}/{database}"
+ );
+ }
+ }
+ }
+ }
+
+ #[test]
+ /// Policies saved by the current UI (versioned rules only) survive a
+ /// v1 → v2 → v1 round trip exactly.
+ fn v1_round_trip_through_v2_is_exact() {
+ let mut rng = Lcg(0x0e9a_c7ed);
+ let mut mismatches = Vec::new();
+ for case in 0..4_000 {
+ let v1 = random_policy(&mut rng);
+ // Legacy unversioned ceilings may come back stricter (covered by
+ // `v1_round_trip_through_v2_is_never_wider`).
+ if v1.connection_policies.iter().any(|rule| rule.execution_mode_policy_version.is_none()) {
+ continue;
+ }
+ let projected = McpAccessPolicy::from_v1(&v1).to_v1();
+ for connection in CONNECTIONS {
+ let path = group_path(connection);
+ let visible = policy_allows_connection(&v1, Some(&path), connection);
+ if visible != policy_allows_connection(&projected, Some(&path), connection) {
+ mismatches.push(format!("case {case}: visibility {connection}"));
+ continue;
+ }
+ if !visible {
+ continue;
+ }
+ for database in DATABASES {
+ let admitted = v1_database_visible(&v1, connection, database);
+ if admitted != v1_database_visible(&projected, connection, database) {
+ mismatches.push(format!("case {case}: admission {connection}/{database}"));
+ continue;
+ }
+ if admitted
+ && effective_database_execution_policy_with_groups(&v1, &path.ids, connection, database)
+ != effective_database_execution_policy_with_groups(
+ &projected, &path.ids, connection, database,
+ )
+ {
+ mismatches.push(format!("case {case}: level {connection}/{database}"));
+ }
+ }
+ }
+ }
+ assert!(
+ mismatches.is_empty(),
+ "{} mismatches, first: {:?}",
+ mismatches.len(),
+ &mismatches[..mismatches.len().min(8)]
+ );
+ }
+
+ #[test]
+ fn v1_projection_never_reexposes_explicitly_selected_denied_nodes() {
+ for ceiling in [false, true] {
+ let mut access = McpAccessPolicy::default();
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "blocked".into() },
+ McpAccessRule {
+ visible: Some(true),
+ access: (!ceiling).then_some(McpAccessLevel::None),
+ ceiling: ceiling.then_some(McpAccessLevel::None),
+ ..Default::default()
+ },
+ );
+ let projected = access.to_v1();
+ assert!(!v1_connection_visible(&projected, None, "blocked"));
+ }
+ let access = McpAccessPolicy { default_access: McpAccessLevel::None, ..Default::default() };
+ assert!(!v1_connection_visible(&access.to_v1(), None, "unlisted"));
+ }
+
+ #[test]
+ fn v1_saves_keep_plugin_scope_rules() {
+ let mut previous = McpAccessPolicy::default();
+ let plugin_scope =
+ McpRuleTarget::Scope { connection_id: "k".into(), scope: "namespace".into(), value: "dev".into() };
+ previous.rules.insert(plugin_scope.clone(), McpAccessRule { visible: Some(true), ..Default::default() });
+ previous.rules.insert(
+ McpRuleTarget::Connection { id: "k".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ previous.rules.insert(
+ McpRuleTarget::Scope { connection_id: "c".into(), scope: "database".into(), value: "old".into() },
+ McpAccessRule { visible: Some(true), ..Default::default() },
+ );
+ let rebuilt = McpAccessPolicy::from_v1(&McpGlobalPolicy::default()).with_v2_only_rules_from(&previous);
+ assert!(rebuilt.rules.contains_key(&plugin_scope));
+ assert_eq!(
+ rebuilt.rules[&McpRuleTarget::Connection { id: "k".into() }].sub_scope,
+ Some(McpSubScopeMode::Selected)
+ );
+ assert!(
+ !rebuilt
+ .rules
+ .keys()
+ .any(|target| matches!(target, McpRuleTarget::Scope { scope, .. } if scope == "database")),
+ "database rules come from v1 only"
+ );
+ }
+
+ #[test]
+ fn v1_saves_keep_plugin_scope_mode_without_values() {
+ let mut previous = McpAccessPolicy::default();
+ previous.rules.insert(
+ McpRuleTarget::Connection { id: "k".into() },
+ McpAccessRule {
+ sub_scope: Some(McpSubScopeMode::None),
+ sub_scope_kind: Some("namespace".into()),
+ ..Default::default()
+ },
+ );
+ let rebuilt = McpAccessPolicy::from_v1(&McpGlobalPolicy::default()).with_v2_only_rules_from(&previous);
+ assert_eq!(rebuilt.rules[&McpRuleTarget::Connection { id: "k".into() }].sub_scope, Some(McpSubScopeMode::None));
+ }
+
+ #[test]
+ fn level_flags_round_trip() {
+ for level in [McpAccessLevel::Read, McpAccessLevel::Write, McpAccessLevel::Full] {
+ let (read_only, dangerous) = level.to_flags();
+ assert_eq!(McpAccessLevel::from_flags(read_only, dangerous), level);
+ }
+ assert_eq!(McpAccessLevel::from_flags(true, true), McpAccessLevel::Read, "read-only wins");
+ assert!(McpAccessLevel::None < McpAccessLevel::Read && McpAccessLevel::Write < McpAccessLevel::Full);
+ }
+
+ #[test]
+ fn inheritance_prefers_scope_then_connection_then_closest_group() {
+ let mut policy = McpAccessPolicy { default_access: McpAccessLevel::Read, ..Default::default() };
+ let groups = vec!["root".to_string(), "leaf".to_string()];
+ policy.rules.insert(
+ McpRuleTarget::Group { id: "root".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Full), ..Default::default() },
+ );
+ assert_eq!(policy.resolve(&groups, "c", None).level, McpAccessLevel::Full);
+ policy.rules.insert(
+ McpRuleTarget::Group { id: "leaf".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Write), ..Default::default() },
+ );
+ let resolved = policy.resolve(&groups, "c", None);
+ assert_eq!(
+ (resolved.level, resolved.source),
+ (McpAccessLevel::Write, McpAccessSource::Group { id: "leaf".into() })
+ );
+ policy.rules.insert(
+ McpRuleTarget::Connection { id: "c".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Read), ..Default::default() },
+ );
+ assert_eq!(policy.resolve(&groups, "c", None).source, McpAccessSource::Connection);
+ policy.rules.insert(
+ McpRuleTarget::Scope { connection_id: "c".into(), scope: "database".into(), value: "billing".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Full), ..Default::default() },
+ );
+ let scoped = policy.resolve(&groups, "c", Some(("database", "billing")));
+ assert_eq!((scoped.level, scoped.source), (McpAccessLevel::Full, McpAccessSource::Scope));
+ assert_eq!(policy.resolve(&groups, "c", Some(("database", "other"))).level, McpAccessLevel::Read);
+ }
+
+ #[test]
+ fn hidden_resources_resolve_to_none() {
+ let mut policy = McpAccessPolicy { visibility: McpVisibilityMode::Selected, ..Default::default() };
+ assert_eq!(policy.resolve(&[], "c", None).level, McpAccessLevel::None);
+ policy.rules.insert(
+ McpRuleTarget::Connection { id: "c".into() },
+ McpAccessRule { visible: Some(true), sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ assert!(policy.resolve(&[], "c", None).visible);
+ assert!(
+ !policy.resolve(&[], "c", Some(("database", "x"))).visible,
+ "selected sub-scope admits only listed values"
+ );
+ }
+
+ #[test]
+ fn all_sub_scope_requests_require_unrestricted_scope_rules() {
+ let mut policy = McpAccessPolicy::default();
+ assert!(policy.sub_scope_allows_all("c", "namespace"));
+
+ policy.rules.insert(
+ McpRuleTarget::Connection { id: "c".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ assert!(!policy.sub_scope_allows_all("c", "namespace"));
+
+ policy.rules.insert(
+ McpRuleTarget::Connection { id: "c".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::All), ..Default::default() },
+ );
+ policy.rules.insert(
+ McpRuleTarget::Scope { connection_id: "c".into(), scope: "namespace".into(), value: "hidden".into() },
+ McpAccessRule { visible: Some(false), ..Default::default() },
+ );
+ assert!(!policy.sub_scope_allows_all("c", "namespace"));
+
+ policy.rules.insert(
+ McpRuleTarget::Scope { connection_id: "c".into(), scope: "namespace".into(), value: "hidden".into() },
+ McpAccessRule { access: Some(McpAccessLevel::None), ..Default::default() },
+ );
+ assert!(!policy.sub_scope_allows_all("c", "namespace"));
+ assert!(policy.sub_scope_allows_all("c", "database"));
+ }
+
+ #[test]
+ fn policy_serializes_rules_as_a_list_and_merges_duplicates_strictly() {
+ let json = serde_json::json!({
+ "version": 2,
+ "defaultAccess": "write",
+ "rules": [
+ { "target": { "kind": "connection", "id": "c" }, "access": "full", "visible": true },
+ { "target": { "kind": "connection", "id": "c" }, "access": "read" },
+ { "target": { "kind": "scope", "connectionId": "c", "scope": "database", "value": "db" }, "access": "none" }
+ ]
+ });
+ let policy: McpAccessPolicy = serde_json::from_value(json).unwrap();
+ let connection = &policy.rules[&McpRuleTarget::Connection { id: "c".into() }];
+ assert_eq!(connection.access, Some(McpAccessLevel::Read), "duplicates merge to the strictest level");
+ assert_eq!(connection.visible, Some(true));
+ let round_trip: McpAccessPolicy = serde_json::from_value(serde_json::to_value(&policy).unwrap()).unwrap();
+ assert_eq!(round_trip, policy);
+ assert!(serde_json::to_value(&policy).unwrap()["rules"].is_array());
+ }
+}
diff --git a/crates/dbx-core/src/ai/mcp_catalog.rs b/crates/dbx-core/src/ai/mcp_catalog.rs
new file mode 100644
index 0000000000..2ebd4309b0
--- /dev/null
+++ b/crates/dbx-core/src/ai/mcp_catalog.rs
@@ -0,0 +1,614 @@
+//! Static descriptor catalog for the built-in `dbx` MCP tools.
+//!
+//! The catalog groups every built-in tool into a toolset owned by a provider,
+//! declares the highest access level the tool can reach, and computes which
+//! connection types the tool works on. Settings UIs render it instead of a
+//! hardcoded checkbox list, so the grouping and the coverage text cannot drift
+//! from the server. It is descriptive only: tool permissions are still the
+//! flat `allowed_tool_names` allowlist enforced by the MCP server.
+//!
+//! `dbx-mcp` asserts that the router and this catalog name the same tools, so
+//! a new tool cannot ship without a descriptor.
+
+use serde::Serialize;
+
+use crate::database_manifest::{self, DatabaseCapability};
+use crate::models::connection::DatabaseType;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum McpAccessLevel {
+ Read,
+ Write,
+ Full,
+}
+
+/// Whether the access level is fixed per tool or decided per call (for
+/// example by the SQL risk classifier).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum McpAccessMode {
+ Static,
+ Classified,
+}
+
+/// How a tool's applicable connection types are derived.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum McpCoverage {
+ /// Not bound to a connection (connection management, plugin router).
+ None,
+ /// Every connection type the MCP server can reach.
+ AllConnections,
+ /// Connection types whose manifest entry advertises the capability,
+ /// minus `exclude` (types the tool rejects explicitly).
+ Capability { capability: DatabaseCapability, exclude: &'static [DatabaseType] },
+ /// A fixed list of connection types.
+ Types(&'static [DatabaseType]),
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct McpToolDescriptor {
+ pub name: &'static str,
+ pub toolset: &'static str,
+ pub access: McpAccessLevel,
+ pub access_mode: McpAccessMode,
+ pub coverage: McpCoverage,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct McpToolsetDescriptor {
+ pub id: &'static str,
+ pub provider: &'static str,
+ /// Resource scopes understood by this toolset. Empty means the toolset is
+ /// connection-less (for example the plugin router); the values are stable
+ /// ids used by the settings resource tree and policy API.
+ pub scope_kinds: &'static [&'static str],
+}
+
+const NO_SCOPE: &[&str] = &[];
+const DATABASE_SCOPE: &[&str] = &["database"];
+const REDIS_SCOPE: &[&str] = &["dbIndex"];
+const MQ_SCOPE: &[&str] = &["topic", "queue"];
+const SALESFORCE_SCOPE: &[&str] = &["org"];
+const NACOS_SCOPE: &[&str] = &["namespace"];
+
+pub const TOOLSETS: &[McpToolsetDescriptor] = &[
+ McpToolsetDescriptor { id: "core.discovery", provider: "builtin:core", scope_kinds: DATABASE_SCOPE },
+ McpToolsetDescriptor { id: "sql.query", provider: "builtin:sql", scope_kinds: DATABASE_SCOPE },
+ McpToolsetDescriptor { id: "sql.session", provider: "builtin:sql", scope_kinds: DATABASE_SCOPE },
+ McpToolsetDescriptor { id: "sql.schema", provider: "builtin:sql", scope_kinds: DATABASE_SCOPE },
+ McpToolsetDescriptor { id: "redis", provider: "builtin:redis", scope_kinds: REDIS_SCOPE },
+ McpToolsetDescriptor { id: "mq", provider: "builtin:mq", scope_kinds: MQ_SCOPE },
+ McpToolsetDescriptor { id: "salesforce", provider: "builtin:salesforce", scope_kinds: SALESFORCE_SCOPE },
+ McpToolsetDescriptor { id: "nacos.config", provider: "builtin:nacos", scope_kinds: NACOS_SCOPE },
+ McpToolsetDescriptor { id: "nacos.service", provider: "builtin:nacos", scope_kinds: NACOS_SCOPE },
+ // A Consul connection already represents one configured datacenter. The
+ // product API does not accept a datacenter selector, so there is no
+ // separate MCP sub-scope to authorize here.
+ McpToolsetDescriptor { id: "consul.kv", provider: "builtin:consul", scope_kinds: NO_SCOPE },
+ McpToolsetDescriptor { id: "consul.service", provider: "builtin:consul", scope_kinds: NO_SCOPE },
+ McpToolsetDescriptor { id: "workbench", provider: "builtin:workbench", scope_kinds: NO_SCOPE },
+ McpToolsetDescriptor { id: "admin.connections", provider: "builtin:admin", scope_kinds: NO_SCOPE },
+ McpToolsetDescriptor { id: "plugin.router", provider: "builtin:plugin", scope_kinds: NO_SCOPE },
+];
+
+const NON_SQL_SESSION: &[DatabaseType] = &[DatabaseType::Redis, DatabaseType::MongoDb, DatabaseType::Salesforce];
+
+/// `dbx_execute_batch` and sessions reject the same types (see their
+/// `DBX_BATCH_UNSUPPORTED` / `SESSION_UNSUPPORTED` guards in `dbx-mcp`).
+const SQL_QUERY: McpCoverage =
+ McpCoverage::Capability { capability: DatabaseCapability::QueryExecution, exclude: NON_SQL_SESSION };
+
+/// Product providers (design §5): one product, one connection type.
+const NACOS: McpCoverage = McpCoverage::Types(&[DatabaseType::Nacos]);
+const CONSUL: McpCoverage = McpCoverage::Types(&[DatabaseType::Consul]);
+
+/// Fixed-session transactions only run on native MySQL
+/// (`transaction_connection_supported` in `dbx-mcp`).
+const TRANSACTIONS: McpCoverage = McpCoverage::Types(&[DatabaseType::Mysql]);
+
+const fn tool(
+ name: &'static str,
+ toolset: &'static str,
+ access: McpAccessLevel,
+ coverage: McpCoverage,
+) -> McpToolDescriptor {
+ McpToolDescriptor { name, toolset, access, access_mode: McpAccessMode::Static, coverage }
+}
+
+const fn classified(name: &'static str, toolset: &'static str, coverage: McpCoverage) -> McpToolDescriptor {
+ McpToolDescriptor { name, toolset, access: McpAccessLevel::Full, access_mode: McpAccessMode::Classified, coverage }
+}
+
+use McpAccessLevel::{Full, Read, Write};
+
+pub const TOOLS: &[McpToolDescriptor] = &[
+ // Listing the configured connections is a discovery operation in its own
+ // right, so it remains available when the workspace has no connections.
+ tool("dbx_list_connections", "core.discovery", Read, McpCoverage::None),
+ tool("dbx_list_databases", "core.discovery", Read, McpCoverage::AllConnections),
+ tool(
+ "dbx_get_schema_context",
+ "core.discovery",
+ Read,
+ McpCoverage::Capability { capability: DatabaseCapability::MetadataBrowse, exclude: &[] },
+ ),
+ classified(
+ "dbx_execute_query",
+ "sql.query",
+ McpCoverage::Capability { capability: DatabaseCapability::QueryExecution, exclude: &[] },
+ ),
+ classified(
+ "dbx_execute_batch",
+ "sql.query",
+ McpCoverage::Capability { capability: DatabaseCapability::SqlFileExecution, exclude: NON_SQL_SESSION },
+ ),
+ tool("dbx_open_session", "sql.session", Read, SQL_QUERY),
+ tool("dbx_begin_transaction", "sql.session", Write, TRANSACTIONS),
+ tool("dbx_commit_transaction", "sql.session", Write, TRANSACTIONS),
+ tool("dbx_rollback_transaction", "sql.session", Read, TRANSACTIONS),
+ tool("dbx_close_session", "sql.session", Read, SQL_QUERY),
+ tool(
+ "dbx_list_tables",
+ "sql.schema",
+ Read,
+ McpCoverage::Capability { capability: DatabaseCapability::MetadataBrowse, exclude: &[] },
+ ),
+ tool(
+ "dbx_describe_table",
+ "sql.schema",
+ Read,
+ McpCoverage::Capability { capability: DatabaseCapability::MetadataBrowse, exclude: &[] },
+ ),
+ tool(
+ "dbx_list_routines",
+ "sql.schema",
+ Read,
+ McpCoverage::Capability { capability: DatabaseCapability::ObjectSource, exclude: &[] },
+ ),
+ tool(
+ "dbx_get_routine_source",
+ "sql.schema",
+ Read,
+ McpCoverage::Capability { capability: DatabaseCapability::ObjectSource, exclude: &[] },
+ ),
+ classified("dbx_execute_redis_command", "redis", McpCoverage::Types(&[DatabaseType::Redis])),
+ tool("dbx_peek_messages", "mq", Read, McpCoverage::Types(&[DatabaseType::MessageQueue])),
+ tool("dbx_send_message", "mq", Write, McpCoverage::Types(&[DatabaseType::MessageQueue])),
+ tool("dbx_salesforce_current_user", "salesforce", Read, McpCoverage::Types(&[DatabaseType::Salesforce])),
+ // Preparing a write does not send it yet, but it is part of the DML
+ // capability and is therefore gated by the same write ceiling as apply.
+ tool("dbx_salesforce_prepare_write", "salesforce", Write, McpCoverage::Types(&[DatabaseType::Salesforce])),
+ tool("dbx_salesforce_apply_write", "salesforce", Write, McpCoverage::Types(&[DatabaseType::Salesforce])),
+ tool("dbx_nacos_list_namespaces", "nacos.config", Read, NACOS),
+ tool("dbx_nacos_list_configs", "nacos.config", Read, NACOS),
+ tool("dbx_nacos_search_configs", "nacos.config", Read, NACOS),
+ tool("dbx_nacos_get_config", "nacos.config", Read, NACOS),
+ tool("dbx_nacos_config_history", "nacos.config", Read, NACOS),
+ tool("dbx_nacos_publish_config", "nacos.config", Write, NACOS),
+ tool("dbx_nacos_rollback_config", "nacos.config", Write, NACOS),
+ tool("dbx_nacos_delete_config", "nacos.config", Full, NACOS),
+ tool("dbx_nacos_list_services", "nacos.service", Read, NACOS),
+ tool("dbx_nacos_get_service", "nacos.service", Read, NACOS),
+ tool("dbx_nacos_list_instances", "nacos.service", Read, NACOS),
+ tool("dbx_nacos_update_instance", "nacos.service", Write, NACOS),
+ tool("dbx_nacos_register_instance", "nacos.service", Write, NACOS),
+ tool("dbx_nacos_deregister_instance", "nacos.service", Full, NACOS),
+ tool("dbx_consul_kv_list", "consul.kv", Read, CONSUL),
+ tool("dbx_consul_kv_get", "consul.kv", Read, CONSUL),
+ tool("dbx_consul_kv_put", "consul.kv", Write, CONSUL),
+ tool("dbx_consul_kv_delete", "consul.kv", Full, CONSUL),
+ tool("dbx_consul_list_services", "consul.service", Read, CONSUL),
+ tool("dbx_consul_list_nodes", "consul.service", Read, CONSUL),
+ tool("dbx_consul_service_health", "consul.service", Read, CONSUL),
+ tool("dbx_consul_set_maintenance", "consul.service", Write, CONSUL),
+ tool(
+ "dbx_open_table",
+ "workbench",
+ Read,
+ McpCoverage::Capability { capability: DatabaseCapability::MetadataBrowse, exclude: &[] },
+ ),
+ classified(
+ "dbx_execute_and_show",
+ "workbench",
+ McpCoverage::Capability { capability: DatabaseCapability::QueryExecution, exclude: &[] },
+ ),
+ tool("dbx_add_connection", "admin.connections", Write, McpCoverage::None),
+ tool("dbx_duplicate_connection", "admin.connections", Write, McpCoverage::None),
+ tool("dbx_remove_connection", "admin.connections", Full, McpCoverage::None),
+ tool("dbx_plugin_list", "plugin.router", Read, McpCoverage::None),
+ tool("dbx_plugin_tools", "plugin.router", Read, McpCoverage::None),
+ classified("dbx_plugin_call", "plugin.router", McpCoverage::None),
+];
+
+/// Connection types the MCP server can reach at all.
+fn mcp_reachable(db_type: &DatabaseType) -> bool {
+ database_manifest::entry(db_type).is_some_and(|entry| entry.mcp_mode != "unsupported")
+}
+
+impl McpCoverage {
+ /// Applicable connection types in manifest order; empty for `None`.
+ pub fn database_types(&self) -> Vec<DatabaseType> {
+ let manifest_types = || database_manifest::entries().iter().map(|entry| entry.db_type);
+ match self {
+ McpCoverage::None => Vec::new(),
+ McpCoverage::AllConnections => manifest_types().filter(mcp_reachable).collect(),
+ McpCoverage::Capability { capability, exclude } => manifest_types()
+ .filter(|db_type| {
+ mcp_reachable(db_type)
+ && !exclude.contains(db_type)
+ && database_manifest::supports_capability(db_type, *capability)
+ })
+ .collect(),
+ McpCoverage::Types(types) => types.to_vec(),
+ }
+ }
+
+ fn kind(&self) -> McpCoverageKind {
+ match self {
+ McpCoverage::None => McpCoverageKind::None,
+ McpCoverage::AllConnections => McpCoverageKind::AllConnections,
+ McpCoverage::Capability { .. } => McpCoverageKind::Capability,
+ McpCoverage::Types(_) => McpCoverageKind::Types,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum McpCoverageKind {
+ None,
+ AllConnections,
+ Capability,
+ Types,
+}
+
+/// One input argument of a tool, flattened from its JSON Schema for display.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpToolParameter {
+ pub name: String,
+ /// Display type such as `string`, `integer`, `string[]` or `latest | earliest | offset`.
+ pub value_type: String,
+ pub required: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub default: Option<serde_json::Value>,
+ pub description: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpToolCatalogTool {
+ pub name: &'static str,
+ pub access: McpAccessLevel,
+ pub access_mode: McpAccessMode,
+ pub coverage_kind: McpCoverageKind,
+ /// Applicable connection types; empty when `coverage_kind` is `none`.
+ pub database_types: Vec<DatabaseType>,
+ /// Description the MCP server advertises to clients (English, for the model).
+ pub description: String,
+ pub parameters: Vec<McpToolParameter>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpToolCatalogToolset {
+ pub id: &'static str,
+ pub provider: &'static str,
+ /// Resource kinds this provider can address. This is the descriptor-level
+ /// equivalent of `resource.kinds` in the capability design.
+ pub resource_kinds: Vec<&'static str>,
+ /// Primary scope argument kind, when the toolset has one.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub scope_kind: Option<&'static str>,
+ pub scope_kinds: Vec<&'static str>,
+ pub tools: Vec<McpToolCatalogTool>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpToolCatalog {
+ pub toolsets: Vec<McpToolCatalogToolset>,
+}
+
+/// The serializable catalog served to settings UIs. Descriptions and
+/// parameters live on the MCP router, so this core view leaves them empty;
+/// `dbx_mcp::DbxMcpServer::tool_catalog` fills them in with
+/// [`McpToolCatalog::with_router_details`].
+pub fn tool_catalog() -> McpToolCatalog {
+ let toolsets = TOOLSETS
+ .iter()
+ .map(|toolset| McpToolCatalogToolset {
+ id: toolset.id,
+ provider: toolset.provider,
+ resource_kinds: toolset.scope_kinds.to_vec(),
+ scope_kind: toolset.scope_kinds.first().copied(),
+ scope_kinds: toolset.scope_kinds.to_vec(),
+ tools: TOOLS
+ .iter()
+ .filter(|tool| tool.toolset == toolset.id)
+ .map(|tool| McpToolCatalogTool {
+ name: tool.name,
+ access: tool.access,
+ access_mode: tool.access_mode,
+ coverage_kind: tool.coverage.kind(),
+ database_types: tool.coverage.database_types(),
+ description: String::new(),
+ parameters: Vec::new(),
+ })
+ .collect(),
+ })
+ .collect();
+ McpToolCatalog { toolsets }
+}
+
+impl McpToolCatalog {
+ /// Fills each tool's advertised description and parameters from the
+ /// router's tool definitions (`name`, `description`, `inputSchema`).
+ pub fn with_router_details<'a>(
+ mut self,
+ router_tools: impl IntoIterator<Item = (&'a str, &'a str, &'a serde_json::Map<String, serde_json::Value>)>,
+ ) -> Self {
+ let details = router_tools.into_iter().collect::<Vec<_>>();
+ for tool in self.toolsets.iter_mut().flat_map(|toolset| toolset.tools.iter_mut()) {
+ if let Some((_, description, schema)) = details.iter().find(|(name, _, _)| *name == tool.name) {
+ tool.description = append_coverage_description(description, descriptor(tool.name).map(|d| d.coverage));
+ tool.parameters = schema_parameters(schema);
+ }
+ }
+ self
+ }
+}
+
+fn append_coverage_description(description: &str, coverage: Option<McpCoverage>) -> String {
+ let Some(coverage) = coverage else { return description.to_string() };
+ let types = coverage.database_types();
+ let suffix = match coverage {
+ McpCoverage::None => "Supported without a database connection.".to_string(),
+ _ if types.is_empty() => "No supported database types are currently available.".to_string(),
+ _ => {
+ let examples = types.iter().take(3).map(|kind| human_database_type(*kind)).collect::<Vec<_>>().join(", ");
+ if types.len() <= 3 {
+ format!("Supported on {} database type(s): {}.", types.len(), examples)
+ } else {
+ format!("Supported on {} database types, including {}.", types.len(), examples)
+ }
+ }
+ };
+ format!("{} {}", description.trim_end(), suffix)
+}
+
+fn human_database_type(kind: DatabaseType) -> String {
+ match kind.as_str() {
+ "mysql" => "MySQL".into(),
+ "postgres" => "PostgreSQL".into(),
+ "sqlserver" => "SQL Server".into(),
+ "sqlite" => "SQLite".into(),
+ "mongodb" => "MongoDB".into(),
+ "redis" => "Redis".into(),
+ "nacos" => "Nacos".into(),
+ "consul" => "Consul".into(),
+ value => value
+ .replace('_', " ")
+ .split_whitespace()
+ .map(|word| {
+ let mut chars = word.chars();
+ chars.next().map(|first| first.to_uppercase().collect::<String>() + chars.as_str()).unwrap_or_default()
+ })
+ .collect::<Vec<_>>()
+ .join(" "),
+ }
+}
+
+/// Flattens a tool input schema's top-level properties for display,
+/// resolving local `#/$defs/...` references. Required arguments come first,
+/// each group keeping the schema's declaration order.
+pub fn schema_parameters(schema: &serde_json::Map<String, serde_json::Value>) -> Vec<McpToolParameter> {
+ let Some(properties) = schema.get("properties").and_then(serde_json::Value::as_object) else {
+ return Vec::new();
+ };
+ let required = schema
+ .get("required")
+ .and_then(serde_json::Value::as_array)
+ .map(|items| items.iter().filter_map(serde_json::Value::as_str).collect::<Vec<_>>())
+ .unwrap_or_default();
+ let mut parameters = properties
+ .iter()
+ .map(|(name, property)| McpToolParameter {
+ name: name.clone(),
+ value_type: schema_value_type(schema, property, 0),
+ required: required.contains(&name.as_str()),
+ default: property.get("default").filter(|value| !value.is_null()).cloned(),
+ description: property
+ .get("description")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ })
+ .collect::<Vec<_>>();
+ parameters.sort_by_key(|parameter| !parameter.required);
+ parameters
+}
+
+fn schema_value_type(
+ root: &serde_json::Map<String, serde_json::Value>,
+ property: &serde_json::Value,
+ depth: usize,
+) -> String {
+ if depth > 4 {
+ return "any".to_string();
+ }
+ if let Some(reference) = property.get("$ref").and_then(serde_json::Value::as_str) {
+ let resolved = reference
+ .strip_prefix("#/$defs/")
+ .and_then(|name| root.get("$defs").and_then(|defs| defs.get(name)))
+ .or_else(|| {
+ reference
+ .strip_prefix("#/definitions/")
+ .and_then(|name| root.get("definitions").and_then(|defs| defs.get(name)))
+ });
+ return resolved
+ .map(|target| schema_value_type(root, target, depth + 1))
+ .unwrap_or_else(|| "object".to_string());
+ }
+ if let Some(values) = property.get("enum").and_then(serde_json::Value::as_array) {
+ return values
+ .iter()
+ .map(|value| value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string()))
+ .collect::<Vec<_>>()
+ .join(" | ");
+ }
+ for key in ["anyOf", "oneOf"] {
+ if let Some(variants) = property.get(key).and_then(serde_json::Value::as_array) {
+ let types = variants
+ .iter()
+ .filter(|variant| variant.get("type").and_then(serde_json::Value::as_str) != Some("null"))
+ .map(|variant| schema_value_type(root, variant, depth + 1))
+ .collect::<Vec<_>>();
+ if !types.is_empty() {
+ return types.join(" | ");
+ }
+ }
+ }
+ let types = match property.get("type") {
+ Some(serde_json::Value::String(kind)) => vec![kind.as_str()],
+ Some(serde_json::Value::Array(kinds)) => {
+ kinds.iter().filter_map(serde_json::Value::as_str).filter(|kind| *kind != "null").collect()
+ }
+ _ => Vec::new(),
+ };
+ match types.as_slice() {
+ ["array"] => {
+ let item = property.get("items").map(|items| schema_value_type(root, items, depth + 1));
+ format!("{}[]", item.unwrap_or_else(|| "any".to_string()))
+ }
+ [] => "any".to_string(),
+ kinds => kinds.join(" | "),
+ }
+}
+
+pub fn descriptor(name: &str) -> Option<&'static McpToolDescriptor> {
+ TOOLS.iter().find(|tool| tool.name == name)
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashSet;
+
+ use super::*;
+
+ #[test]
+ fn every_tool_belongs_to_a_declared_toolset_and_names_are_unique() {
+ let toolsets = TOOLSETS.iter().map(|toolset| toolset.id).collect::<HashSet<_>>();
+ assert_eq!(toolsets.len(), TOOLSETS.len(), "toolset ids are unique");
+ let mut names = HashSet::new();
+ for tool in TOOLS {
+ assert!(toolsets.contains(tool.toolset), "{} has an unknown toolset {}", tool.name, tool.toolset);
+ assert!(names.insert(tool.name), "duplicate descriptor {}", tool.name);
+ assert!(tool.name.starts_with("dbx_") && !tool.name.contains("__"), "{} is a router name", tool.name);
+ }
+ for toolset in TOOLSETS {
+ assert!(TOOLS.iter().any(|tool| tool.toolset == toolset.id), "{} has no tools", toolset.id);
+ }
+ }
+
+ #[test]
+ fn coverage_follows_manifest_capabilities() {
+ let routines = descriptor("dbx_get_routine_source").unwrap().coverage.database_types();
+ assert!(routines.contains(&DatabaseType::Mysql));
+ assert!(routines.contains(&DatabaseType::Oracle));
+ assert!(!routines.contains(&DatabaseType::Sqlite));
+
+ let query = descriptor("dbx_execute_query").unwrap().coverage.database_types();
+ assert!(query.contains(&DatabaseType::Redis), "execute_query also routes Redis/Mongo commands");
+ assert!(!query.contains(&DatabaseType::Nacos), "MCP-unsupported types never count");
+
+ let batch = descriptor("dbx_execute_batch").unwrap().coverage.database_types();
+ assert!(batch.contains(&DatabaseType::Postgres));
+ assert!(!batch.contains(&DatabaseType::Redis) && !batch.contains(&DatabaseType::MongoDb));
+ assert!(!batch.contains(&DatabaseType::Salesforce));
+
+ assert_eq!(descriptor("dbx_begin_transaction").unwrap().coverage.database_types(), vec![DatabaseType::Mysql]);
+ assert!(descriptor("dbx_add_connection").unwrap().coverage.database_types().is_empty());
+ }
+
+ #[test]
+ fn schema_parameters_flatten_types_refs_and_required_order() {
+ let schema = serde_json::json!({
+ "type": "object",
+ "properties": {
+ "partition": { "type": ["integer", "null"], "default": null },
+ "start_position": { "$ref": "#/$defs/Start", "default": "latest", "description": "Where to start" },
+ "topic": { "type": "string", "description": "Topic name" },
+ "tables": { "type": "array", "items": { "type": "string" } },
+ "arguments": {}
+ },
+ "required": ["topic"],
+ "$defs": { "Start": { "type": "string", "enum": ["latest", "earliest"] } }
+ });
+ let parameters = schema_parameters(schema.as_object().unwrap());
+ let summary = parameters
+ .iter()
+ .map(|parameter| (parameter.name.as_str(), parameter.value_type.as_str(), parameter.required))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ summary,
+ [
+ ("topic", "string", true),
+ ("partition", "integer", false),
+ ("start_position", "latest | earliest", false),
+ ("tables", "string[]", false),
+ ("arguments", "any", false),
+ ]
+ );
+ assert_eq!(parameters[0].description, "Topic name");
+ assert_eq!(parameters[1].default, None, "null defaults are dropped");
+ assert_eq!(parameters[2].default, Some(serde_json::json!("latest")));
+ assert!(schema_parameters(serde_json::json!({ "type": "object" }).as_object().unwrap()).is_empty());
+ }
+
+ #[test]
+ fn catalog_serializes_for_settings_ui() {
+ let catalog = serde_json::to_value(tool_catalog()).unwrap();
+ let first = &catalog["toolsets"][0];
+ assert_eq!(first["id"], "core.discovery");
+ assert_eq!(first["resourceKinds"], serde_json::json!(["database"]));
+ assert_eq!(first["scopeKind"], "database");
+ assert_eq!(first["scopeKinds"], serde_json::json!(["database"]));
+ assert_eq!(first["tools"][0]["name"], "dbx_list_connections");
+ assert_eq!(first["tools"][0]["coverageKind"], "none");
+ let query = catalog["toolsets"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .flat_map(|toolset| toolset["tools"].as_array().unwrap())
+ .find(|tool| tool["name"] == "dbx_execute_query")
+ .unwrap();
+ assert_eq!(query["accessMode"], "classified");
+ assert!(query["databaseTypes"].as_array().unwrap().iter().any(|value| value == "mysql"));
+ assert_eq!(descriptor("dbx_salesforce_prepare_write").unwrap().access, McpAccessLevel::Write);
+ }
+
+ #[test]
+ fn product_toolsets_declare_their_resource_scope_kinds() {
+ let catalog = serde_json::to_value(tool_catalog()).unwrap();
+ let scope_kinds = |id: &str| {
+ catalog["toolsets"].as_array().unwrap().iter().find(|toolset| toolset["id"] == id).unwrap()["scopeKinds"]
+ .clone()
+ };
+ assert_eq!(scope_kinds("redis"), serde_json::json!(["dbIndex"]));
+ assert_eq!(scope_kinds("mq"), serde_json::json!(["topic", "queue"]));
+ assert_eq!(scope_kinds("nacos.config"), serde_json::json!(["namespace"]));
+ assert_eq!(scope_kinds("consul.kv"), serde_json::json!([]));
+ assert_eq!(scope_kinds("plugin.router"), serde_json::json!([]));
+ }
+
+ #[test]
+ fn router_descriptions_include_bounded_coverage_suffix() {
+ let description =
+ append_coverage_description("Execute a query.", descriptor("dbx_execute_query").map(|tool| tool.coverage));
+ assert!(description.starts_with("Execute a query. "));
+ assert!(description.contains("Supported on"));
+ assert!(description.len() <= 200);
+ }
+}
diff --git a/crates/dbx-core/src/ai/mod.rs b/crates/dbx-core/src/ai/mod.rs
index 16e75fd2ae..41df460166 100644
--- a/crates/dbx-core/src/ai/mod.rs
+++ b/crates/dbx-core/src/ai/mod.rs
@@ -4,7 +4,10 @@ pub mod agent_explain;
pub mod agent_kv;
pub mod agent_loop;
pub mod agent_tools;
+pub mod mcp_access;
+pub mod mcp_catalog;
pub mod mcp_policy;
+pub mod plugin_mcp;
pub mod plugin_tools;
pub mod prompt_template;
pub mod skill_tools;
diff --git a/crates/dbx-core/src/ai/plugin_mcp.rs b/crates/dbx-core/src/ai/plugin_mcp.rs
new file mode 100644
index 0000000000..7cac777a08
--- /dev/null
+++ b/crates/dbx-core/src/ai/plugin_mcp.rs
@@ -0,0 +1,710 @@
+//! Per-plugin governance of plugin tools on the external `dbx` MCP server.
+//!
+//! Three layers decide whether one plugin tool is exposed:
+//!
+//! 1. **Author contract.** The manifest `mcp` contribution must declare
+//! `external_tools: true`, and every exposed tool must be declared in its
+//! `tools` map with an `access` level. Undeclared tools never reach the
+//! external server: MCP annotations are client hints, not a contract.
+//! 2. **User grant** ([`PluginMcpGrant`]). Nothing is exposed until the user
+//! authorizes the plugin: the switch, the access ceiling, the tools the
+//! user accepted (with the level each had), and per-tool opt-outs.
+//! 3. **Tool level.** A tool above the ceiling stays hidden; a tool that
+//! needs more than read access and was not accepted at its current level
+//! (new or escalated after a plugin update) waits for confirmation.
+//!
+//! The global MCP policy (tool allowlist, execution mode, connection scope)
+//! still applies on top of everything decided here.
+
+use std::collections::{HashMap, HashSet};
+
+use serde::Serialize;
+
+use crate::ai::plugin_tools::RawPluginTool;
+use crate::plugins::{PluginManifest, PluginMcpAccess, PluginMcpContribution};
+use crate::storage::{PluginMcpAccessLevel, PluginMcpGrant};
+
+/// Toolset id used for tools a plugin does not assign to a declared toolset.
+pub const DEFAULT_PLUGIN_TOOLSET: &str = "default";
+
+/// Why a tool is or is not exposed on the external server.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum PluginToolExposure {
+ Exposed,
+ /// The author did not declare this tool's access level in the manifest.
+ Undeclared,
+ /// The plugin switch is off (or the author did not opt in).
+ PluginDisabled,
+ /// The user switched this tool off.
+ ToolDisabled,
+ /// The tool needs more than the granted ceiling.
+ AboveCeiling,
+ /// New or escalated since the user's last review; waits for confirmation.
+ PendingApproval,
+}
+
+impl PluginToolExposure {
+ pub fn is_exposed(self) -> bool {
+ self == Self::Exposed
+ }
+}
+
+impl From<PluginMcpAccess> for PluginMcpAccessLevel {
+ fn from(access: PluginMcpAccess) -> Self {
+ match access {
+ PluginMcpAccess::Read => Self::Read,
+ PluginMcpAccess::Write => Self::Write,
+ PluginMcpAccess::Full => Self::Full,
+ }
+ }
+}
+
+/// Declared access level of one tool; `None` when the manifest does not
+/// declare it (such a tool is never exposed externally).
+pub fn tool_access(contribution: Option<&PluginMcpContribution>, tool: &str) -> Option<PluginMcpAccessLevel> {
+ contribution.and_then(|mcp| mcp.declared_access(tool)).map(Into::into)
+}
+
+/// Toolset of one tool: the declared toolset when it exists, else the default group.
+pub fn tool_toolset(contribution: Option<&PluginMcpContribution>, tool: &str) -> String {
+ contribution
+ .and_then(|mcp| {
+ mcp.declared_toolset(tool).filter(|toolset| mcp.toolsets.iter().any(|declared| declared.id == *toolset))
+ })
+ .unwrap_or(DEFAULT_PLUGIN_TOOLSET)
+ .to_string()
+}
+
+/// Whether the author opted the plugin into the external server.
+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(),
+ })
+}
+
+/// Decides one tool's exposure under an effective grant.
+pub fn tool_exposure(manifest: &PluginManifest, grant: &PluginMcpGrant, tool: &str) -> PluginToolExposure {
+ let Some(access) = tool_access(manifest.mcp_contribution(), tool) else {
+ return PluginToolExposure::Undeclared;
+ };
+ if !author_allows_external(manifest) || !grant.external {
+ return PluginToolExposure::PluginDisabled;
+ }
+ if grant.disabled_tools.iter().any(|name| name == tool) {
+ return PluginToolExposure::ToolDisabled;
+ }
+ if access > grant.ceiling {
+ return PluginToolExposure::AboveCeiling;
+ }
+ if access > PluginMcpAccessLevel::Read && grant.approved_tools.get(tool).is_none_or(|approved| access > *approved) {
+ return PluginToolExposure::PendingApproval;
+ }
+ PluginToolExposure::Exposed
+}
+
+/// Accepts every listed, declared tool at its current access level.
+pub fn approvals(
+ manifest: &PluginManifest,
+ tools: &[RawPluginTool],
+) -> std::collections::BTreeMap<String, PluginMcpAccessLevel> {
+ tools
+ .iter()
+ .filter_map(|tool| tool_access(manifest.mcp_contribution(), &tool.name).map(|level| (tool.name.clone(), level)))
+ .collect()
+}
+
+/// The grant suggested when the user turns a plugin on for the first time:
+/// every listed declared tool is accepted, and the ceiling defaults to the
+/// lower of the plugin's highest tool level and `write`.
+pub fn initial_grant(manifest: &PluginManifest, tools: &[RawPluginTool]) -> PluginMcpGrant {
+ let highest = tools
+ .iter()
+ .filter_map(|tool| tool_access(manifest.mcp_contribution(), &tool.name))
+ .max()
+ .unwrap_or(PluginMcpAccessLevel::Read);
+ PluginMcpGrant {
+ external: author_allows_external(manifest),
+ ceiling: highest.min(PluginMcpAccessLevel::Write),
+ approved_tools: approvals(manifest, tools),
+ disabled_tools: Vec::new(),
+ }
+}
+
+/// Keeps only the exposed tools of one plugin listing. The declared level is
+/// authoritative on the external server, so each kept tool's `read_only` flag
+/// and MCP hints are rewritten from it: the global read-only mode and client
+/// annotations then follow the manifest contract, not the sidecar's own hints.
+pub fn exposed_tools(
+ manifest: &PluginManifest,
+ saved: Option<&PluginMcpGrant>,
+ tools: Vec<RawPluginTool>,
+) -> Vec<RawPluginTool> {
+ let grant = effective_grant(saved);
+ tools
+ .into_iter()
+ .filter(|tool| tool_exposure(manifest, &grant, &tool.name).is_exposed())
+ .map(|mut tool| {
+ if let Some(level) = tool_access(manifest.mcp_contribution(), &tool.name) {
+ apply_declared_level(&mut tool, level);
+ }
+ tool
+ })
+ .collect()
+}
+
+fn apply_declared_level(tool: &mut RawPluginTool, level: PluginMcpAccessLevel) {
+ tool.read_only = level == PluginMcpAccessLevel::Read;
+ if !tool.annotations.is_object() {
+ tool.annotations = serde_json::json!({});
+ }
+ let annotations = tool.annotations.as_object_mut().expect("annotations object");
+ annotations.insert("readOnlyHint".to_string(), serde_json::Value::Bool(level == PluginMcpAccessLevel::Read));
+ annotations.insert("destructiveHint".to_string(), serde_json::Value::Bool(level == PluginMcpAccessLevel::Full));
+}
+
+// ---------------------------------------------------------------------------
+// Settings view
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginMcpToolView {
+ pub name: String,
+ pub description: String,
+ pub toolset: String,
+ /// Declared access level; `None` for an undeclared (never exposed) tool.
+ pub access: Option<PluginMcpAccessLevel>,
+ pub exposure: PluginToolExposure,
+ /// Parameters flattened from the tool's input schema for display.
+ pub parameters: Vec<crate::mcp_catalog::McpToolParameter>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginMcpToolsetView {
+ pub id: String,
+ /// Declared title; `None` for the default group (the UI names it).
+ pub title: Option<String>,
+ pub description: Option<String>,
+}
+
+/// One plugin card in the MCP capability tab.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginMcpView {
+ pub plugin_id: String,
+ pub plugin_name: String,
+ pub version: String,
+ /// The author declared `external_tools: true`.
+ pub author_allows_external: bool,
+ /// The user has authorized this plugin at least once.
+ pub has_saved_grant: bool,
+ pub grant: PluginMcpGrant,
+ pub toolsets: Vec<PluginMcpToolsetView>,
+ pub tools: Vec<PluginMcpToolView>,
+ /// `mcp/tools` failed; the tool list is empty and this explains why.
+ pub discovery_error: Option<String>,
+}
+
+impl PluginMcpView {
+ pub fn pending_tool_count(&self) -> usize {
+ self.tools.iter().filter(|tool| tool.exposure == PluginToolExposure::PendingApproval).count()
+ }
+}
+
+/// Builds the settings view of one plugin from its manifest, saved grant and
+/// `mcp/tools` listing (`Err` when discovery failed).
+pub fn plugin_view(
+ manifest: &PluginManifest,
+ saved: Option<&PluginMcpGrant>,
+ listing: Result<Vec<RawPluginTool>, String>,
+) -> PluginMcpView {
+ let (tools, discovery_error) = match listing {
+ Ok(tools) => (tools, None),
+ Err(error) => (Vec::new(), Some(error)),
+ };
+ let contribution = manifest.mcp_contribution();
+ let grant = effective_grant(saved);
+ let tool_views = tools
+ .iter()
+ .map(|tool| PluginMcpToolView {
+ name: tool.name.clone(),
+ description: tool.description.clone(),
+ toolset: tool_toolset(contribution, &tool.name),
+ access: tool_access(contribution, &tool.name),
+ exposure: tool_exposure(manifest, &grant, &tool.name),
+ parameters: tool.input_schema.as_object().map(crate::mcp_catalog::schema_parameters).unwrap_or_default(),
+ })
+ .collect::<Vec<_>>();
+ let used = tool_views.iter().map(|tool| tool.toolset.as_str()).collect::<HashSet<_>>();
+ let mut toolsets = contribution
+ .map(|mcp| {
+ mcp.toolsets
+ .iter()
+ .filter(|toolset| used.contains(toolset.id.as_str()))
+ .map(|toolset| PluginMcpToolsetView {
+ id: toolset.id.clone(),
+ title: Some(toolset.title.clone()),
+ description: toolset.description.clone(),
+ })
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default();
+ if used.contains(DEFAULT_PLUGIN_TOOLSET) {
+ toolsets.push(PluginMcpToolsetView { id: DEFAULT_PLUGIN_TOOLSET.to_string(), title: None, description: None });
+ }
+ PluginMcpView {
+ plugin_id: manifest.id.clone(),
+ plugin_name: manifest.name.clone(),
+ version: manifest.version.clone(),
+ author_allows_external: author_allows_external(manifest),
+ has_saved_grant: saved.is_some(),
+ grant,
+ toolsets,
+ tools: tool_views,
+ discovery_error,
+ }
+}
+
+/// Plugins carrying the "provides MCP tools" mark (backend + `mcp`
+/// contribution), compatible with this host. Only these get a card in the
+/// MCP capability tab; the author's `external_tools` decides whether the
+/// card's switch can be turned on.
+pub fn mcp_capable_plugins(plugins: &[crate::plugins::InstalledPlugin]) -> Vec<&crate::plugins::InstalledPlugin> {
+ let mut capable = plugins
+ .iter()
+ .filter(|plugin| plugin.compatibility.compatible && plugin.manifest.provides_mcp_tools())
+ .collect::<Vec<_>>();
+ capable.sort_by(|left, right| {
+ left.manifest.name.cmp(&right.manifest.name).then(left.manifest.id.cmp(&right.manifest.id))
+ });
+ capable
+}
+
+/// Probe budget for one plugin's `mcp/tools` while building the settings
+/// view; matches the external discovery budget.
+const SETTINGS_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8);
+
+fn lacks_tool_surface(error: &str) -> bool {
+ let lower = error.to_ascii_lowercase();
+ lower.contains("unknown method") || lower.contains("method not found") || lower.contains("-32601")
+}
+
+async fn probe_tools(state: &crate::connection::AppState, plugin_id: &str) -> Result<Vec<RawPluginTool>, String> {
+ match state
+ .plugin_host
+ .invoke::<serde_json::Value>(plugin_id, "mcp/tools", serde_json::json!({}), None, Some(SETTINGS_PROBE_TIMEOUT))
+ .await
+ {
+ Ok(listing) => Ok(crate::ai::plugin_tools::parse_tool_list(&listing)),
+ Err(error) if lacks_tool_surface(&error) => Ok(Vec::new()),
+ Err(error) => Err(error),
+ }
+}
+
+/// Settings view of every MCP-capable plugin. User initiated, so it may start
+/// sidecars; probes run concurrently and a failing plugin reports its error
+/// on its own card. Plugins without the author opt-in are listed (with the
+/// switch locked) but not probed.
+pub async fn list_plugin_views(state: &crate::connection::AppState) -> Result<Vec<PluginMcpView>, String> {
+ let plugins = state.plugins.list_installed()?;
+ let grants = state.storage.load_plugin_mcp_grants().await?;
+ let capable = mcp_capable_plugins(&plugins);
+ let views = capable.into_iter().map(|plugin| {
+ let grants = &grants;
+ async move {
+ let listing = if author_allows_external(&plugin.manifest) {
+ probe_tools(state, &plugin.manifest.id).await
+ } else {
+ Ok(Vec::new())
+ };
+ plugin_view(&plugin.manifest, grants.get(&plugin.manifest.id), listing)
+ }
+ });
+ Ok(futures::future::join_all(views).await)
+}
+
+/// One plugin's settings view (after a save or a refresh).
+pub async fn plugin_view_for(state: &crate::connection::AppState, plugin_id: &str) -> Result<PluginMcpView, String> {
+ let plugin =
+ state.plugins.find_plugin(plugin_id)?.ok_or_else(|| format!("Plugin '{plugin_id}' is not installed"))?;
+ if !plugin.manifest.provides_mcp_tools() {
+ return Err(format!("Plugin '{plugin_id}' does not provide MCP tools"));
+ }
+ let grants = state.storage.load_plugin_mcp_grants().await?;
+ let listing =
+ if author_allows_external(&plugin.manifest) { probe_tools(state, plugin_id).await } else { Ok(Vec::new()) };
+ Ok(plugin_view(&plugin.manifest, grants.get(plugin_id), listing))
+}
+
+/// Saves the user's grant for one plugin and returns the refreshed view.
+/// Enabling requires the author opt-in; `approve_current` additionally
+/// accepts every tool the plugin lists right now (first enable, or the
+/// "confirm new tools" action), so the pending set is computed against the
+/// live listing rather than a stale client copy.
+pub async fn save_plugin_grant(
+ state: &crate::connection::AppState,
+ plugin_id: &str,
+ mut grant: PluginMcpGrant,
+ approve_current: bool,
+) -> Result<PluginMcpView, String> {
+ let plugin =
+ state.plugins.find_plugin(plugin_id)?.ok_or_else(|| format!("Plugin '{plugin_id}' is not installed"))?;
+ if grant.external && !author_allows_external(&plugin.manifest) {
+ return Err(format!("Plugin '{plugin_id}' does not allow external MCP access"));
+ }
+ if approve_current {
+ let tools = probe_tools(state, plugin_id).await?;
+ grant.approved_tools.extend(approvals(&plugin.manifest, &tools));
+ }
+ state.storage.save_plugin_mcp_grant(plugin_id, grant).await?;
+ plugin_view_for(state, plugin_id).await
+}
+
+/// Lookup helper: saved grants by plugin id.
+pub fn saved_grant<'a>(grants: &'a HashMap<String, PluginMcpGrant>, plugin_id: &str) -> Option<&'a PluginMcpGrant> {
+ grants.get(plugin_id)
+}
+
+/// Resolve a scope kind from the actual provider, not a global list: plugins
+/// may declare custom kinds but cannot write rules for another connection.
+fn validate_scope_kind(
+ db_type: crate::models::connection::DatabaseType,
+ plugin_id: Option<&str>,
+ manifest: Option<&PluginManifest>,
+ kind: &str,
+) -> Result<(), String> {
+ let expected = if let Some(plugin_id) = plugin_id {
+ manifest
+ .filter(|manifest| manifest.id == plugin_id)
+ .and_then(|manifest| manifest.mcp_contribution())
+ .and_then(|mcp| mcp.scope.as_ref())
+ .map(|scope| scope.kind.as_str())
+ } else if db_type == crate::models::connection::DatabaseType::Nacos {
+ Some("namespace")
+ } else {
+ None
+ };
+ if kind == "database" || expected != Some(kind) {
+ return Err("MCP_SCOPE_INVALID: This scope kind is not supported by the connection's provider".to_string());
+ }
+ Ok(())
+}
+
+pub async fn set_scope_rule(
+ state: &crate::connection::AppState,
+ connection_id: &str,
+ kind: &str,
+ value: Option<&str>,
+ rule: Option<crate::mcp_access::McpAccessRule>,
+ sub_scope: Option<crate::mcp_access::McpSubScopeMode>,
+) -> Result<crate::mcp_access::McpAccessPolicy, String> {
+ let connection = state
+ .storage
+ .load_connections()
+ .await?
+ .into_iter()
+ .find(|connection| connection.id == connection_id.trim())
+ .ok_or_else(|| "CONNECTION_NOT_FOUND: connection is not available".to_string())?;
+ let manifest = match connection.plugin_id.as_deref() {
+ Some(id) => state
+ .plugins
+ .list_installed()?
+ .into_iter()
+ .find(|plugin| plugin.manifest.id == id)
+ .map(|plugin| plugin.manifest),
+ None => None,
+ };
+ validate_scope_kind(connection.db_type, connection.plugin_id.as_deref(), manifest.as_ref(), kind.trim())?;
+ if rule.as_ref().is_some_and(|rule| {
+ rule.sub_scope.is_some() || rule.sub_scope_kind.is_some() || !rule.toolset_ceilings.is_empty()
+ }) {
+ return Err("MCP_SCOPE_INVALID: Child scope rules cannot change connection settings".to_string());
+ }
+ if rule.is_some() && value.is_none_or(|value| value.trim().is_empty()) {
+ return Err("MCP_SCOPE_INVALID: A scope value is required for a rule".to_string());
+ }
+ state.storage.set_mcp_plugin_scope_rule(&connection.id, kind.trim(), value, rule, sub_scope).await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ai::plugin_tools::parse_tool_list;
+ use serde_json::json;
+
+ fn manifest(mcp: serde_json::Value) -> PluginManifest {
+ let mut contributions = Vec::new();
+ if !mcp.is_null() {
+ let mut contribution = json!({ "type": "mcp", "id": "io.dbx.example.mcp" });
+ contribution.as_object_mut().unwrap().extend(mcp.as_object().cloned().unwrap_or_default());
+ contributions.push(contribution);
+ }
+ serde_json::from_value(json!({
+ "manifest_version": 1,
+ "id": "io.dbx.example",
+ "name": "Example",
+ "version": "1.2.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": { "backend": { "executable": "bin/example" } },
+ "contributions": contributions
+ }))
+ .unwrap()
+ }
+
+ #[test]
+ fn scope_kinds_must_match_the_connection_provider_including_custom_plugins() {
+ use crate::models::connection::DatabaseType;
+ let custom = manifest(json!({"scope": {"kind": "workspace", "title": "Workspace", "argument": "workspace"}}));
+ assert!(validate_scope_kind(DatabaseType::Mysql, None, None, "topic").is_err());
+ assert!(validate_scope_kind(DatabaseType::Nacos, None, None, "namespace").is_ok());
+ assert!(validate_scope_kind(DatabaseType::Nacos, None, None, "topic").is_err());
+ assert!(validate_scope_kind(DatabaseType::Mysql, Some("io.dbx.example"), Some(&custom), "workspace").is_ok());
+ assert!(validate_scope_kind(DatabaseType::Mysql, Some("other"), Some(&custom), "workspace").is_err());
+ assert!(validate_scope_kind(DatabaseType::Mysql, Some("io.dbx.example"), None, "workspace").is_err());
+ assert!(validate_scope_kind(DatabaseType::Mysql, Some("io.dbx.example"), Some(&custom), "database").is_err());
+ }
+
+ #[tokio::test]
+ async fn scope_service_rejects_invalid_provider_and_child_fields_without_mutation() {
+ use crate::mcp_access::{McpAccessRule, McpSubScopeMode};
+ use crate::models::connection::{ConnectionConfig, DatabaseType};
+ let dir = tempfile::tempdir().unwrap();
+ let storage = crate::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();
+ let state = crate::connection::AppState::new_with_plugin_and_agent_dir_and_app_version(
+ storage,
+ dir.path().join("plugins"),
+ dir.path().join("agents"),
+ "test",
+ );
+ let connections = [DatabaseType::Mysql, DatabaseType::Nacos]
+ .into_iter()
+ .enumerate()
+ .map(|(i, db_type)| {
+ serde_json::from_value::<ConnectionConfig>(json!({
+ "id": i.to_string(), "name": "Test", "db_type": db_type,
+ "host": "localhost", "port": 3306, "username": "", "password": "", "database": ""
+ }))
+ .unwrap()
+ })
+ .collect::<Vec<_>>();
+ state.storage.save_connections(&connections).await.unwrap();
+ let before = state.storage.load_mcp_access_policy().await.unwrap();
+ for (id, kind) in [("missing", "namespace"), ("0", "topic"), ("1", "topic")] {
+ assert!(set_scope_rule(&state, id, kind, None, None, Some(McpSubScopeMode::None)).await.is_err());
+ }
+ assert!(set_scope_rule(
+ &state,
+ "1",
+ "namespace",
+ Some("team"),
+ Some(McpAccessRule { sub_scope: Some(McpSubScopeMode::All), ..Default::default() }),
+ None
+ )
+ .await
+ .is_err());
+ assert!(set_scope_rule(&state, "1", "namespace", None, Some(McpAccessRule::default()), None).await.is_err());
+ assert_eq!(state.storage.load_mcp_access_policy().await.unwrap(), before);
+ let saved = set_scope_rule(
+ &state,
+ "1",
+ "namespace",
+ Some("team"),
+ Some(McpAccessRule { visible: Some(true), ..Default::default() }),
+ Some(McpSubScopeMode::Selected),
+ )
+ .await
+ .unwrap();
+ assert!(saved.sub_scope_visible("1", "namespace", "team"));
+ assert!(!saved.sub_scope_visible("1", "namespace", "other"));
+ }
+
+ /// Author opt-in with all three tools declared.
+ fn declared() -> PluginManifest {
+ manifest(json!({
+ "external_tools": true,
+ "tools": {
+ "list_dir": { "access": "read" },
+ "upload": { "access": "write" },
+ "exec": { "access": "full" }
+ }
+ }))
+ }
+
+ fn tools() -> Vec<RawPluginTool> {
+ parse_tool_list(&json!({
+ "tools": [
+ { "name": "list_dir", "annotations": { "readOnlyHint": true },
+ "inputSchema": { "type": "object", "properties": { "path": { "type": "string" } }, "required": ["path"] } },
+ { "name": "upload" },
+ { "name": "exec", "annotations": { "destructiveHint": true } }
+ ]
+ }))
+ }
+
+ fn full_grant(manifest: &PluginManifest) -> PluginMcpGrant {
+ PluginMcpGrant { ceiling: PluginMcpAccessLevel::Full, ..initial_grant(manifest, &tools()) }
+ }
+
+ fn exposed(manifest: &PluginManifest, grant: Option<&PluginMcpGrant>) -> Vec<String> {
+ exposed_tools(manifest, grant, tools()).into_iter().map(|tool| tool.name).collect()
+ }
+
+ #[test]
+ fn nothing_is_exposed_before_the_user_authorizes() {
+ assert!(exposed(&declared(), None).is_empty());
+ let view = plugin_view(&declared(), None, Ok(tools()));
+ assert!(!view.has_saved_grant && !view.grant.external);
+ assert!(view.tools.iter().all(|tool| tool.exposure == PluginToolExposure::PluginDisabled));
+ }
+
+ #[test]
+ fn undeclared_tools_are_never_exposed_and_annotations_do_not_count() {
+ // A legacy plugin remains hidden even if an old grant approved its tools.
+ for contribution in
+ [json!({ "external_tools": true }), json!({ "external_tools": true, "tools": { "list_dir": {} } })]
+ {
+ let legacy = manifest(contribution);
+ let grant = full_grant(&declared());
+ assert!(exposed(&legacy, Some(&grant)).is_empty());
+ let view = plugin_view(&legacy, Some(&grant), Ok(tools()));
+ assert!(view.tools.iter().all(|tool| tool.exposure == PluginToolExposure::Undeclared));
+ }
+ // Only list_dir is declared; annotations on the others are ignored.
+ let partial = manifest(json!({ "external_tools": true, "tools": { "list_dir": { "access": "read" } } }));
+ let grant = full_grant(&partial);
+ assert_eq!(grant.approved_tools.keys().collect::<Vec<_>>(), ["list_dir"], "undeclared tools are not approved");
+ assert_eq!(exposed(&partial, Some(&grant)), ["list_dir"]);
+ let view = plugin_view(&partial, Some(&grant), Ok(tools()));
+ assert_eq!(view.tools[1].access, None);
+ assert_eq!(view.tools[1].exposure, PluginToolExposure::Undeclared);
+ assert_eq!(tool_access(partial.mcp_contribution(), "exec"), None);
+ }
+
+ #[test]
+ fn author_opt_in_is_a_hard_ceiling() {
+ let closed = manifest(json!({ "tools": { "list_dir": { "access": "read" } } }));
+ let mut grant = initial_grant(&closed, &tools());
+ grant.external = true;
+ assert!(exposed(&closed, Some(&grant)).is_empty(), "a saved grant cannot override the author");
+ assert!(exposed(&manifest(json!(null)), Some(&grant)).is_empty(), "no mcp contribution at all");
+ }
+
+ #[test]
+ fn initial_grant_defaults_to_at_most_write_and_accepts_declared_tools() {
+ let grant = initial_grant(&declared(), &tools());
+ assert_eq!(grant.ceiling, PluginMcpAccessLevel::Write);
+ assert!(grant.external);
+ assert_eq!(
+ grant.approved_tools.clone().into_iter().collect::<Vec<_>>(),
+ [
+ ("exec".to_string(), PluginMcpAccessLevel::Full),
+ ("list_dir".to_string(), PluginMcpAccessLevel::Read),
+ ("upload".to_string(), PluginMcpAccessLevel::Write),
+ ]
+ );
+ assert_eq!(exposed(&declared(), Some(&grant)), ["list_dir", "upload"], "exec is above the write ceiling");
+
+ let read_only = manifest(json!({ "external_tools": true, "tools": { "list_dir": { "access": "read" } } }));
+ assert_eq!(initial_grant(&read_only, &tools()).ceiling, PluginMcpAccessLevel::Read);
+ }
+
+ #[test]
+ fn new_write_tools_wait_for_approval_but_new_read_tools_follow_the_switch() {
+ let grant = PluginMcpGrant {
+ external: true,
+ ceiling: PluginMcpAccessLevel::Full,
+ approved_tools: Default::default(),
+ disabled_tools: vec![],
+ };
+ let exposure = ["list_dir", "upload", "exec"].map(|tool| tool_exposure(&declared(), &grant, tool));
+ assert_eq!(
+ exposure,
+ [PluginToolExposure::Exposed, PluginToolExposure::PendingApproval, PluginToolExposure::PendingApproval]
+ );
+ }
+
+ #[test]
+ fn escalated_tools_wait_for_approval_again() {
+ // upload was accepted while it was read-only; it now needs write.
+ let mut grant = full_grant(&declared());
+ grant.approved_tools.insert("upload".to_string(), PluginMcpAccessLevel::Read);
+ assert_eq!(tool_exposure(&declared(), &grant, "upload"), PluginToolExposure::PendingApproval);
+ assert_eq!(tool_exposure(&declared(), &grant, "exec"), PluginToolExposure::Exposed);
+ // A tool that drops to a lower level stays exposed.
+ grant.approved_tools.insert("upload".to_string(), PluginMcpAccessLevel::Full);
+ assert_eq!(tool_exposure(&declared(), &grant, "upload"), PluginToolExposure::Exposed);
+ }
+
+ #[test]
+ fn exposed_tools_carry_the_declared_level_not_the_sidecar_hints() {
+ // The sidecar marks exec destructive and list_dir read-only, but the
+ // manifest says exec is read and list_dir is write.
+ let contract = manifest(json!({
+ "external_tools": true,
+ "tools": { "list_dir": { "access": "write" }, "exec": { "access": "read" } }
+ }));
+ let grant = full_grant(&contract);
+ let kept = exposed_tools(&contract, Some(&grant), tools());
+ let list_dir = kept.iter().find(|tool| tool.name == "list_dir").unwrap();
+ assert!(!list_dir.read_only);
+ assert_eq!(list_dir.annotations["readOnlyHint"], json!(false));
+ let exec = kept.iter().find(|tool| tool.name == "exec").unwrap();
+ assert!(exec.read_only);
+ assert_eq!(exec.annotations["destructiveHint"], json!(false));
+ }
+
+ #[test]
+ fn plugin_switch_and_tool_opt_outs_hide_tools() {
+ let mut grant = full_grant(&declared());
+ grant.disabled_tools = vec!["upload".to_string()];
+ assert_eq!(exposed(&declared(), Some(&grant)), ["list_dir", "exec"]);
+ grant.external = false;
+ assert!(exposed(&declared(), Some(&grant)).is_empty());
+ }
+
+ #[test]
+ fn view_groups_tools_and_reports_pending_and_errors() {
+ let grouped = manifest(json!({
+ "external_tools": true,
+ "toolsets": [{ "id": "files", "title": "Files" }, { "id": "unused", "title": "Unused" }],
+ "tools": {
+ "list_dir": { "toolset": "files", "access": "read" },
+ "upload": { "toolset": "files", "access": "write" },
+ "exec": { "access": "full" }
+ }
+ }));
+ let grant = PluginMcpGrant {
+ external: true,
+ ceiling: PluginMcpAccessLevel::Full,
+ approved_tools: [
+ ("list_dir".to_string(), PluginMcpAccessLevel::Read),
+ ("upload".to_string(), PluginMcpAccessLevel::Write),
+ ]
+ .into(),
+ disabled_tools: vec![],
+ };
+ let view = plugin_view(&grouped, Some(&grant), Ok(tools()));
+ assert!(view.has_saved_grant && view.author_allows_external);
+ assert_eq!(view.toolsets.iter().map(|toolset| toolset.id.as_str()).collect::<Vec<_>>(), ["files", "default"]);
+ assert_eq!(view.tools[0].toolset, "files");
+ assert_eq!(view.tools[0].parameters[0].name, "path");
+ assert_eq!(view.tools[2].toolset, DEFAULT_PLUGIN_TOOLSET);
+ assert_eq!(view.pending_tool_count(), 1, "exec is new and above read");
+
+ let failed = plugin_view(&grouped, None, Err("sidecar crashed".to_string()));
+ assert!(failed.tools.is_empty());
+ assert_eq!(failed.discovery_error.as_deref(), Some("sidecar crashed"));
+ assert!(!failed.has_saved_grant);
+ }
+}
diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rs
index 3aa5af14a2..1dac3c32a4 100644
--- a/crates/dbx-core/src/lib.rs
+++ b/crates/dbx-core/src/lib.rs
@@ -55,7 +55,10 @@ pub use admin::mq;
#[cfg(feature = "mq-admin")]
pub use admin::mqtt;
pub use admin::nacos;
+pub use ai::mcp_access;
+pub use ai::mcp_catalog;
pub use ai::mcp_policy;
+pub use ai::plugin_mcp;
pub use ai::prompt_template;
pub use connection::driver_runtime;
pub use connection::jdbc;
diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs
index 22e012d079..b707e182c8 100644
--- a/crates/dbx-core/src/persistence/storage.rs
+++ b/crates/dbx-core/src/persistence/storage.rs
@@ -68,6 +68,29 @@ const APP_STATE_SAVED_SQL_EDITOR_POSITIONS_KEY: &str = "saved_sql_editor_positio
const APP_STATE_TRANSFER_TASK_LIBRARY_KEY: &str = "transfer_task_library";
const APP_APPEARANCE_SETTINGS_KEY: &str = "app_appearance";
const MCP_GLOBAL_POLICY_KEY: &str = "mcp_global_policy";
+/// Policy v2 (`dbx_core::mcp_access::McpAccessPolicy`). Written next to the
+/// v1 key on every save; v1 keeps a never-wider projection for hosts that
+/// only read v1 (an older standalone `dbx-mcp`).
+const MCP_ACCESS_POLICY_KEY: &str = "mcp_access_policy";
+/// Decode the authoritative policy without falling back after corruption.
+fn saved_mcp_access_policy(
+ settings: &serde_json::Map<String, serde_json::Value>,
+) -> Result<Option<crate::mcp_access::McpAccessPolicy>, String> {
+ let Some(value) = settings.get(MCP_ACCESS_POLICY_KEY) else { return Ok(None) };
+ let mut access: crate::mcp_access::McpAccessPolicy =
+ serde_json::from_value(value.clone()).map_err(|e| format!("invalid MCP access policy: {e}"))?;
+ if access.version != crate::mcp_access::MCP_ACCESS_POLICY_VERSION {
+ return Err(format!("invalid MCP access policy version: {}", access.version));
+ }
+ if let Some(legacy) = settings
+ .get(MCP_GLOBAL_POLICY_KEY)
+ .and_then(|value| serde_json::from_value::<McpGlobalPolicy>(value.clone()).ok())
+ {
+ access.restore_legacy_salesforce_opt_ins(&legacy.normalized());
+ }
+ Ok(Some(access))
+}
+
const MCP_HTTP_SERVER_SETTINGS_KEY: &str = "mcp_http_server_settings";
const WEB_MCP_SETTINGS_KEY: &str = "web_mcp_settings";
const MAX_RETRIES_KEY: &str = "max_retries";
@@ -82,6 +105,10 @@ const AI_PLUGIN_TOOL_PLUGINS_KEY: &str = "ai_plugin_tool_plugins";
/// excluded even if they reappear on the opt-in list, so a revocation
/// survives restarts and plugin updates.
const AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY: &str = "ai_plugin_tool_disabled_plugins";
+/// `{ pluginId: PluginMcpGrant }` — the user's decisions about a plugin's
+/// tools on the external `dbx` MCP server. Absent entries fall back to the
+/// manifest declaration (see `dbx_core::ai::plugin_mcp`).
+const PLUGIN_MCP_GRANTS_KEY: &str = "plugin_mcp_grants";
/// `{ pluginId: [connectionId, ...] }` — connections a plugin may read through
/// the `host.data:read` Host API. Written only after an explicit user consent.
const PLUGIN_DATA_GRANTS_KEY: &str = "plugin_data_grants";
@@ -569,6 +596,56 @@ pub struct AppAppearanceSettingsPatch {
pub corner_style: Option<String>,
}
+/// Access ceiling the user granted a plugin's tools on the external `dbx`
+/// MCP server. Ordered: `Read < Write < Full`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum PluginMcpAccessLevel {
+ Read,
+ Write,
+ Full,
+}
+
+/// The user's external MCP decision for one plugin. Built-in AI access keeps
+/// its own Plugin Center switch.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginMcpGrant {
+ /// Whether the plugin's tools are exposed on the external MCP server.
+ /// The manifest's `external_tools` remains an upper bound.
+ pub external: bool,
+ /// Highest access level the plugin's tools may reach.
+ pub ceiling: PluginMcpAccessLevel,
+ /// Tools the user has seen and accepted, with the access level each had
+ /// at that moment. A tool that needs more than read access waits for
+ /// confirmation when it is missing here (new after an update) or now
+ /// needs more than the level it was accepted at (escalated).
+ #[serde(default)]
+ pub approved_tools: std::collections::BTreeMap<String, PluginMcpAccessLevel>,
+ /// Tools the user switched off individually.
+ #[serde(default)]
+ pub disabled_tools: Vec<String>,
+}
+
+impl PluginMcpGrant {
+ pub fn normalized(mut self) -> Self {
+ self.approved_tools = std::mem::take(&mut self.approved_tools)
+ .into_iter()
+ .map(|(tool, level)| (tool.trim().to_string(), level))
+ .filter(|(tool, _)| !tool.is_empty())
+ .take(256)
+ .collect();
+ self.disabled_tools.retain(|tool| !tool.trim().is_empty());
+ for tool in self.disabled_tools.iter_mut() {
+ *tool = tool.trim().to_string();
+ }
+ self.disabled_tools.sort();
+ self.disabled_tools.dedup();
+ self.disabled_tools.truncate(256);
+ self
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct McpGlobalPolicy {
@@ -579,6 +656,9 @@ pub struct McpGlobalPolicy {
/// This never relaxes read-only, connection, database-scope or production protections.
#[serde(default)]
pub prompt_high_risk_sql: bool,
+ /// Explicit call safety policy. Missing preserves the legacy boolean's meaning.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub call_confirmation: Option<crate::mcp_access::McpConfirmPolicy>,
pub allowed_connection_ids: Option<Vec<String>>,
/// Stable sidebar group ids whose current descendant connections are
/// exposed when an explicit connection scope is configured.
@@ -599,6 +679,8 @@ pub struct McpGlobalPolicy {
pub group_policies: Vec<McpGroupPolicy>,
#[serde(default)]
pub query_timeout_secs: Option<u64>,
+ #[serde(default = "crate::mcp_access::McpPluginToolsMode::legacy_default")]
+ pub plugin_tools_mode: crate::mcp_access::McpPluginToolsMode,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -756,6 +838,9 @@ pub struct McpGlobalPolicyState {
pub allow_dangerous_sql: bool,
#[serde(default)]
pub prompt_high_risk_sql: bool,
+ /// Explicit call safety policy. Missing preserves the legacy boolean's meaning.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub call_confirmation: Option<crate::mcp_access::McpConfirmPolicy>,
pub allowed_connection_ids: Option<Vec<String>>,
#[serde(default)]
pub allowed_group_ids: Vec<String>,
@@ -767,6 +852,8 @@ pub struct McpGlobalPolicyState {
pub group_policies: Vec<McpGroupPolicy>,
#[serde(default)]
pub query_timeout_secs: Option<u64>,
+ #[serde(default)]
+ pub plugin_tools_mode: crate::mcp_access::McpPluginToolsMode,
}
impl McpGlobalPolicyState {
@@ -775,17 +862,27 @@ impl McpGlobalPolicyState {
read_only: self.read_only,
allow_dangerous_sql: self.allow_dangerous_sql,
prompt_high_risk_sql: self.prompt_high_risk_sql,
+ call_confirmation: self.call_confirmation,
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,
+ plugin_tools_mode: self.plugin_tools_mode,
}
}
}
impl McpGlobalPolicy {
+ pub fn confirmation_policy(&self) -> crate::mcp_access::McpConfirmPolicy {
+ self.call_confirmation.unwrap_or(if self.prompt_high_risk_sql {
+ crate::mcp_access::McpConfirmPolicy::Full
+ } else {
+ crate::mcp_access::McpConfirmPolicy::Off
+ })
+ }
+
/// Produces the single fail-closed representation persisted by the MCP
/// policy API. This protects the policy boundary even when a caller does
/// not use the desktop settings form (for example, a Web API client).
@@ -916,13 +1013,18 @@ impl McpGlobalPolicy {
Self {
read_only: self.read_only,
allow_dangerous_sql: !self.read_only && self.allow_dangerous_sql,
- prompt_high_risk_sql: !self.read_only && self.prompt_high_risk_sql,
+ // Canonical v1 representation retains old booleans losslessly.
+ // Explicit Off clears legacy elevation; HighRisk never enables it.
+ prompt_high_risk_sql: self.confirmation_policy() == crate::mcp_access::McpConfirmPolicy::Full,
+ call_confirmation: (self.confirmation_policy() == crate::mcp_access::McpConfirmPolicy::HighRisk)
+ .then_some(crate::mcp_access::McpConfirmPolicy::HighRisk),
allowed_connection_ids,
allowed_group_ids,
allowed_tool_names,
connection_policies,
group_policies,
query_timeout_secs: self.query_timeout_secs,
+ plugin_tools_mode: self.plugin_tools_mode,
}
}
}
@@ -3810,6 +3912,28 @@ fn normalized_string_list(value: Option<&serde_json::Value>) -> Vec<String> {
values
}
+fn plugin_mcp_grants_from(value: Option<&serde_json::Value>) -> HashMap<String, PluginMcpGrant> {
+ let Some(serde_json::Value::Object(grants)) = value else {
+ return HashMap::new();
+ };
+ grants
+ .iter()
+ .filter_map(|(plugin_id, grant)| {
+ let plugin_id = plugin_id.trim();
+ if plugin_id.is_empty() {
+ return None;
+ }
+ match serde_json::from_value::<PluginMcpGrant>(grant.clone()) {
+ Ok(grant) => Some((plugin_id.to_string(), grant.normalized())),
+ Err(error) => {
+ warn!("[plugins] ignoring malformed MCP grant for {plugin_id}: {error}");
+ None
+ }
+ }
+ })
+ .collect()
+}
+
fn normalized_setting_id(value: &str, label: &str) -> Result<String, String> {
let trimmed = value.trim();
if trimmed.is_empty() || trimmed.chars().count() > 256 {
@@ -5256,12 +5380,14 @@ impl Storage {
let dedicated_keys = [
APP_APPEARANCE_SETTINGS_KEY,
MCP_GLOBAL_POLICY_KEY,
+ MCP_ACCESS_POLICY_KEY,
WEB_MCP_SETTINGS_KEY,
MAX_RETRIES_KEY,
SQL_FILE_UPLOAD_MAX_MB_KEY,
HISTORY_RETENTION_LIMIT_KEY,
AI_PLUGIN_TOOL_PLUGINS_KEY,
PLUGIN_DATA_GRANTS_KEY,
+ PLUGIN_MCP_GRANTS_KEY,
MCP_HISTORY_RETENTION_LIMIT_KEY,
];
for key in dedicated_keys {
@@ -5309,12 +5435,14 @@ impl Storage {
read_only: policy.read_only,
allow_dangerous_sql: policy.allow_dangerous_sql,
prompt_high_risk_sql: policy.prompt_high_risk_sql,
+ call_confirmation: policy.call_confirmation,
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,
+ plugin_tools_mode: policy.plugin_tools_mode,
});
};
let settings = serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&json)
@@ -5326,12 +5454,14 @@ impl Storage {
read_only: policy.read_only,
allow_dangerous_sql: policy.allow_dangerous_sql,
prompt_high_risk_sql: policy.prompt_high_risk_sql,
+ call_confirmation: policy.call_confirmation,
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,
+ plugin_tools_mode: policy.plugin_tools_mode,
});
};
let policy = serde_json::from_value::<McpGlobalPolicy>(value.clone())
@@ -5342,20 +5472,179 @@ impl Storage {
read_only: policy.read_only,
allow_dangerous_sql: policy.allow_dangerous_sql,
prompt_high_risk_sql: policy.prompt_high_risk_sql,
+ call_confirmation: policy.call_confirmation,
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,
+ plugin_tools_mode: policy.plugin_tools_mode,
})
})
.await;
result.map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))
}
+ /// The policy every MCP host enforces, in v1 shape. A saved v2 policy is
+ /// authoritative and projected (never wider); otherwise the saved v1
+ /// policy is used as is. Hosts read this instead of the raw v1 key so a
+ /// v2 policy written by the settings UI takes effect immediately, while
+ /// the v1 key keeps serving older standalone `dbx-mcp` binaries.
+ pub async fn load_enforced_mcp_policy(&self) -> Result<McpGlobalPolicyState, String> {
+ let settings = self.load_app_settings_json().await.map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?;
+ let Some(access) = saved_mcp_access_policy(&settings).map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?
+ else {
+ return self.load_mcp_global_policy().await;
+ };
+ let policy = access.to_v1();
+ Ok(McpGlobalPolicyState {
+ configured: settings.contains_key(MCP_GLOBAL_POLICY_KEY),
+ read_only: policy.read_only,
+ allow_dangerous_sql: policy.allow_dangerous_sql,
+ prompt_high_risk_sql: policy.prompt_high_risk_sql,
+ call_confirmation: policy.call_confirmation,
+ 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,
+ plugin_tools_mode: access.plugin_tools_mode,
+ })
+ }
+
+ /// The v2 access policy: the saved v2 value when present, else the
+ /// lossless mapping of the saved v1 policy (or the default).
+ pub async fn load_mcp_access_policy(&self) -> Result<crate::mcp_access::McpAccessPolicy, String> {
+ let settings = self.load_app_settings_json().await.map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?;
+ if let Some(access) = saved_mcp_access_policy(&settings).map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))? {
+ return Ok(access);
+ }
+ Ok(crate::mcp_access::McpAccessPolicy::from_v1(&self.load_mcp_global_policy().await?.policy()))
+ }
+
+ /// Explicit recovery only: preserve corrupt data and reset access to deny
+ /// all. Ordinary saves and runtime reads must continue to fail closed.
+ pub async fn reset_invalid_mcp_access_policy(&self) -> Result<(), String> {
+ self.with_conn(|conn| {
+ let mut settings = app_settings_map_from_conn(conn)?;
+ if saved_mcp_access_policy(&settings).is_ok() {
+ return Err("MCP policy is valid; recovery is not required".to_string());
+ }
+ let backup_key = format!("mcp_policy_recovery_backup_{}", Uuid::new_v4());
+ settings.insert(
+ backup_key,
+ serde_json::json!({
+ "v1": settings.get(MCP_GLOBAL_POLICY_KEY),
+ "v2": settings.get(MCP_ACCESS_POLICY_KEY),
+ }),
+ );
+ let access = crate::mcp_access::McpAccessPolicy {
+ default_access: crate::mcp_access::McpAccessLevel::Read,
+ visibility: crate::mcp_access::McpVisibilityMode::Selected,
+ allowed_tool_names: Some(Vec::new()),
+ ..Default::default()
+ };
+ settings.insert(
+ MCP_GLOBAL_POLICY_KEY.to_string(),
+ serde_json::to_value(access.to_v1()).map_err(|e| e.to_string())?,
+ );
+ settings
+ .insert(MCP_ACCESS_POLICY_KEY.to_string(), serde_json::to_value(access).map_err(|e| e.to_string())?);
+ write_app_settings_map(conn, &settings)
+ })
+ .await
+ .map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))
+ }
+
+ /// Saves a v2 policy together with its never-wider v1 projection in one
+ /// write, so v1-only readers can never see a wider policy than v2.
+ pub async fn save_mcp_access_policy(&self, policy: &crate::mcp_access::McpAccessPolicy) -> Result<(), String> {
+ let access = serde_json::to_value(policy).map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?;
+ let projected = serde_json::to_value(policy.to_v1()).map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?;
+ self.with_conn(move |conn| {
+ let mut settings = app_settings_map_from_conn(conn)?;
+ settings.insert(MCP_ACCESS_POLICY_KEY.to_string(), access);
+ settings.insert(MCP_GLOBAL_POLICY_KEY.to_string(), projected);
+ write_app_settings_map(conn, &settings)
+ })
+ .await
+ .map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))
+ }
+
+ /// Sets one plugin sub-scope rule (`kind` other than `database`) and the
+ /// connection's admission mode for that kind, in one write. Passing
+ /// `rule: None` removes the rule. Used by the access-control tree, which
+ /// otherwise edits the v1 draft; database rules stay on the v1 path.
+ pub async fn set_mcp_plugin_scope_rule(
+ &self,
+ connection_id: &str,
+ kind: &str,
+ value: Option<&str>,
+ rule: Option<crate::mcp_access::McpAccessRule>,
+ sub_scope: Option<crate::mcp_access::McpSubScopeMode>,
+ ) -> Result<crate::mcp_access::McpAccessPolicy, String> {
+ if kind.trim().is_empty() || kind.trim() == "database" {
+ return Err("A plugin scope kind other than `database` is required".to_string());
+ }
+ let connection_id = normalized_setting_id(connection_id, "connection id")?;
+ let kind = kind.trim().to_string();
+ let value = value.map(str::trim).filter(|value| !value.is_empty()).map(str::to_string);
+ self.with_conn(move |conn| {
+ // Read, merge and write under the same storage lock: edits on two
+ // connection rows must not overwrite one another's saved rules.
+ let mut settings = app_settings_map_from_conn(conn)?;
+ let mut access = if let Some(access) = saved_mcp_access_policy(&settings)? {
+ access
+ } else {
+ let policy = settings
+ .get(MCP_GLOBAL_POLICY_KEY)
+ .map(|value| serde_json::from_value::<McpGlobalPolicy>(value.clone()))
+ .transpose()
+ .map_err(|e| e.to_string())?
+ .unwrap_or_default();
+ crate::mcp_access::McpAccessPolicy::from_v1(&policy)
+ };
+ if let Some(value) = value {
+ let target = crate::mcp_access::McpRuleTarget::Scope {
+ connection_id: connection_id.clone(),
+ scope: kind.clone(),
+ value,
+ };
+ match rule {
+ Some(rule) => {
+ access.rules.insert(target, rule);
+ }
+ None => {
+ access.rules.remove(&target);
+ }
+ }
+ }
+ let connection =
+ access.rules.entry(crate::mcp_access::McpRuleTarget::Connection { id: connection_id }).or_default();
+ connection.sub_scope_kind = Some(kind);
+ if let Some(mode) = sub_scope {
+ connection.sub_scope = Some(mode);
+ }
+ settings
+ .insert(MCP_ACCESS_POLICY_KEY.to_string(), serde_json::to_value(&access).map_err(|e| e.to_string())?);
+ settings.insert(
+ MCP_GLOBAL_POLICY_KEY.to_string(),
+ serde_json::to_value(access.to_v1()).map_err(|e| e.to_string())?,
+ );
+ write_app_settings_map(conn, &settings)?;
+ Ok(access)
+ })
+ .await
+ .map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))
+ }
+
+ /// Saves the v1 settings draft while preserving v2-only restrictions.
+ /// The merged policy also supplies the conservative v1 compatibility view.
pub async fn save_mcp_global_policy(&self, policy: &McpGlobalPolicy) -> Result<(), String> {
- let policy = serde_json::to_value(policy.normalized()).map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?;
+ let rebuilt = crate::mcp_access::McpAccessPolicy::from_v1(policy);
+ let draft = policy.normalized();
self.with_conn(move |conn| {
let current: Option<String> = conn
.query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))
@@ -5366,7 +5655,19 @@ impl Storage {
.map_err(|e| format!("invalid app settings JSON: {e}"))?,
None => serde_json::Map::new(),
};
+ // Keep rules only v2 can express (plugin sub-scopes) across v1 saves.
+ let previous = saved_mcp_access_policy(&settings)?;
+ let access = match previous {
+ Some(previous) => rebuilt.clone().with_v2_only_rules_from(&previous),
+ None => rebuilt.clone(),
+ };
+ // Preserve the v1 representation for ordinary v1 edits. Only a
+ // merge of v2-only rules needs a lossy compatibility projection.
+ let policy = if access == rebuilt { draft } else { access.to_v1() };
+ let policy = serde_json::to_value(policy).map_err(|e| e.to_string())?;
+ let access = serde_json::to_value(access).map_err(|e| e.to_string())?;
settings.insert(MCP_GLOBAL_POLICY_KEY.to_string(), policy);
+ settings.insert(MCP_ACCESS_POLICY_KEY.to_string(), access);
let json = serde_json::to_string(&settings).map_err(|e| e.to_string())?;
conn.execute("INSERT OR REPLACE INTO app_settings (id, settings_json) VALUES (1, ?1)", [json])
.map(|_| ())
@@ -5475,6 +5776,36 @@ impl Storage {
.await
}
+ /// Every saved external MCP grant, keyed by plugin id. Malformed entries
+ /// are skipped so one broken record never hides the others.
+ pub async fn load_plugin_mcp_grants(&self) -> Result<HashMap<String, PluginMcpGrant>, String> {
+ let settings = self.load_app_settings_json().await?;
+ Ok(plugin_mcp_grants_from(settings.get(PLUGIN_MCP_GRANTS_KEY)))
+ }
+
+ /// Replaces one plugin's external MCP grant (read-modify-write inside one
+ /// connection closure) and returns the stored value.
+ pub async fn save_plugin_mcp_grant(
+ &self,
+ plugin_id: &str,
+ grant: PluginMcpGrant,
+ ) -> Result<PluginMcpGrant, String> {
+ let plugin_id = normalized_setting_id(plugin_id, "plugin id")?;
+ let grant = grant.normalized();
+ self.with_conn(move |conn| {
+ let mut settings = app_settings_map_from_conn(conn)?;
+ let mut grants = match settings.remove(PLUGIN_MCP_GRANTS_KEY) {
+ Some(serde_json::Value::Object(grants)) => grants,
+ _ => serde_json::Map::new(),
+ };
+ grants.insert(plugin_id, serde_json::to_value(&grant).map_err(|error| error.to_string())?);
+ settings.insert(PLUGIN_MCP_GRANTS_KEY.to_string(), serde_json::Value::Object(grants));
+ write_app_settings_map(conn, &settings)?;
+ Ok(grant)
+ })
+ .await
+ }
+
/// Drops everything the user granted to a plugin (AI tool access and data
/// grants). Called after uninstall so a reinstall starts without consent.
pub async fn forget_plugin_permissions(&self, plugin_id: &str) -> Result<(), String> {
@@ -5490,6 +5821,9 @@ impl Storage {
if let Some(serde_json::Value::Object(grants)) = settings.get_mut(PLUGIN_DATA_GRANTS_KEY) {
grants.remove(&plugin_id);
}
+ if let Some(serde_json::Value::Object(grants)) = settings.get_mut(PLUGIN_MCP_GRANTS_KEY) {
+ grants.remove(&plugin_id);
+ }
write_app_settings_map(conn, &settings)
})
.await
@@ -10106,10 +10440,14 @@ fn map_from_sql_err(err: serde_json::Error) -> rusqlite::Error {
#[cfg(test)]
mod tests {
+ use super::{
+ app_settings_map_from_conn, plugin_mcp_grants_from, write_app_settings_map, PluginMcpAccessLevel,
+ PluginMcpGrant,
+ };
use super::{
maybe_import_user_data_db, AppAppearanceSettingsPatch, DataDbImportResult, DesktopIconTheme, DesktopSettings,
McpGlobalPolicy, McpGlobalPolicyState, Storage, SyncImportPlan, KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION,
- MCP_GLOBAL_POLICY_KEY,
+ MCP_ACCESS_POLICY_KEY, MCP_GLOBAL_POLICY_KEY,
};
use crate::ai::{
AiActiveModelSelection, AiAssistantMode, AiChatMessage, AiChatSelectionState, AiConversation,
@@ -13344,12 +13682,14 @@ mod tests {
read_only: false,
allow_dangerous_sql: false,
prompt_high_risk_sql: false,
+ call_confirmation: None,
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,
+ plugin_tools_mode: crate::mcp_access::McpPluginToolsMode::Flat,
}
);
@@ -13372,12 +13712,14 @@ mod tests {
read_only: true,
allow_dangerous_sql: false,
prompt_high_risk_sql: false,
+ call_confirmation: None,
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),
+ plugin_tools_mode: crate::mcp_access::McpPluginToolsMode::Flat,
}
);
assert_eq!(storage.load_password_hash().await.unwrap().as_deref(), Some("preserved"));
@@ -13392,6 +13734,83 @@ mod tests {
assert!(storage.load_mcp_global_policy().await.unwrap().read_only);
}
+ #[tokio::test]
+ async fn mcp_plugin_tools_mode_preserves_new_saved_and_legacy_policies() {
+ use crate::mcp_access::{McpAccessPolicy, McpPluginToolsMode};
+ let path = temp_db_path("mcp-plugin-tools-mode");
+ let storage = crate::persistence::test_storage::open(&path).await.unwrap();
+ assert_eq!(McpAccessPolicy::default().plugin_tools_mode, McpPluginToolsMode::Flat);
+ assert_eq!(storage.load_mcp_global_policy().await.unwrap().plugin_tools_mode, McpPluginToolsMode::Flat);
+ assert_eq!(storage.load_mcp_access_policy().await.unwrap().plugin_tools_mode, McpPluginToolsMode::Flat);
+ // Unrelated saved settings do not turn a fresh MCP policy into a legacy one.
+ storage.save_password_hash("preserved").await.unwrap();
+ assert_eq!(storage.load_enforced_mcp_policy().await.unwrap().plugin_tools_mode, McpPluginToolsMode::Flat);
+
+ for mode in [McpPluginToolsMode::Auto, McpPluginToolsMode::Flat, McpPluginToolsMode::Lazy] {
+ storage
+ .save_mcp_global_policy(&McpGlobalPolicy { plugin_tools_mode: mode, ..Default::default() })
+ .await
+ .unwrap();
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ assert_eq!(access.plugin_tools_mode, mode);
+ storage.save_mcp_access_policy(&access).await.unwrap();
+ assert_eq!(storage.load_mcp_global_policy().await.unwrap().plugin_tools_mode, mode);
+ assert_eq!(storage.load_enforced_mcp_policy().await.unwrap().plugin_tools_mode, mode);
+ }
+
+ for (key, mut value) in [
+ (MCP_GLOBAL_POLICY_KEY, serde_json::to_value(McpGlobalPolicy::default()).unwrap()),
+ (MCP_ACCESS_POLICY_KEY, serde_json::to_value(McpAccessPolicy::default()).unwrap()),
+ ] {
+ value.as_object_mut().unwrap().remove("pluginToolsMode");
+ let settings = serde_json::Map::from_iter([(key.to_string(), value)]);
+ // Seed the old persisted shape directly; the generic settings
+ // writer intentionally preserves the dedicated MCP policy keys.
+ storage.with_conn(move |conn| write_app_settings_map(conn, &settings)).await.unwrap();
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ assert_eq!(access.plugin_tools_mode, McpPluginToolsMode::Auto, "legacy {key}");
+ assert_eq!(storage.load_enforced_mcp_policy().await.unwrap().plugin_tools_mode, McpPluginToolsMode::Auto);
+ storage.save_mcp_access_policy(&access).await.unwrap();
+ assert_eq!(storage.load_mcp_global_policy().await.unwrap().plugin_tools_mode, McpPluginToolsMode::Auto);
+ }
+ }
+
+ #[tokio::test]
+ async fn mcp_call_safety_preserves_legacy_storage_until_explicit_migration() {
+ use crate::mcp_access::{McpAccessPolicy, McpConfirmPolicy};
+ let root = tempfile::tempdir().unwrap();
+ let storage = crate::persistence::test_storage::open(&root.path().join("storage.db")).await.unwrap();
+ for key in [MCP_GLOBAL_POLICY_KEY, MCP_ACCESS_POLICY_KEY] {
+ let value = if key == MCP_GLOBAL_POLICY_KEY {
+ serde_json::json!({"readOnly": false, "promptHighRiskSql": true})
+ } else {
+ serde_json::json!({"version": 2, "defaultAccess": "write", "confirm": "full"})
+ };
+ let settings = serde_json::Map::from_iter([(key.to_string(), value)]);
+ storage.with_conn(move |conn| write_app_settings_map(conn, &settings)).await.unwrap();
+ assert_eq!(
+ storage.load_enforced_mcp_policy().await.unwrap().policy().confirmation_policy(),
+ McpConfirmPolicy::Full
+ );
+ let mut policy = storage.load_enforced_mcp_policy().await.unwrap().policy();
+ policy.query_timeout_secs = Some(20);
+ storage.save_mcp_global_policy(&policy).await.unwrap();
+ assert_eq!(storage.load_mcp_access_policy().await.unwrap().confirm, McpConfirmPolicy::Full);
+ policy.call_confirmation = Some(McpConfirmPolicy::HighRisk);
+ storage.save_mcp_global_policy(&policy).await.unwrap();
+ let saved = storage.load_mcp_global_policy().await.unwrap().policy();
+ assert!(!saved.prompt_high_risk_sql);
+ assert_eq!(saved.confirmation_policy(), McpConfirmPolicy::HighRisk);
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ storage.save_mcp_access_policy(&access).await.unwrap();
+ assert_eq!(storage.load_enforced_mcp_policy().await.unwrap().policy(), saved);
+ assert_eq!(McpAccessPolicy::from_v1(&saved).confirm, McpConfirmPolicy::HighRisk);
+ policy.call_confirmation = Some(McpConfirmPolicy::Off);
+ storage.save_mcp_global_policy(&policy).await.unwrap();
+ assert_eq!(storage.load_mcp_access_policy().await.unwrap().confirm, McpConfirmPolicy::Off);
+ }
+ }
+
#[test]
fn legacy_mcp_policy_does_not_enable_high_risk_prompts() {
let policy: McpGlobalPolicy =
@@ -13401,6 +13820,33 @@ mod tests {
assert!(!policy.normalized().prompt_high_risk_sql);
}
+ #[tokio::test]
+ async fn mcp_confirmation_survives_read_only_default_with_resource_overrides() {
+ let root = tempfile::tempdir().unwrap();
+ let storage = crate::persistence::test_storage::open(&root.path().join("storage.db")).await.unwrap();
+ let policy = McpGlobalPolicy {
+ read_only: true,
+ prompt_high_risk_sql: true,
+ connection_policies: vec![serde_json::from_value(serde_json::json!({
+ "connectionId": "dev", "readOnly": false,
+ "executionModeConfigured": true, "executionModePolicyVersion": 1
+ }))
+ .unwrap()],
+ ..Default::default()
+ };
+ storage.save_mcp_global_policy(&policy).await.unwrap();
+ let saved = storage.load_mcp_global_policy().await.unwrap().policy();
+ let enforced = storage.load_enforced_mcp_policy().await.unwrap().policy();
+ for value in [saved, enforced] {
+ assert!(value.read_only);
+ assert!(value.prompt_high_risk_sql);
+ assert!(!value.allow_dangerous_sql);
+ }
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ assert_eq!(access.resolve(&[], "other", None).level, crate::mcp_access::McpAccessLevel::Read);
+ assert_eq!(access.resolve(&[], "dev", None).level, crate::mcp_access::McpAccessLevel::Write);
+ }
+
#[tokio::test]
async fn mcp_global_policy_fails_closed_on_malformed_settings() {
let path = temp_db_path("mcp-global-policy-malformed");
@@ -14012,6 +14458,320 @@ mod tests {
assert!(storage.load_ai_plugin_tool_disabled_plugin_ids().await.unwrap().is_empty());
}
+ #[tokio::test]
+ async fn plugin_mcp_grants_round_trip_and_survive_settings_rewrites() {
+ let path = temp_db_path("plugin-mcp-grants");
+ let storage = crate::persistence::test_storage::open(&path).await.unwrap();
+ assert!(storage.load_plugin_mcp_grants().await.unwrap().is_empty());
+
+ let grant = PluginMcpGrant {
+ external: true,
+ ceiling: PluginMcpAccessLevel::Write,
+ approved_tools: [
+ (" list_dir ".to_string(), PluginMcpAccessLevel::Read),
+ ("".to_string(), PluginMcpAccessLevel::Full),
+ ]
+ .into(),
+ disabled_tools: vec!["b".to_string(), " a ".to_string(), "b".to_string(), " ".to_string()],
+ };
+ let saved = storage.save_plugin_mcp_grant("io.dbx.ssh", grant).await.unwrap();
+ assert_eq!(saved.approved_tools.keys().collect::<Vec<_>>(), ["list_dir"], "names are trimmed, blanks dropped");
+ assert_eq!(saved.disabled_tools, ["a", "b"]);
+ storage
+ .save_plugin_mcp_grant(
+ "io.dbx.k8s",
+ PluginMcpGrant {
+ external: false,
+ ceiling: PluginMcpAccessLevel::Read,
+ approved_tools: Default::default(),
+ disabled_tools: vec![],
+ },
+ )
+ .await
+ .unwrap();
+
+ // Whole-map settings writers keep the dedicated key.
+ storage.save_app_settings_json(&serde_json::Map::new()).await.unwrap();
+ let grants = storage.load_plugin_mcp_grants().await.unwrap();
+ assert_eq!(grants.get("io.dbx.ssh"), Some(&saved));
+ assert!(!grants["io.dbx.k8s"].external);
+
+ // Uninstall forgets only that plugin.
+ storage.forget_plugin_permissions("io.dbx.ssh").await.unwrap();
+ let grants = storage.load_plugin_mcp_grants().await.unwrap();
+ assert!(!grants.contains_key("io.dbx.ssh"));
+ assert!(grants.contains_key("io.dbx.k8s"));
+ assert!(storage.save_plugin_mcp_grant(" ", saved).await.is_err());
+ }
+
+ #[tokio::test]
+ async fn mcp_visibility_and_database_edits_do_not_grant_dml_or_keep_stale_scopes() {
+ let storage = crate::persistence::test_storage::open(&temp_db_path("mcp-review-roundtrip")).await.unwrap();
+ let mut policy =
+ McpGlobalPolicy { allowed_connection_ids: Some(vec!["sf".into(), "sql".into()]), ..Default::default() };
+ storage.save_mcp_global_policy(&policy).await.unwrap();
+ assert!(!crate::mcp_policy::connection_allows_salesforce_dml(
+ &storage.load_enforced_mcp_policy().await.unwrap().policy(),
+ "sf"
+ ));
+ policy.connection_policies.push(
+ serde_json::from_value(serde_json::json!({
+ "connectionId": "sql", "executionModeConfigured": false, "executionModePolicyVersion": 1,
+ "databaseScope": "selected", "allowedDatabases": ["one"]
+ }))
+ .unwrap(),
+ );
+ storage.save_mcp_global_policy(&policy).await.unwrap();
+ assert!(!storage.load_mcp_access_policy().await.unwrap().sub_scope_visible("sql", "database", "two"));
+ policy.connection_policies.clear();
+ storage.save_mcp_global_policy(&policy).await.unwrap();
+ assert!(storage.load_mcp_access_policy().await.unwrap().sub_scope_visible("sql", "database", "two"));
+ assert!(!crate::mcp_policy::connection_allows_salesforce_dml(
+ &storage.load_enforced_mcp_policy().await.unwrap().policy(),
+ "sf"
+ ));
+ }
+
+ #[tokio::test]
+ async fn mcp_legacy_salesforce_opt_in_migrates_from_saved_v1_evidence() {
+ use crate::mcp_access::{McpAccessPolicy, McpRuleTarget, SALESFORCE_WRITE_TOOLSET};
+ let storage = crate::persistence::test_storage::open(&temp_db_path("mcp-legacy-dml")).await.unwrap();
+ for allowed in [false, true] {
+ let legacy: McpGlobalPolicy = serde_json::from_value(serde_json::json!({
+ "readOnly": false,
+ "connectionPolicies": [{"connectionId": "sf", "allowSalesforceDml": allowed,
+ "readOnly": false, "executionModeConfigured": true, "executionModePolicyVersion": 1}]
+ }))
+ .unwrap();
+ let mut old_v2 = McpAccessPolicy::from_v1(&legacy);
+ old_v2
+ .rules
+ .get_mut(&McpRuleTarget::Connection { id: "sf".into() })
+ .unwrap()
+ .toolset_ceilings
+ .remove(SALESFORCE_WRITE_TOOLSET);
+ let v1_json = serde_json::to_value(&legacy).unwrap();
+ let v2_json = serde_json::to_value(&old_v2).unwrap();
+ storage
+ .with_conn(move |conn| {
+ let mut settings = app_settings_map_from_conn(conn)?;
+ settings.insert(MCP_GLOBAL_POLICY_KEY.into(), v1_json);
+ settings.insert(MCP_ACCESS_POLICY_KEY.into(), v2_json);
+ write_app_settings_map(conn, &settings)
+ })
+ .await
+ .unwrap();
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ assert_eq!(crate::mcp_policy::connection_allows_salesforce_dml(&access.to_v1(), "sf"), allowed);
+ storage.save_mcp_access_policy(&access).await.unwrap();
+ assert_eq!(
+ crate::mcp_policy::connection_allows_salesforce_dml(
+ &storage.load_enforced_mcp_policy().await.unwrap().policy(),
+ "sf"
+ ),
+ allowed
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn mcp_explicit_recovery_backs_up_corruption_and_denies_all_tools() {
+ let storage = crate::persistence::test_storage::open(&temp_db_path("mcp-recovery")).await.unwrap();
+ storage.save_mcp_global_policy(&McpGlobalPolicy::default()).await.unwrap();
+ assert!(storage.reset_invalid_mcp_access_policy().await.is_err());
+ storage
+ .with_conn(|conn| {
+ let mut settings = app_settings_map_from_conn(conn)?;
+ settings.insert(MCP_ACCESS_POLICY_KEY.into(), serde_json::json!({"broken": true}));
+ settings.insert("unrelated".into(), serde_json::json!(42));
+ write_app_settings_map(conn, &settings)
+ })
+ .await
+ .unwrap();
+ assert!(storage.load_enforced_mcp_policy().await.is_err());
+ storage.reset_invalid_mcp_access_policy().await.unwrap();
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ assert!(!access.connection_visible(&[], "any"));
+ assert_eq!(access.allowed_tool_names, Some(vec![]));
+ let settings = storage.load_app_settings_json().await.unwrap();
+ assert_eq!(settings["unrelated"], 42);
+ let backup = settings.iter().find(|(key, _)| key.starts_with("mcp_policy_recovery_backup_")).unwrap().1;
+ assert_eq!(backup["v2"], serde_json::json!({"broken": true}));
+ assert!(backup["v1"].is_object());
+ let before = settings;
+ assert!(storage.reset_invalid_mcp_access_policy().await.is_err());
+ assert_eq!(storage.load_app_settings_json().await.unwrap(), before);
+ }
+
+ #[tokio::test]
+ async fn mcp_v1_save_rejects_invalid_v2_without_overwriting_either_policy() {
+ let path = temp_db_path("mcp-invalid-v2-draft");
+ let storage = crate::persistence::test_storage::open(&path).await.unwrap();
+ storage.save_mcp_global_policy(&McpGlobalPolicy::default()).await.unwrap();
+ for invalid in [
+ serde_json::Value::Null,
+ serde_json::json!({ "version": 2, "defaultAccess": "invalid" }),
+ serde_json::json!({ "version": 2, "rules": [{ "target": { "kind": "unknown" } }] }),
+ ] {
+ storage
+ .with_conn(move |conn| {
+ let mut settings = app_settings_map_from_conn(conn)?;
+ settings.insert(super::MCP_ACCESS_POLICY_KEY.to_string(), invalid);
+ write_app_settings_map(conn, &settings)
+ })
+ .await
+ .unwrap();
+ let before = storage.load_app_settings_json().await.unwrap();
+ let draft = McpGlobalPolicy { read_only: true, query_timeout_secs: Some(99), ..Default::default() };
+ let error = storage.save_mcp_global_policy(&draft).await.unwrap_err();
+ assert!(error.starts_with("MCP_POLICY_UNAVAILABLE: invalid MCP access policy:"), "{error}");
+ assert_eq!(storage.load_app_settings_json().await.unwrap(), before);
+ assert!(storage.load_mcp_access_policy().await.is_err());
+ }
+ }
+
+ #[tokio::test]
+ async fn mcp_v1_saves_preserve_immediate_scopes_but_allow_salesforce_dml_changes() {
+ use crate::mcp_access::{
+ McpAccessLevel, McpAccessRule, McpRuleTarget, McpSubScopeMode, SALESFORCE_WRITE_TOOLSET,
+ };
+ let path = temp_db_path("mcp-scope-draft-merge");
+ let storage = crate::persistence::test_storage::open(&path).await.unwrap();
+ let mut draft = McpGlobalPolicy { read_only: false, ..Default::default() };
+ let rule: crate::storage::McpConnectionPolicy = serde_json::from_value(serde_json::json!({
+ "connectionId": "nacos", "readOnly": false, "executionModeConfigured": true,
+ "executionModePolicyVersion": 1, "databaseScope": "all"
+ }))
+ .unwrap();
+ draft.connection_policies.push(rule);
+ storage.save_mcp_global_policy(&draft).await.unwrap();
+ storage
+ .set_mcp_plugin_scope_rule(
+ "nacos",
+ "namespace",
+ Some("dev"),
+ Some(McpAccessRule { visible: Some(true), access: Some(McpAccessLevel::Write), ..Default::default() }),
+ Some(McpSubScopeMode::Selected),
+ )
+ .await
+ .unwrap();
+ // Applying an already-open v1 form must not undo the immediate namespace save.
+ draft.query_timeout_secs = Some(42);
+ storage.save_mcp_global_policy(&draft).await.unwrap();
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ assert_eq!(access.sub_scope_mode("nacos"), McpSubScopeMode::Selected);
+ assert!(!access.resolve(&[], "nacos", Some(("namespace", "prod"))).visible);
+ assert_eq!(
+ storage.load_mcp_global_policy().await.unwrap().policy(),
+ access.to_v1(),
+ "v1 readers must retain the saved scope restriction after a stale draft is applied"
+ );
+ // Mode-only rules also survive, even with an existing v1 connection rule.
+ storage.set_mcp_plugin_scope_rule("nacos", "namespace", None, None, Some(McpSubScopeMode::None)).await.unwrap();
+ storage.save_mcp_global_policy(&draft).await.unwrap();
+ assert_eq!(storage.load_mcp_access_policy().await.unwrap().sub_scope_mode("nacos"), McpSubScopeMode::None);
+ assert_eq!(
+ storage.load_mcp_global_policy().await.unwrap().policy(),
+ storage.load_mcp_access_policy().await.unwrap().to_v1()
+ );
+ for allowed in [true, false, true] {
+ draft.connection_policies[0].allow_salesforce_dml = allowed;
+ storage.save_mcp_global_policy(&draft).await.unwrap();
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ assert_eq!(
+ access.toolset_ceiling("nacos", SALESFORCE_WRITE_TOOLSET) == Some(McpAccessLevel::Full),
+ allowed
+ );
+ }
+ // Two independent row saves retain both changes.
+ let (a, b) = tokio::join!(
+ storage.set_mcp_plugin_scope_rule(
+ "a",
+ "namespace",
+ Some("one"),
+ Some(McpAccessRule { visible: Some(true), ..Default::default() }),
+ Some(McpSubScopeMode::Selected)
+ ),
+ storage.set_mcp_plugin_scope_rule(
+ "b",
+ "namespace",
+ Some("two"),
+ Some(McpAccessRule { visible: Some(true), ..Default::default() }),
+ Some(McpSubScopeMode::Selected)
+ )
+ );
+ a.unwrap();
+ b.unwrap();
+ let access = storage.load_mcp_access_policy().await.unwrap();
+ for (id, value) in [("a", "one"), ("b", "two")] {
+ assert!(access.rules.contains_key(&McpRuleTarget::Scope {
+ connection_id: id.into(),
+ scope: "namespace".into(),
+ value: value.into()
+ }));
+ }
+ }
+
+ #[tokio::test]
+ async fn mcp_access_policy_round_trips_and_keeps_v1_in_sync() {
+ use crate::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+ let path = temp_db_path("mcp-access-policy");
+ let storage = crate::persistence::test_storage::open(&path).await.unwrap();
+ // Nothing saved: v2 is the mapping of the v1 default.
+ let default = storage.load_mcp_access_policy().await.unwrap();
+ assert_eq!(default, McpAccessPolicy::from_v1(&McpGlobalPolicy::default()));
+
+ // Saving v1 writes the matching v2.
+ let v1 = McpGlobalPolicy { read_only: false, allow_dangerous_sql: true, ..Default::default() };
+ storage.save_mcp_global_policy(&v1).await.unwrap();
+ assert_eq!(storage.load_mcp_access_policy().await.unwrap().default_access, McpAccessLevel::Full);
+
+ // Saving v2 writes the never-wider v1 projection.
+ let mut v2 = McpAccessPolicy { default_access: McpAccessLevel::Write, ..Default::default() };
+ v2.rules.insert(
+ McpRuleTarget::Connection { id: "c".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Read), ..Default::default() },
+ );
+ storage.save_mcp_access_policy(&v2).await.unwrap();
+ assert_eq!(storage.load_mcp_access_policy().await.unwrap(), v2);
+ let projected = storage.load_mcp_global_policy().await.unwrap().policy();
+ assert!(!projected.read_only && !projected.allow_dangerous_sql);
+ assert!(projected.connection_policies.iter().any(|rule| rule.connection_id == "c" && rule.read_only));
+
+ // Whole-map settings writers keep both keys.
+ storage.save_app_settings_json(&serde_json::Map::new()).await.unwrap();
+ assert_eq!(storage.load_mcp_access_policy().await.unwrap(), v2);
+
+ // Hosts enforce the v2 policy even if the v1 key was rewritten by an
+ // older writer with something wider.
+ let mut wider = projected.clone();
+ wider.read_only = false;
+ wider.allow_dangerous_sql = true;
+ wider.connection_policies.clear();
+ storage
+ .with_conn(move |conn| {
+ let mut settings = app_settings_map_from_conn(conn)?;
+ settings.insert(MCP_GLOBAL_POLICY_KEY.to_string(), serde_json::to_value(&wider).unwrap());
+ write_app_settings_map(conn, &settings)
+ })
+ .await
+ .unwrap();
+ let enforced = storage.load_enforced_mcp_policy().await.unwrap().policy();
+ assert!(!enforced.allow_dangerous_sql, "v2 stays authoritative");
+ assert!(enforced.connection_policies.iter().any(|rule| rule.connection_id == "c" && rule.read_only));
+ }
+
+ #[test]
+ fn malformed_plugin_mcp_grants_are_skipped() {
+ let grants = plugin_mcp_grants_from(Some(&serde_json::json!({
+ "io.ok": { "external": true, "ceiling": "read", "approvedTools": {}, "disabledTools": [] },
+ "io.bad": { "external": "yes" },
+ " ": { "external": true, "ceiling": "read" }
+ })));
+ assert_eq!(grants.keys().collect::<Vec<_>>(), ["io.ok"]);
+ assert!(plugin_mcp_grants_from(Some(&serde_json::json!([]))).is_empty());
+ }
+
#[tokio::test]
async fn max_retries_survives_stale_app_settings_save() {
let path = temp_db_path("max-retries-stale-save");
diff --git a/crates/dbx-mcp/src/approval.rs b/crates/dbx-mcp/src/approval.rs
new file mode 100644
index 0000000000..2dfae46eef
--- /dev/null
+++ b/crates/dbx-mcp/src/approval.rs
@@ -0,0 +1,113 @@
+//! Desktop confirmation for high-risk non-SQL MCP tool calls.
+//!
+//! SQL keeps its dedicated token flow (`approve_high_risk_sql`): the server
+//! re-validates the exact statement after the prompt and consumes a one-shot
+//! token. Other tools use this simpler contract: the desktop shows what will
+//! run, the person answers, and the server re-checks policy before running.
+//!
+//! Call safety is evaluated after resource authorization. HighRisk confirms
+//! authorized Full operations too; only the explicit legacy Full policy may
+//! temporarily elevate Write. Every handler rechecks authorization after approval.
+
+use serde::{Deserialize, Serialize};
+
+/// Upper bound for the argument preview shown in the confirmation dialog.
+const MAX_ARGUMENT_PREVIEW_CHARS: usize = 4_000;
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ToolApprovalKind {
+ /// A plugin tool declared `full` in its manifest.
+ PluginTool,
+ /// A Redis command classified as dangerous (FLUSHALL, KEYS *, …).
+ RedisCommand,
+ /// A MongoDB command requiring Full access.
+ MongoCommand,
+ /// A product-provider tool declared `full` (Nacos config delete, …).
+ ProductTool,
+ /// A destructive host operation such as removing a connection.
+ ConnectionManagement,
+}
+
+/// What the desktop shows and the person confirms.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ToolApprovalRequest {
+ pub kind: ToolApprovalKind,
+ /// Exposed MCP tool name (`dbx_ssh__exec`, `dbx_execute_redis_command`).
+ pub tool: String,
+ /// Plugin display name for plugin tools.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub plugin: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub connection_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub database: Option<String>,
+ /// Human-readable summary of the call (command line, arguments JSON).
+ pub detail: String,
+}
+
+impl ToolApprovalRequest {
+ pub fn new(kind: ToolApprovalKind, tool: impl Into<String>, detail: impl Into<String>) -> Self {
+ Self {
+ kind,
+ tool: tool.into(),
+ plugin: None,
+ connection_id: None,
+ database: None,
+ detail: preview(detail.into()),
+ }
+ }
+
+ pub fn with_plugin(mut self, plugin: impl Into<String>) -> Self {
+ self.plugin = Some(plugin.into());
+ self
+ }
+
+ pub fn with_target(mut self, connection_id: Option<&str>, database: Option<&str>) -> Self {
+ self.connection_id = connection_id.map(str::to_string);
+ self.database = database.map(str::to_string);
+ self
+ }
+}
+
+/// Pretty JSON of call arguments for the dialog, capped in length.
+pub fn arguments_preview(arguments: &serde_json::Value) -> String {
+ preview(serde_json::to_string_pretty(arguments).unwrap_or_else(|_| arguments.to_string()))
+}
+
+fn preview(text: String) -> String {
+ if text.chars().count() <= MAX_ARGUMENT_PREVIEW_CHARS {
+ return text;
+ }
+ let mut truncated = text.chars().take(MAX_ARGUMENT_PREVIEW_CHARS).collect::<String>();
+ truncated.push_str("\n…");
+ truncated
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn requests_serialize_for_the_bridge_and_cap_previews() {
+ let request = ToolApprovalRequest::new(
+ ToolApprovalKind::PluginTool,
+ "dbx_ssh__exec",
+ arguments_preview(&json!({ "command": "rm -rf /tmp/x" })),
+ )
+ .with_plugin("Terminal")
+ .with_target(Some("c1"), None);
+ let value = serde_json::to_value(&request).unwrap();
+ assert_eq!(value["kind"], "plugin_tool");
+ assert_eq!(value["plugin"], "Terminal");
+ assert!(value.get("database").is_none());
+ assert!(value["detail"].as_str().unwrap().contains("rm -rf"));
+ let round_trip: ToolApprovalRequest = serde_json::from_value(value).unwrap();
+ assert_eq!(round_trip, request);
+
+ let long = arguments_preview(&json!({ "payload": "x".repeat(10_000) }));
+ assert!(long.chars().count() <= MAX_ARGUMENT_PREVIEW_CHARS + 2);
+ assert!(long.ends_with('…'));
+ }
+}
diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rs
index 5e44923533..64c9f3e503 100644
--- a/crates/dbx-mcp/src/backend.rs
+++ b/crates/dbx-mcp/src/backend.rs
@@ -58,17 +58,38 @@ impl From<&ConnectionConfig> for ConnectionSummary {
}
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),
- "0" | "false" => Some(false),
- _ => None,
- }
+ parse_legacy_mcp_allow_writes(&std::env::var("DBX_MCP_ALLOW_WRITES").ok()?)
+}
+
+fn parse_legacy_mcp_allow_writes(value: &str) -> Option<bool> {
+ Some(match value.trim().to_ascii_lowercase().as_str() {
+ "1" | "true" => true,
+ "0" | "false" | "no" | "yes" | "" => false,
+ // Fail closed for values that are not understood by the CLI flag
+ // parser; an invalid setting must never silently enable writes.
+ _ => false,
+ })
}
fn effective_mcp_policy(state: McpGlobalPolicyState) -> McpGlobalPolicy {
effective_mcp_policy_with_legacy_allow_writes(state, legacy_mcp_allow_writes())
}
+fn effective_mcp_access_policy(
+ mut access: dbx_core::mcp_access::McpAccessPolicy,
+) -> dbx_core::mcp_access::McpAccessPolicy {
+ // Both local storage and Web responses must honor the CLI run's read-only
+ // restriction. Cap every override while leaving visibility/scopes intact.
+ if legacy_mcp_allow_writes() == Some(false) {
+ let read = dbx_core::mcp_access::McpAccessLevel::Read;
+ access.default_access = access.default_access.min(read);
+ for rule in access.rules.values_mut() {
+ rule.access = rule.access.map(|level| level.min(read));
+ }
+ }
+ access
+}
+
fn effective_mcp_policy_with_legacy_allow_writes(
state: McpGlobalPolicyState,
legacy_allow_writes: Option<bool>,
@@ -281,6 +302,12 @@ impl DbxBackend for UnavailableBackend {
#[async_trait]
pub trait DbxBackend: Send + Sync {
async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String>;
+ /// The v2 access policy, for decisions v1 cannot express (plugin
+ /// sub-scopes). Defaults to the v1 mapping, which carries no plugin
+ /// sub-scope rules and so admits every value at the connection level.
+ async fn load_mcp_access_policy(&self) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {
+ Ok(dbx_core::mcp_access::McpAccessPolicy::from_v1(&self.load_mcp_global_policy().await?))
+ }
async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String>;
async fn save_history_entry(&self, entry: &HistoryEntry) -> Result<(), String> {
@@ -493,6 +520,26 @@ pub trait DbxBackend: Send + Sync {
let _ = (token, connection_id, database, sql);
Err("SQL_BLOCKED: Desktop approval is unavailable for this MCP backend.".to_string())
}
+ /// Runs one product-provider operation (Nacos, Consul, …) on a resolved
+ /// connection. Policy, scope and access level are checked by the server
+ /// before this is reached.
+ async fn product_call(
+ &self,
+ connection: &ConnectionConfig,
+ call: &crate::products::ProductCall,
+ ) -> Result<Value, String> {
+ let _ = (connection, call);
+ Err("This MCP backend does not support product tools.".to_string())
+ }
+ /// Asks the desktop user to confirm one high-risk non-SQL tool call
+ /// (a plugin tool declared `full`, a dangerous Redis command). Returns
+ /// once the person answered: `Ok(())` to proceed, `Err` with a
+ /// `TOOL_BLOCKED:` message otherwise. Backends without a desktop UI
+ /// refuse, so a call needing confirmation never runs unconfirmed.
+ async fn approve_high_risk_tool(&self, request: &crate::approval::ToolApprovalRequest) -> Result<(), String> {
+ let _ = request;
+ Err("TOOL_BLOCKED: Desktop confirmation is unavailable for this MCP backend.".to_string())
+ }
async fn collect_docs_snapshot(
&self,
connection: &ConnectionConfig,
@@ -521,6 +568,11 @@ pub trait DbxBackend: Send + Sync {
let _ = self;
Err("Plugin tools are not supported by this backend.".to_string())
}
+ /// Lists a plugin-declared sub-scope for one saved connection.
+ async fn list_plugin_mcp_scopes(&self, plugin_id: &str, connection_id: &str) -> Result<Vec<String>, String> {
+ let _ = (plugin_id, connection_id);
+ Err("Plugin scope listing is not supported by this backend.".to_string())
+ }
/// Calls one plugin MCP tool. `connection_id` (already policy-checked by
/// the server) selects the saved connection whose host-generated
/// lifecycle payload is sent to the plugin; `None` targets
@@ -977,40 +1029,77 @@ impl LocalBackend {
/// Opt-in, parallel `mcp/tools` discovery for the external surface:
/// installed + compatible + backend plugins whose manifest declares
- /// `external_tools: true`. A plugin that fails to list skips itself
- /// (with a warning) instead of failing the whole `tools/list`.
+ /// `external_tools: true`, narrowed by the user's per-plugin grant
+ /// (`dbx_core::plugin_mcp`). A plugin that fails to list skips itself
+ /// (with a warning) instead of failing the whole `tools/list`; an
+ /// unreadable grant store hides every plugin rather than widening.
pub async fn detect_plugin_tool_providers(&self) -> Result<Vec<crate::plugin_tools::PluginToolProvider>, String> {
let plugins = self.state.plugins.list_installed()?;
- let candidates: Vec<(String, String)> = plugins
+ let grants = self.state.storage.load_plugin_mcp_grants().await.map_err(|error| {
+ log::warn!("[mcp] cannot read plugin MCP grants: {error}");
+ format!("Plugin MCP grants are unavailable: {error}")
+ })?;
+ let candidates: Vec<dbx_core::plugins::PluginManifest> = plugins
.into_iter()
.filter(|plugin| {
plugin.compatibility.compatible
&& plugin.manifest.backend_entrypoint().is_some()
- && !plugin.manifest.external_tools_excluded()
+ && dbx_core::plugin_mcp::author_allows_external(&plugin.manifest)
+ && grants.get(&plugin.manifest.id).is_none_or(|grant| grant.external)
})
- .map(|plugin| (plugin.manifest.id.clone(), plugin.manifest.name.clone()))
+ .map(|plugin| plugin.manifest)
.collect();
// Discovery uses short-lived sessions: merely listing tools must not keep every
// installed plugin loaded in every independent MCP host.
- let probes = candidates.into_iter().map(|(plugin_id, plugin_name)| {
+ let probes = candidates.into_iter().map(|manifest| {
let state = Arc::clone(&self.state);
async move {
let listing = state
.plugin_host
- .probe::<Value>(&plugin_id, "mcp/tools", json!({}), Some(PLUGIN_TOOLS_PROBE_TIMEOUT))
+ .probe::<Value>(&manifest.id, "mcp/tools", json!({}), Some(PLUGIN_TOOLS_PROBE_TIMEOUT))
.await;
- (plugin_id, plugin_name, listing)
+ (manifest, listing)
}
});
let mut providers = Vec::new();
- for (plugin_id, plugin_name, listing) in futures::future::join_all(probes).await {
+ for (manifest, listing) in futures::future::join_all(probes).await {
+ let plugin_id = manifest.id.clone();
+ let plugin_name = manifest.name.clone();
match listing {
Ok(value) => {
- let tools = dbx_core::ai::plugin_tools::parse_tool_list(&value);
+ let tools = dbx_core::plugin_mcp::exposed_tools(
+ &manifest,
+ grants.get(&plugin_id),
+ dbx_core::ai::plugin_tools::parse_tool_list(&value),
+ );
if tools.is_empty() {
log::debug!("[mcp] plugin {plugin_id} exposes no MCP tools");
} else {
- providers.push(crate::plugin_tools::PluginToolProvider { plugin_id, plugin_name, tools });
+ let scope = manifest
+ .mcp_contribution()
+ .and_then(|mcp| mcp.scope.as_ref())
+ .map(|scope| (scope.kind.clone(), scope.argument.clone()));
+ let scope_list_method = manifest
+ .mcp_contribution()
+ .and_then(|mcp| mcp.scope.as_ref())
+ .and_then(|scope| scope.list_method.clone());
+ let toolsets = tools
+ .iter()
+ .map(|tool| {
+ (
+ tool.name.clone(),
+ dbx_core::plugin_mcp::tool_toolset(manifest.mcp_contribution(), &tool.name),
+ )
+ })
+ .collect();
+ providers.push(crate::plugin_tools::PluginToolProvider {
+ plugin_id,
+ plugin_name,
+ tools,
+ scope,
+ scope_list_method,
+ toolsets,
+ });
}
}
Err(err) if plugin_lacks_mcp_surface(&err) => {
@@ -1149,6 +1238,34 @@ impl DbxBackend for LocalBackend {
.map(ToOwned::to_owned)
.ok_or_else(|| "SQL_BLOCKED: Invalid desktop approval response".to_string())
}
+ async fn product_call(
+ &self,
+ connection: &ConnectionConfig,
+ call: &crate::products::ProductCall,
+ ) -> Result<Value, String> {
+ crate::products::dispatch_local(&self.state, &connection.id, call).await
+ }
+
+ async fn approve_high_risk_tool(&self, request: &crate::approval::ToolApprovalRequest) -> Result<(), String> {
+ let port = tokio::fs::read_to_string(self.data_dir.join("mcp-bridge-port"))
+ .await
+ .map_err(|_| "TOOL_BLOCKED: DBX desktop is not running, so the call cannot be confirmed.".to_string())?;
+ let response = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(100))
+ .build()
+ .map_err(|error| error.to_string())?
+ .post(format!("http://127.0.0.1:{}/approve-high-risk-tool", port.trim()))
+ .json(request)
+ .send()
+ .await
+ .map_err(|error| format!("TOOL_BLOCKED: Desktop confirmation unavailable: {error}"))?;
+ if response.status().is_success() {
+ Ok(())
+ } else {
+ Err(response.text().await.unwrap_or_else(|_| "TOOL_BLOCKED: Confirmation failed".to_string()))
+ }
+ }
+
async fn consume_high_risk_sql_approval(
&self,
token: &str,
@@ -1174,13 +1291,49 @@ impl DbxBackend for LocalBackend {
Ok(())
}
async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String> {
- self.state.storage.load_mcp_global_policy().await.map(effective_mcp_policy)
+ self.state.storage.load_enforced_mcp_policy().await.map(effective_mcp_policy)
+ }
+
+ async fn load_mcp_access_policy(&self) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {
+ self.state.storage.load_mcp_access_policy().await.map(effective_mcp_access_policy)
}
async fn list_plugin_mcp_tools(&self) -> Result<Vec<crate::plugin_tools::PluginToolProvider>, String> {
self.detect_plugin_tool_providers().await
}
+ async fn list_plugin_mcp_scopes(&self, plugin_id: &str, connection_id: &str) -> Result<Vec<String>, String> {
+ let manifest = self
+ .state
+ .plugins
+ .list_installed()?
+ .into_iter()
+ .find(|plugin| plugin.manifest.id == plugin_id)
+ .ok_or_else(|| format!("Plugin `{plugin_id}` is not installed."))?
+ .manifest;
+ let method = manifest
+ .mcp_contribution()
+ .and_then(|mcp| mcp.scope.as_ref())
+ .and_then(|scope| scope.list_method.as_deref())
+ .ok_or_else(|| "This plugin does not declare a scope list method.".to_string())?;
+ let value = self
+ .state
+ .plugin_host
+ .invoke::<Value>(
+ plugin_id,
+ method,
+ json!({ "connectionId": connection_id }),
+ None,
+ Some(PLUGIN_TOOLS_PROBE_TIMEOUT),
+ )
+ .await?;
+ value
+ .get("values")
+ .and_then(Value::as_array)
+ .ok_or_else(|| "Plugin scope list must return { values: string[] }.".to_string())
+ .map(|values| values.iter().filter_map(Value::as_str).map(str::to_string).collect())
+ }
+
async fn call_plugin_mcp_tool(
&self,
plugin_id: &str,
@@ -1627,6 +1780,16 @@ impl DbxBackend for WebBackend {
.map_err(|error| format!("Invalid MCP policy response: {error}"))
}
+ 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)
+ .await?
+ .bytes()
+ .await
+ .map_err(|error| format!("Invalid MCP access policy response: {error}"))?;
+ parse_mcp_access_policy(&body).map(effective_mcp_access_policy)
+ }
+
async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {
self.request(reqwest::Method::GET, "/api/connection/list", None)
.await?
@@ -2773,6 +2936,10 @@ fn url_encode(value: &str) -> String {
url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
}
+fn parse_mcp_access_policy(body: &[u8]) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {
+ serde_json::from_slice(body).map_err(|error| format!("Invalid MCP access policy response: {error}"))
+}
+
pub(crate) fn format_query_result(result: &dbx_core::db::QueryResult, max_rows: usize) -> String {
let mut output = if result.columns.is_empty() {
format!("Query executed. {} row(s) affected.", result.affected_rows)
@@ -3216,12 +3383,14 @@ mod tests {
read_only,
allow_dangerous_sql: false,
prompt_high_risk_sql: false,
+ call_confirmation: None,
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,
+ plugin_tools_mode: dbx_core::mcp_access::McpPluginToolsMode::Auto,
}
}
@@ -3254,6 +3423,16 @@ mod tests {
assert!(effective_mcp_policy_with_legacy_allow_writes(policy_state(true, true), None).read_only);
}
+ #[test]
+ fn legacy_allow_writes_parser_fails_closed_for_unknown_values() {
+ assert_eq!(parse_legacy_mcp_allow_writes("1"), Some(true));
+ assert_eq!(parse_legacy_mcp_allow_writes("yes"), Some(false));
+ assert_eq!(parse_legacy_mcp_allow_writes("0"), Some(false));
+ assert_eq!(parse_legacy_mcp_allow_writes("no"), Some(false));
+ assert_eq!(parse_legacy_mcp_allow_writes(""), Some(false));
+ assert_eq!(parse_legacy_mcp_allow_writes("unexpected"), Some(false));
+ }
+
#[test]
fn legacy_read_only_also_revokes_the_salesforce_dml_opt_in() {
// DBX_MCP_ALLOW_WRITES=0 marks an unconfirmed CLI run. The Salesforce DML
@@ -3438,6 +3617,193 @@ mod tests {
assert_eq!(paths.get("web-db"), Some(&vec!["Project".to_string()]));
}
+ #[tokio::test]
+ async fn web_backend_loads_v2_access_policy_with_plugin_scope_rules() {
+ // The desktop test suite normally exercises the HTTP path below. Some
+ // restricted CI sandboxes disallow local listeners altogether; the
+ // parser test that follows still covers the v2 wire shape there.
+ let Ok(listener) = TcpListener::bind("127.0.0.1:0") else { return };
+ 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();
+ let body = r#"{"version":2,"defaultAccess":"read","confirm":"off","visibility":"all","rules":[{"target":{"kind":"scope","connectionId":"plugin-connection","scope":"namespace","value":"dev"},"subScope":"selected"}],"pluginToolsMode":"lazy"}"#;
+ 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 policy = backend.load_mcp_access_policy().await.unwrap();
+
+ server.join().unwrap();
+ assert_eq!(request_receiver.recv().unwrap(), "GET /api/app-settings/mcp-access-policy HTTP/1.1");
+ assert_eq!(policy.version, 2);
+ assert_eq!(policy.plugin_tools_mode, dbx_core::mcp_access::McpPluginToolsMode::Lazy);
+ assert!(policy.rules.contains_key(&dbx_core::mcp_access::McpRuleTarget::Scope {
+ connection_id: "plugin-connection".to_string(),
+ scope: "namespace".to_string(),
+ value: "dev".to_string(),
+ }));
+ }
+
+ #[tokio::test]
+ async fn web_backend_enforces_run_scoped_read_only() {
+ use axum::{extract::Request, response::IntoResponse, Json, Router};
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy};
+ use rmcp::{model::CallToolRequestParams, ServiceExt};
+ const CHILD: &str = "DBX_MCP_WEB_READ_ONLY_TEST_CHILD";
+ // Never mutate the test runner's process-wide environment: exercise the
+ // real env reader in isolated children, as the CLI launches MCP.
+ if std::env::var_os(CHILD).is_none() {
+ for mode in ["0", "false", "1", "unset"] {
+ let mut command = std::process::Command::new(std::env::current_exe().unwrap());
+ command
+ .args(["--exact", "backend::tests::web_backend_enforces_run_scoped_read_only", "--nocapture"])
+ .env(CHILD, mode)
+ .env_remove("DBX_MCP_CONFIRMED_WRITE_SQL");
+ if mode == "unset" {
+ command.env_remove("DBX_MCP_ALLOW_WRITES");
+ } else {
+ command.env("DBX_MCP_ALLOW_WRITES", mode);
+ }
+ assert!(command.status().unwrap().success(), "isolated Web mode {mode} failed");
+ }
+ return;
+ }
+ let restricted = matches!(std::env::var(CHILD).unwrap().as_str(), "0" | "false");
+ let access: McpAccessPolicy = serde_json::from_value(json!({
+ "version": 2, "defaultAccess": "full", "confirm": "off", "visibility": "all",
+ "pluginToolsMode": "lazy", "rules": [
+ {"target": {"kind": "group", "id": "team"}, "access": "write"},
+ {"target": {"kind": "connection", "id": "redis"}, "access": "full", "subScope": "selected"},
+ {"target": {"kind": "scope", "connectionId": "redis", "scope": "database", "value": "0"}, "access": "full", "visible": true},
+ {"target": {"kind": "scope", "connectionId": "redis", "scope": "database", "value": "2"}, "access": "read", "visible": true},
+ {"target": {"kind": "scope", "connectionId": "redis", "scope": "database", "value": "3"}, "access": "none", "visible": false},
+ {"target": {"kind": "connection", "id": "plugin"}, "subScope": "selected", "subScopeKind": "namespace", "toolsetCeilings": {"admin": "read"}},
+ {"target": {"kind": "scope", "connectionId": "plugin", "scope": "namespace", "value": "dev"}, "access": "write", "visible": true}
+ ]
+ })).unwrap();
+ let mut v1 = serde_json::to_value(access.to_v1()).unwrap();
+ v1["configured"] = json!(true);
+ let v2 = serde_json::to_value(&access).unwrap();
+ let executions = Arc::new(std::sync::Mutex::new(Vec::<Value>::new()));
+ let recorded = executions.clone();
+ let router = Router::new().fallback(move |request: Request| {
+ let (v1, v2, recorded) = (v1.clone(), v2.clone(), recorded.clone());
+ async move {
+ let response = match request.uri().path() {
+ "/api/auth/check" => json!({"authenticated": true, "required": false, "setup_required": false}),
+ "/api/app-settings/mcp-policy" => v1,
+ "/api/app-settings/mcp-access-policy" => v2,
+ "/api/connection/list" => json!([{
+ "id": "redis", "name": "redis", "db_type": "redis", "host": "localhost",
+ "port": 6379, "username": "", "password": "", "database": "0", "ssl": false
+ }]),
+ "/api/layout/sidebar" => json!({"groups": [], "order": []}),
+ "/api/connection/connect" => json!({}),
+ "/api/redis/execute-command" => {
+ let body = axum::body::to_bytes(request.into_body(), 8192).await.unwrap();
+ let arguments: Value = serde_json::from_slice(&body).unwrap();
+ recorded.lock().unwrap().push(arguments.clone());
+ json!({"command": arguments["command"], "safety": "allowed", "value": "OK"})
+ }
+ _ => return axum::http::StatusCode::NOT_FOUND.into_response(),
+ };
+ Json(response).into_response()
+ }
+ });
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let http_server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
+ let backend = Arc::new(WebBackend::new(format!("http://{address}"), String::new()).unwrap());
+ let loaded = backend.load_mcp_access_policy().await.unwrap();
+ let full = if restricted { McpAccessLevel::Read } else { McpAccessLevel::Full };
+ let write = if restricted { McpAccessLevel::Read } else { McpAccessLevel::Write };
+ assert_eq!(loaded.default_access, full);
+ assert_eq!(loaded.resolve(&["team".into()], "unconfigured", None).level, write);
+ assert_eq!(loaded.resolve(&[], "redis", None).level, full);
+ assert_eq!(loaded.resolve(&[], "redis", Some(("database", "0"))).level, full);
+ assert_eq!(loaded.resolve(&[], "redis", Some(("database", "2"))).level, McpAccessLevel::Read);
+ assert!(!loaded.resolve(&[], "redis", Some(("database", "3"))).visible);
+ assert!(!loaded.resolve(&[], "redis", Some(("database", "1"))).visible);
+ assert_eq!(loaded.resolve(&[], "plugin", Some(("namespace", "dev"))).level, write);
+ assert!(!loaded.resolve(&[], "plugin", Some(("namespace", "prod"))).visible);
+ assert_eq!(loaded.toolset_ceiling("plugin", "admin"), Some(McpAccessLevel::Read));
+ assert_eq!(loaded.plugin_tools_mode, access.plugin_tools_mode);
+ if !restricted {
+ assert_eq!(loaded, access);
+ }
+ let directory = tempfile::tempdir().unwrap();
+ let local = connection_mutation_backend(directory.path()).await;
+ local.state.storage.save_mcp_access_policy(&access).await.unwrap();
+ assert_eq!(local.load_mcp_access_policy().await.unwrap(), loaded);
+
+ let server = crate::DbxMcpServer::with_runtime_options(backend, crate::McpScope::default(), true);
+ let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
+ let server_task = tokio::spawn(async move { server.serve(server_transport).await.unwrap() });
+ let client = ().serve(client_transport).await.unwrap();
+ for (db, command, error) in [
+ (0, "SET probe value", restricted.then_some("MCP_READ_ONLY")),
+ (0, "GET probe", None),
+ (2, "SET probe value", Some("MCP_READ_ONLY")),
+ (1, "GET probe", Some("DATABASE_OUT_OF_SCOPE")),
+ ] {
+ let before = executions.lock().unwrap().len();
+ let result = client
+ .peer()
+ .call_tool(CallToolRequestParams::new("dbx_execute_redis_command").with_arguments(
+ json!({"connection_id": "redis", "db": db, "command": command}).as_object().unwrap().clone(),
+ ))
+ .await
+ .unwrap();
+ if let Some(error) = error {
+ assert_eq!(result.is_error, Some(true), "{result:?}");
+ assert!(result.content[0].as_text().unwrap().text.contains(error), "{result:?}");
+ assert_eq!(executions.lock().unwrap().len(), before, "denied call must not reach the execution API");
+ } else {
+ assert!(!result.is_error.unwrap_or(false), "{result:?}");
+ assert_eq!(executions.lock().unwrap().len(), before + 1);
+ assert_eq!(executions.lock().unwrap().last().unwrap()["command"], command);
+ }
+ }
+ client.cancel().await.unwrap();
+ server_task.await.unwrap().cancel().await.unwrap();
+ http_server.abort();
+ }
+
+ #[test]
+ fn parses_v2_access_policy_without_dropping_sub_scope_rules() {
+ let policy = parse_mcp_access_policy(
+ br#"{"version":2,"defaultAccess":"read","rules":[{"target":{"kind":"scope","connectionId":"c1","scope":"namespace","value":"dev"},"visible":true}],"pluginToolsMode":"auto"}"#,
+ )
+ .unwrap();
+ assert_eq!(policy.version, 2);
+ assert_eq!(policy.default_access, dbx_core::mcp_access::McpAccessLevel::Read);
+ assert_eq!(policy.rules.len(), 1);
+ assert!(policy.rules.contains_key(&dbx_core::mcp_access::McpRuleTarget::Scope {
+ connection_id: "c1".to_string(),
+ scope: "namespace".to_string(),
+ value: "dev".to_string(),
+ }));
+ }
+
#[test]
fn agent_query_timeout_web_policy_applies_over_connection_effective_timeout() {
// Unset policy inherits the connection's effective timeout
diff --git a/crates/dbx-mcp/src/http.rs b/crates/dbx-mcp/src/http.rs
index 6965ba2141..c85c7b2909 100644
--- a/crates/dbx-mcp/src/http.rs
+++ b/crates/dbx-mcp/src/http.rs
@@ -11,7 +11,7 @@ use tower_http::cors::{AllowOrigin, Any, CorsLayer};
use crate::{
diagnostics::health,
http_auth::{authorize_request, HttpAuth},
- runtime::HttpRuntimeConfig,
+ runtime::{HttpRuntimeConfig, McpTransport},
server::{PendingSalesforceWrites, PluginToolsMode, SALESFORCE_WRITE_CONFIRM_TTL},
DbxBackend, DbxMcpServer, McpScope, McpSessionStore,
};
@@ -88,7 +88,8 @@ fn build_streamable_http_router(
plugin_tools_mode,
sessions.clone(),
pending_salesforce_writes.clone(),
- ))
+ )
+ .with_transport(McpTransport::StreamableHttp))
},
session_manager,
rmcp_config,
diff --git a/crates/dbx-mcp/src/lib.rs b/crates/dbx-mcp/src/lib.rs
index 6eb93b1265..485dffa1cb 100644
--- a/crates/dbx-mcp/src/lib.rs
+++ b/crates/dbx-mcp/src/lib.rs
@@ -1,11 +1,13 @@
#![recursion_limit = "256"]
+pub mod approval;
pub mod backend;
pub mod diagnostics;
pub mod http;
pub mod http_auth;
pub mod paths;
pub mod plugin_tools;
+pub mod products;
pub mod runtime;
pub mod server;
pub mod session;
diff --git a/crates/dbx-mcp/src/plugin_tools.rs b/crates/dbx-mcp/src/plugin_tools.rs
index 70e43064e2..9092259f3a 100644
--- a/crates/dbx-mcp/src/plugin_tools.rs
+++ b/crates/dbx-mcp/src/plugin_tools.rs
@@ -14,7 +14,7 @@
//! never cross the process boundary, and a connection saved for plugin A can
//! never be reached through plugin B's tools.
-use std::collections::HashSet;
+use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
use serde_json::{json, Value};
@@ -40,6 +40,12 @@ pub struct PluginToolProvider {
pub plugin_id: String,
pub plugin_name: String,
pub tools: Vec<RawPluginTool>,
+ /// The plugin's declared sub-scope (`mcp.scope`): `(kind, argument)`.
+ pub scope: Option<(String, String)>,
+ pub scope_list_method: Option<String>,
+ /// Manifest-declared toolset for each listed tool. Tools without an
+ /// explicit declaration use the stable `default` toolset.
+ pub toolsets: BTreeMap<String, String>,
}
/// One externally exposed plugin tool.
@@ -49,11 +55,25 @@ pub struct PluginToolEntry {
pub plugin_name: String,
pub exposed_name: String,
pub tool: RawPluginTool,
+ /// Declared sub-scope `(kind, argument)` of the owning plugin.
+ pub scope: Option<(String, String)>,
+ pub scope_list_method: Option<String>,
+ /// Manifest-declared toolset used for connection-level ceilings.
+ pub toolset: String,
/// The plugin schema declares `connectionId`, so the host injects the
/// bound connection's id into the forwarded arguments.
pub injects_connection_id: bool,
}
+impl PluginToolEntry {
+ /// A tool with a host-bound `connectionId` or a declared plugin scope must
+ /// run against one of the plugin's saved connections. Connection-less
+ /// tools deliberately keep working when a plugin has no connections.
+ pub fn requires_connection(&self) -> bool {
+ self.injects_connection_id || self.scope.is_some()
+ }
+}
+
/// Whether `name` sits in the plugin-tool namespace (`dbx_<prefix>__<tool>`).
/// The static `dbx_*` router tools never contain `__`, so this cannot swallow
/// one, and unknown plugin names simply fail resolution at call time.
@@ -87,6 +107,9 @@ pub fn build_catalog(providers: &[PluginToolProvider]) -> Vec<PluginToolEntry> {
exposed_name: format!("dbx_{}", exposed_tool_name(prefix, &tool.name, &mut used)),
plugin_id: provider.plugin_id.clone(),
plugin_name: provider.plugin_name.clone(),
+ scope: provider.scope.clone(),
+ scope_list_method: provider.scope_list_method.clone(),
+ toolset: provider.toolsets.get(&tool.name).cloned().unwrap_or_else(|| "default".to_string()),
injects_connection_id: tool.input_schema.pointer("/properties/connectionId").is_some(),
tool: tool.clone(),
});
@@ -235,6 +258,9 @@ mod tests {
fn provider(plugin_id: &str, plugin_name: &str, tools: Value) -> PluginToolProvider {
PluginToolProvider {
+ scope: None,
+ scope_list_method: None,
+ toolsets: BTreeMap::new(),
plugin_id: plugin_id.to_string(),
plugin_name: plugin_name.to_string(),
tools: parse_tool_list(&tools),
diff --git a/crates/dbx-mcp/src/products.rs b/crates/dbx-mcp/src/products.rs
new file mode 100644
index 0000000000..6d9c3c8ace
--- /dev/null
+++ b/crates/dbx-mcp/src/products.rs
@@ -0,0 +1,338 @@
+//! Product providers (design §5): MCP tools for non-SQL products, one
+//! provider per product, each tool shaped after that product's own model.
+//!
+//! Every provider follows the onboarding checklist: `dbx_<product>_*` names,
+//! toolsets with management operations off by default, a declared access
+//! level per tool, a declared sub-scope kind (Nacos `namespace`, Consul
+//! `datacenter`), business logic reused from `dbx_core::admin::<product>`,
+//! and no cluster-level destructive operations. Nacos exposes namespace
+//! sub-scopes; Consul uses the datacenter stored on its connection.
+//!
+//! The server reaches a product through one backend entry point,
+//! [`crate::backend::DbxBackend::product_call`], so adding a product does not
+//! widen the backend trait: the local backend dispatches to `dbx-core`, other
+//! backends report the product as unavailable.
+
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+/// Products with an MCP provider.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Product {
+ Nacos,
+ Consul,
+}
+
+impl Product {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Product::Nacos => "nacos",
+ Product::Consul => "consul",
+ }
+ }
+
+ /// Sub-scope kind the product declares in the access-control tree.
+ /// Consul connections already carry their configured datacenter and do
+ /// not expose a separate request-level scope.
+ pub fn scope_kind(self) -> Option<&'static str> {
+ match self {
+ Product::Nacos => Some("namespace"),
+ Product::Consul => None,
+ }
+ }
+}
+
+/// One product operation; `args` is the operation's JSON input.
+#[derive(Debug, Clone, PartialEq)]
+pub struct ProductCall {
+ pub product: Product,
+ pub operation: &'static str,
+ pub args: Value,
+}
+
+// ---------------------------------------------------------------------------
+// Local dispatch (desktop / standalone binary reading the shared storage)
+// ---------------------------------------------------------------------------
+
+#[derive(Deserialize)]
+struct Args<T> {
+ #[serde(flatten)]
+ inner: T,
+}
+
+fn parse<T: for<'de> Deserialize<'de>>(args: &Value) -> Result<T, String> {
+ serde_json::from_value::<Args<T>>(args.clone())
+ .map(|args| args.inner)
+ .map_err(|error| format!("INVALID_ARGUMENTS: {error}"))
+}
+
+fn to_json<T: serde::Serialize>(value: T) -> Result<Value, String> {
+ serde_json::to_value(value).map_err(|error| error.to_string())
+}
+
+/// Runs a product operation against `dbx-core`. The caller has already
+/// resolved the connection and checked policy, scope and access level.
+pub async fn dispatch_local(
+ state: &dbx_core::connection::AppState,
+ connection_id: &str,
+ call: &ProductCall,
+) -> Result<Value, String> {
+ match call.product {
+ Product::Nacos => dispatch_nacos(state, connection_id, call.operation, &call.args).await,
+ Product::Consul => dispatch_consul(state, connection_id, call.operation, &call.args).await,
+ }
+}
+
+async fn dispatch_nacos(
+ state: &dbx_core::connection::AppState,
+ id: &str,
+ operation: &str,
+ args: &Value,
+) -> Result<Value, String> {
+ use dbx_core::nacos::service as nacos;
+ use dbx_core::nacos::*;
+ match operation {
+ "list_namespaces" => to_json(nacos::nacos_list_namespaces_core(state, id).await?),
+ "search_configs" => to_json(
+ nacos::nacos_search_config_content_core(state, id, parse::<NacosContentSearchRequest>(args)?, |_| async {})
+ .await?,
+ ),
+ "list_configs" => to_json(nacos::nacos_list_configs_core(state, id, parse::<NacosConfigQuery>(args)?).await?),
+ "get_config" => to_json(nacos::nacos_get_config_core(state, id, parse::<NacosConfigKey>(args)?).await?),
+ "config_history" => {
+ to_json(nacos::nacos_list_config_history_core(state, id, parse::<NacosConfigHistoryQuery>(args)?).await?)
+ }
+ "publish_config" => {
+ nacos::nacos_publish_config_core(state, id, parse::<NacosConfigUpsert>(args)?).await?;
+ Ok(json!({ "ok": true }))
+ }
+ "delete_config" => {
+ nacos::nacos_delete_config_core(state, id, parse::<NacosConfigKey>(args)?).await?;
+ Ok(json!({ "ok": true }))
+ }
+ "rollback_config" => {
+ nacos::nacos_rollback_config_core(state, id, parse::<NacosConfigRollbackRequest>(args)?).await?;
+ Ok(json!({ "ok": true }))
+ }
+ "list_services" => {
+ to_json(nacos::nacos_list_services_core(state, id, parse::<NacosServiceQuery>(args)?).await?)
+ }
+ "get_service" => to_json(nacos::nacos_get_service_core(state, id, parse::<NacosServiceQuery>(args)?).await?),
+ "list_instances" => {
+ to_json(nacos::nacos_list_instances_core(state, id, parse::<NacosInstanceQuery>(args)?).await?)
+ }
+ "update_instance" => {
+ nacos::nacos_update_instance_core(state, id, parse::<NacosInstanceUpdateRequest>(args)?).await?;
+ Ok(json!({ "ok": true }))
+ }
+ "register_instance" => {
+ nacos::nacos_register_instance_core(state, id, parse::<NacosInstanceRegistration>(args)?).await?;
+ Ok(json!({ "ok": true }))
+ }
+ "deregister_instance" => {
+ nacos::nacos_deregister_instance_core(state, id, parse::<NacosInstanceRef>(args)?).await?;
+ Ok(json!({ "ok": true }))
+ }
+ other => Err(format!("Unknown Nacos operation `{other}`")),
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsulKvListArgs {
+ #[serde(default)]
+ prefix: String,
+ #[serde(default)]
+ limit: Option<usize>,
+ #[serde(default)]
+ continuation: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct ConsulKvKeyArgs {
+ key: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsulKvPutArgs {
+ key: String,
+ value: String,
+ #[serde(default)]
+ base64: bool,
+ /// Compare-and-set: only write when the key's ModifyIndex matches.
+ #[serde(default)]
+ cas: Option<i64>,
+}
+
+impl ConsulKvPutArgs {
+ fn options(&self) -> Result<dbx_core::agent_kv::KvPutOptions, String> {
+ use dbx_core::agent_kv::{KvPutOptions, KvWriteMode};
+ match self.cas {
+ Some(0) => Ok(KvPutOptions { write_mode: Some(KvWriteMode::Create), ..Default::default() }),
+ Some(revision) if revision > 0 => {
+ Ok(KvPutOptions { expected_mod_revision: Some(revision.into()), ..Default::default() })
+ }
+ Some(_) => Err("INVALID_ARGUMENTS: cas must be non-negative".to_string()),
+ None => Err("CONSUL_CAS_REQUIRED: Pass cas=0 to create, or the current ModifyIndex to update".to_string()),
+ }
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsulKvDeleteArgs {
+ key: String,
+ #[serde(default)]
+ cas: Option<i64>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsulFilterArgs {
+ #[serde(default)]
+ filter: Option<String>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsulServiceHealthArgs {
+ service: String,
+ #[serde(default)]
+ passing: Option<bool>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsulMaintenanceArgs {
+ service_id: String,
+ enable: bool,
+ #[serde(default)]
+ reason: Option<String>,
+}
+
+/// Upper bound for one KV listing page through MCP.
+const MAX_KV_LIST: usize = 500;
+
+async fn dispatch_consul(
+ state: &dbx_core::connection::AppState,
+ id: &str,
+ operation: &str,
+ args: &Value,
+) -> Result<Value, String> {
+ use dbx_core::agent_kv::{KvDeleteOptions, KvValue, KvValueEncoding};
+ use dbx_core::consul;
+ let read_options = |filter: Option<String>| consul::ConsulReadOptions { filter, ..Default::default() };
+ match operation {
+ "kv_list" => {
+ let args = parse::<ConsulKvListArgs>(args)?;
+ let limit = args.limit.unwrap_or(100).clamp(1, MAX_KV_LIST);
+ to_json(
+ consul::consul_list_prefix_core(state, id, &args.prefix, limit, args.continuation.as_deref()).await?,
+ )
+ }
+ "kv_get" => to_json(consul::consul_get_core(state, id, &parse::<ConsulKvKeyArgs>(args)?.key).await?),
+ "kv_put" => {
+ let args = parse::<ConsulKvPutArgs>(args)?;
+ let options = args.options()?;
+ let value = KvValue {
+ encoding: if args.base64 { KvValueEncoding::Base64 } else { KvValueEncoding::Utf8 },
+ data: args.value,
+ };
+ to_json(consul::consul_put_core(state, id, &args.key, value, options).await?)
+ }
+ "kv_delete" => {
+ let args = parse::<ConsulKvDeleteArgs>(args)?;
+ let options = KvDeleteOptions { expected_mod_revision: args.cas.map(Into::into), ..Default::default() };
+ to_json(consul::consul_delete_core(state, id, &args.key, options).await?)
+ }
+ "list_datacenters" => to_json(consul::consul_catalog_datacenters_core(state, id).await?),
+ "list_services" => {
+ let args = parse::<ConsulFilterArgs>(args)?;
+ to_json(consul::consul_catalog_services_core(state, id, read_options(args.filter)).await?)
+ }
+ "list_nodes" => {
+ let args = parse::<ConsulFilterArgs>(args)?;
+ to_json(consul::consul_catalog_nodes_core(state, id, read_options(args.filter)).await?)
+ }
+ "service_health" => {
+ let args = parse::<ConsulServiceHealthArgs>(args)?;
+ to_json(
+ consul::consul_health_service_core(state, id, &args.service, args.passing, read_options(None)).await?,
+ )
+ }
+ "set_maintenance" => {
+ let args = parse::<ConsulMaintenanceArgs>(args)?;
+ to_json(
+ consul::consul_agent_service_maintenance_core(
+ state,
+ id,
+ &args.service_id,
+ args.enable,
+ args.reason.as_deref(),
+ )
+ .await?,
+ )
+ }
+ other => Err(format!("Unknown Consul operation `{other}`")),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn consul_put_preserves_create_only_and_revision_preconditions() {
+ use dbx_core::agent_kv::KvWriteMode;
+ let create = parse::<ConsulKvPutArgs>(&json!({"key":"new", "value":"v", "cas":0})).unwrap().options().unwrap();
+ assert!(matches!(create.write_mode, Some(KvWriteMode::Create)));
+ assert!(create.expected_mod_revision.is_none());
+ let update = parse::<ConsulKvPutArgs>(&json!({"key":"old", "value":"v", "cas":7})).unwrap().options().unwrap();
+ assert_eq!(update.expected_mod_revision.unwrap().as_str(), "7");
+ assert!(update.write_mode.is_none());
+ for cas in [json!(null), json!(-1)] {
+ assert!(parse::<ConsulKvPutArgs>(&json!({"key":"k", "value":"v", "cas":cas})).unwrap().options().is_err());
+ }
+ }
+
+ #[test]
+ fn product_metadata_matches_the_onboarding_spec() {
+ assert_eq!(Product::Nacos.scope_kind(), Some("namespace"));
+ assert_eq!(Product::Consul.scope_kind(), None);
+ assert_eq!(Product::Consul.as_str(), "consul");
+ }
+
+ #[test]
+ fn arguments_parse_into_core_types_and_report_bad_input() {
+ let key = parse::<dbx_core::nacos::NacosConfigKey>(
+ &json!({ "dataId": "app.yaml", "group": "DEFAULT_GROUP", "namespace": "dev" }),
+ )
+ .unwrap();
+ assert_eq!((key.data_id.as_str(), key.namespace.as_deref()), ("app.yaml", Some("dev")));
+ let error = parse::<dbx_core::nacos::NacosConfigKey>(&json!({ "group": "x" })).unwrap_err();
+ assert!(error.starts_with("INVALID_ARGUMENTS"), "{error}");
+ let search = parse::<dbx_core::nacos::NacosContentSearchRequest>(&json!({
+ "operationId": "op-1", "query": "host", "scope": "currentNamespace"
+ }))
+ .unwrap();
+ assert_eq!(search.operation_id, "op-1");
+ let rollback = parse::<dbx_core::nacos::NacosConfigRollbackRequest>(&json!({
+ "dataId": "app.yaml", "group": "DEFAULT_GROUP", "historyId": "h1"
+ }))
+ .unwrap();
+ assert_eq!(rollback.history_id, "h1");
+ let registration = parse::<dbx_core::nacos::NacosInstanceRegistration>(&json!({
+ "serviceName": "api", "ip": "127.0.0.1", "port": 8080
+ }))
+ .unwrap();
+ assert_eq!((registration.service_name, registration.port), ("api".into(), 8080));
+ let deregistration = parse::<dbx_core::nacos::NacosInstanceRef>(&json!({
+ "serviceName": "api", "ip": "127.0.0.1", "port": 8080
+ }))
+ .unwrap();
+ assert_eq!(deregistration.service_name, "api");
+ let put = parse::<ConsulKvPutArgs>(&json!({ "key": "a/b", "value": "1", "cas": 7 })).unwrap();
+ assert_eq!((put.key.as_str(), put.cas, put.base64), ("a/b", Some(7), false));
+ }
+}
diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rs
index c8844086b8..a8cd937b72 100644
--- a/crates/dbx-mcp/src/server.rs
+++ b/crates/dbx-mcp/src/server.rs
@@ -1,4 +1,9 @@
-use std::{collections::HashMap, sync::Arc, time::Duration, time::Instant};
+use std::{
+ collections::{HashMap, HashSet},
+ sync::Arc,
+ time::Duration,
+ time::Instant,
+};
use rmcp::{
handler::server::{router::tool::ToolRouter, wrapper::Parameters},
@@ -16,6 +21,7 @@ use uuid::Uuid;
use crate::backend::{format_query_result, new_connection_config, parse_database_type, ConnectionSummary, DbxBackend};
use crate::mongo::{self, MongoCommand, MongoSafetyError};
+use crate::runtime::McpTransport;
use crate::session::{McpSession, McpSessionStore};
use crate::transaction::{TransactionFailure, TransactionResult, TransactionStatus};
use dbx_core::{
@@ -30,6 +36,7 @@ use dbx_core::{
self as docs_notes, SchemaNoteBudget, SCHEMA_NOTE_COLUMN_MAX_CHARS, SCHEMA_NOTE_TABLE_MAX_CHARS,
},
history::HistoryEntry,
+ mcp_access::{McpAccessLevel, McpCallDecision, McpConfirmPolicy},
mcp_policy::connection_allows_salesforce_dml,
models::connection::ConnectionConfig,
models::connection::DatabaseType,
@@ -105,6 +112,220 @@ pub struct ConnectionSelector {
pub connection_name: Option<String>,
}
+// ---------- Product providers: Nacos ----------
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosNamespacesRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosListConfigsRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ #[schemars(description = "Namespace id; omit for the connection's default namespace")]
+ pub namespace: Option<String>,
+ #[schemars(description = "Exact group name filter")]
+ pub group: Option<String>,
+ #[schemars(description = "dataId filter (supports * wildcards)")]
+ pub data_id: Option<String>,
+ #[schemars(description = "Free-text search over dataId and group")]
+ pub search: Option<String>,
+ #[schemars(description = "Page number, starting at 1")]
+ pub page_no: Option<u32>,
+ #[schemars(description = "Page size (default 20, max 100)")]
+ pub page_size: Option<u32>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosConfigKeyRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub namespace: Option<String>,
+ #[schemars(description = "Configuration dataId")]
+ pub data_id: String,
+ #[schemars(description = "Configuration group, e.g. DEFAULT_GROUP")]
+ pub group: String,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosPublishConfigRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub namespace: Option<String>,
+ pub data_id: String,
+ pub group: String,
+ #[schemars(description = "Full configuration content")]
+ pub content: String,
+ #[schemars(description = "Content type: text, json, yaml, properties, xml, html")]
+ pub config_type: Option<String>,
+ #[schemars(description = "Compare-and-set: the current content MD5; the publish fails when it changed")]
+ pub cas_md5: Option<String>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosSearchConfigsRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub operation_id: String,
+ pub namespace: Option<String>,
+ #[serde(default)]
+ pub scope: Option<String>,
+ pub query: String,
+ pub group: Option<String>,
+ pub data_id: Option<String>,
+ pub max_results: Option<usize>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosRollbackConfigRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub namespace: Option<String>,
+ pub data_id: String,
+ pub group: String,
+ pub history_id: String,
+ pub nid: Option<i64>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosServicesRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub namespace: Option<String>,
+ pub group_name: Option<String>,
+ #[schemars(description = "Service name filter")]
+ pub service_name: Option<String>,
+ pub page_no: Option<u32>,
+ pub page_size: Option<u32>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosInstancesRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub namespace: Option<String>,
+ pub service_name: String,
+ pub group_name: Option<String>,
+ #[schemars(description = "Comma-separated cluster names")]
+ pub clusters: Option<String>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosUpdateInstanceRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub namespace: Option<String>,
+ pub service_name: String,
+ pub group_name: Option<String>,
+ pub cluster_name: Option<String>,
+ pub ip: String,
+ pub port: u16,
+ #[schemars(description = "Bring the instance online (true) or take it offline (false)")]
+ pub enabled: Option<bool>,
+ #[schemars(description = "New load-balancing weight")]
+ pub weight: Option<f64>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosRegisterInstanceRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub namespace: Option<String>,
+ pub service_name: String,
+ pub ip: String,
+ pub port: u16,
+ pub group_name: Option<String>,
+ pub cluster_name: Option<String>,
+ pub weight: Option<f64>,
+ pub metadata: Option<serde_json::Value>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct NacosDeregisterInstanceRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub namespace: Option<String>,
+ pub service_name: String,
+ pub ip: String,
+ pub port: u16,
+ pub group_name: Option<String>,
+ pub cluster_name: Option<String>,
+ pub ephemeral: Option<bool>,
+}
+
+// ---------- Product providers: Consul ----------
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct ConsulKvListRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ #[schemars(description = "Key prefix; empty lists the root")]
+ pub prefix: Option<String>,
+ #[schemars(description = "Maximum keys to return (default 100, max 500)")]
+ pub limit: Option<usize>,
+ #[schemars(description = "Continuation token from a previous page")]
+ pub continuation: Option<String>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct ConsulKvKeyRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub key: String,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct ConsulKvPutRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub key: String,
+ #[schemars(description = "Value; UTF-8 text unless base64 is true")]
+ pub value: String,
+ #[schemars(description = "The value is base64-encoded binary")]
+ pub base64: Option<bool>,
+ #[schemars(description = "Compare-and-set: the key's ModifyIndex; 0 creates only when absent")]
+ pub cas: Option<i64>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct ConsulKvDeleteRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub key: String,
+ #[schemars(description = "Compare-and-set: the key's ModifyIndex")]
+ pub cas: Option<i64>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct ConsulFilterRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ #[schemars(description = "Consul filter expression")]
+ pub filter: Option<String>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct ConsulServiceHealthRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ pub service: String,
+ #[schemars(description = "Only instances whose checks pass")]
+ pub passing: Option<bool>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct ConsulMaintenanceRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ #[schemars(description = "Agent service id")]
+ pub service_id: String,
+ #[schemars(description = "true enters maintenance (takes the service out of rotation)")]
+ pub enable: bool,
+ pub reason: Option<String>,
+}
+
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ListTablesRequest {
#[serde(flatten)]
@@ -549,6 +770,29 @@ tokio::task_local! {
static CALL_HISTORY: std::sync::Mutex<HistoryEntry>;
}
+fn update_call_history_details<F>(update: F)
+where
+ F: FnOnce(&mut serde_json::Map<String, serde_json::Value>),
+{
+ let _ = CALL_HISTORY.try_with(|current| {
+ let mut entry = current.lock().unwrap();
+ let mut details = entry
+ .details_json
+ .as_deref()
+ .and_then(|value| serde_json::from_str::<serde_json::Value>(value).ok())
+ .and_then(|value| value.as_object().cloned())
+ .unwrap_or_default();
+ update(&mut details);
+ entry.details_json = Some(serde_json::Value::Object(details).to_string());
+ });
+}
+
+fn mark_call_confirmation(status: &'static str) {
+ update_call_history_details(|details| {
+ details.insert("confirmation".into(), json!(status));
+ });
+}
+
struct CallHistoryGuard {
backend: Arc<dyn DbxBackend>,
fallback: Option<HistoryEntry>,
@@ -701,31 +945,38 @@ pub struct DbxMcpServer {
plugin_tools_mode: PluginToolsMode,
sessions: Arc<McpSessionStore>,
pending_salesforce_writes: Arc<PendingSalesforceWrites>,
+ transport: McpTransport,
tool_router: ToolRouter<Self>,
}
/// How plugin tools appear on the external server (`DBX_MCP_PLUGIN_TOOLS`):
-/// `flat` lists every plugin tool in `tools/list` (default, compatible),
+/// `Auto` defers to the saved policy (new policies default to flat).
+/// `flat` lists every plugin tool in `tools/list`,
/// `lazy` exposes only the `dbx_plugin_*` meta tools so schemas enter the
/// context on demand, `both` advertises both views.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PluginToolsMode {
#[default]
+ Auto,
Flat,
Lazy,
Both,
}
impl PluginToolsMode {
- pub fn from_env() -> Self {
+ pub fn from_env_override() -> Option<Self> {
match std::env::var("DBX_MCP_PLUGIN_TOOLS").ok().as_deref().map(str::trim) {
- Some(value) if value.eq_ignore_ascii_case("lazy") => Self::Lazy,
- Some(value) if value.eq_ignore_ascii_case("both") => Self::Both,
- Some(value) if value.eq_ignore_ascii_case("flat") => Self::Flat,
- _ => Self::default(),
+ Some(value) if value.eq_ignore_ascii_case("lazy") => Some(Self::Lazy),
+ Some(value) if value.eq_ignore_ascii_case("both") => Some(Self::Both),
+ Some(value) if value.eq_ignore_ascii_case("flat") => Some(Self::Flat),
+ _ => None,
}
}
+ pub fn from_env() -> Self {
+ Self::from_env_override().unwrap_or_default()
+ }
+
pub fn advertise_flat(&self) -> bool {
matches!(self, Self::Flat | Self::Both)
}
@@ -795,8 +1046,247 @@ impl McpScope {
}
impl DbxMcpServer {
- /// A desktop confirmation can lift only the high-risk SQL tier for one
- /// already-scoped operation. All other policy checks run before the prompt.
+ /// Shared gate for product-provider tools (design §5): tool allowlist,
+ /// connection resolution and product type, sub-scope admission and level
+ /// from the v2 policy, connection read-only and production protection for
+ /// writes, then the backend call. Results are returned as pretty JSON.
+ async fn run_product_tool(
+ &self,
+ tool: &'static str,
+ selector: &ConnectionSelector,
+ product: crate::products::Product,
+ operation: &'static str,
+ level: dbx_core::mcp_access::McpAccessLevel,
+ scope_value: Option<&str>,
+ mut args: serde_json::Value,
+ ) -> CallToolResult {
+ use dbx_core::mcp_access::McpAccessLevel;
+ if let Err(error) = self.ensure_tool_allowed(tool).await {
+ return error;
+ }
+ let resolved = match self.resolve_connection(selector).await {
+ Ok(resolved) => resolved,
+ Err(error) => return error,
+ };
+ let mut connection = resolved.connection.clone();
+ let expected = match product {
+ crate::products::Product::Nacos => DatabaseType::Nacos,
+ crate::products::Product::Consul => DatabaseType::Consul,
+ };
+ if connection.db_type != expected {
+ let available = dbx_core::mcp_catalog::TOOLS
+ .iter()
+ .filter(|descriptor| descriptor.coverage.database_types().contains(&connection.db_type))
+ .map(|descriptor| descriptor.name)
+ .collect::<Vec<_>>();
+ return tool_error(
+ "WRONG_CONNECTION_TYPE",
+ format!(
+ "\"{}\" is not a {} connection. Available MCP tools for {} connections: {}.",
+ connection.name,
+ product.as_str(),
+ connection.db_type.as_str(),
+ if available.is_empty() { "none".to_string() } else { available.join(", ") }
+ ),
+ );
+ }
+ let scope_kind = product.scope_kind();
+ let access = match self.backend.load_mcp_access_policy().await {
+ Ok(access) => access,
+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),
+ };
+ // Nacos APIs default to the connection's configured namespace when
+ // the request omits it. A cross-namespace search is the exception:
+ // it must be evaluated as an aggregate request, then admitted only
+ // when the policy allows every namespace.
+ let all_namespaces_search = product == crate::products::Product::Nacos
+ && operation == "search_configs"
+ && args.get("scope").and_then(serde_json::Value::as_str) == Some("allNamespaces");
+ let scope_value =
+ if product == crate::products::Product::Nacos && operation != "list_namespaces" && !all_namespaces_search {
+ // Nacos treats the empty id and `public` as the same namespace.
+ // Use one policy identity, including the connection default.
+ let namespace =
+ scope_value.unwrap_or_else(|| connection.database.as_deref().unwrap_or_default()).trim();
+ Some(if namespace.is_empty() { "public" } else { namespace }.to_owned())
+ } else {
+ scope_value.map(str::trim).filter(|value| !value.is_empty()).map(str::to_owned)
+ };
+ if let Some(namespace) = scope_value.as_deref() {
+ if product == crate::products::Product::Nacos {
+ let target = if operation == "update_instance" { args.get_mut("target") } else { Some(&mut args) };
+ if let Some(object) = target.and_then(serde_json::Value::as_object_mut) {
+ object.insert("namespace".to_string(), serde_json::Value::String(namespace.to_string()));
+ }
+ }
+ }
+ let resolved_access =
+ access.resolve(&resolved.group_ids, &connection.id, scope_kind.zip(scope_value.as_deref()));
+ let effective_level = dbx_core::mcp_catalog::descriptor(tool)
+ .and_then(|descriptor| access.toolset_ceiling(&connection.id, descriptor.toolset))
+ .map_or(resolved_access.level, |ceiling| resolved_access.level.min(ceiling));
+ if !resolved_access.visible {
+ return tool_error(
+ "SCOPE_OUT_OF_POLICY",
+ format!(
+ "{} \"{}\" is not allowed by DBX MCP settings for this connection.",
+ scope_kind.unwrap_or("connection"),
+ scope_value.as_deref().unwrap_or_default()
+ ),
+ );
+ }
+ if all_namespaces_search && !access.sub_scope_allows_all(&connection.id, "namespace") {
+ return tool_error(
+ "SCOPE_OUT_OF_POLICY",
+ "Searching all Nacos namespaces requires unrestricted namespace scope access.",
+ );
+ }
+ let required_level = if level == McpAccessLevel::Read { McpAccessLevel::Read } else { McpAccessLevel::Write };
+ if effective_level < required_level {
+ return tool_error(
+ "MCP_READ_ONLY",
+ format!(
+ "The effective MCP permission for this {} is insufficient for this operation.",
+ scope_kind.unwrap_or("connection")
+ ),
+ );
+ }
+ if level > McpAccessLevel::Read {
+ if connection.read_only {
+ return tool_error(
+ "CONNECTION_READ_ONLY",
+ format!("Connection \"{}\" has read-only protection enabled.", connection.name),
+ );
+ }
+ if is_production_database(&connection, scope_value.as_deref().unwrap_or_default()) {
+ return tool_error("PRODUCTION_WRITE_BLOCKED", "MCP cannot change a production connection.");
+ }
+ let policy = match self.load_policy().await {
+ Ok(policy) => policy,
+ Err(error) => return error,
+ };
+ let decision = policy.confirmation_policy().decide(effective_level, level, level == McpAccessLevel::Full);
+ if decision == McpCallDecision::Deny {
+ return tool_error("TOOL_BLOCKED", format!("{tool} exceeds the effective MCP permission."));
+ }
+ if decision == McpCallDecision::Confirm {
+ let request = crate::approval::ToolApprovalRequest::new(
+ crate::approval::ToolApprovalKind::ProductTool,
+ tool,
+ crate::approval::arguments_preview(&args),
+ )
+ .with_target(Some(&connection.id), scope_value.as_deref());
+ mark_call_confirmation("requested");
+ if let Err(error) = self.backend.approve_high_risk_tool(&request).await {
+ mark_call_confirmation("denied");
+ return tool_error("TOOL_BLOCKED", error);
+ }
+ mark_call_confirmation("confirmed");
+
+ // Authorization may change while the desktop dialog is open.
+ // Resolve the connection and both policy layers again before
+ // allowing the product request to reach its backend.
+ let refreshed = match self.resolve_connection(selector).await {
+ Ok(refreshed) => refreshed,
+ Err(error) => return error,
+ };
+ if refreshed.connection.db_type != expected {
+ return tool_error(
+ "WRONG_CONNECTION_TYPE",
+ "The connection type changed while approval was pending.",
+ );
+ }
+ let refreshed_policy = match self.load_policy().await {
+ Ok(policy) => policy,
+ Err(error) => return error,
+ };
+ if refreshed.connection != connection || !policy_allows_tool(&refreshed_policy, tool) {
+ return tool_error("TOOL_BLOCKED", "Product-tool approval was revoked while the dialog was open.");
+ }
+ let refreshed_access = match self.backend.load_mcp_access_policy().await {
+ Ok(access) => access,
+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),
+ };
+ let refreshed_scope = refreshed_access.resolve(
+ &refreshed.group_ids,
+ &refreshed.connection.id,
+ scope_kind.zip(scope_value.as_deref()),
+ );
+ let refreshed_level = dbx_core::mcp_catalog::descriptor(tool)
+ .and_then(|descriptor| {
+ refreshed_access.toolset_ceiling(&refreshed.connection.id, descriptor.toolset)
+ })
+ .map_or(refreshed_scope.level, |ceiling| refreshed_scope.level.min(ceiling));
+ if !refreshed_scope.visible
+ || refreshed_policy.confirmation_policy() != policy.confirmation_policy()
+ || refreshed_policy.confirmation_policy().decide(refreshed_level, level, true)
+ != McpCallDecision::Confirm
+ {
+ return tool_error(
+ "SCOPE_OUT_OF_POLICY",
+ "Product-tool approval was revoked while the dialog was open.",
+ );
+ }
+ if refreshed.connection.read_only {
+ return tool_error(
+ "CONNECTION_READ_ONLY",
+ "The connection became read-only while approval was pending.",
+ );
+ }
+ if is_production_database(&refreshed.connection, scope_value.as_deref().unwrap_or_default()) {
+ return tool_error(
+ "PRODUCTION_WRITE_BLOCKED",
+ "The connection became production while approval was pending.",
+ );
+ }
+ connection = refreshed.connection;
+ }
+ }
+ let _ = CALL_HISTORY.try_with(|entry| {
+ let mut entry = entry.lock().unwrap();
+ entry.connection_id = connection.id.clone();
+ entry.connection_name = connection.name.clone();
+ });
+ let call = crate::products::ProductCall { product, operation, args };
+ match self.backend.product_call(&connection, &call).await {
+ Ok(value) if product == crate::products::Product::Nacos && operation == "list_namespaces" => {
+ let filtered = value
+ .as_array()
+ .map(|items| {
+ items
+ .iter()
+ .filter(|item| {
+ item.get("namespace").and_then(serde_json::Value::as_str).is_some_and(|namespace| {
+ access.sub_scope_visible(
+ &connection.id,
+ "namespace",
+ if namespace.trim().is_empty() { "public" } else { namespace.trim() },
+ )
+ })
+ })
+ .cloned()
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default();
+ text(serde_json::to_string_pretty(&filtered).unwrap_or_else(|_| "[]".to_string()))
+ }
+ Ok(value) => text(serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string())),
+ Err(error) => backend_tool_error("DBX_TOOL_ERROR", error),
+ }
+ }
+
+ /// The built-in tool catalog for settings UIs, with each tool's advertised
+ /// description and parameters taken from this router so they cannot drift
+ /// from what MCP clients actually receive.
+ pub fn tool_catalog() -> dbx_core::mcp_catalog::McpToolCatalog {
+ let tools = Self::tool_router().list_all();
+ dbx_core::mcp_catalog::tool_catalog().with_router_details(tools.iter().map(|tool| {
+ (tool.name.as_ref(), tool.description.as_deref().unwrap_or_default(), tool.input_schema.as_ref())
+ }))
+ }
+
+ /// Authorize before prompting. Only the explicitly preserved legacy policy
+ /// may temporarily lift Write to Full; new confirmation never grants access.
async fn approved_sql_policy(
&self,
connection: &ConnectionConfig,
@@ -804,21 +1294,36 @@ impl DbxMcpServer {
database: &str,
sql: &str,
allow_database_switch: bool,
- bridge_execution: bool,
+ defer_token_consumption: bool,
) -> Result<(McpGlobalPolicy, Option<String>), CallToolResult> {
let high_risk = classify_sql_risk_for_database(sql, connection.db_type).is_ok_and(|risk| risk == SqlRisk::Ddl)
|| is_dangerous_sql_for_database(sql, connection.db_type);
- if policy.allow_dangerous_sql || !policy.prompt_high_risk_sql || !high_risk {
+ if !high_risk {
+ return Ok((policy.clone(), None));
+ }
+ let decision = policy.confirmation_policy().decide(
+ McpAccessLevel::from_flags(policy.read_only, policy.allow_dangerous_sql),
+ McpAccessLevel::Full,
+ true,
+ );
+ if decision == McpCallDecision::Deny {
+ validate_sql_policy(connection, policy, database, sql, allow_database_switch)?;
+ return Err(tool_error("SQL_BLOCKED", "High-risk SQL exceeds the effective MCP permission."));
+ }
+ if decision == McpCallDecision::Allow {
return Ok((policy.clone(), None));
}
let mut approved = policy.clone();
- approved.allow_dangerous_sql = true;
+ if policy.confirmation_policy() == McpConfirmPolicy::Full {
+ approved.allow_dangerous_sql = true;
+ }
validate_sql_policy(connection, &approved, database, sql, allow_database_switch)?;
- let token = self
- .backend
- .approve_high_risk_sql(&connection.id, database, sql)
- .await
- .map_err(|error| tool_error("SQL_BLOCKED", error))?;
+ mark_call_confirmation("requested");
+ let token = self.backend.approve_high_risk_sql(&connection.id, database, sql).await.map_err(|error| {
+ mark_call_confirmation("denied");
+ tool_error("SQL_BLOCKED", error)
+ })?;
+ mark_call_confirmation("confirmed");
// A user may change the scope, connection, or permissions while the dialog
// is open. The approval is valid only for the original target and SQL.
let refreshed = self
@@ -835,12 +1340,22 @@ impl DbxMcpServer {
ensure_sql_database_execution_scope(&refreshed.policy, connection, database, sql)?;
let mut current =
effective_policy_for_database_with_groups(&refreshed.policy, &refreshed.group_ids, connection, database);
- if !current.prompt_high_risk_sql || current.read_only {
+ if current.confirmation_policy() != policy.confirmation_policy()
+ || current.confirmation_policy().decide(
+ McpAccessLevel::from_flags(current.read_only, current.allow_dangerous_sql),
+ McpAccessLevel::Full,
+ true,
+ ) != McpCallDecision::Confirm
+ {
return Err(tool_error("SQL_BLOCKED", "High-risk SQL approval was revoked."));
}
- current.allow_dangerous_sql = true;
+ if current.confirmation_policy() == McpConfirmPolicy::Full {
+ current.allow_dangerous_sql = true;
+ }
validate_sql_policy(connection, &current, database, sql, allow_database_switch)?;
- if !bridge_execution {
+ // The desktop bridge and queued transaction calls consume the token
+ // at their final execution gate, keeping it revocable until then.
+ if !defer_token_consumption {
self.backend
.consume_high_risk_sql_approval(&token, &connection.id, database, sql)
.await
@@ -849,6 +1364,51 @@ impl DbxMcpServer {
Ok((current, Some(token)))
}
+ /// Recheck the approval after acquiring a transaction's execution lease.
+ /// A token from another confirmation mode must never grant permissions,
+ /// and an expired/revoked token must not survive time spent in the queue.
+ async fn queued_sql_permissions(
+ &self,
+ connection: &ConnectionConfig,
+ admitted_policy: &McpGlobalPolicy,
+ mut current: McpGlobalPolicy,
+ database: &str,
+ sql: &str,
+ token: Option<&str>,
+ ) -> Result<dbx_core::agent_tools::AgentSqlPermissions, CallToolResult> {
+ let high_risk = classify_sql_risk_for_database(sql, connection.db_type).is_ok_and(|risk| risk == SqlRisk::Ddl)
+ || is_dangerous_sql_for_database(sql, connection.db_type);
+ if high_risk {
+ if current.confirmation_policy() != admitted_policy.confirmation_policy() {
+ return Err(tool_error("SQL_BLOCKED", "SQL confirmation policy changed while queued. Retry the call."));
+ }
+ let decision = current.confirmation_policy().decide(
+ McpAccessLevel::from_flags(current.read_only, current.allow_dangerous_sql),
+ McpAccessLevel::Full,
+ true,
+ );
+ if decision == McpCallDecision::Confirm {
+ if token.is_none() {
+ return Err(tool_error(
+ "SQL_BLOCKED",
+ "Queued high-risk SQL requires confirmation. Retry the call.",
+ ));
+ }
+ if current.confirmation_policy() == McpConfirmPolicy::Full {
+ current.allow_dangerous_sql = true;
+ }
+ }
+ }
+ let permissions = validate_sql_policy(connection, &current, database, sql, false)?;
+ if let Some(token) = token {
+ self.backend
+ .consume_high_risk_sql_approval(token, &connection.id, database, sql)
+ .await
+ .map_err(|error| tool_error("SQL_BLOCKED", error))?;
+ }
+ Ok(permissions)
+ }
+
pub fn new(backend: Arc<dyn DbxBackend>) -> Self {
Self::with_runtime_options(backend, McpScope::from_env(), std::env::var_os("DBX_WEB_URL").is_some())
}
@@ -897,6 +1457,13 @@ impl DbxMcpServer {
Self::build(backend, scope, web_mode, plugin_tools_mode, sessions, pending_salesforce_writes)
}
+ /// Overrides the transport label recorded in MCP call history. Embedded
+ /// HTTP servers use this after constructing a per-request server.
+ pub fn with_transport(mut self, transport: McpTransport) -> Self {
+ self.transport = transport;
+ self
+ }
+
fn build(
backend: Arc<dyn DbxBackend>,
scope: McpScope,
@@ -925,15 +1492,27 @@ impl DbxMcpServer {
tool_router.disable_route("dbx_send_message");
tool_router.disable_route("dbx_peek_messages");
}
- // In `flat` mode plugin tools are merged directly into tools/list and
- // the lazy meta tools would only duplicate them; in `lazy`/`both`
- // they stay enabled so clients can discover on demand.
- if !plugin_tools_mode.advertise_meta() {
+ // Explicit flat mode keeps the lazy meta routes out of the router.
+ // Auto retains them so saved mode changes can take effect; scoped
+ // sessions always use the flat, in-scope view.
+ if plugin_tools_mode == PluginToolsMode::Flat || scope.enabled() {
tool_router.disable_route("dbx_plugin_list");
tool_router.disable_route("dbx_plugin_tools");
tool_router.disable_route("dbx_plugin_call");
}
- Self { backend, scope, plugin_tools_mode, sessions, pending_salesforce_writes, tool_router }
+ // Plugin routes remain registered for the lifetime of the server.
+ // The effective flat/lazy mode is read from the current policy for
+ // every listing and call, so settings changes take effect without a
+ // transport restart.
+ Self {
+ backend,
+ scope,
+ plugin_tools_mode,
+ sessions,
+ pending_salesforce_writes,
+ transport: McpTransport::Stdio,
+ tool_router,
+ }
}
fn spawn_session_cleanup(&self, session: McpSession) -> tokio::sync::oneshot::Receiver<SessionCleanupResult> {
@@ -1043,7 +1622,16 @@ impl DbxMcpServer {
target: String::new(),
affected_rows,
rollback_sql: None,
- details_json: Some(r#"{"source":"mcp"}"#.to_string()),
+ details_json: Some(
+ json!({
+ "source": "mcp",
+ "transport": "stdio",
+ "accessLevel": "full",
+ "accessMode": "classified",
+ "confirmation": "not_required",
+ })
+ .to_string(),
+ ),
source: "mcp".to_string(),
mcp_tool_name: Some(tool_name.to_string()),
mcp_request_json: None,
@@ -1074,33 +1662,517 @@ impl DbxMcpServer {
#[tool_router]
impl DbxMcpServer {
#[tool(
- name = "dbx_plugin_list",
- description = "List DBX plugins that contribute MCP tools. Returns each plugin's id, name, tool count, and the number of connections available for its tools. Use dbx_plugin_tools with a plugin id to inspect its tools; call them through dbx_plugin_call.",
+ name = "dbx_nacos_list_namespaces",
+ description = "List the namespaces of a Nacos connection that DBX can display. Use the namespace id in other dbx_nacos_* tools.",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
- async fn plugin_list(&self, Parameters(request): Parameters<PluginListRequest>) -> CallToolResult {
- if let Err(error) = self.ensure_tool_allowed("dbx_plugin_list").await {
- return error;
- }
- let (rows, note) = match self.plugin_tool_catalog().await {
- Ok(catalog) => catalog,
- Err(error) => return error,
- };
- let filter = request.filter.as_deref().map(str::trim).filter(|value| !value.is_empty());
- let mut lines = Vec::new();
- for (plugin_id, plugin_name, tool_count, connection_count) in &rows {
- let matches = |haystack: &str| -> bool {
- filter.is_none_or(|needle| haystack.to_ascii_lowercase().contains(&needle.to_ascii_lowercase()))
- };
- if filter.is_some() && !matches(plugin_id) && !matches(plugin_name) {
- continue;
- }
- lines.push(format!(
- "- {plugin_id} · {plugin_name} · {tool_count} tool(s) · {connection_count} allowed connection(s)"
- ));
- }
- if lines.is_empty() {
- return text(match (filter, &note) {
+ async fn nacos_list_namespaces(&self, Parameters(request): Parameters<NacosNamespacesRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ self.run_product_tool(
+ "dbx_nacos_list_namespaces",
+ &request.selector,
+ Nacos,
+ "list_namespaces",
+ Read,
+ None,
+ json!({}),
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_list_configs",
+ description = "List Nacos configurations (dataId, group) in a namespace, with optional group / dataId / text filters and paging.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_list_configs(&self, Parameters(request): Parameters<NacosListConfigsRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({
+ "namespace": request.namespace, "group": request.group, "dataId": request.data_id, "search": request.search,
+ "pageNo": request.page_no, "pageSize": request.page_size.map(|size| size.clamp(1, 100)),
+ });
+ self.run_product_tool(
+ "dbx_nacos_list_configs",
+ &request.selector,
+ Nacos,
+ "list_configs",
+ Read,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_get_config",
+ description = "Read one Nacos configuration's content and metadata (type, md5) by namespace, dataId and group.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_get_config(&self, Parameters(request): Parameters<NacosConfigKeyRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({ "namespace": request.namespace, "dataId": request.data_id, "group": request.group });
+ self.run_product_tool(
+ "dbx_nacos_get_config",
+ &request.selector,
+ Nacos,
+ "get_config",
+ Read,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_config_history",
+ description = "List the publish history of one Nacos configuration.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_config_history(&self, Parameters(request): Parameters<NacosConfigKeyRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({ "namespace": request.namespace, "dataId": request.data_id, "group": request.group });
+ self.run_product_tool(
+ "dbx_nacos_config_history",
+ &request.selector,
+ Nacos,
+ "config_history",
+ Read,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_publish_config",
+ description = "Create or overwrite one Nacos configuration. Pass cas_md5 (from dbx_nacos_get_config) to avoid overwriting a concurrent change.",
+ annotations(read_only_hint = false, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_publish_config(&self, Parameters(request): Parameters<NacosPublishConfigRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Write;
+ let args = json!({
+ "namespace": request.namespace, "dataId": request.data_id, "group": request.group, "content": request.content,
+ "configType": request.config_type, "casMd5": request.cas_md5,
+ });
+ self.run_product_tool(
+ "dbx_nacos_publish_config",
+ &request.selector,
+ Nacos,
+ "publish_config",
+ Write,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_search_configs",
+ description = "Search Nacos configuration content across the current namespace or all namespaces.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_search_configs(&self, Parameters(request): Parameters<NacosSearchConfigsRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({
+ "operationId": request.operation_id, "namespace": request.namespace,
+ "scope": request.scope.unwrap_or_else(|| "currentNamespace".into()),
+ "query": request.query, "group": request.group, "dataId": request.data_id, "maxResults": request.max_results,
+ });
+ self.run_product_tool(
+ "dbx_nacos_search_configs",
+ &request.selector,
+ Nacos,
+ "search_configs",
+ Read,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_rollback_config",
+ description = "Rollback a Nacos configuration to a selected history entry.",
+ annotations(read_only_hint = false, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_rollback_config(
+ &self,
+ Parameters(request): Parameters<NacosRollbackConfigRequest>,
+ ) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Write;
+ let args = json!({ "namespace": request.namespace, "dataId": request.data_id, "group": request.group, "historyId": request.history_id, "nid": request.nid });
+ self.run_product_tool(
+ "dbx_nacos_rollback_config",
+ &request.selector,
+ Nacos,
+ "rollback_config",
+ Write,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_delete_config",
+ description = "Delete one Nacos configuration. High-risk: allowed under a high-risk permission, or after desktop confirmation when enabled.",
+ annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_delete_config(&self, Parameters(request): Parameters<NacosConfigKeyRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Full;
+ let args = json!({ "namespace": request.namespace, "dataId": request.data_id, "group": request.group });
+ self.run_product_tool(
+ "dbx_nacos_delete_config",
+ &request.selector,
+ Nacos,
+ "delete_config",
+ Full,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_list_services",
+ description = "List Nacos services in a namespace, optionally filtered by group and service name.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_list_services(&self, Parameters(request): Parameters<NacosServicesRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({
+ "namespace": request.namespace, "groupName": request.group_name, "serviceName": request.service_name,
+ "pageNo": request.page_no, "pageSize": request.page_size.map(|size| size.clamp(1, 100)),
+ });
+ self.run_product_tool(
+ "dbx_nacos_list_services",
+ &request.selector,
+ Nacos,
+ "list_services",
+ Read,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_get_service",
+ description = "Get details for one Nacos service.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_get_service(&self, Parameters(request): Parameters<NacosServicesRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({ "namespace": request.namespace, "groupName": request.group_name, "serviceName": request.service_name, "pageNo": request.page_no, "pageSize": request.page_size });
+ self.run_product_tool(
+ "dbx_nacos_get_service",
+ &request.selector,
+ Nacos,
+ "get_service",
+ Read,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_list_instances",
+ description = "List the instances of one Nacos service with health, weight and enabled state.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_list_instances(&self, Parameters(request): Parameters<NacosInstancesRequest>) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({
+ "namespace": request.namespace, "serviceName": request.service_name, "groupName": request.group_name, "clusters": request.clusters,
+ });
+ self.run_product_tool(
+ "dbx_nacos_list_instances",
+ &request.selector,
+ Nacos,
+ "list_instances",
+ Read,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_update_instance",
+ description = "Bring a Nacos instance online/offline or change its weight.",
+ annotations(read_only_hint = false, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_update_instance(
+ &self,
+ Parameters(request): Parameters<NacosUpdateInstanceRequest>,
+ ) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Write;
+ if request.enabled.is_none() && request.weight.is_none() {
+ return tool_error("INVALID_ARGUMENTS", "Pass enabled and/or weight.");
+ }
+ let args = json!({
+ "target": {
+ "namespace": request.namespace, "serviceName": request.service_name, "groupName": request.group_name,
+ "clusterName": request.cluster_name, "ip": request.ip, "port": request.port,
+ },
+ "patch": { "enabled": request.enabled, "weight": request.weight },
+ });
+ self.run_product_tool(
+ "dbx_nacos_update_instance",
+ &request.selector,
+ Nacos,
+ "update_instance",
+ Write,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_register_instance",
+ description = "Register a persistent Nacos service instance (ephemeral=false).",
+ annotations(read_only_hint = false, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_register_instance(
+ &self,
+ Parameters(request): Parameters<NacosRegisterInstanceRequest>,
+ ) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Write;
+ let args = json!({
+ "namespace": request.namespace, "serviceName": request.service_name, "ip": request.ip, "port": request.port,
+ "groupName": request.group_name, "clusterName": request.cluster_name, "weight": request.weight, "metadata": request.metadata,
+ });
+ self.run_product_tool(
+ "dbx_nacos_register_instance",
+ &request.selector,
+ Nacos,
+ "register_instance",
+ Write,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_nacos_deregister_instance",
+ description = "Deregister a Nacos service instance. Defaults to persistent (ephemeral=false), matching dbx_nacos_register_instance; pass ephemeral=true for an ephemeral instance.",
+ annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn nacos_deregister_instance(
+ &self,
+ Parameters(request): Parameters<NacosDeregisterInstanceRequest>,
+ ) -> CallToolResult {
+ use crate::products::Product::Nacos;
+ use dbx_core::mcp_access::McpAccessLevel::Full;
+ let args = json!({
+ "namespace": request.namespace, "serviceName": request.service_name, "ip": request.ip, "port": request.port,
+ "groupName": request.group_name, "clusterName": request.cluster_name, "ephemeral": request.ephemeral,
+ });
+ self.run_product_tool(
+ "dbx_nacos_deregister_instance",
+ &request.selector,
+ Nacos,
+ "deregister_instance",
+ Full,
+ request.namespace.as_deref(),
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_consul_kv_list",
+ description = "List Consul KV keys under a prefix (one page; pass continuation for the next).",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn consul_kv_list(&self, Parameters(request): Parameters<ConsulKvListRequest>) -> CallToolResult {
+ use crate::products::Product::Consul;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({ "prefix": request.prefix.unwrap_or_default(), "limit": request.limit, "continuation": request.continuation });
+ self.run_product_tool("dbx_consul_kv_list", &request.selector, Consul, "kv_list", Read, None, args).await
+ }
+
+ #[tool(
+ name = "dbx_consul_kv_get",
+ description = "Read one Consul KV key: value and ModifyIndex (use it as cas for safe writes).",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn consul_kv_get(&self, Parameters(request): Parameters<ConsulKvKeyRequest>) -> CallToolResult {
+ use crate::products::Product::Consul;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ self.run_product_tool(
+ "dbx_consul_kv_get",
+ &request.selector,
+ Consul,
+ "kv_get",
+ Read,
+ None,
+ json!({ "key": request.key }),
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_consul_kv_put",
+ description = "Write one Consul KV key. cas is required: use 0 to create only when absent, or the ModifyIndex from dbx_consul_kv_get to update without overwriting a concurrent change.",
+ annotations(read_only_hint = false, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn consul_kv_put(&self, Parameters(request): Parameters<ConsulKvPutRequest>) -> CallToolResult {
+ use crate::products::Product::Consul;
+ use dbx_core::mcp_access::McpAccessLevel::Write;
+ let args = json!({ "key": request.key, "value": request.value, "base64": request.base64.unwrap_or(false), "cas": request.cas });
+ self.run_product_tool("dbx_consul_kv_put", &request.selector, Consul, "kv_put", Write, None, args).await
+ }
+
+ #[tool(
+ name = "dbx_consul_kv_delete",
+ description = "Delete one Consul KV key. High-risk: allowed under a high-risk permission, or after desktop confirmation when enabled.",
+ annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn consul_kv_delete(&self, Parameters(request): Parameters<ConsulKvDeleteRequest>) -> CallToolResult {
+ use crate::products::Product::Consul;
+ use dbx_core::mcp_access::McpAccessLevel::Full;
+ let args = json!({ "key": request.key, "cas": request.cas });
+ self.run_product_tool("dbx_consul_kv_delete", &request.selector, Consul, "kv_delete", Full, None, args).await
+ }
+
+ #[tool(
+ name = "dbx_consul_list_services",
+ description = "List Consul catalog services with their tags.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn consul_list_services(&self, Parameters(request): Parameters<ConsulFilterRequest>) -> CallToolResult {
+ use crate::products::Product::Consul;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ self.run_product_tool(
+ "dbx_consul_list_services",
+ &request.selector,
+ Consul,
+ "list_services",
+ Read,
+ None,
+ json!({ "filter": request.filter }),
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_consul_list_nodes",
+ description = "List Consul catalog nodes.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn consul_list_nodes(&self, Parameters(request): Parameters<ConsulFilterRequest>) -> CallToolResult {
+ use crate::products::Product::Consul;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ self.run_product_tool(
+ "dbx_consul_list_nodes",
+ &request.selector,
+ Consul,
+ "list_nodes",
+ Read,
+ None,
+ json!({ "filter": request.filter }),
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_consul_service_health",
+ description = "List the instances of one Consul service with their health checks.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn consul_service_health(
+ &self,
+ Parameters(request): Parameters<ConsulServiceHealthRequest>,
+ ) -> CallToolResult {
+ use crate::products::Product::Consul;
+ use dbx_core::mcp_access::McpAccessLevel::Read;
+ let args = json!({ "service": request.service, "passing": request.passing });
+ self.run_product_tool(
+ "dbx_consul_service_health",
+ &request.selector,
+ Consul,
+ "service_health",
+ Read,
+ None,
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_consul_set_maintenance",
+ description = "Put a Consul agent service into or out of maintenance mode.",
+ annotations(read_only_hint = false, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn consul_set_maintenance(
+ &self,
+ Parameters(request): Parameters<ConsulMaintenanceRequest>,
+ ) -> CallToolResult {
+ use crate::products::Product::Consul;
+ use dbx_core::mcp_access::McpAccessLevel::Write;
+ let args = json!({ "serviceId": request.service_id, "enable": request.enable, "reason": request.reason });
+ self.run_product_tool(
+ "dbx_consul_set_maintenance",
+ &request.selector,
+ Consul,
+ "set_maintenance",
+ Write,
+ None,
+ args,
+ )
+ .await
+ }
+
+ #[tool(
+ name = "dbx_plugin_list",
+ description = "List DBX plugins that contribute MCP tools. Returns each plugin's id, name, tool count, and the number of connections available for its tools. Use dbx_plugin_tools with a plugin id to inspect its tools; call them through dbx_plugin_call.",
+ annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
+ )]
+ async fn plugin_list(&self, Parameters(request): Parameters<PluginListRequest>) -> CallToolResult {
+ if let Err(error) = self.ensure_tool_allowed("dbx_plugin_list").await {
+ return error;
+ }
+ if let Err(error) =
+ self.ensure_global_mcp_access(dbx_core::mcp_access::McpAccessLevel::Read, "dbx_plugin_list").await
+ {
+ return error;
+ }
+ let (rows, note) = match self.plugin_tool_catalog().await {
+ Ok(catalog) => catalog,
+ Err(error) => return error,
+ };
+ let filter = request.filter.as_deref().map(str::trim).filter(|value| !value.is_empty());
+ let mut lines = Vec::new();
+ for (plugin_id, plugin_name, tool_count, connection_count) in &rows {
+ let matches = |haystack: &str| -> bool {
+ filter.is_none_or(|needle| haystack.to_ascii_lowercase().contains(&needle.to_ascii_lowercase()))
+ };
+ if filter.is_some() && !matches(plugin_id) && !matches(plugin_name) {
+ continue;
+ }
+ lines.push(format!(
+ "- {plugin_id} · {plugin_name} · {tool_count} tool(s) · {connection_count} allowed connection(s)"
+ ));
+ }
+ if lines.is_empty() {
+ return text(match (filter, &note) {
(Some(_), _) => "No DBX plugin matches the filter.".to_string(),
(None, Some(note)) => note.clone(),
(None, None) => "No DBX plugin contributes MCP tools.".to_string(),
@@ -1123,6 +2195,11 @@ impl DbxMcpServer {
if let Err(error) = self.ensure_tool_allowed("dbx_plugin_tools").await {
return error;
}
+ if let Err(error) =
+ self.ensure_global_mcp_access(dbx_core::mcp_access::McpAccessLevel::Read, "dbx_plugin_tools").await
+ {
+ return error;
+ }
let plugin_id = request.plugin_id.trim();
if plugin_id.is_empty() {
return tool_error("PLUGIN_ID_REQUIRED", "plugin_id is required; use dbx_plugin_list to find plugin ids.");
@@ -1136,7 +2213,7 @@ impl DbxMcpServer {
// allowlist filters the listing just like `tools/list`, with a count
// of hidden tools so the caller knows the view is narrowed.
let policy = self.load_policy().await.ok();
- let (owned, hidden) = {
+ let (mut owned, mut hidden) = {
let owned: Vec<&crate::plugin_tools::PluginToolEntry> = entries
.iter()
.filter(|entry| {
@@ -1148,30 +2225,60 @@ impl DbxMcpServer {
let hidden = total - owned.len();
(owned, hidden)
};
- if owned.is_empty() {
- // An all-allowlist-hidden plugin and a nonexistent one answer
- // identically, so this meta tool cannot fingerprint installed
- // plugin ids. dbx_plugin_list stays the enumeration surface and
- // only shows what the caller may see.
- return tool_error(
- "PLUGIN_NOT_FOUND",
- format!(
- "Plugin \"{plugin_id}\" does not contribute visible MCP tools. It may not exist, may not contribute tools, or every tool may be hidden by the DBX MCP settings. Use dbx_plugin_list to list visible plugins."
- ),
- );
- }
- let allowed = match self.allowed_plugin_connections_for(plugin_id).await {
+ let allowed_connections = match self.allowed_plugin_connections_for(plugin_id).await {
Ok(allowed) => allowed,
Err(error) => return error,
};
- if self.scope.enabled() && allowed.is_empty() {
+ if self.scope.enabled() && allowed_connections.is_empty() {
return tool_error(
"PLUGIN_OUT_OF_SCOPE",
format!("Plugin \"{plugin_id}\" has no connection inside the current DBX MCP session scope."),
);
}
+ let access = self.backend.load_mcp_access_policy().await.ok();
+ let group_paths = match (access.as_ref(), policy.as_ref()) {
+ (Some(_), Some(policy)) => self.load_group_paths_for_policy(policy).await.ok(),
+ _ => None,
+ };
+ let connection_hidden = owned
+ .iter()
+ .filter(|entry| {
+ !plugin_entry_has_allowed_connection(access.as_ref(), group_paths.as_ref(), entry, &allowed_connections)
+ })
+ .count();
+ hidden += connection_hidden;
+ owned.retain(|entry| {
+ plugin_entry_has_allowed_connection(access.as_ref(), group_paths.as_ref(), entry, &allowed_connections)
+ });
+ if owned.is_empty() {
+ // An all-allowlist-hidden plugin, a plugin with no usable
+ // connection, and a nonexistent one answer identically, so this
+ // meta tool cannot fingerprint installed plugin ids. dbx_plugin_list
+ // stays the enumeration surface and only shows visible plugins.
+ return tool_error(
+ "PLUGIN_NOT_FOUND",
+ format!(
+ "Plugin \"{plugin_id}\" does not contribute visible MCP tools. It may not exist, may not contribute tools, or every tool may be hidden by the DBX MCP settings. Use dbx_plugin_list to list visible plugins."
+ ),
+ );
+ }
let mut lines = Vec::new();
for entry in &owned {
+ let entry_connections = match (&access, &group_paths) {
+ (Some(access), Some(group_paths)) => allowed_connections
+ .iter()
+ .filter(|(connection_id, _)| {
+ plugin_connection_level_allowed(
+ access,
+ group_paths.get(connection_id).map(|path| path.ids.as_slice()).unwrap_or(&[]),
+ entry,
+ connection_id,
+ )
+ })
+ .cloned()
+ .collect::<Vec<_>>(),
+ _ => allowed_connections.clone(),
+ };
let mut line = format!(
"### {}\n{}",
entry.tool.name,
@@ -1180,23 +2287,26 @@ impl DbxMcpServer {
if entry.tool.read_only {
line.push_str("\nRead-only.");
}
- let schema = crate::plugin_tools::external_tool_parameters(&entry.tool.input_schema, &allowed);
+ let schema = crate::plugin_tools::external_tool_parameters(&entry.tool.input_schema, &entry_connections);
line.push_str(&format!("\nArguments schema: {schema}"));
if entry.injects_connection_id {
line.push_str("\nThe host injects the bound connection's id automatically.");
}
lines.push(line);
}
- let connection_note = match allowed.len() {
+ let connection_note = match allowed_connections.len() {
0 => "No allowed connection is configured for this plugin; only connection-less tools can run.".to_string(),
- 1 => format!("Tools run on connection {} ({}); you may omit dbx_connection.", allowed[0].0, allowed[0].1),
+ 1 => format!(
+ "Tools run on connection {} ({}); you may omit dbx_connection.",
+ allowed_connections[0].0, allowed_connections[0].1
+ ),
_ => format!(
"Pass dbx_connection to choose among: {}",
- allowed.iter().map(|(id, name)| format!("{id} = {name}")).collect::<Vec<_>>().join("; ")
+ allowed_connections.iter().map(|(id, name)| format!("{id} = {name}")).collect::<Vec<_>>().join("; ")
),
};
let hidden_note = (hidden > 0)
- .then(|| format!("\n{} further tool(s) of this plugin are hidden by the DBX MCP tool allowlist.", hidden));
+ .then(|| format!("\n{} further tool(s) of this plugin are hidden by the DBX MCP settings.", hidden));
text(format!(
"{} tool(s) of plugin {plugin_id}:\n\n{}\n\n{connection_note}\nCall through dbx_plugin_call (plugin_id + tool + arguments).{}",
owned.len(),
@@ -1253,6 +2363,11 @@ impl DbxMcpServer {
if let Err(error) = self.ensure_tool_allowed("dbx_list_connections").await {
return error;
}
+ if let Err(error) =
+ self.ensure_global_mcp_access(dbx_core::mcp_access::McpAccessLevel::Read, "dbx_list_connections").await
+ {
+ return error;
+ }
match self.load_scoped_connections().await {
Ok(connections) if connections.is_empty() => text("No connections configured in DBX."),
Ok(connections) => {
@@ -1633,6 +2748,56 @@ impl DbxMcpServer {
Ok(command) => command,
Err(error) => return error,
};
+ if policy.confirmation_policy() == McpConfirmPolicy::HighRisk
+ && (command.is_dangerous() || command.has_effectively_unbounded_filter())
+ {
+ // Mongo's authorization (including aggregate output scopes) was
+ // checked above. Confirmation cannot relax any of those checks.
+ let target_database = match &command {
+ MongoCommand::InDatabase { database, .. } => database.as_str(),
+ _ => &database,
+ };
+ let approval = crate::approval::ToolApprovalRequest::new(
+ crate::approval::ToolApprovalKind::MongoCommand,
+ "dbx_execute_query",
+ &request.sql,
+ )
+ .with_target(Some(&connection.id), Some(target_database));
+ mark_call_confirmation("requested");
+ if let Err(error) = self.backend.approve_high_risk_tool(&approval).await {
+ mark_call_confirmation("denied");
+ return tool_error("TOOL_BLOCKED", error);
+ }
+ mark_call_confirmation("confirmed");
+ if let Err(error) = self.ensure_tool_allowed("dbx_execute_query").await {
+ return error;
+ }
+ let refreshed = match self
+ .resolve_connection(&ConnectionSelector {
+ connection_id: Some(connection.id.clone()),
+ connection_name: None,
+ })
+ .await
+ {
+ Ok(value) => value,
+ Err(error) => return error,
+ };
+ if refreshed.connection != *connection
+ || refreshed.policy.confirmation_policy() != McpConfirmPolicy::HighRisk
+ {
+ return tool_error("TOOL_BLOCKED", "MongoDB call approval was revoked.");
+ }
+ if let Err(error) = validate_mongo_command_with_groups(
+ &refreshed.connection,
+ &refreshed.policy,
+ &refreshed.group_ids,
+ &refreshed.database_scope,
+ &database,
+ &request.sql,
+ ) {
+ return error;
+ }
+ }
return match self.backend.execute_mongo_command(connection, &database, &command).await {
Ok(result) => match explicit_cell_window {
Some(window) => match format_query_result_as_text(&result, 100, window) {
@@ -1660,12 +2825,24 @@ impl DbxMcpServer {
}
}
let (policy, approval_token) = match self
- .approved_sql_policy(connection, &policy, &database, &request.sql, allow_database_switch, false)
+ .approved_sql_policy(
+ connection,
+ &policy,
+ &database,
+ &request.sql,
+ allow_database_switch,
+ session.as_ref().is_some_and(|session| session.transaction_owner.is_some()),
+ )
.await
{
Ok(approval) => approval,
Err(error) => return error,
};
+ if approval_token.is_some() {
+ if let Err(error) = self.ensure_tool_allowed("dbx_execute_query").await {
+ return error;
+ }
+ }
let permissions = match validate_sql_policy(connection, &policy, &database, &request.sql, allow_database_switch)
{
Ok(permissions) => permissions,
@@ -1726,22 +2903,23 @@ impl DbxMcpServer {
) {
return error;
}
- let mut refreshed_policy = effective_policy_for_database_with_groups(
+ let refreshed_policy = effective_policy_for_database_with_groups(
&refreshed.policy,
&refreshed.group_ids,
&refreshed.connection,
&session.database,
);
- if approval_token.is_some() && refreshed_policy.prompt_high_risk_sql && !refreshed_policy.read_only {
- refreshed_policy.allow_dangerous_sql = true;
- }
- let refreshed_permissions = match validate_sql_policy(
- &refreshed.connection,
- &refreshed_policy,
- &session.database,
- &request.sql,
- false,
- ) {
+ let refreshed_permissions = match self
+ .queued_sql_permissions(
+ &refreshed.connection,
+ &policy,
+ refreshed_policy,
+ &session.database,
+ &request.sql,
+ approval_token.as_deref(),
+ )
+ .await
+ {
Ok(permissions) => permissions,
Err(error) => return error,
};
@@ -1984,11 +3162,25 @@ 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 (policy, approval_token) =
- match self.approved_sql_policy(connection, &policy, &database, sql, allow_database_switch, false).await {
- Ok(approval) => approval,
- Err(error) => return error,
- };
+ let (policy, approval_token) = match self
+ .approved_sql_policy(
+ connection,
+ &policy,
+ &database,
+ sql,
+ allow_database_switch,
+ session.as_ref().is_some_and(|session| session.transaction_owner.is_some()),
+ )
+ .await
+ {
+ Ok(approval) => approval,
+ Err(error) => return error,
+ };
+ if approval_token.is_some() {
+ if let Err(error) = self.ensure_tool_allowed("dbx_execute_batch").await {
+ return error;
+ }
+ }
let permissions = match validate_sql_policy(connection, &policy, &database, sql, allow_database_switch) {
Ok(permissions) => permissions,
Err(error) => return error,
@@ -2047,20 +3239,26 @@ impl DbxMcpServer {
{
return error;
}
- let mut refreshed_policy = effective_policy_for_database_with_groups(
+ let refreshed_policy = effective_policy_for_database_with_groups(
&refreshed.policy,
&refreshed.group_ids,
&refreshed.connection,
&session.database,
);
- if approval_token.is_some() && refreshed_policy.prompt_high_risk_sql && !refreshed_policy.read_only {
- refreshed_policy.allow_dangerous_sql = true;
- }
- let refreshed_permissions =
- match validate_sql_policy(&refreshed.connection, &refreshed_policy, &session.database, sql, false) {
- Ok(permissions) => permissions,
- Err(error) => return error,
- };
+ let refreshed_permissions = match self
+ .queued_sql_permissions(
+ &refreshed.connection,
+ &policy,
+ refreshed_policy,
+ &session.database,
+ sql,
+ approval_token.as_deref(),
+ )
+ .await
+ {
+ Ok(permissions) => permissions,
+ Err(error) => return error,
+ };
if let Some(message) = confirmed_batch_sql_block_reason(
sql,
refreshed.connection.db_type,
@@ -2518,8 +3716,29 @@ impl DbxMcpServer {
connection,
&database.to_string(),
);
- let permissions = mcp_permissions(connection, &policy);
- if safety != RedisCommandSafety::Allowed && policy.read_only {
+ let access = match self.backend.load_mcp_access_policy().await {
+ Ok(access) => access,
+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),
+ };
+ let scoped_access = redis_database_access(&access, &resolved.group_ids, &connection.id, database);
+ let effective_level = access
+ .toolset_ceiling(&connection.id, "redis")
+ .map_or(scoped_access.level, |ceiling| scoped_access.level.min(ceiling));
+ let required_level = if safety == RedisCommandSafety::Allowed {
+ dbx_core::mcp_access::McpAccessLevel::Read
+ } else {
+ dbx_core::mcp_access::McpAccessLevel::Write
+ };
+ if !scoped_access.visible {
+ return tool_error("SCOPE_OUT_OF_POLICY", "Redis database is not allowed by DBX MCP settings.");
+ }
+ if effective_level < required_level {
+ return tool_error("MCP_READ_ONLY", "The effective MCP permission for this Redis database is read-only.");
+ }
+ let mut effective_policy = policy.clone();
+ (effective_policy.read_only, effective_policy.allow_dangerous_sql) = effective_level.to_flags();
+ let permissions = mcp_permissions(connection, &effective_policy);
+ if safety != RedisCommandSafety::Allowed && effective_policy.read_only {
return tool_error(
"MCP_READ_ONLY",
format!("MCP execution permission for Redis database {database} is read-only. Redis command blocked."),
@@ -2531,11 +3750,71 @@ impl DbxMcpServer {
format!("Connection \"{}\" has read-only protection enabled. Redis command blocked.", connection.name),
);
}
- if safety == RedisCommandSafety::Blocked && !permissions.allow_dangerous {
+ let mut permissions = permissions;
+ let decision = policy.confirmation_policy().decide(
+ effective_level,
+ if safety == RedisCommandSafety::Blocked { McpAccessLevel::Full } else { required_level },
+ safety == RedisCommandSafety::Blocked,
+ );
+ if decision == McpCallDecision::Deny {
return tool_error(
"REDIS_COMMAND_BLOCKED",
- format!("Dangerous Redis command \"{}\" is disabled in DBX MCP settings.", cmd_name),
+ format!("Dangerous Redis command \"{}\" exceeds the effective MCP permission.", cmd_name),
+ );
+ }
+ if safety != RedisCommandSafety::Allowed && is_production_database(connection, &database.to_string()) {
+ return tool_error("PRODUCTION_WRITE_BLOCKED", "MCP cannot change a production database.");
+ }
+ if decision == McpCallDecision::Confirm {
+ let request = crate::approval::ToolApprovalRequest::new(
+ crate::approval::ToolApprovalKind::RedisCommand,
+ "dbx_execute_redis_command",
+ request.command.clone(),
+ )
+ .with_target(Some(&connection.id), Some(&database.to_string()));
+ mark_call_confirmation("requested");
+ if let Err(error) = self.backend.approve_high_risk_tool(&request).await {
+ mark_call_confirmation("denied");
+ return tool_error("REDIS_COMMAND_BLOCKED", error);
+ }
+ mark_call_confirmation("confirmed");
+ // Re-read the policy: a revocation during the dialog wins.
+ if let Err(error) = self.ensure_tool_allowed("dbx_execute_redis_command").await {
+ return error;
+ }
+ let refreshed = match self
+ .resolve_connection(&ConnectionSelector {
+ connection_id: Some(connection.id.clone()),
+ connection_name: None,
+ })
+ .await
+ {
+ Ok(refreshed) => refreshed,
+ Err(error) => return error,
+ };
+ let current = effective_policy_for_database_with_groups(
+ &refreshed.policy,
+ &refreshed.group_ids,
+ &refreshed.connection,
+ &database.to_string(),
);
+ let access = match self.backend.load_mcp_access_policy().await {
+ Ok(access) => access,
+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),
+ };
+ let scoped = redis_database_access(&access, &refreshed.group_ids, &connection.id, database);
+ let level = access
+ .toolset_ceiling(&connection.id, "redis")
+ .map_or(scoped.level, |ceiling| scoped.level.min(ceiling));
+ if refreshed.connection != *connection
+ || !scoped.visible
+ || current.confirmation_policy() != policy.confirmation_policy()
+ || current.confirmation_policy().decide(level, McpAccessLevel::Full, true) != McpCallDecision::Confirm
+ || self.resolve_redis_database(Some(database), &refreshed).is_err()
+ {
+ return tool_error("REDIS_COMMAND_BLOCKED", "High-risk Redis command approval was revoked.");
+ }
+ permissions.allow_dangerous = true;
}
if safety != RedisCommandSafety::Allowed && !permissions.allow_writes {
return tool_error(
@@ -2664,6 +3943,26 @@ impl DbxMcpServer {
connection,
connection.database.as_deref().unwrap_or(""),
);
+ let access = match self.backend.load_mcp_access_policy().await {
+ Ok(access) => access,
+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),
+ };
+ let connection_access = access.resolve(&resolved.group_ids, &connection.id, None);
+ let effective_level = access
+ .toolset_ceiling(&connection.id, "mq")
+ .map_or(connection_access.level, |ceiling| connection_access.level.min(ceiling));
+ if !connection_access.visible {
+ return tool_error(
+ "SCOPE_OUT_OF_POLICY",
+ "The message-queue connection is not allowed by DBX MCP settings.",
+ );
+ }
+ if effective_level < dbx_core::mcp_access::McpAccessLevel::Write {
+ return tool_error(
+ "MCP_READ_ONLY",
+ "The effective MCP permission for this message-queue connection is read-only.",
+ );
+ }
if policy.read_only {
return tool_error(
"MCP_READ_ONLY",
@@ -2816,6 +4115,11 @@ impl DbxMcpServer {
if let Err(error) = self.ensure_tool_allowed("dbx_add_connection").await {
return error;
}
+ if let Err(error) =
+ self.ensure_global_mcp_access(dbx_core::mcp_access::McpAccessLevel::Write, "dbx_add_connection").await
+ {
+ return error;
+ }
let policy = match self.load_policy().await {
Ok(policy) => policy,
Err(error) => return error,
@@ -2874,6 +4178,11 @@ impl DbxMcpServer {
if let Err(error) = self.ensure_tool_allowed("dbx_duplicate_connection").await {
return error;
}
+ if let Err(error) =
+ self.ensure_global_mcp_access(dbx_core::mcp_access::McpAccessLevel::Write, "dbx_duplicate_connection").await
+ {
+ return error;
+ }
let policy = match self.load_policy().await {
Ok(policy) => policy,
Err(error) => return error,
@@ -2993,6 +4302,44 @@ impl DbxMcpServer {
format!("Connection \"{}\" is not allowed by DBX MCP settings.", target.id),
);
}
+ if let Err(error) =
+ self.ensure_global_mcp_access(dbx_core::mcp_access::McpAccessLevel::Full, "dbx_remove_connection").await
+ {
+ return error;
+ }
+ if policy.confirmation_policy() == McpConfirmPolicy::HighRisk {
+ let approval = crate::approval::ToolApprovalRequest::new(
+ crate::approval::ToolApprovalKind::ConnectionManagement,
+ "dbx_remove_connection",
+ format!("Remove connection: {} ({})", target.name, target.id),
+ )
+ .with_target(Some(&target.id), None);
+ mark_call_confirmation("requested");
+ if let Err(error) = self.backend.approve_high_risk_tool(&approval).await {
+ mark_call_confirmation("denied");
+ return tool_error("TOOL_BLOCKED", error);
+ }
+ mark_call_confirmation("confirmed");
+ if let Err(error) = self.ensure_tool_allowed("dbx_remove_connection").await {
+ return error;
+ }
+ if let Err(error) = self.ensure_global_mcp_access(McpAccessLevel::Full, "dbx_remove_connection").await {
+ return error;
+ }
+ let refreshed = match self
+ .resolve_connection(&ConnectionSelector {
+ connection_id: Some(target.id.clone()),
+ connection_name: None,
+ })
+ .await
+ {
+ Ok(value) => value,
+ Err(error) => return error,
+ };
+ if refreshed.connection != target || refreshed.policy.confirmation_policy() != McpConfirmPolicy::HighRisk {
+ return tool_error("TOOL_BLOCKED", "Connection removal approval was revoked.");
+ }
+ }
match self.backend.remove_connection_for_mcp(&target.id).await {
Ok(true) => text(format!("Connection \"{}\" (id: {}) removed.", target.name, target.id)),
Ok(false) => tool_error("CONNECTION_NOT_FOUND", format!("Connection \"{}\" not found.", target.name)),
@@ -3083,6 +4430,11 @@ impl DbxMcpServer {
Err(error) => return error,
}
};
+ if approval_token.is_some() {
+ if let Err(error) = self.ensure_tool_allowed("dbx_execute_and_show").await {
+ return error;
+ }
+ }
let permissions = if connection.db_type == DatabaseType::MongoDb {
mcp_permissions(connection, &policy)
} else {
@@ -3174,6 +4526,29 @@ impl DbxMcpServer {
if connection.db_type != DatabaseType::Salesforce {
return not_salesforce_error(connection);
}
+ if resolved.policy.read_only {
+ return tool_error(
+ "MCP_READ_ONLY",
+ "The effective MCP execution permission is read-only. Salesforce writes are blocked.",
+ );
+ }
+ let access = match self.backend.load_mcp_access_policy().await {
+ Ok(access) => access,
+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),
+ };
+ let resolved_access = access.resolve(&resolved.group_ids, &connection.id, None);
+ let effective_level = access
+ .toolset_ceiling(&connection.id, dbx_core::mcp_access::SALESFORCE_WRITE_TOOLSET)
+ .map_or(resolved_access.level, |ceiling| resolved_access.level.min(ceiling));
+ if !resolved_access.visible || effective_level < dbx_core::mcp_access::McpAccessLevel::Write {
+ return tool_error(
+ "SALESFORCE_DML_DISABLED",
+ format!(
+ "Salesforce writes are above the effective MCP access level for connection \"{}\".",
+ connection.name
+ ),
+ );
+ }
let database = match self.resolve_database(request.database, &resolved) {
Ok(database) => database,
Err(error) => return error,
@@ -3280,6 +4655,29 @@ impl DbxMcpServer {
if connection.db_type != DatabaseType::Salesforce {
return not_salesforce_error(connection);
}
+ if resolved.policy.read_only {
+ return tool_error(
+ "MCP_READ_ONLY",
+ "The effective MCP execution permission is read-only. Salesforce writes are blocked.",
+ );
+ }
+ let access = match self.backend.load_mcp_access_policy().await {
+ Ok(access) => access,
+ Err(error) => return backend_tool_error("MCP_POLICY_UNAVAILABLE", error),
+ };
+ let resolved_access = access.resolve(&resolved.group_ids, &connection.id, None);
+ let effective_level = access
+ .toolset_ceiling(&connection.id, dbx_core::mcp_access::SALESFORCE_WRITE_TOOLSET)
+ .map_or(resolved_access.level, |ceiling| resolved_access.level.min(ceiling));
+ if !resolved_access.visible || effective_level < dbx_core::mcp_access::McpAccessLevel::Write {
+ return tool_error(
+ "SALESFORCE_DML_DISABLED",
+ format!(
+ "Salesforce writes are above the effective MCP access level for connection \"{}\".",
+ connection.name
+ ),
+ );
+ }
if !connection_allows_salesforce_dml(&resolved.policy, &connection.id) {
return tool_error(
"SALESFORCE_DML_DISABLED",
@@ -3357,11 +4755,17 @@ 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 access = self.backend.load_mcp_access_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, group_paths.get(&connection.id), connection))
+ .filter(|connection| {
+ let group_ids = group_paths.get(&connection.id).map(|path| path.ids.as_slice()).unwrap_or(&[]);
+ let resolved = access.resolve(group_ids, &connection.id, None);
+ resolved.visible && resolved.level >= dbx_core::mcp_access::McpAccessLevel::Read
+ })
.filter(|connection| !self.scope.connection_scope_enabled() || self.scope.matches(connection))
.collect())
}
@@ -3439,46 +4843,225 @@ impl DbxMcpServer {
}
}
- /// Scoped-session and read-only enforcement shared by both plugin-tool
- /// call paths, closing the gap between what the flat `tools/list`
- /// advertises and what the lazy/meta surface executes:
- /// - under a read-only execution policy, only tools the plugin declares
- /// with `readOnlyHint` may run. The hint is the plugin author's claim,
- /// so the host defaults to deny for undeclared tools instead of
- /// letting an opaque write bypass the mode;
- /// - with a scope active, only plugins owning at least one in-scope
- /// connection stay callable — a connection-less tool of an
- /// out-of-scope plugin must not become a side door.
#[allow(clippy::result_large_err)]
- async fn ensure_plugin_tool_policy(
+ async fn ensure_global_mcp_access(
&self,
- entry: &crate::plugin_tools::PluginToolEntry,
+ required: dbx_core::mcp_access::McpAccessLevel,
+ tool_name: &str,
) -> Result<(), CallToolResult> {
- let policy = self.load_policy().await?;
- if policy.read_only && !entry.tool.read_only {
- return Err(tool_error(
+ let access = self
+ .backend
+ .load_mcp_access_policy()
+ .await
+ .map_err(|error| backend_tool_error("MCP_POLICY_UNAVAILABLE", error))?;
+ if access.default_access >= required {
+ Ok(())
+ } else {
+ Err(tool_error(
"MCP_READ_ONLY",
- format!(
- "Plugin tool \"{}\" is not declared read-only, but the DBX MCP execution policy is read-only.",
- entry.exposed_name
- ),
- ));
+ format!("Tool \"{tool_name}\" is above the effective global DBX MCP access level."),
+ ))
}
+ }
+
+ /// Resolves the plugin exposure mode at call time. Environment variables
+ /// are an explicit override; otherwise the persisted v1/v2 setting wins.
+ async fn effective_plugin_tools_mode(&self, policy: Option<&McpGlobalPolicy>) -> PluginToolsMode {
+ // Scoped routers have no lazy meta routes. This takes precedence over
+ // both saved settings and environment overrides, for lists and calls.
if self.scope.enabled() {
+ return PluginToolsMode::Flat;
+ }
+ if let Some(mode) = PluginToolsMode::from_env_override() {
+ return mode;
+ }
+ if self.plugin_tools_mode != PluginToolsMode::Auto {
+ return self.plugin_tools_mode;
+ }
+ let configured = policy
+ .map(|policy| match policy.plugin_tools_mode {
+ dbx_core::mcp_access::McpPluginToolsMode::Auto => PluginToolsMode::Auto,
+ dbx_core::mcp_access::McpPluginToolsMode::Flat => PluginToolsMode::Flat,
+ dbx_core::mcp_access::McpPluginToolsMode::Lazy => PluginToolsMode::Lazy,
+ })
+ .unwrap_or(PluginToolsMode::Flat);
+ if configured != PluginToolsMode::Auto {
+ return configured;
+ }
+ let count = self
+ .backend
+ .list_plugin_mcp_tools()
+ .await
+ .map(|providers| crate::plugin_tools::build_catalog(&providers).len())
+ .unwrap_or(0);
+ if count <= 40 {
+ PluginToolsMode::Flat
+ } else {
+ PluginToolsMode::Lazy
+ }
+ }
+
+ /// Both plugin dispatch paths share the resolved resource level. A global
+ /// default must neither widen a connection ceiling nor defeat an override.
+ #[allow(clippy::result_large_err)]
+ async fn ensure_plugin_tool_policy(
+ &self,
+ entry: &crate::plugin_tools::PluginToolEntry,
+ connection_id: Option<&str>,
+ arguments: &mut serde_json::Value,
+ ) -> Result<(), CallToolResult> {
+ // Policy values are trimmed when saved; forward the same canonical
+ // argument that is authorized, so sidecar trimming cannot change target.
+ if let Some((_, argument)) = &entry.scope {
+ if let Some(serde_json::Value::String(value)) = arguments.get_mut(argument) {
+ *value = value.trim().to_string();
+ }
+ }
+ let level = self.check_plugin_scope(entry, connection_id, arguments).await?;
+ let policy = self.load_policy().await?;
+ let connection = if let Some(id) = connection_id {
let allowed = self.allowed_plugin_connections().await?;
- if !allowed.contains_key(&entry.plugin_id) {
+ if !allowed
+ .get(&entry.plugin_id)
+ .is_some_and(|connections| connections.iter().any(|(candidate, _)| candidate == id))
+ {
+ return Err(tool_error("PLUGIN_OUT_OF_SCOPE", "Plugin connection is no longer allowed."));
+ }
+ let connection = self
+ .backend
+ .load_connections()
+ .await
+ .map_err(|error| backend_tool_error("CONNECTION_LOAD_ERROR", error))?
+ .into_iter()
+ .find(|connection| connection.id == id && connection.plugin_id.as_deref() == Some(&entry.plugin_id))
+ .ok_or_else(|| tool_error("CONNECTION_NOT_FOUND", "Plugin connection changed."))?;
+ if !entry.tool.read_only {
+ if connection.read_only {
+ return Err(tool_error(
+ "CONNECTION_READ_ONLY",
+ "Plugin connection has read-only protection enabled.",
+ ));
+ }
+ if is_production_database(&connection, connection.database.as_deref().unwrap_or_default()) {
+ return Err(tool_error(
+ "PRODUCTION_WRITE_BLOCKED",
+ "Plugin connection has production protection enabled.",
+ ));
+ }
+ }
+ Some(connection)
+ } else {
+ if self.scope.enabled() && !self.allowed_plugin_connections().await?.contains_key(&entry.plugin_id) {
return Err(tool_error(
"PLUGIN_OUT_OF_SCOPE",
- format!(
- "Plugin \"{}\" has no connection inside the current DBX MCP session scope.",
- entry.plugin_id
- ),
+ "Plugin has no connection inside the current MCP scope.",
));
}
+ None
+ };
+ let high_risk = plugin_tool_is_destructive(&entry.tool);
+ let decision = policy.confirmation_policy().decide(
+ level,
+ if high_risk { McpAccessLevel::Full } else { plugin_tool_required_access(entry) },
+ high_risk,
+ );
+ if decision == McpCallDecision::Deny {
+ return Err(tool_error(
+ "TOOL_BLOCKED",
+ "The effective MCP permission does not allow this high-risk plugin tool.",
+ ));
+ }
+ if decision == McpCallDecision::Confirm {
+ let scope = entry
+ .scope
+ .as_ref()
+ .and_then(|(_, argument)| arguments.get(argument))
+ .and_then(serde_json::Value::as_str);
+ let request = crate::approval::ToolApprovalRequest::new(
+ crate::approval::ToolApprovalKind::PluginTool,
+ &entry.exposed_name,
+ crate::approval::arguments_preview(arguments),
+ )
+ .with_plugin(&entry.plugin_name)
+ .with_target(connection_id, scope);
+ mark_call_confirmation("requested");
+ self.backend.approve_high_risk_tool(&request).await.map_err(|error| {
+ mark_call_confirmation("denied");
+ tool_error("TOOL_BLOCKED", error)
+ })?;
+ mark_call_confirmation("confirmed");
+ self.ensure_tool_allowed(&entry.exposed_name).await?;
+ let current = self.load_policy().await?;
+ let level = self.check_plugin_scope(entry, connection_id, arguments).await?;
+ if current.confirmation_policy() != policy.confirmation_policy()
+ || current.confirmation_policy().decide(level, McpAccessLevel::Full, true) != McpCallDecision::Confirm
+ {
+ return Err(tool_error("TOOL_BLOCKED", "High-risk tool approval was revoked."));
+ }
+ if let Some(connection) = connection {
+ let allowed = self.allowed_plugin_connections().await?;
+ let refreshed = self
+ .resolve_connection(&ConnectionSelector {
+ connection_id: Some(connection.id.clone()),
+ connection_name: None,
+ })
+ .await?;
+ if refreshed.connection != connection
+ || !allowed
+ .get(&entry.plugin_id)
+ .is_some_and(|connections| connections.iter().any(|(id, _)| id == &connection.id))
+ {
+ return Err(tool_error("TOOL_BLOCKED", "Plugin connection changed while the dialog was open."));
+ }
+ }
+ let current_entries = self
+ .backend
+ .list_plugin_mcp_tools()
+ .await
+ .map_err(|error| backend_tool_error("MCP_POLICY_UNAVAILABLE", error))?;
+ let still_exposed = crate::plugin_tools::build_catalog(&current_entries).into_iter().any(|candidate| {
+ candidate.exposed_name == entry.exposed_name
+ && candidate.plugin_id == entry.plugin_id
+ && candidate.tool.name == entry.tool.name
+ && candidate.tool.read_only == entry.tool.read_only
+ && candidate.tool.annotations == entry.tool.annotations
+ && candidate.scope == entry.scope
+ && candidate.toolset == entry.toolset
+ });
+ if !still_exposed {
+ return Err(tool_error("TOOL_BLOCKED", "Plugin-tool authorization changed while the dialog was open."));
+ }
}
Ok(())
}
+ /// Loads the v2 policy and group path, then applies [`ensure_plugin_scope`].
+ /// Only plugins that declare a scope pay for the extra loads.
+ #[allow(clippy::result_large_err)]
+ async fn check_plugin_scope(
+ &self,
+ entry: &crate::plugin_tools::PluginToolEntry,
+ connection_id: Option<&str>,
+ arguments: &serde_json::Value,
+ ) -> Result<dbx_core::mcp_access::McpAccessLevel, CallToolResult> {
+ let access = self
+ .backend
+ .load_mcp_access_policy()
+ .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);
+ }
+ 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 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 advertised `tools/list` view: router-enabled tools narrowed to the
/// global policy's tool allowlist, plus the automatically exposed plugin
/// tools (`dbx_<prefix>__<tool>`). When the policy cannot be loaded every
@@ -3486,16 +5069,46 @@ impl DbxMcpServer {
/// the plain router view rather than adding a new failure mode here.
pub async fn policy_filtered_tools(&self) -> Vec<rmcp::model::Tool> {
let policy = self.load_policy().await.ok();
+ let plugin_mode = self.effective_plugin_tools_mode(policy.as_ref()).await;
+ let visible_scoped_tools = self.visible_scoped_tools().await;
let mut tools: Vec<rmcp::model::Tool> = match &policy {
Some(policy) => self
.tool_router
.list_all()
.into_iter()
.filter(|tool| policy_allows_tool(policy, tool.name.as_ref()))
+ .filter(|tool| {
+ let name = tool.name.as_ref();
+ if matches!(name, "dbx_plugin_list" | "dbx_plugin_tools" | "dbx_plugin_call") {
+ return plugin_mode.advertise_meta()
+ && visible_scoped_tools.as_ref().is_none_or(|(_, global_access)| {
+ dbx_core::mcp_catalog::descriptor(name)
+ .is_none_or(|descriptor| *global_access >= catalog_advertised_access(descriptor))
+ });
+ }
+ visible_scoped_tools.as_ref().is_none_or(|(visible, global_access)| {
+ dbx_core::mcp_catalog::descriptor(name).is_none_or(|descriptor| {
+ (descriptor.coverage == dbx_core::mcp_catalog::McpCoverage::None
+ && *global_access >= catalog_advertised_access(descriptor))
+ || visible.contains(name)
+ })
+ })
+ })
+ .collect(),
+ None => self
+ .tool_router
+ .list_all()
+ .into_iter()
+ .filter(|tool| {
+ if matches!(tool.name.as_ref(), "dbx_plugin_list" | "dbx_plugin_tools" | "dbx_plugin_call") {
+ plugin_mode.advertise_meta()
+ } else {
+ true
+ }
+ })
.collect(),
- None => self.tool_router.list_all(),
};
- if self.plugin_tools_mode.advertise_flat() {
+ if plugin_mode.advertise_flat() {
tools.extend(self.plugin_tools_view(policy.as_ref()).await);
}
for tool in &mut tools {
@@ -3504,6 +5117,75 @@ impl DbxMcpServer {
tools
}
+ /// Tool-list convenience only. Calls still run the authoritative v1/v2
+ /// checks, and policy/connection loading failures deliberately keep the
+ /// full advertisement so a transient read cannot hide capabilities.
+ async fn visible_scoped_tools(&self) -> Option<(HashSet<&'static str>, dbx_core::mcp_access::McpAccessLevel)> {
+ let Ok(access) = self.backend.load_mcp_access_policy().await else { return None };
+ let Ok(connections) = self.backend.load_connections().await else { return None };
+ let policy = match self.load_policy().await {
+ Ok(policy) => policy,
+ Err(_) => return None,
+ };
+ let group_paths = match self.load_group_paths_for_policy(&policy).await {
+ Ok(paths) => paths,
+ Err(_) => return None,
+ };
+ let mut visible = HashSet::new();
+ for descriptor in dbx_core::mcp_catalog::TOOLS {
+ if descriptor.coverage == dbx_core::mcp_catalog::McpCoverage::None {
+ continue;
+ }
+ // Salesforce keeps its read-only identity tool in the public
+ // `salesforce` toolset, while DML has a narrower opt-in ceiling.
+ // Use that dedicated ceiling for both prepare and apply so the
+ // advertised surface matches their runtime gate.
+ let policy_toolset = match descriptor.name {
+ "dbx_salesforce_prepare_write" | "dbx_salesforce_apply_write" => {
+ dbx_core::mcp_access::SALESFORCE_WRITE_TOOLSET
+ }
+ _ => descriptor.toolset,
+ };
+ let required = match descriptor.access_mode {
+ dbx_core::mcp_catalog::McpAccessMode::Classified => dbx_core::mcp_access::McpAccessLevel::Read,
+ dbx_core::mcp_catalog::McpAccessMode::Static => match descriptor.access {
+ dbx_core::mcp_catalog::McpAccessLevel::Read => dbx_core::mcp_access::McpAccessLevel::Read,
+ dbx_core::mcp_catalog::McpAccessLevel::Write => dbx_core::mcp_access::McpAccessLevel::Write,
+ dbx_core::mcp_catalog::McpAccessLevel::Full => dbx_core::mcp_access::McpAccessLevel::Full,
+ },
+ };
+ let required = if required == dbx_core::mcp_access::McpAccessLevel::Full
+ && policy.confirmation_policy() == McpConfirmPolicy::Full
+ && (descriptor.toolset.starts_with("nacos.") || descriptor.toolset.starts_with("consul."))
+ {
+ dbx_core::mcp_access::McpAccessLevel::Write
+ } else {
+ required
+ };
+ let types = descriptor.coverage.database_types();
+ let scopes = dbx_core::mcp_catalog::TOOLSETS
+ .iter()
+ .find(|toolset| toolset.id == descriptor.toolset)
+ .map_or(&[][..], |toolset| toolset.scope_kinds);
+ let has_match = connections.iter().any(|connection| {
+ types.contains(&connection.db_type)
+ && policy_allows_connection(&policy, group_paths.get(&connection.id), connection)
+ && connection_has_tool_access(
+ &access,
+ group_paths.get(&connection.id).map(|path| path.ids.as_slice()).unwrap_or(&[]),
+ &connection.id,
+ policy_toolset,
+ scopes,
+ required,
+ )
+ });
+ if has_match {
+ visible.insert(descriptor.name);
+ }
+ }
+ Some((visible, access.default_access))
+ }
+
// CallToolResult is the rmcp wire response type; keeping it unboxed avoids conversions at every tool boundary.
#[allow(clippy::result_large_err)]
fn resolve_database(
@@ -3582,12 +5264,34 @@ impl DbxMcpServer {
#[allow(clippy::result_large_err)]
async fn resolve_connection(&self, selector: &ConnectionSelector) -> Result<ResolvedConnection, CallToolResult> {
let policy = self.load_policy().await?;
+ let access = self
+ .backend
+ .load_mcp_access_policy()
+ .await
+ .map_err(|error| backend_tool_error("MCP_POLICY_UNAVAILABLE", error))?;
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))?;
+ let ensure_access = |connection: &ConnectionConfig| -> Result<(), CallToolResult> {
+ let group_ids = group_paths.get(&connection.id).map(|path| path.ids.as_slice()).unwrap_or(&[]);
+ let resolved = access.resolve(group_ids, &connection.id, None);
+ if !resolved.visible {
+ return Err(tool_error(
+ "CONNECTION_OUT_OF_SCOPE",
+ format!("Connection \"{}\" is not allowed by DBX MCP settings.", connection.id),
+ ));
+ }
+ if resolved.level < dbx_core::mcp_access::McpAccessLevel::Read {
+ return Err(tool_error(
+ "MCP_READ_ONLY",
+ format!("Connection \"{}\" is above the effective DBX MCP access level.", connection.name),
+ ));
+ }
+ Ok(())
+ };
if let Some(id) = selector.connection_id.as_deref().map(str::trim).filter(|id| !id.is_empty()) {
let connection = connections
.into_iter()
@@ -3605,6 +5309,7 @@ impl DbxMcpServer {
format!("Connection \"{id}\" is not allowed by DBX MCP settings."),
));
}
+ ensure_access(&connection)?;
return Ok(resolved_connection(policy, connection, group_paths.get(id)));
}
if self.scope.connection_scope_enabled() {
@@ -3626,6 +5331,7 @@ impl DbxMcpServer {
"The DBX AI session scope is outside the global MCP connection allowlist.",
));
}
+ ensure_access(&connection)?;
let path = group_paths.get(&connection.id);
return Ok(resolved_connection(policy, connection, path));
}
@@ -3647,7 +5353,10 @@ impl DbxMcpServer {
"CONNECTION_OUT_OF_SCOPE",
format!("Connection \"{name}\" is not allowed by DBX MCP settings."),
)),
- [connection] => Ok(resolved_connection(policy, connection.clone(), group_paths.get(&connection.id))),
+ [connection] => {
+ ensure_access(connection)?;
+ Ok(resolved_connection(policy, connection.clone(), group_paths.get(&connection.id)))
+ }
_ => Err(tool_error("AMBIGUOUS_CONNECTION", ambiguous_connections(name, &allowed))),
}
}
@@ -3701,14 +5410,39 @@ 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 access = self.backend.load_mcp_access_policy().await.ok();
+ let policy = policy.cloned();
+ let group_paths = match policy.as_ref() {
+ Some(policy) => self.load_group_paths_for_policy(policy).await.ok(),
+ None => None,
+ };
entries
.into_iter()
- .filter(|entry| policy.is_none_or(|policy| policy_allows_tool(policy, &entry.exposed_name)))
- .filter(|entry| !self.scope.enabled() || allowed.contains_key(&entry.plugin_id))
- .map(|entry| {
+ .filter(|entry| policy.as_ref().is_none_or(|policy| policy_allows_tool(policy, &entry.exposed_name)))
+ .filter_map(|entry| {
+ if self.scope.enabled() && !allowed.contains_key(&entry.plugin_id) {
+ return None;
+ }
let connections = allowed.get(&entry.plugin_id).cloned().unwrap_or_default();
- crate::plugin_tools::to_rmcp_tool(&entry, &connections)
- })
+ if !plugin_entry_has_allowed_connection(access.as_ref(), group_paths.as_ref(), &entry, &connections) {
+ return None;
+ }
+ let connections = match (&access, &group_paths) {
+ (Some(access), Some(group_paths)) => connections
+ .into_iter()
+ .filter(|(connection_id, _)| {
+ plugin_connection_level_allowed(
+ access,
+ group_paths.get(connection_id).map(|path| path.ids.as_slice()).unwrap_or(&[]),
+ &entry,
+ connection_id,
+ )
+ })
+ .collect(),
+ _ => connections,
+ };
+ Some(crate::plugin_tools::to_rmcp_tool(&entry, &connections))
+ })
.collect()
}
@@ -3722,6 +5456,12 @@ impl DbxMcpServer {
name: &str,
mut arguments: serde_json::Value,
) -> Result<CallToolResult, ErrorData> {
+ if !self.effective_plugin_tools_mode(self.load_policy().await.ok().as_ref()).await.advertise_flat() {
+ return Ok(tool_error(
+ "PLUGIN_TOOLS_MODE",
+ "Plugin MCP tools are exposed through lazy discovery; use dbx_plugin_call.",
+ ));
+ }
if let Err(error) = self.ensure_tool_allowed(name).await {
return Ok(error);
}
@@ -3733,11 +5473,17 @@ impl DbxMcpServer {
let Some(entry) = entry else {
return Ok(tool_error("TOOL_NOT_FOUND", format!("Plugin tool \"{name}\" is not available.")));
};
- // Same policy stack as the flat surface: allowlist above, then
- // read-only mode and session scope before the backend is reached.
- if let Err(error) = self.ensure_plugin_tool_policy(&entry).await {
- return Ok(error);
- }
+ update_call_history_details(|details| {
+ let access = if entry.tool.read_only {
+ "read"
+ } else if plugin_tool_is_destructive(&entry.tool) {
+ "full"
+ } else {
+ "write"
+ };
+ details.insert("accessLevel".into(), json!(access));
+ details.insert("accessMode".into(), json!("declared"));
+ });
let selector = crate::plugin_tools::connection_selector_from(&arguments).map(str::to_string);
if let Some(object) = arguments.as_object_mut() {
for key in crate::plugin_tools::CONNECTION_SELECTOR_ARGUMENTS {
@@ -3752,6 +5498,12 @@ impl DbxMcpServer {
Ok(bound) => bound.cloned(),
Err(message) => return Ok(tool_error("CONNECTION_NOT_FOUND", message)),
};
+ if entry.requires_connection() && bound.is_none() {
+ return Ok(tool_error(
+ "CONNECTION_NOT_FOUND",
+ format!("Plugin tool \"{}\" requires an allowed plugin connection.", entry.exposed_name),
+ ));
+ }
if let Some((connection_id, connection_name)) = &bound {
let _ = CALL_HISTORY.try_with(|history| {
let mut history = history.lock().unwrap();
@@ -3759,6 +5511,11 @@ impl DbxMcpServer {
history.connection_name.clone_from(connection_name);
});
}
+ if let Err(error) =
+ self.ensure_plugin_tool_policy(&entry, bound.as_ref().map(|(id, _)| id.as_str()), &mut arguments).await
+ {
+ return Ok(error);
+ }
if entry.injects_connection_id {
if let Some((connection_id, _)) = &bound {
if let Some(object) = arguments.as_object_mut() {
@@ -3802,6 +5559,11 @@ impl DbxMcpServer {
// `dbx_plugin_tools`/`dbx_plugin_call` still fail closed.
let allowed = self.allowed_plugin_connections().await.unwrap_or_default();
let policy = self.load_policy().await.ok();
+ let access = self.backend.load_mcp_access_policy().await.ok();
+ let group_paths = match policy.as_ref() {
+ Some(policy) => self.load_group_paths_for_policy(policy).await.ok(),
+ None => None,
+ };
let mut grouped: std::collections::BTreeMap<String, (String, usize, bool)> = Default::default();
for entry in &entries {
let record =
@@ -3813,7 +5575,7 @@ impl DbxMcpServer {
}
let mut rows = Vec::new();
let mut hidden = 0usize;
- for (plugin_id, (plugin_name, tool_count, any_allowed)) in grouped {
+ for (plugin_id, (plugin_name, _tool_count, any_allowed)) in grouped {
// Mirror the flat tools/list scoping: with a scope active,
// plugins without an in-scope connection are not enumerable
// either. They are hidden by scope (not by the allowlist), so
@@ -3821,12 +5583,45 @@ impl DbxMcpServer {
if self.scope.enabled() && !allowed.contains_key(&plugin_id) {
continue;
}
- if any_allowed {
- let connections = allowed.get(&plugin_id).map_or(0, Vec::len);
- rows.push((plugin_id, plugin_name, tool_count, connections));
- } else {
+ if !any_allowed {
hidden += 1;
+ continue;
+ }
+ let connections = allowed.get(&plugin_id).map_or(&[][..], Vec::as_slice);
+ let visible_entries = entries
+ .iter()
+ .filter(|entry| {
+ entry.plugin_id == plugin_id
+ && policy.as_ref().is_none_or(|policy| policy_allows_tool(policy, &entry.exposed_name))
+ && plugin_entry_has_allowed_connection(
+ access.as_ref(),
+ group_paths.as_ref(),
+ entry,
+ connections,
+ )
+ })
+ .collect::<Vec<_>>();
+ if visible_entries.is_empty() {
+ continue;
}
+ let connection_count = connections
+ .iter()
+ .filter(|(connection_id, _)| {
+ visible_entries.iter().any(|entry| {
+ entry.requires_connection()
+ && match (access.as_ref(), group_paths.as_ref()) {
+ (Some(access), Some(group_paths)) => plugin_connection_level_allowed(
+ access,
+ group_paths.get(connection_id).map(|path| path.ids.as_slice()).unwrap_or(&[]),
+ entry,
+ connection_id,
+ ),
+ _ => true,
+ }
+ })
+ })
+ .count();
+ rows.push((plugin_id, plugin_name, visible_entries.len(), connection_count));
}
let note = (hidden > 0).then(|| format!("{hidden} plugin(s) are hidden by the DBX MCP tool allowlist."));
Ok((rows, note))
@@ -3869,7 +5664,6 @@ impl DbxMcpServer {
// by addressing a tool through its plugin id instead. Read-only mode
// and session scope gate the call through the same shared check.
self.ensure_tool_allowed(&entry.exposed_name).await?;
- self.ensure_plugin_tool_policy(&entry).await?;
let selector = crate::plugin_tools::connection_selector_from(&arguments).map(str::to_string);
if let Some(object) = arguments.as_object_mut() {
for key in crate::plugin_tools::CONNECTION_SELECTOR_ARGUMENTS {
@@ -3884,6 +5678,12 @@ impl DbxMcpServer {
Ok(bound) => bound.cloned(),
Err(message) => return Err(tool_error("CONNECTION_NOT_FOUND", message)),
};
+ if entry.requires_connection() && bound.is_none() {
+ return Err(tool_error(
+ "CONNECTION_NOT_FOUND",
+ format!("Plugin tool \"{}\" requires an allowed plugin connection.", entry.exposed_name),
+ ));
+ }
if let Some((connection_id, connection_name)) = &bound {
let _ = CALL_HISTORY.try_with(|history| {
let mut history = history.lock().unwrap();
@@ -3891,6 +5691,8 @@ impl DbxMcpServer {
history.connection_name.clone_from(connection_name);
});
}
+ self.ensure_plugin_tool_policy(&entry, bound.as_ref().map(|(id, _)| id.as_str()), &mut arguments).await?;
+ self.ensure_tool_allowed("dbx_plugin_call").await?;
if entry.injects_connection_id {
if let Some((connection_id, _)) = &bound {
if let Some(object) = arguments.as_object_mut() {
@@ -3946,6 +5748,21 @@ impl ServerHandler for DbxMcpServer {
let started = Instant::now();
let args = serde_json::Value::Object(request.arguments.clone().unwrap_or_default());
let arg = |name: &str| args.get(name).and_then(|value| value.as_str()).unwrap_or_default().to_string();
+ // Which MCP client made the call (from `initialize`), for the call
+ // history. Informational only: it never takes part in a decision.
+ let client = context
+ .peer
+ .peer_info()
+ .map(|info| json!({ "name": info.client_info.name, "version": info.client_info.version }));
+ let descriptor = dbx_core::mcp_catalog::descriptor(request.name.as_ref());
+ let details = json!({
+ "source": "mcp",
+ "transport": match self.transport { McpTransport::Stdio => "stdio", McpTransport::StreamableHttp => "http" },
+ "client": client,
+ "accessLevel": descriptor.map(|item| item.access),
+ "accessMode": descriptor.map(|item| item.access_mode),
+ "confirmation": "not_required",
+ }).to_string();
let entry = HistoryEntry {
id: Uuid::new_v4().to_string(),
connection_id: arg("connection_id"),
@@ -3961,7 +5778,7 @@ impl ServerHandler for DbxMcpServer {
target: arg("table"),
affected_rows: None,
rollback_sql: None,
- details_json: Some(r#"{"source":"mcp"}"#.into()),
+ details_json: Some(details),
source: "mcp".into(),
mcp_tool_name: Some(request.name.to_string()),
mcp_request_json: Some(bounded_history_request(&args)),
@@ -4459,6 +6276,178 @@ fn policy_allows_connection(
dbx_core::mcp_policy::policy_allows_connection(policy, group_path, &connection.id)
}
+fn catalog_advertised_access(
+ descriptor: &dbx_core::mcp_catalog::McpToolDescriptor,
+) -> dbx_core::mcp_access::McpAccessLevel {
+ match descriptor.access_mode {
+ dbx_core::mcp_catalog::McpAccessMode::Classified => dbx_core::mcp_access::McpAccessLevel::Read,
+ dbx_core::mcp_catalog::McpAccessMode::Static => catalog_access_level(descriptor.access),
+ }
+}
+
+fn catalog_access_level(level: dbx_core::mcp_catalog::McpAccessLevel) -> dbx_core::mcp_access::McpAccessLevel {
+ match level {
+ dbx_core::mcp_catalog::McpAccessLevel::Read => dbx_core::mcp_access::McpAccessLevel::Read,
+ dbx_core::mcp_catalog::McpAccessLevel::Write => dbx_core::mcp_access::McpAccessLevel::Write,
+ dbx_core::mcp_catalog::McpAccessLevel::Full => dbx_core::mcp_access::McpAccessLevel::Full,
+ }
+}
+
+/// Discovery must include tools usable through an admitted sub-scope override,
+/// even when the inherited connection level is lower. Actual calls still
+/// resolve and authorize their concrete scope independently.
+fn connection_has_tool_access(
+ access: &dbx_core::mcp_access::McpAccessPolicy,
+ group_ids: &[String],
+ connection_id: &str,
+ toolset: &str,
+ scope_kinds: &[&str],
+ required: dbx_core::mcp_access::McpAccessLevel,
+) -> bool {
+ let ceiling = access.toolset_ceiling(connection_id, toolset);
+ let allowed = |scope| {
+ let resolved = access.resolve(group_ids, connection_id, scope);
+ resolved.visible && ceiling.map_or(resolved.level, |ceiling| resolved.level.min(ceiling)) >= required
+ };
+ allowed(None)
+ || access.rules.keys().any(|target| match target {
+ dbx_core::mcp_access::McpRuleTarget::Scope { connection_id: id, scope, value }
+ if id == connection_id && scope_kinds.contains(&scope.as_str()) =>
+ {
+ allowed(Some((scope.as_str(), value.as_str())))
+ }
+ _ => false,
+ })
+}
+
+fn plugin_connection_level_allowed(
+ access: &dbx_core::mcp_access::McpAccessPolicy,
+ group_ids: &[String],
+ entry: &crate::plugin_tools::PluginToolEntry,
+ connection_id: &str,
+) -> bool {
+ let required = plugin_tool_required_access(entry);
+ let scopes = entry.scope.as_ref().map(|(kind, _)| [kind.as_str()]);
+ connection_has_tool_access(
+ access,
+ group_ids,
+ connection_id,
+ &entry.toolset,
+ scopes.as_ref().map_or(&[], |scopes| scopes.as_slice()),
+ required,
+ )
+}
+
+fn plugin_tool_required_access(entry: &crate::plugin_tools::PluginToolEntry) -> dbx_core::mcp_access::McpAccessLevel {
+ if entry.tool.read_only {
+ dbx_core::mcp_access::McpAccessLevel::Read
+ } else {
+ // Full-level tools still use the separate high-risk confirmation tier;
+ // ordinary write access is the minimum resource level before that
+ // confirmation can be considered.
+ dbx_core::mcp_access::McpAccessLevel::Write
+ }
+}
+
+fn plugin_entry_has_allowed_connection(
+ access: Option<&dbx_core::mcp_access::McpAccessPolicy>,
+ group_paths: Option<&HashMap<String, dbx_core::mcp_policy::McpConnectionGroupPath>>,
+ entry: &crate::plugin_tools::PluginToolEntry,
+ connections: &[(String, String)],
+) -> bool {
+ if !entry.requires_connection() {
+ return access.is_none_or(|access| access.default_access >= plugin_tool_required_access(entry));
+ }
+ if connections.is_empty() {
+ return false;
+ }
+ match (access, group_paths) {
+ (Some(access), Some(group_paths)) => connections.iter().any(|(connection_id, _)| {
+ plugin_connection_level_allowed(
+ access,
+ group_paths.get(connection_id).map(|path| path.ids.as_slice()).unwrap_or(&[]),
+ entry,
+ connection_id,
+ )
+ }),
+ _ => true,
+ }
+}
+
+/// Plugin connection and sub-scope check. The v2 access policy is authoritative
+/// for plugin calls just as it is for built-in product calls: connection
+/// visibility, connection access, selected/none sub-scope admission, and the
+/// connection's toolset ceiling are all evaluated before the sidecar runs.
+#[allow(clippy::result_large_err)] // Keep the MCP error response, as in the other scope guards.
+fn ensure_plugin_scope(
+ access: &dbx_core::mcp_access::McpAccessPolicy,
+ entry: &crate::plugin_tools::PluginToolEntry,
+ group_ids: &[String],
+ connection_id: Option<&str>,
+ arguments: &serde_json::Value,
+) -> Result<dbx_core::mcp_access::McpAccessLevel, CallToolResult> {
+ let Some(connection_id) = connection_id else {
+ if entry.scope.is_some() {
+ return Err(tool_error(
+ "SCOPE_OUT_OF_POLICY",
+ format!("Plugin tool \"{}\" requires a policy-bound connection.", entry.exposed_name),
+ ));
+ }
+ if access.default_access < plugin_tool_required_access(entry) {
+ return Err(tool_error(
+ "MCP_READ_ONLY",
+ format!("Plugin tool \"{}\" is above the effective DBX MCP access level.", entry.exposed_name),
+ ));
+ }
+ return Ok(access.default_access);
+ };
+
+ let needed = plugin_tool_required_access(entry);
+ let ceiling = access.toolset_ceiling(connection_id, &entry.toolset);
+ let cap = |level: dbx_core::mcp_access::McpAccessLevel| ceiling.map_or(level, |ceiling| level.min(ceiling));
+ let resolved = if let Some((kind, argument)) = entry.scope.as_ref() {
+ let value =
+ arguments.get(argument).and_then(serde_json::Value::as_str).filter(|value| !value.trim().is_empty());
+ match value {
+ Some(value) => access.resolve(group_ids, connection_id, Some((kind, value))),
+ None => {
+ let has_level_rules = access.rules.iter().any(|(target, rule)| {
+ matches!(target, dbx_core::mcp_access::McpRuleTarget::Scope { connection_id: id, scope, .. } if id == connection_id && scope == kind)
+ && (rule.access.is_some() || rule.ceiling.is_some())
+ });
+ if !access.sub_scope_allows_all(connection_id, kind) || has_level_rules {
+ return Err(tool_error(
+ "SCOPE_REQUIRED",
+ format!("Plugin tool \"{}\" requires the scope argument {argument}.", entry.exposed_name),
+ ));
+ }
+ access.resolve(group_ids, connection_id, None)
+ }
+ }
+ } else {
+ access.resolve(group_ids, connection_id, None)
+ };
+ if !resolved.visible {
+ return Err(tool_error(
+ "SCOPE_OUT_OF_POLICY",
+ format!("Connection \"{connection_id}\" is not allowed by DBX MCP settings."),
+ ));
+ }
+ 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),
+ ));
+ }
+ Ok(cap(resolved.level))
+}
+
+/// 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 {
+ tool.annotations.get("destructiveHint").and_then(serde_json::Value::as_bool) == Some(true)
+}
+
fn policy_allows_tool(policy: &McpGlobalPolicy, tool_name: &str) -> bool {
let Some(allowed) = policy.allowed_tool_names.as_ref() else { return true };
if allowed.iter().any(|name| name == tool_name) {
@@ -5346,6 +7335,39 @@ fn escape_cell(value: &str) -> String {
value.replace('|', "\\|").replace('\n', " ")
}
+/// Settings inherited from v1 store Redis logical databases under `database`,
+/// while native v2 providers can describe them as `dbIndex`. Resolve the kind
+/// actually present on this connection; if both exist, neither may widen the
+/// other. In particular a selected v1 database must not be checked against an
+/// empty dbIndex allowlist, nor may its per-database level be skipped.
+fn redis_database_access(
+ access: &dbx_core::mcp_access::McpAccessPolicy,
+ group_ids: &[String],
+ connection_id: &str,
+ database: u32,
+) -> dbx_core::mcp_access::McpResolvedAccess {
+ let has_kind = |kind: &str| {
+ access.rules.keys().any(|target| {
+ matches!(target, dbx_core::mcp_access::McpRuleTarget::Scope { connection_id: id, scope, .. }
+ if id == connection_id && scope == kind)
+ })
+ };
+ let has_database = has_kind("database");
+ let has_index = has_kind("dbIndex");
+ let value = database.to_string();
+ let mut resolved = access.resolve(
+ group_ids,
+ connection_id,
+ Some((if has_index && !has_database { "dbIndex" } else { "database" }, &value)),
+ );
+ if has_index && has_database {
+ let indexed = access.resolve(group_ids, connection_id, Some(("dbIndex", &value)));
+ resolved.visible &= indexed.visible;
+ resolved.level = resolved.level.min(indexed.level);
+ }
+ resolved
+}
+
fn redis_database(connection: &dbx_core::models::connection::ConnectionConfig) -> Option<u32> {
connection.database.as_deref().and_then(parse_redis_database)
}
@@ -5656,9 +7678,20 @@ mod tests {
salesforce_identity: Option<SalesforceCurrentUser>,
approved_sql: std::sync::Mutex<Vec<String>>,
consumed_sql: std::sync::Mutex<Vec<String>>,
+ sql_approval_revoked: std::sync::atomic::AtomicBool,
revoke_on_approval: bool,
plugin_providers: Vec<crate::plugin_tools::PluginToolProvider>,
plugin_tool_calls: RecordedPluginToolCalls,
+ /// Answer for `approve_high_risk_tool`: `None` = backend has no desktop.
+ tool_approval_answer: Option<bool>,
+ /// v2 policy override for plugin sub-scope decisions.
+ access_policy: Option<dbx_core::mcp_access::McpAccessPolicy>,
+ access_policy_loads: AtomicUsize,
+ access_after_approval: Option<dbx_core::mcp_access::McpAccessPolicy>,
+ policy_after_approval: Option<McpGlobalPolicy>,
+ product_calls: std::sync::Mutex<Vec<crate::products::ProductCall>>,
+ tool_approvals: std::sync::Mutex<Vec<crate::approval::ToolApprovalRequest>>,
+ nacos_namespaces: Option<Vec<String>>,
}
impl Default for FakeBackend {
@@ -5683,9 +7716,18 @@ mod tests {
salesforce_identity: None,
approved_sql: std::sync::Mutex::new(Vec::new()),
consumed_sql: std::sync::Mutex::new(Vec::new()),
+ sql_approval_revoked: std::sync::atomic::AtomicBool::new(false),
revoke_on_approval: false,
plugin_providers: Vec::new(),
plugin_tool_calls: std::sync::Mutex::new(Vec::new()),
+ tool_approval_answer: None,
+ access_policy: None,
+ access_policy_loads: AtomicUsize::new(0),
+ access_after_approval: None,
+ policy_after_approval: None,
+ product_calls: std::sync::Mutex::new(Vec::new()),
+ tool_approvals: std::sync::Mutex::new(Vec::new()),
+ nacos_namespaces: None,
}
}
}
@@ -5705,6 +7747,167 @@ mod tests {
.unwrap()
}
+ fn call_safety_policy(full: bool) -> McpGlobalPolicy {
+ McpGlobalPolicy {
+ allow_dangerous_sql: full,
+ call_confirmation: Some(McpConfirmPolicy::HighRisk),
+ ..Default::default()
+ }
+ }
+
+ async fn call_safety_tool(server: &DbxMcpServer, kind: &str) -> CallToolResult {
+ match kind {
+ "plugin_flat" => {
+ server.call_plugin_tool_dispatch("dbx_ssh__ssh_exec", json!({"command":"test"})).await.unwrap()
+ }
+ "plugin_lazy" => {
+ server
+ .plugin_call(Parameters(PluginCallRequest {
+ plugin_id: "io.dbx.ssh".into(),
+ tool: "ssh_exec".into(),
+ arguments: Some(json!({"command":"test"})),
+ dbx_connection: None,
+ }))
+ .await
+ }
+ "product" => {
+ server
+ .consul_kv_delete(Parameters(ConsulKvDeleteRequest {
+ selector: selector("consul"),
+ key: "config/app".into(),
+ cas: None,
+ }))
+ .await
+ }
+ "redis" => {
+ server
+ .execute_redis_command(Parameters(ExecuteRedisCommandRequest {
+ selector: selector("redis"),
+ db: Some(0),
+ command: "FLUSHALL".into(),
+ }))
+ .await
+ }
+ "mongo" => {
+ server
+ .execute_query(Parameters(ExecuteQueryRequest {
+ selector: selector("mongo"),
+ database: Some("app".into()),
+ sql: "db.items.drop()".into(),
+ session_id: None,
+ cell_char_offset: None,
+ cell_char_limit: None,
+ max_rows: None,
+ }))
+ .await
+ }
+ "connection" => {
+ server
+ .remove_connection(Parameters(RemoveConnectionRequest {
+ connection_id: Some("consul".into()),
+ connection_name: None,
+ }))
+ .await
+ }
+ _ => panic!("unknown test tool"),
+ }
+ }
+
+ fn call_safety_backend(
+ policy: McpGlobalPolicy,
+ answer: Option<bool>,
+ revoked: Option<McpGlobalPolicy>,
+ ) -> Arc<FakeBackend> {
+ Arc::new(FakeBackend {
+ policy,
+ tool_approval_answer: answer,
+ policy_after_approval: revoked,
+ connections: vec![
+ connection("consul", "consul", "consul", ""),
+ connection("redis", "redis", "redis", "0"),
+ connection("mongo", "mongo", "mongodb", "app"),
+ ],
+ plugin_providers: vec![plugin_provider("io.dbx.ssh", "Terminal", destructive_plugin_listing())],
+ ..Default::default()
+ })
+ }
+
+ #[tokio::test]
+ async fn call_safety_applies_to_full_access_across_tool_families_and_plugin_routes() {
+ for kind in ["plugin_flat", "plugin_lazy", "product", "redis", "mongo", "connection"] {
+ for full in [false, true] {
+ for answer in [None, Some(false), Some(true)] {
+ let backend = call_safety_backend(call_safety_policy(full), answer, None);
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = call_safety_tool(&server, kind).await;
+ assert_eq!(
+ backend.tool_approvals.lock().unwrap().len(),
+ usize::from(full),
+ "{kind} full={full}: {}",
+ result_text(&result)
+ );
+ if !full || answer != Some(true) {
+ assert!(result.is_error.unwrap_or(false), "{kind}: {}", result_text(&result));
+ assert!(backend.plugin_tool_calls.lock().unwrap().is_empty());
+ assert!(backend.product_calls.lock().unwrap().is_empty());
+ } else if kind != "redis" && kind != "mongo" {
+ assert!(!result.is_error.unwrap_or(false), "{kind}: {}", result_text(&result));
+ } else {
+ // These fake drivers report unsupported only after the gate.
+ assert!(!result_text(&result).contains("BLOCKED"), "{kind}: {}", result_text(&result));
+ }
+ }
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn call_safety_cannot_elevate_a_revoked_full_grant_after_confirmation() {
+ for kind in ["plugin_flat", "plugin_lazy", "product", "redis", "mongo", "connection"] {
+ for after in [
+ call_safety_policy(false),
+ McpGlobalPolicy { call_confirmation: Some(McpConfirmPolicy::Off), ..call_safety_policy(true) },
+ ] {
+ let backend = call_safety_backend(call_safety_policy(true), Some(true), Some(after));
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = call_safety_tool(&server, kind).await;
+ assert!(result.is_error.unwrap_or(false), "{kind}: {}", result_text(&result));
+ assert_eq!(backend.tool_approvals.lock().unwrap().len(), 1, "{kind}");
+ assert!(backend.plugin_tool_calls.lock().unwrap().is_empty());
+ assert!(backend.product_calls.lock().unwrap().is_empty());
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn call_safety_sql_authorizes_full_then_confirms_and_rechecks() {
+ let conn = connection("mysql", "mysql", "mysql", "app");
+ for full in [false, true] {
+ for revoke in [false, true] {
+ let policy = call_safety_policy(full);
+ let backend = Arc::new(FakeBackend {
+ connections: vec![conn.clone()],
+ policy: policy.clone(),
+ policy_after_approval: revoke.then_some(call_safety_policy(false)),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = server.approved_sql_policy(&conn, &policy, "app", "DROP TABLE items", false, false).await;
+ assert_eq!(result.is_ok(), full && !revoke);
+ assert_eq!(backend.approved_sql.lock().unwrap().len(), usize::from(full));
+ assert_eq!(backend.consumed_sql.lock().unwrap().len(), usize::from(full && !revoke));
+ }
+ }
+ let policy = call_safety_policy(true);
+ let backend =
+ Arc::new(FakeBackend { connections: vec![conn.clone()], policy: policy.clone(), ..Default::default() });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ for sql in ["SELECT 1", "UPDATE items SET value = 1 WHERE id = 1"] {
+ assert!(server.approved_sql_policy(&conn, &policy, "app", sql, false, false).await.unwrap().1.is_none());
+ }
+ assert!(backend.approved_sql.lock().unwrap().is_empty());
+ }
+
#[tokio::test]
async fn high_risk_sql_approval_is_bound_to_one_execution_and_rechecked() {
let sql = "CREATE TABLE approved_test (id INT)";
@@ -5742,6 +7945,30 @@ mod tests {
assert!(result_text(&error).contains("PRODUCTION_WRITE_BLOCKED"));
}
+ #[tokio::test]
+ async fn sql_tool_revocation_while_awaiting_approval_prevents_execution() {
+ let policy = McpGlobalPolicy { prompt_high_risk_sql: true, ..Default::default() };
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("mysql", "MySQL", "mysql", "app")],
+ policy: policy.clone(),
+ policy_after_approval: Some(McpGlobalPolicy { allowed_tool_names: Some(vec![]), ..policy }),
+ ..Default::default()
+ });
+ let result = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false)
+ .execute_query(Parameters(ExecuteQueryRequest {
+ selector: selector("mysql"),
+ database: None,
+ sql: "CREATE TABLE revoked (id INT)".into(),
+ session_id: None,
+ cell_char_offset: None,
+ cell_char_limit: None,
+ max_rows: None,
+ }))
+ .await;
+ assert!(result_text(&result).contains("TOOL_OUT_OF_SCOPE"), "{}", result_text(&result));
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty());
+ }
+
#[tokio::test]
async fn high_risk_sql_tools_require_and_consume_desktop_approval() {
let query_sql = "CREATE TABLE approved_query (id INT)";
@@ -5819,6 +8046,9 @@ mod tests {
*self.policy_override.lock().unwrap() =
Some(McpGlobalPolicy { read_only: true, ..self.policy.clone() });
}
+ if let Some(policy) = &self.policy_after_approval {
+ *self.policy_override.lock().unwrap() = Some(policy.clone());
+ }
Ok("test-approval-token".to_string())
}
@@ -5829,7 +8059,10 @@ mod tests {
_database: &str,
sql: &str,
) -> Result<(), String> {
- if token != "test-approval-token" || self.consumed_sql.lock().unwrap().contains(&sql.to_string()) {
+ if self.sql_approval_revoked.load(std::sync::atomic::Ordering::SeqCst)
+ || token != "test-approval-token"
+ || self.consumed_sql.lock().unwrap().contains(&sql.to_string())
+ {
return Err("SQL_BLOCKED: Invalid or replayed approval".to_string());
}
self.consumed_sql.lock().unwrap().push(sql.to_string());
@@ -5844,6 +8077,19 @@ mod tests {
Ok(self.policy_override.lock().unwrap().clone().unwrap_or_else(|| self.policy.clone()))
}
+ 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() {
+ if let Some(access) = &self.access_after_approval {
+ return Ok(access.clone());
+ }
+ }
+ match &self.access_policy {
+ Some(access) => Ok(access.clone()),
+ None => Ok(dbx_core::mcp_access::McpAccessPolicy::from_v1(&self.load_mcp_global_policy().await?)),
+ }
+ }
+
async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {
Ok(self.connections.clone())
}
@@ -5852,6 +8098,41 @@ mod tests {
Ok(self.plugin_providers.clone())
}
+ async fn product_call(
+ &self,
+ _connection: &ConnectionConfig,
+ call: &crate::products::ProductCall,
+ ) -> Result<serde_json::Value, String> {
+ self.product_calls.lock().unwrap().push(call.clone());
+ if call.product == crate::products::Product::Nacos && call.operation == "list_namespaces" {
+ return Ok(serde_json::Value::Array(
+ self.nacos_namespaces
+ .clone()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|namespace| json!({ "namespace": namespace }))
+ .collect(),
+ ));
+ }
+ Ok(json!({ "ok": true, "operation": call.operation }))
+ }
+
+ async fn approve_high_risk_tool(&self, request: &crate::approval::ToolApprovalRequest) -> Result<(), String> {
+ self.tool_approvals.lock().unwrap().push(request.clone());
+ if self.revoke_on_approval {
+ *self.policy_override.lock().unwrap() =
+ Some(McpGlobalPolicy { read_only: true, ..self.policy.clone() });
+ }
+ if let Some(policy) = &self.policy_after_approval {
+ *self.policy_override.lock().unwrap() = Some(policy.clone());
+ }
+ match self.tool_approval_answer {
+ Some(true) => Ok(()),
+ Some(false) => Err("TOOL_BLOCKED: MCP confirmation denied.".to_string()),
+ None => Err("TOOL_BLOCKED: Desktop confirmation is unavailable for this MCP backend.".to_string()),
+ }
+ }
+
async fn call_plugin_mcp_tool(
&self,
plugin_id: &str,
@@ -6118,6 +8399,9 @@ mod tests {
tools: serde_json::Value,
) -> crate::plugin_tools::PluginToolProvider {
crate::plugin_tools::PluginToolProvider {
+ scope: None,
+ scope_list_method: None,
+ toolsets: std::collections::BTreeMap::new(),
plugin_id: plugin_id.to_string(),
plugin_name: plugin_name.to_string(),
tools: dbx_core::ai::plugin_tools::parse_tool_list(&tools),
@@ -6178,6 +8462,115 @@ mod tests {
assert!(list.annotations.as_ref().and_then(|a| a.read_only_hint).expect("readOnlyHint passthrough"));
}
+ #[tokio::test]
+ async fn connection_bound_plugin_tools_require_an_allowed_connection() {
+ let backend = Arc::new(FakeBackend {
+ plugin_providers: vec![plugin_provider(
+ "io.dbx.plugins",
+ "Plugins",
+ json!({
+ "tools": [
+ {
+ "name": "read_file",
+ "inputSchema": {
+ "type": "object",
+ "properties": { "connectionId": { "type": "string" }, "path": { "type": "string" } },
+ "required": ["connectionId", "path"]
+ }
+ },
+ { "name": "version", "annotations": { "readOnlyHint": true } }
+ ]
+ }),
+ )],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+
+ let names =
+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<Vec<_>>();
+ assert!(!names.iter().any(|name| name == "dbx_plugins__read_file"), "{names:?}");
+ assert!(names.iter().any(|name| name == "dbx_plugins__version"), "connection-less tools stay available");
+
+ let result =
+ server.call_plugin_tool_dispatch("dbx_plugins__read_file", json!({ "path": "/tmp/a" })).await.unwrap();
+ assert!(result_text(&result).contains("requires an allowed plugin connection"), "{}", result_text(&result));
+ assert!(backend.plugin_tool_calls.lock().unwrap().is_empty(), "the sidecar must not run without a binding");
+
+ let details = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.plugins".into() })).await;
+ assert_eq!(details.is_error, Some(false));
+ let details = result_text(&details);
+ assert!(!details.contains("read_file"), "connection-bound tools must stay out of lazy discovery: {details}");
+ assert!(details.contains("version"), "connection-less tools remain discoverable: {details}");
+
+ let mut access = dbx_core::mcp_access::McpAccessPolicy {
+ default_access: dbx_core::mcp_access::McpAccessLevel::Full,
+ ..Default::default()
+ };
+ access.rules.insert(
+ dbx_core::mcp_access::McpRuleTarget::Connection { id: "k1".into() },
+ dbx_core::mcp_access::McpAccessRule {
+ access: Some(dbx_core::mcp_access::McpAccessLevel::Read),
+ ..Default::default()
+ },
+ );
+ let restricted_backend = Arc::new(FakeBackend {
+ access_policy: Some(access),
+ connections: vec![plugin_connection("k1", "prod", "io.dbx.plugins")],
+ plugin_providers: vec![plugin_provider(
+ "io.dbx.plugins",
+ "Plugins",
+ json!({
+ "tools": [
+ {
+ "name": "read_file",
+ "inputSchema": {
+ "type": "object",
+ "properties": { "connectionId": { "type": "string" }, "path": { "type": "string" } },
+ "required": ["connectionId", "path"]
+ }
+ },
+ { "name": "version", "annotations": { "readOnlyHint": true } }
+ ]
+ }),
+ )],
+ ..Default::default()
+ });
+ let restricted_server = DbxMcpServer::with_runtime_options(restricted_backend, McpScope::default(), false);
+ let details =
+ restricted_server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.plugins".into() })).await;
+ let details = result_text(&details);
+ assert!(!details.contains("read_file"), "v2 read-only access must filter lazy write tools: {details}");
+ assert!(details.contains("version"), "v2 read-only access keeps lazy read tools: {details}");
+ }
+
+ #[tokio::test]
+ async fn connectionless_plugin_tools_honor_global_v2_access() {
+ let backend = Arc::new(FakeBackend {
+ access_policy: Some(dbx_core::mcp_access::McpAccessPolicy {
+ default_access: dbx_core::mcp_access::McpAccessLevel::None,
+ ..Default::default()
+ }),
+ plugin_providers: vec![plugin_provider(
+ "io.dbx.version",
+ "Version",
+ json!({ "tools": [{ "name": "version", "annotations": { "readOnlyHint": true } }] }),
+ )],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+
+ let names =
+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<HashSet<_>>();
+ assert!(!names.contains("dbx_version__version"), "{names:?}");
+
+ let listed = server.plugin_list(Parameters(PluginListRequest { filter: None })).await;
+ assert!(result_text(&listed).contains("MCP_READ_ONLY"), "{}", result_text(&listed));
+
+ let result = server.call_plugin_tool_dispatch("dbx_version__version", json!({})).await.unwrap();
+ assert!(result_text(&result).contains("MCP_READ_ONLY"), "{}", result_text(&result));
+ assert!(backend.plugin_tool_calls.lock().unwrap().is_empty());
+ }
+
#[tokio::test]
async fn plugin_meta_tools_discover_and_call_by_plugin_id() {
let backend = Arc::new(FakeBackend {
@@ -6245,12 +8638,68 @@ mod tests {
}
#[tokio::test]
- async fn plugin_meta_tools_respect_mode_and_policy() {
- // flat 模式(默认构造走 env;此处直接构造 Lazy 验证过滤)——先验证 policy。
- let restricted = Arc::new(FakeBackend {
- policy: McpGlobalPolicy {
- allowed_tool_names: Some(vec!["dbx_plugin_list".to_string(), "dbx_list_connections".to_string()]),
- ..Default::default()
+ async fn plugin_list_counts_only_v2_visible_tools_and_connections() {
+ let mut access = dbx_core::mcp_access::McpAccessPolicy {
+ default_access: dbx_core::mcp_access::McpAccessLevel::Full,
+ ..Default::default()
+ };
+ access.rules.insert(
+ dbx_core::mcp_access::McpRuleTarget::Connection { id: "k1".into() },
+ dbx_core::mcp_access::McpAccessRule {
+ access: Some(dbx_core::mcp_access::McpAccessLevel::Read),
+ ..Default::default()
+ },
+ );
+ let backend = Arc::new(FakeBackend {
+ connections: vec![plugin_connection("k1", "prod", "io.dbx.kafka")],
+ access_policy: Some(access),
+ plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+
+ let list = server.plugin_list(Parameters(PluginListRequest { filter: None })).await;
+ let output = result_text(&list);
+ assert!(output.contains("1 tool(s)"), "{output}");
+ assert!(output.contains("1 allowed connection(s)"), "{output}");
+ assert!(!output.contains("2 tool(s)"), "{output}");
+
+ let tools = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.kafka".into() })).await;
+ let output = result_text(&tools);
+ assert!(output.contains("kafka_topics_list"), "{output}");
+ assert!(!output.contains("kafka_topics_delete"), "{output}");
+ }
+
+ #[tokio::test]
+ async fn plugin_list_keeps_connectionless_tools_without_connections() {
+ let backend = Arc::new(FakeBackend {
+ plugin_providers: vec![plugin_provider(
+ "io.dbx.version",
+ "Version",
+ json!({
+ "tools": [{
+ "name": "version",
+ "annotations": { "readOnlyHint": true }
+ }]
+ }),
+ )],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+
+ let list = server.plugin_list(Parameters(PluginListRequest { filter: None })).await;
+ let output = result_text(&list);
+ assert!(output.contains("io.dbx.version"), "{output}");
+ assert!(output.contains("1 tool(s) · 0 allowed connection(s)"), "{output}");
+ }
+
+ #[tokio::test]
+ async fn plugin_meta_tools_respect_mode_and_policy() {
+ // flat 模式(默认构造走 env;此处直接构造 Lazy 验证过滤)——先验证 policy。
+ let restricted = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy {
+ allowed_tool_names: Some(vec!["dbx_plugin_list".to_string(), "dbx_list_connections".to_string()]),
+ ..Default::default()
},
plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())],
..Default::default()
@@ -6285,6 +8734,7 @@ mod tests {
]),
..Default::default()
},
+ connections: vec![plugin_connection("k1", "prod", "io.dbx.kafka")],
plugin_providers: vec![
plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing()),
plugin_provider(
@@ -6441,6 +8891,164 @@ mod tests {
assert_eq!(backend.plugin_tool_calls.lock().unwrap().len(), 1);
}
+ #[tokio::test]
+ async fn plugin_tools_honor_v2_connection_access_on_flat_and_lazy_paths() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "k1".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Read), ..Default::default() },
+ );
+ let backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy { read_only: false, prompt_high_risk_sql: true, ..Default::default() },
+ access_policy: Some(access),
+ connections: vec![plugin_connection("k1", "prod", "io.dbx.kafka")],
+ plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())],
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let flat = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let flat =
+ flat.call_plugin_tool_dispatch("dbx_kafka__kafka_topics_delete", json!({ "topics": ["t"] })).await.unwrap();
+ assert!(result_text(&flat).contains("MCP_READ_ONLY"), "{}", result_text(&flat));
+
+ let lazy =
+ DbxMcpServer::with_plugin_tools_mode(backend.clone(), McpScope::default(), false, PluginToolsMode::Lazy);
+ let lazy = lazy
+ .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(&lazy).contains("MCP_READ_ONLY"), "{}", result_text(&lazy));
+ assert!(backend.plugin_tool_calls.lock().unwrap().is_empty(), "read-only connection must not reach plugin");
+
+ let listed = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false)
+ .policy_filtered_tools()
+ .await
+ .into_iter()
+ .map(|tool| tool.name.to_string())
+ .collect::<Vec<_>>();
+ assert!(!listed.iter().any(|name| name == "dbx_kafka__kafka_topics_delete"), "{listed:?}");
+ assert!(listed.iter().any(|name| name == "dbx_kafka__kafka_topics_list"), "{listed:?}");
+
+ let mut ceiling = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ let mut rule = McpAccessRule::default();
+ rule.toolset_ceilings.insert("default".into(), McpAccessLevel::Read);
+ ceiling.rules.insert(McpRuleTarget::Connection { id: "k1".into() }, rule);
+ let ceiling_backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy { read_only: false, prompt_high_risk_sql: true, ..Default::default() },
+ access_policy: Some(ceiling),
+ connections: vec![plugin_connection("k1", "prod", "io.dbx.kafka")],
+ plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())],
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let denied = DbxMcpServer::with_runtime_options(ceiling_backend.clone(), McpScope::default(), false)
+ .call_plugin_tool_dispatch("dbx_kafka__kafka_topics_delete", json!({ "topics": ["t"] }))
+ .await
+ .unwrap();
+ assert!(result_text(&denied).contains("MCP_READ_ONLY"), "{}", result_text(&denied));
+ assert!(ceiling_backend.plugin_tool_calls.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn plugin_confirmation_uses_resource_level_and_rechecks_revocations() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+ for lazy in [false, true] {
+ for revoked in [false, true] {
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "k1".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Write), ..Default::default() },
+ );
+ let mut after = access.clone();
+ after.rules.get_mut(&McpRuleTarget::Connection { id: "k1".into() }).unwrap().access =
+ Some(McpAccessLevel::Read);
+ let backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy {
+ read_only: false,
+ allow_dangerous_sql: true,
+ prompt_high_risk_sql: true,
+ ..Default::default()
+ },
+ access_policy: Some(access),
+ access_after_approval: revoked.then_some(after),
+ connections: vec![plugin_connection("k1", "test", "io.dbx.ssh")],
+ plugin_providers: vec![plugin_provider("io.dbx.ssh", "Terminal", destructive_plugin_listing())],
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = if lazy {
+ server
+ .plugin_call(Parameters(PluginCallRequest {
+ plugin_id: "io.dbx.ssh".into(),
+ tool: "ssh_exec".into(),
+ arguments: Some(json!({"command": "test"})),
+ dbx_connection: Some("k1".into()),
+ }))
+ .await
+ } else {
+ server
+ .call_plugin_tool_dispatch(
+ "dbx_ssh__ssh_exec",
+ json!({"dbx_connection": "k1", "command": "test"}),
+ )
+ .await
+ .unwrap()
+ };
+ assert_eq!(
+ backend.tool_approvals.lock().unwrap().len(),
+ 1,
+ "resource write requires confirmation: {}",
+ result_text(&result)
+ );
+ assert_eq!(result.is_error.unwrap_or(false), revoked, "{}", result_text(&result));
+ assert_eq!(backend.plugin_tool_calls.lock().unwrap().len(), usize::from(!revoked));
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn plugin_resource_override_can_grant_write_under_global_read() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Read, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "k1".into() },
+ McpAccessRule { access: Some(McpAccessLevel::Full), ..Default::default() },
+ );
+ let backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy { read_only: true, ..Default::default() },
+ access_policy: Some(access),
+ connections: vec![plugin_connection("k1", "test", "io.dbx.ssh")],
+ plugin_providers: vec![plugin_provider("io.dbx.ssh", "Terminal", destructive_plugin_listing())],
+ ..Default::default()
+ });
+ let result = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false)
+ .call_plugin_tool_dispatch("dbx_ssh__ssh_exec", json!({"dbx_connection": "k1"}))
+ .await
+ .unwrap();
+ assert!(!result.is_error.unwrap_or(false), "{}", result_text(&result));
+ assert_eq!(backend.plugin_tool_calls.lock().unwrap().len(), 1);
+ }
+
+ #[tokio::test]
+ async fn lazy_router_is_advertised_for_read_and_write_permissions() {
+ for read_only in [true, false] {
+ let backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy { read_only, allow_dangerous_sql: false, ..Default::default() },
+ ..Default::default()
+ });
+ let server =
+ DbxMcpServer::with_plugin_tools_mode(backend, McpScope::default(), false, PluginToolsMode::Lazy);
+ assert!(server.policy_filtered_tools().await.iter().any(|tool| tool.name == "dbx_plugin_call"));
+ }
+ }
+
#[tokio::test]
async fn plugin_tools_enforce_session_scope() {
// A scoped session must not reach plugins whose connections are all
@@ -6500,12 +9108,173 @@ mod tests {
assert_eq!(allowed.is_error, Some(false), "{}", result_text(&allowed));
}
+ #[tokio::test]
+ async fn product_confirmation_uses_overrides_and_honors_scope_revocation() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+ for product in [crate::products::Product::Nacos, crate::products::Product::Consul] {
+ for revoked in [false, true] {
+ let id = product.as_str();
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Read, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: id.into() },
+ McpAccessRule { access: Some(McpAccessLevel::Write), ..Default::default() },
+ );
+ let mut after = access.clone();
+ after.rules.get_mut(&McpRuleTarget::Connection { id: id.into() }).unwrap().visible = Some(false);
+ let backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy { read_only: true, prompt_high_risk_sql: true, ..Default::default() },
+ connections: vec![connection(id, id, id, "")],
+ access_policy: Some(access),
+ access_after_approval: revoked.then_some(after),
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let tool = if product == crate::products::Product::Nacos {
+ "dbx_nacos_delete_config"
+ } else {
+ "dbx_consul_kv_delete"
+ };
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ assert!(
+ server.policy_filtered_tools().await.iter().any(|entry| entry.name == tool),
+ "confirmable tool must be discoverable"
+ );
+ let result = server
+ .run_product_tool(
+ tool,
+ &selector(id),
+ product,
+ "delete",
+ McpAccessLevel::Full,
+ Some("dev"),
+ json!({}),
+ )
+ .await;
+ assert_eq!(result.is_error.unwrap_or(false), revoked, "{id}: {}", result_text(&result));
+ assert_eq!(backend.product_calls.lock().unwrap().len(), usize::from(!revoked));
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn nacos_public_alias_and_nested_target_share_the_authorized_namespace() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget, McpSubScopeMode};
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Write, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "nacos".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "nacos".into(), scope: "namespace".into(), value: "public".into() },
+ McpAccessRule { visible: Some(true), ..Default::default() },
+ );
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("nacos", "Nacos", "nacos", "")],
+ access_policy: Some(access),
+ nacos_namespaces: Some(vec!["".into(), "dev".into()]),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ for namespace in [None, Some(""), Some("public")] {
+ let result = server
+ .run_product_tool(
+ "dbx_nacos_update_instance",
+ &selector("nacos"),
+ crate::products::Product::Nacos,
+ "update_instance",
+ McpAccessLevel::Write,
+ namespace,
+ json!({"target": {"namespace": namespace}, "patch": {"enabled": true}}),
+ )
+ .await;
+ assert!(!result.is_error.unwrap_or(false), "{}", result_text(&result));
+ }
+ assert!(backend.product_calls.lock().unwrap().iter().all(|call| call.args["target"]["namespace"] == "public"));
+ let list =
+ server.nacos_list_namespaces(Parameters(NacosNamespacesRequest { selector: selector("nacos") })).await;
+ assert_eq!(serde_json::from_str::<serde_json::Value>(result_text(&list)).unwrap(), json!([{"namespace": ""}]));
+ }
+
+ #[tokio::test]
+ async fn nacos_namespace_listing_filters_selected_sub_scope() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget, McpSubScopeMode};
+
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Write, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "nacos".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "nacos".into(), scope: "namespace".into(), value: "dev".into() },
+ McpAccessRule { visible: Some(true), ..Default::default() },
+ );
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("nacos", "nacos", "nacos", "")],
+ access_policy: Some(access),
+ nacos_namespaces: Some(vec!["dev".into(), "staging".into(), "prod".into()]),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+
+ let result = server
+ .nacos_list_namespaces(Parameters(NacosNamespacesRequest {
+ selector: ConnectionSelector { connection_id: Some("nacos".into()), connection_name: None },
+ }))
+ .await;
+ let values: serde_json::Value = serde_json::from_str(result_text(&result)).unwrap();
+ assert_eq!(values, json!([{ "namespace": "dev" }]));
+ }
+
+ #[test]
+ fn tool_catalog_describes_every_router_tool() {
+ // The settings UI renders the dbx-core catalog, so a router tool
+ // without a descriptor would be invisible there (and vice versa).
+ let routed = DbxMcpServer::tool_router()
+ .list_all()
+ .into_iter()
+ .map(|tool| tool.name.to_string())
+ .collect::<std::collections::BTreeSet<_>>();
+ let described = dbx_core::mcp_catalog::TOOLS
+ .iter()
+ .map(|tool| tool.name.to_string())
+ .collect::<std::collections::BTreeSet<_>>();
+ assert_eq!(routed, described);
+
+ // The settings catalog carries the advertised description and
+ // parameters of every tool.
+ let catalog = DbxMcpServer::tool_catalog();
+ let tools = catalog.toolsets.iter().flat_map(|toolset| toolset.tools.iter()).collect::<Vec<_>>();
+ assert!(tools.iter().all(|tool| !tool.description.is_empty()), "every tool has a description");
+ let query = tools.iter().find(|tool| tool.name == "dbx_execute_query").unwrap();
+ assert!(query.parameters.iter().any(|parameter| parameter.name == "sql" && parameter.required));
+ let peek = tools.iter().find(|tool| tool.name == "dbx_peek_messages").unwrap();
+ let start = peek.parameters.iter().find(|parameter| parameter.name == "start_position").unwrap();
+ assert_eq!(start.value_type, "latest | earliest | offset", "local $defs references resolve");
+
+ // Declared read-only tools must not claim a write level in the catalog.
+ for tool in DbxMcpServer::tool_router().list_all() {
+ let descriptor = dbx_core::mcp_catalog::descriptor(tool.name.as_ref()).unwrap();
+ if tool.annotations.as_ref().and_then(|annotations| annotations.read_only_hint) == Some(true) {
+ assert_eq!(
+ descriptor.access,
+ dbx_core::mcp_catalog::McpAccessLevel::Read,
+ "{} is annotated read-only",
+ tool.name
+ );
+ }
+ }
+ }
+
#[tokio::test]
async fn plugin_tools_mode_switches_advertised_views() {
- // default(flat):router 禁用 meta 路由。
+ // Auto keeps both capabilities available so a persisted lazy setting
+ // can take effect without recreating the transport; the advertised
+ // view still chooses flat when no plugin tools are present.
let flat = DbxMcpServer::with_runtime_options(Arc::new(FakeBackend::default()), McpScope::default(), false);
let flat_router = &flat.tool_router;
- assert!(flat_router.list_all().iter().all(|tool| !tool.name.as_ref().starts_with("dbx_plugin_")));
+ assert!(flat_router.list_all().iter().any(|tool| tool.name == "dbx_plugin_list"));
+ let advertised = flat.policy_filtered_tools().await;
+ assert!(advertised.iter().all(|tool| !tool.name.as_ref().starts_with("dbx_plugin_")));
// lazy 模式:保留 meta 路由(mode 注入,避免并行测试间的环境变量竞态)。
let lazy = DbxMcpServer::with_plugin_tools_mode(
Arc::new(FakeBackend::default()),
@@ -6520,6 +9289,551 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn scoped_plugin_modes_always_advertise_and_dispatch_flat_tools() {
+ use dbx_core::mcp_access::McpPluginToolsMode;
+ for mode in [McpPluginToolsMode::Lazy, McpPluginToolsMode::Auto, McpPluginToolsMode::Flat] {
+ let tools = (0..41)
+ .map(|i| json!({"name": format!("t{i}"), "annotations": {"readOnlyHint": true}}))
+ .collect::<Vec<_>>();
+ let backend = Arc::new(FakeBackend {
+ connections: vec![
+ plugin_connection("only", "Allowed", "io.dbx.big"),
+ plugin_connection("outside", "Outside", "io.dbx.big"),
+ ],
+ policy: McpGlobalPolicy { plugin_tools_mode: mode, ..Default::default() },
+ plugin_providers: vec![plugin_provider("io.dbx.big", "Big", json!({"tools": tools}))],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_plugin_tools_mode(
+ backend,
+ McpScope { connection_ids: vec!["only".into()], ..Default::default() },
+ false,
+ PluginToolsMode::Auto,
+ );
+ let tools = server.policy_filtered_tools().await;
+ assert_eq!(tools.iter().filter(|tool| tool.name.starts_with("dbx_big__")).count(), 41);
+ assert!(!tools.iter().any(|tool| tool.name == "dbx_plugin_call"));
+ let result = server.call_plugin_tool_dispatch("dbx_big__t0", json!({})).await.unwrap();
+ assert_ne!(result.is_error, Some(true), "{}", result_text(&result));
+ let denied =
+ server.call_plugin_tool_dispatch("dbx_big__t0", json!({"connectionId": "outside"})).await.unwrap();
+ assert_eq!(denied.is_error, Some(true));
+ }
+ let server = DbxMcpServer::with_plugin_tools_mode(
+ Arc::new(FakeBackend::default()),
+ McpScope { database: Some("db".into()), ..Default::default() },
+ false,
+ PluginToolsMode::Lazy,
+ );
+ assert_eq!(server.effective_plugin_tools_mode(None).await, PluginToolsMode::Flat);
+ }
+
+ #[tokio::test]
+ async fn auto_mode_switches_to_lazy_discovery_beyond_the_flat_budget() {
+ // 41 read-only tools: auto must advertise the meta tools, keep them
+ // callable, and drop the flat plugin entries.
+ let tools = (0..41)
+ .map(|index| json!({ "name": format!("t{index}"), "annotations": { "readOnlyHint": true } }))
+ .collect::<Vec<_>>();
+ let backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy {
+ read_only: false,
+ plugin_tools_mode: dbx_core::mcp_access::McpPluginToolsMode::Auto,
+ ..Default::default()
+ },
+ plugin_providers: vec![plugin_provider("io.dbx.big", "Big", json!({ "tools": tools }))],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_plugin_tools_mode(backend, McpScope::default(), false, PluginToolsMode::Auto);
+ let names =
+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<Vec<_>>();
+ assert!(names.iter().any(|name| name == "dbx_plugin_list"), "{names:?}");
+ assert!(!names.iter().any(|name| name.starts_with("dbx_big__")), "flat entries hidden in lazy mode");
+ let listed = server.plugin_list(Parameters(PluginListRequest { filter: None })).await;
+ assert_eq!(listed.is_error, Some(false), "{}", result_text(&listed));
+ assert!(result_text(&listed).contains("io.dbx.big"));
+ }
+
+ #[tokio::test]
+ async fn new_policy_lists_large_plugin_catalogs_directly_and_honors_saved_mode_changes() {
+ use dbx_core::mcp_access::McpPluginToolsMode;
+ let tools = (0..41)
+ .map(|index| json!({ "name": format!("t{index}"), "annotations": { "readOnlyHint": true } }))
+ .collect::<Vec<_>>();
+ let backend = Arc::new(FakeBackend {
+ plugin_providers: vec![plugin_provider("io.dbx.big", "Big", json!({ "tools": tools }))],
+ ..Default::default()
+ });
+ let server =
+ DbxMcpServer::with_plugin_tools_mode(backend.clone(), McpScope::default(), false, PluginToolsMode::Auto);
+ let initial = server.policy_filtered_tools().await;
+ assert_eq!(initial.iter().filter(|tool| tool.name.starts_with("dbx_big__")).count(), 41);
+ for mode in
+ [McpPluginToolsMode::Flat, McpPluginToolsMode::Lazy, McpPluginToolsMode::Auto, McpPluginToolsMode::Flat]
+ {
+ *backend.policy_override.lock().unwrap() =
+ Some(McpGlobalPolicy { plugin_tools_mode: mode, ..Default::default() });
+ let tools = server.policy_filtered_tools().await;
+ assert_eq!(
+ tools.iter().filter(|tool| tool.name.starts_with("dbx_big__")).count(),
+ if mode == McpPluginToolsMode::Flat { 41 } else { 0 }
+ );
+ assert_eq!(tools.iter().any(|tool| tool.name == "dbx_plugin_call"), mode != McpPluginToolsMode::Flat);
+ }
+ }
+
+ fn destructive_plugin_listing() -> serde_json::Value {
+ json!({
+ "tools": [
+ { "name": "ssh_exec", "description": "Run a command", "annotations": { "destructiveHint": true },
+ "inputSchema": { "type": "object", "properties": { "command": { "type": "string" } } } },
+ { "name": "ssh_ping", "description": "Ping", "annotations": { "readOnlyHint": true } }
+ ]
+ })
+ }
+
+ #[tokio::test]
+ async fn destructive_plugin_tools_follow_the_high_risk_tier() {
+ let setup = |policy: McpGlobalPolicy, answer: Option<bool>, revoke: bool| {
+ let backend = Arc::new(FakeBackend {
+ policy,
+ plugin_providers: vec![plugin_provider("io.dbx.ssh", "Terminal", destructive_plugin_listing())],
+ tool_approval_answer: answer,
+ revoke_on_approval: revoke,
+ ..Default::default()
+ });
+ (DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false), backend)
+ };
+ let safe_write = McpGlobalPolicy { read_only: false, allow_dangerous_sql: false, ..Default::default() };
+ let confirm = McpGlobalPolicy { prompt_high_risk_sql: true, ..safe_write.clone() };
+ let call = |server: &DbxMcpServer| {
+ let server = server.clone();
+ async move { server.call_plugin_tool_dispatch("dbx_ssh__ssh_exec", json!({ "command": "rm x" })).await.unwrap() }
+ };
+
+ // Safe-write without the confirm switch refuses outright, without asking.
+ let (server, backend) = setup(safe_write.clone(), Some(true), false);
+ let refused = call(&server).await;
+ assert!(result_text(&refused).contains("TOOL_BLOCKED"), "{}", result_text(&refused));
+ assert!(backend.tool_approvals.lock().unwrap().is_empty());
+ assert!(backend.plugin_tool_calls.lock().unwrap().is_empty());
+
+ // With the switch on, a confirmed call runs and the dialog saw the arguments.
+ let (server, backend) = setup(confirm.clone(), Some(true), false);
+ let ok = call(&server).await;
+ assert_eq!(ok.is_error, Some(false), "{}", result_text(&ok));
+ {
+ let approvals = backend.tool_approvals.lock().unwrap();
+ assert_eq!(approvals.len(), 1);
+ assert_eq!(approvals[0].plugin.as_deref(), Some("Terminal"));
+ assert!(approvals[0].detail.contains("rm x"));
+ }
+ assert_eq!(backend.plugin_tool_calls.lock().unwrap().len(), 1);
+
+ // Denied, no desktop, or revoked while the dialog was open: never runs.
+ for (answer, revoke) in [(Some(false), false), (None, false), (Some(true), true)] {
+ let (server, backend) = setup(confirm.clone(), answer, revoke);
+ let blocked = call(&server).await;
+ assert_eq!(blocked.is_error, Some(true), "{answer:?}/{revoke}: {}", result_text(&blocked));
+ assert!(backend.plugin_tool_calls.lock().unwrap().is_empty(), "{answer:?}/{revoke}");
+ }
+
+ // A high-risk policy needs no confirmation; read tools never ask.
+ let (server, backend) = setup(McpGlobalPolicy { allow_dangerous_sql: true, ..safe_write.clone() }, None, false);
+ assert_eq!(call(&server).await.is_error, Some(false));
+ let ping = server.call_plugin_tool_dispatch("dbx_ssh__ssh_ping", json!({})).await.unwrap();
+ assert_eq!(ping.is_error, Some(false));
+ assert!(backend.tool_approvals.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn scoped_access_overrides_keep_builtin_and_plugin_tools_discoverable() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget, McpSubScopeMode};
+
+ for (visible, mode, ceiling, expected) in [
+ (true, McpSubScopeMode::Selected, None, true),
+ (false, McpSubScopeMode::Selected, None, false),
+ (true, McpSubScopeMode::None, None, false),
+ (true, McpSubScopeMode::Selected, Some(McpAccessLevel::Read), false),
+ ] {
+ let mut access = McpAccessPolicy::default();
+ for (id, kind, toolset) in [
+ ("nacos", "namespace", "nacos.config"),
+ ("mysql", "database", "sql.session"),
+ ("k1", "namespace", "default"),
+ ] {
+ access.rules.insert(
+ McpRuleTarget::Connection { id: id.into() },
+ McpAccessRule {
+ sub_scope: Some(mode),
+ toolset_ceilings: ceiling
+ .map(|level| [(toolset.to_string(), level)].into())
+ .unwrap_or_default(),
+ ..Default::default()
+ },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: id.into(), scope: kind.into(), value: "dev".into() },
+ McpAccessRule { visible: Some(visible), access: Some(McpAccessLevel::Write), ..Default::default() },
+ );
+ }
+ let mut provider = plugin_provider(
+ "io.dbx.k8s",
+ "Kubernetes",
+ json!({ "tools": [
+ { "name": "scale", "annotations": { "readOnlyHint": false } }
+ ] }),
+ );
+ provider.scope = Some(("namespace".into(), "namespace".into()));
+ let backend = Arc::new(FakeBackend {
+ policy: access.to_v1(),
+ access_policy: Some(access),
+ connections: vec![
+ connection("nacos", "Nacos", "nacos", "dev"),
+ connection("mysql", "MySQL", "mysql", "dev"),
+ plugin_connection("k1", "cluster", "io.dbx.k8s"),
+ ],
+ plugin_providers: vec![provider],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+ let names =
+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<Vec<_>>();
+ for name in ["dbx_nacos_publish_config", "dbx_begin_transaction", "dbx_k8s__scale"] {
+ assert_eq!(
+ names.iter().any(|tool| tool == name),
+ expected,
+ "{name}: visible={visible}, mode={mode:?}, ceiling={ceiling:?}"
+ );
+ }
+ let lazy = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.k8s".into() })).await;
+ assert_eq!(lazy.is_error, Some(!expected), "{}", result_text(&lazy));
+ if expected {
+ let call =
+ server.call_plugin_tool_dispatch("dbx_k8s__scale", json!({ "namespace": "dev" })).await.unwrap();
+ assert_eq!(call.is_error, Some(false), "{}", result_text(&call));
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn plugin_scope_values_follow_the_access_policy() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget, McpSubScopeMode};
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Write, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "k1".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "k1".into(), scope: "namespace".into(), value: "dev".into() },
+ McpAccessRule { visible: Some(true), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "k1".into(), scope: "namespace".into(), value: "staging".into() },
+ McpAccessRule { visible: Some(true), access: Some(McpAccessLevel::Read), ..Default::default() },
+ );
+ let mut provider = plugin_provider(
+ "io.dbx.k8s",
+ "Kubernetes",
+ json!({ "tools": [
+ { "name": "get_pods", "annotations": { "readOnlyHint": true } },
+ { "name": "scale", "annotations": { "readOnlyHint": false } }
+ ] }),
+ );
+ provider.scope = Some(("namespace".to_string(), "namespace".to_string()));
+ let backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy { read_only: false, ..Default::default() },
+ connections: vec![plugin_connection("k1", "cluster", "io.dbx.k8s")],
+ plugin_providers: vec![provider],
+ access_policy: Some(access),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let call = |tool: &'static str, namespace: Option<&'static str>| {
+ let server = server.clone();
+ async move {
+ let arguments = match namespace {
+ Some(namespace) => json!({ "namespace": namespace }),
+ None => json!({}),
+ };
+ server.call_plugin_tool_dispatch(tool, arguments).await.unwrap()
+ }
+ };
+ // Admitted namespace with write access: both tools run.
+ assert_eq!(call("dbx_k8s__scale", Some("dev")).await.is_error, Some(false));
+ // Namespace outside the selected set is refused before the plugin runs.
+ let outside = call("dbx_k8s__get_pods", Some("prod")).await;
+ assert!(result_text(&outside).contains("SCOPE_OUT_OF_POLICY"), "{}", result_text(&outside));
+ // The policy and sidecar must receive the same canonical scope.
+ assert_eq!(call("dbx_k8s__scale", Some(" dev ")).await.is_error, Some(false));
+ let padded = call("dbx_k8s__scale", Some(" prod ")).await;
+ assert!(result_text(&padded).contains("SCOPE_OUT_OF_POLICY"));
+ // Read-only namespace: reads pass, writes are refused.
+ assert_eq!(call("dbx_k8s__get_pods", Some("staging")).await.is_error, Some(false));
+ let write = call("dbx_k8s__scale", Some("staging")).await;
+ assert!(result_text(&write).contains("MCP_READ_ONLY"), "{}", result_text(&write));
+ // Selected sub-scope policies require an explicit scope argument;
+ // evaluating the call at the connection level would bypass the
+ // selected namespace set.
+ let missing = call("dbx_k8s__get_pods", None).await;
+ assert!(result_text(&missing).contains("SCOPE_REQUIRED"), "{}", result_text(&missing));
+ let calls = backend.plugin_tool_calls.lock().unwrap();
+ assert_eq!(calls.iter().map(|call| call.1.as_str()).collect::<Vec<_>>(), ["scale", "scale", "get_pods"]);
+ assert_eq!(calls[1].3["namespace"], "dev");
+ }
+
+ #[test]
+ fn plugin_implicit_scope_cannot_bypass_named_restrictions() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+ let mut provider = plugin_provider("io.dbx.k8s", "Kubernetes", json!({"tools": [{"name": "scale"}]}));
+ provider.scope = Some(("namespace".into(), "namespace".into()));
+ let entry = crate::plugin_tools::build_catalog(&[provider]).remove(0);
+ for rule in [
+ McpAccessRule { visible: Some(false), ..Default::default() },
+ McpAccessRule { access: Some(McpAccessLevel::Read), ..Default::default() },
+ ] {
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Write, ..Default::default() };
+ access.rules.insert(
+ 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();
+ assert!(result_text(&error).contains("SCOPE_REQUIRED"));
+ }
+ }
+
+ #[tokio::test]
+ async fn plugin_writes_honor_connection_hard_protections() {
+ for production in [false, true] {
+ let mut connection = plugin_connection("k1", "test", "io.dbx.ssh");
+ connection.read_only = !production;
+ connection.is_production = production;
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection],
+ policy: McpGlobalPolicy { allow_dangerous_sql: true, ..Default::default() },
+ plugin_providers: vec![plugin_provider("io.dbx.ssh", "Terminal", destructive_plugin_listing())],
+ ..Default::default()
+ });
+ let result = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false)
+ .call_plugin_tool_dispatch("dbx_ssh__ssh_exec", json!({}))
+ .await
+ .unwrap();
+ assert!(result_text(&result).contains(if production {
+ "PRODUCTION_WRITE_BLOCKED"
+ } else {
+ "CONNECTION_READ_ONLY"
+ }));
+ assert!(backend.plugin_tool_calls.lock().unwrap().is_empty());
+ }
+ }
+
+ #[tokio::test]
+ async fn product_tools_follow_scope_level_and_protections() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget, McpSubScopeMode};
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Write, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "nacos".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "nacos".into(), scope: "namespace".into(), value: "dev".into() },
+ McpAccessRule { visible: Some(true), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "nacos".into(), scope: "namespace".into(), value: "staging".into() },
+ McpAccessRule { visible: Some(true), access: Some(McpAccessLevel::Read), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "nacos".into(), scope: "namespace".into(), value: "blocked".into() },
+ McpAccessRule { visible: Some(true), access: Some(McpAccessLevel::None), ..Default::default() },
+ );
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("nacos", "nacos", "nacos", "prod"), connection("pg", "pg", "postgres", "app")],
+ policy: McpGlobalPolicy { read_only: false, ..Default::default() },
+ access_policy: Some(access),
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let selector = || ConnectionSelector { connection_id: Some("nacos".to_string()), connection_name: None };
+ let key = |namespace: &str| NacosConfigKeyRequest {
+ selector: selector(),
+ namespace: Some(namespace.to_string()),
+ data_id: "app.yaml".to_string(),
+ group: "DEFAULT_GROUP".to_string(),
+ };
+ let publish = |namespace: &str| NacosPublishConfigRequest {
+ selector: selector(),
+ namespace: Some(namespace.to_string()),
+ data_id: "app.yaml".to_string(),
+ group: "DEFAULT_GROUP".to_string(),
+ content: "a: 1".to_string(),
+ config_type: Some("yaml".to_string()),
+ cas_md5: None,
+ };
+
+ // Admitted namespace: read and write reach the backend with the args mapped.
+ assert_eq!(server.nacos_get_config(Parameters(key("dev"))).await.is_error, Some(false));
+ assert_eq!(server.nacos_publish_config(Parameters(publish("dev"))).await.is_error, Some(false));
+ {
+ let calls = backend.product_calls.lock().unwrap();
+ assert_eq!(calls.iter().map(|call| call.operation).collect::<Vec<_>>(), ["get_config", "publish_config"]);
+ assert_eq!(calls[1].args["dataId"], "app.yaml");
+ assert_eq!(calls[1].args["namespace"], "dev");
+ }
+ // Namespace outside the selected set.
+ let outside = server.nacos_get_config(Parameters(key("prod"))).await;
+ assert!(result_text(&outside).contains("SCOPE_OUT_OF_POLICY"), "{}", result_text(&outside));
+ // An explicitly denied scope must reject reads before the product
+ // backend is reached, just like a denied write.
+ let denied = server.nacos_get_config(Parameters(key("blocked"))).await;
+ assert!(result_text(&denied).contains("MCP_READ_ONLY"), "{}", result_text(&denied));
+ // Omitting namespace still resolves the connection's default (`prod`)
+ // before policy evaluation, so it cannot bypass the selected scope.
+ let omitted = server
+ .nacos_get_config(Parameters(NacosConfigKeyRequest {
+ selector: selector(),
+ namespace: None,
+ data_id: "app.yaml".to_string(),
+ group: "DEFAULT_GROUP".to_string(),
+ }))
+ .await;
+ assert!(result_text(&omitted).contains("SCOPE_OUT_OF_POLICY"), "{}", result_text(&omitted));
+ // Read-only namespace refuses writes.
+ let read_only = server.nacos_publish_config(Parameters(publish("staging"))).await;
+ assert!(result_text(&read_only).contains("MCP_READ_ONLY"), "{}", result_text(&read_only));
+ // Full-level delete under a write level is refused without the confirm switch...
+ let delete = server.nacos_delete_config(Parameters(key("dev"))).await;
+ assert!(result_text(&delete).contains("TOOL_BLOCKED"), "{}", result_text(&delete));
+ assert!(backend.tool_approvals.lock().unwrap().is_empty());
+ // Wrong connection type.
+ let wrong = server
+ .consul_kv_get(Parameters(ConsulKvKeyRequest {
+ selector: ConnectionSelector { connection_id: Some("pg".to_string()), connection_name: None },
+ key: "a".to_string(),
+ }))
+ .await;
+ assert!(result_text(&wrong).contains("WRONG_CONNECTION_TYPE"), "{}", result_text(&wrong));
+ assert_eq!(backend.product_calls.lock().unwrap().len(), 2, "refused calls never reach the backend");
+ }
+
+ #[tokio::test]
+ async fn nacos_all_namespace_search_requires_unrestricted_scope_access() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget, McpSubScopeMode};
+
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Read, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "nacos".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "nacos".into(), scope: "namespace".into(), value: "dev".into() },
+ McpAccessRule { visible: Some(true), access: Some(McpAccessLevel::Read), ..Default::default() },
+ );
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("nacos", "nacos", "nacos", "dev")],
+ access_policy: Some(access),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = server
+ .nacos_search_configs(Parameters(NacosSearchConfigsRequest {
+ selector: ConnectionSelector { connection_id: Some("nacos".into()), connection_name: None },
+ operation_id: "all-namespaces".into(),
+ namespace: None,
+ scope: Some("allNamespaces".into()),
+ query: "host".into(),
+ group: None,
+ data_id: None,
+ max_results: Some(10),
+ }))
+ .await;
+ assert!(result_text(&result).contains("SCOPE_OUT_OF_POLICY"), "{}", result_text(&result));
+ assert!(backend.product_calls.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn product_toolset_ceilings_narrow_runtime_access_and_advertising() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ let mut rule = McpAccessRule::default();
+ rule.toolset_ceilings.insert("nacos.config".into(), McpAccessLevel::Read);
+ access.rules.insert(McpRuleTarget::Connection { id: "nacos".into() }, rule);
+ let backend = Arc::new(FakeBackend {
+ policy: McpGlobalPolicy { read_only: false, ..Default::default() },
+ access_policy: Some(access),
+ connections: vec![connection("nacos", "nacos", "nacos", "dev")],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = server
+ .nacos_publish_config(Parameters(NacosPublishConfigRequest {
+ selector: ConnectionSelector { connection_id: Some("nacos".into()), connection_name: None },
+ namespace: Some("dev".into()),
+ data_id: "app.yaml".into(),
+ group: "DEFAULT_GROUP".into(),
+ content: "a: 1".into(),
+ config_type: Some("yaml".into()),
+ cas_md5: None,
+ }))
+ .await;
+ assert!(result_text(&result).contains("MCP_READ_ONLY"), "{}", result_text(&result));
+ assert!(backend.product_calls.lock().unwrap().is_empty());
+
+ let names =
+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<Vec<_>>();
+ assert!(!names.iter().any(|name| name == "dbx_nacos_publish_config"), "{names:?}");
+ assert!(names.iter().any(|name| name == "dbx_nacos_get_config"), "{names:?}");
+ }
+
+ #[tokio::test]
+ async fn product_delete_is_confirmed_when_the_switch_is_on() {
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("consul", "consul", "consul", "")],
+ policy: McpGlobalPolicy { read_only: false, prompt_high_risk_sql: true, ..Default::default() },
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = server
+ .consul_kv_delete(Parameters(ConsulKvDeleteRequest {
+ selector: ConnectionSelector { connection_id: Some("consul".to_string()), connection_name: None },
+ key: "config/app".to_string(),
+ cas: Some(3),
+ }))
+ .await;
+ assert_eq!(result.is_error, Some(false), "{}", result_text(&result));
+ {
+ let approvals = backend.tool_approvals.lock().unwrap();
+ assert_eq!(approvals.len(), 1);
+ assert_eq!(approvals[0].kind, crate::approval::ToolApprovalKind::ProductTool);
+ assert!(approvals[0].detail.contains("config/app"));
+ }
+ assert_eq!(backend.product_calls.lock().unwrap()[0].args["cas"], 3);
+
+ // A policy change while the confirmation dialog is open wins over the
+ // earlier approval and prevents the product call.
+ let revoked = Arc::new(FakeBackend {
+ connections: vec![connection("consul", "consul", "consul", "")],
+ policy: McpGlobalPolicy { read_only: false, prompt_high_risk_sql: true, ..Default::default() },
+ tool_approval_answer: Some(true),
+ revoke_on_approval: true,
+ ..Default::default()
+ });
+ let revoked_server = DbxMcpServer::with_runtime_options(revoked.clone(), McpScope::default(), false);
+ let blocked = revoked_server
+ .consul_kv_delete(Parameters(ConsulKvDeleteRequest {
+ selector: ConnectionSelector { connection_id: Some("consul".to_string()), connection_name: None },
+ key: "config/app".to_string(),
+ cas: None,
+ }))
+ .await;
+ assert!(blocked.is_error == Some(true), "{}", result_text(&blocked));
+ assert!(revoked.product_calls.lock().unwrap().is_empty());
+ }
+
#[tokio::test]
async fn plugin_tool_calls_bind_connections_and_respect_policy() {
let backend = Arc::new(FakeBackend {
@@ -6597,6 +9911,40 @@ mod tests {
assert!(!tools.iter().any(|tool| tool.name.as_ref() == "dbx_kafka__kafka_topics_delete"));
}
+ #[tokio::test]
+ async fn plugin_dispatch_checks_scope_once_per_call() {
+ let backend = Arc::new(FakeBackend {
+ connections: vec![plugin_connection("k1", "prod", "io.dbx.kafka")],
+ plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())],
+ access_policy: Some(dbx_core::mcp_access::McpAccessPolicy::default()),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+
+ let result = server.call_plugin_tool_dispatch("dbx_kafka__kafka_topics_list", json!({})).await.unwrap();
+ assert_eq!(result.is_error, Some(false), "{}", result_text(&result));
+ assert_eq!(backend.access_policy_loads.load(std::sync::atomic::Ordering::SeqCst), 1);
+
+ let backend = Arc::new(FakeBackend {
+ connections: vec![plugin_connection("k1", "prod", "io.dbx.kafka")],
+ plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())],
+ access_policy: Some(dbx_core::mcp_access::McpAccessPolicy::default()),
+ ..Default::default()
+ });
+ let server =
+ DbxMcpServer::with_plugin_tools_mode(backend.clone(), McpScope::default(), false, PluginToolsMode::Lazy);
+ let result = server
+ .plugin_call(Parameters(PluginCallRequest {
+ plugin_id: "io.dbx.kafka".into(),
+ tool: "kafka_topics_list".into(),
+ arguments: None,
+ dbx_connection: None,
+ }))
+ .await;
+ assert_eq!(result.is_error, Some(false), "{}", result_text(&result));
+ assert_eq!(backend.access_policy_loads.load(std::sync::atomic::Ordering::SeqCst), 1);
+ }
+
#[cfg(feature = "mq-admin")]
#[tokio::test]
async fn peek_messages_rejects_invalid_options_before_backend_call() {
@@ -6730,10 +10078,13 @@ mod tests {
let server = DbxMcpServer::with_runtime_options(Arc::new(FakeBackend::default()), McpScope::default(), false);
let tools = server.tool_router.list_all();
let names = tools.iter().map(|tool| tool.name.as_ref()).collect::<Vec<_>>();
+ // 22 product-provider tools (14 Nacos + 8 Consul), plus the three
+ // runtime-selectable plugin meta tools retained by auto mode.
#[cfg(feature = "mq-admin")]
- assert_eq!(tools.len(), 25);
+ assert_eq!(tools.len(), 50);
#[cfg(not(feature = "mq-admin"))]
- assert_eq!(tools.len(), 23);
+ assert_eq!(tools.len(), 48);
+ assert!(names.contains(&"dbx_nacos_get_config") && names.contains(&"dbx_consul_kv_get"));
#[cfg(feature = "mq-admin")]
assert!(names.contains(&"dbx_peek_messages"));
#[cfg(not(feature = "mq-admin"))]
@@ -6808,7 +10159,11 @@ mod tests {
..Default::default()
};
let server = DbxMcpServer::with_runtime_options(
- Arc::new(FakeBackend { policy, ..Default::default() }),
+ Arc::new(FakeBackend {
+ policy,
+ connections: vec![connection("pg", "Postgres", "postgres", "app")],
+ ..Default::default()
+ }),
McpScope::default(),
false,
);
@@ -6820,12 +10175,164 @@ mod tests {
}
#[tokio::test]
- async fn tools_list_keeps_the_full_view_without_an_allowlist() {
+ async fn tools_list_keeps_connectionless_view_without_an_allowlist() {
let server = DbxMcpServer::with_runtime_options(Arc::new(FakeBackend::default()), McpScope::default(), false);
let tools = server.policy_filtered_tools().await;
- assert_eq!(tools.len(), server.tool_router.list_all().len());
+ assert!(tools.iter().all(|tool| !tool.name.as_ref().starts_with("dbx_plugin_")));
+ let names = tools.iter().map(|tool| tool.name.as_ref()).collect::<HashSet<_>>();
+ assert!(names.contains("dbx_list_connections"));
+ assert!(names.contains("dbx_add_connection"));
+ assert!(!names.contains("dbx_list_databases"));
+ assert!(!names.contains("dbx_execute_query"));
+ assert!(!names.contains("dbx_nacos_list_configs"));
+ }
+
+ #[tokio::test]
+ async fn tools_list_hides_connection_bound_tools_without_connections() {
+ let server = DbxMcpServer::with_runtime_options(Arc::new(FakeBackend::default()), McpScope::default(), false);
+ let names =
+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<HashSet<_>>();
+
+ for name in ["dbx_list_databases", "dbx_list_tables", "dbx_execute_query", "dbx_nacos_list_configs"] {
+ assert!(!names.contains(name), "{name} requires a visible connection");
+ }
+ for name in ["dbx_list_connections", "dbx_add_connection", "dbx_duplicate_connection"] {
+ assert!(names.contains(name), "{name} is connection-less");
+ }
+ assert!(!names.contains("dbx_remove_connection"), "full-level removal needs a full global grant");
+ }
+
+ #[tokio::test]
+ async fn tools_list_and_connection_discovery_honor_global_none_access() {
+ let backend = Arc::new(FakeBackend {
+ access_policy: Some(dbx_core::mcp_access::McpAccessPolicy {
+ default_access: dbx_core::mcp_access::McpAccessLevel::None,
+ ..Default::default()
+ }),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+ let names =
+ server.policy_filtered_tools().await.into_iter().map(|tool| tool.name.to_string()).collect::<HashSet<_>>();
+ assert!(!names.contains("dbx_list_connections"), "read-level discovery needs a global grant");
+ assert!(!names.contains("dbx_add_connection"), "write-level management needs a global grant");
+
+ let result = server.list_connections(Parameters(ListConnectionsRequest {})).await;
+ assert!(result_text(&result).contains("MCP_READ_ONLY"), "{}", result_text(&result));
+ }
+
+ #[tokio::test]
+ async fn tools_list_hides_static_writes_for_read_only_resources() {
+ let mut access = dbx_core::mcp_access::McpAccessPolicy {
+ default_access: dbx_core::mcp_access::McpAccessLevel::Read,
+ ..Default::default()
+ };
+ access.rules.insert(
+ dbx_core::mcp_access::McpRuleTarget::Connection { id: "pg".into() },
+ dbx_core::mcp_access::McpAccessRule {
+ access: Some(dbx_core::mcp_access::McpAccessLevel::Read),
+ ..Default::default()
+ },
+ );
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("pg", "Postgres", "postgres", "app")],
+ access_policy: Some(access),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+ let names = server
+ .policy_filtered_tools()
+ .await
+ .into_iter()
+ .map(|tool| tool.name.to_string())
+ .collect::<std::collections::BTreeSet<_>>();
+ assert!(names.contains("dbx_execute_batch"));
+ assert!(!names.contains("dbx_begin_transaction"));
+ assert!(!names.contains("dbx_remove_connection"));
+ assert!(names.contains("dbx_execute_query"));
+ assert!(names.contains("dbx_list_tables"));
+ assert!(!names.contains("dbx_nacos_search_configs"));
+ assert!(!names.contains("dbx_nacos_rollback_config"));
+ assert!(!names.contains("dbx_consul_kv_get"));
+ assert!(!names.contains("dbx_salesforce_current_user"));
+ }
+
+ #[tokio::test]
+ async fn nacos_extended_tools_use_product_gateway() {
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("nacos", "Nacos", "nacos", "public")],
+ access_policy: Some(dbx_core::mcp_access::McpAccessPolicy {
+ default_access: dbx_core::mcp_access::McpAccessLevel::Full,
+ ..Default::default()
+ }),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let selector = || ConnectionSelector { connection_id: Some("nacos".into()), connection_name: None };
+ let _ = server
+ .nacos_search_configs(Parameters(NacosSearchConfigsRequest {
+ selector: selector(),
+ operation_id: "op-1".into(),
+ namespace: Some("public".into()),
+ scope: Some("currentNamespace".into()),
+ query: "host".into(),
+ group: None,
+ data_id: None,
+ max_results: Some(10),
+ }))
+ .await;
+ let _ = server
+ .nacos_rollback_config(Parameters(NacosRollbackConfigRequest {
+ selector: selector(),
+ namespace: Some("public".into()),
+ data_id: "app.yaml".into(),
+ group: "DEFAULT_GROUP".into(),
+ history_id: "h1".into(),
+ nid: Some(1),
+ }))
+ .await;
+ let _ = server
+ .nacos_get_service(Parameters(NacosServicesRequest {
+ selector: selector(),
+ namespace: Some("public".into()),
+ group_name: None,
+ service_name: Some("api".into()),
+ page_no: None,
+ page_size: None,
+ }))
+ .await;
+ let _ = server
+ .nacos_register_instance(Parameters(NacosRegisterInstanceRequest {
+ selector: selector(),
+ namespace: Some("public".into()),
+ service_name: "api".into(),
+ ip: "127.0.0.1".into(),
+ port: 8080,
+ group_name: None,
+ cluster_name: None,
+ weight: None,
+ metadata: None,
+ }))
+ .await;
+ let _ = server
+ .nacos_deregister_instance(Parameters(NacosDeregisterInstanceRequest {
+ selector: selector(),
+ namespace: Some("public".into()),
+ service_name: "api".into(),
+ ip: "127.0.0.1".into(),
+ port: 8080,
+ group_name: None,
+ cluster_name: None,
+ ephemeral: None,
+ }))
+ .await;
+ let operations = backend.product_calls.lock().unwrap().iter().map(|call| call.operation).collect::<Vec<_>>();
+ assert_eq!(
+ operations,
+ ["search_configs", "rollback_config", "get_service", "register_instance", "deregister_instance"]
+ );
}
#[test]
@@ -7107,10 +10614,11 @@ mod tests {
false,
);
let names = server.tool_router.list_all().into_iter().map(|tool| tool.name).collect::<Vec<_>>();
+ // Product tools stay available: they are bound to in-scope connections.
#[cfg(feature = "mq-admin")]
- assert_eq!(names.len(), 20);
+ assert_eq!(names.len(), 42);
#[cfg(not(feature = "mq-admin"))]
- assert_eq!(names.len(), 18);
+ assert_eq!(names.len(), 40);
assert!(!names.iter().any(|name| name == "dbx_add_connection"));
assert!(!names.iter().any(|name| name == "dbx_duplicate_connection"));
assert!(!names.iter().any(|name| name == "dbx_remove_connection"));
@@ -7225,6 +10733,219 @@ mod tests {
assert!(result_text(&result).contains("Set the db argument"));
}
+ #[tokio::test]
+ async fn dangerous_redis_commands_are_confirmed_when_the_switch_is_on() {
+ let run = |policy: McpGlobalPolicy, answer: Option<bool>| async move {
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("redis", "redis", "redis", "0")],
+ policy,
+ tool_approval_answer: answer,
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = server
+ .execute_redis_command(Parameters(ExecuteRedisCommandRequest {
+ selector: ConnectionSelector { connection_name: None, connection_id: Some("redis".to_string()) },
+ db: Some(0),
+ command: "FLUSHALL".to_string(),
+ }))
+ .await;
+ let asked = backend.tool_approvals.lock().unwrap().clone();
+ (result_text(&result).to_string(), asked)
+ };
+ let safe_write = McpGlobalPolicy { read_only: false, allow_dangerous_sql: false, ..Default::default() };
+
+ // Switch off: rejected without asking.
+ let (text, asked) = run(safe_write.clone(), Some(true)).await;
+ assert!(text.contains("REDIS_COMMAND_BLOCKED"), "{text}");
+ assert!(asked.is_empty());
+
+ // Switch on and confirmed: passes the gate and reaches the backend
+ // (the fake backend has no Redis, so it answers "not supported").
+ let confirm = McpGlobalPolicy { prompt_high_risk_sql: true, ..safe_write.clone() };
+ let (text, asked) = run(confirm.clone(), Some(true)).await;
+ assert!(!text.contains("REDIS_COMMAND_BLOCKED"), "{text}");
+ assert_eq!(asked.len(), 1);
+ assert_eq!(asked[0].kind, crate::approval::ToolApprovalKind::RedisCommand);
+ assert_eq!(asked[0].detail, "FLUSHALL");
+
+ // Denied: blocked.
+ let (text, _) = run(confirm.clone(), Some(false)).await;
+ assert!(text.contains("REDIS_COMMAND_BLOCKED"), "{text}");
+
+ // Read-only policies never offer a confirmation.
+ let (text, asked) =
+ run(McpGlobalPolicy { read_only: true, prompt_high_risk_sql: true, ..Default::default() }, Some(true))
+ .await;
+ assert!(text.contains("MCP_READ_ONLY"), "{text}");
+ assert!(asked.is_empty());
+ }
+
+ #[tokio::test]
+ async fn redis_confirmation_honors_v2_ceiling_and_rechecks_all_gates() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget, McpSubScopeMode};
+ for revocation in ["none", "tool", "scope", "ceiling"] {
+ let policy = McpGlobalPolicy {
+ read_only: false,
+ allow_dangerous_sql: true,
+ prompt_high_risk_sql: true,
+ ..Default::default()
+ };
+ let mut access = McpAccessPolicy::from_v1(&policy);
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "redis".into() },
+ McpAccessRule {
+ toolset_ceilings: [("redis".into(), McpAccessLevel::Write)].into(),
+ ..Default::default()
+ },
+ );
+ let mut after = access.clone();
+ let rule = after.rules.get_mut(&McpRuleTarget::Connection { id: "redis".into() }).unwrap();
+ if revocation == "scope" {
+ rule.sub_scope = Some(McpSubScopeMode::None);
+ }
+ if revocation == "ceiling" {
+ rule.toolset_ceilings.insert("redis".into(), McpAccessLevel::Read);
+ }
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("redis", "redis", "redis", "0")],
+ policy: policy.clone(),
+ access_policy: Some(access),
+ access_after_approval: Some(after),
+ policy_after_approval: (revocation == "tool")
+ .then_some(McpGlobalPolicy { allowed_tool_names: Some(vec![]), ..policy }),
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let result = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false)
+ .execute_redis_command(Parameters(ExecuteRedisCommandRequest {
+ selector: selector("redis"),
+ db: Some(0),
+ command: "FLUSHALL".into(),
+ }))
+ .await;
+ assert_eq!(backend.tool_approvals.lock().unwrap().len(), 1, "write ceiling requires approval");
+ // The fake has no Redis adapter: reaching it yields REDIS_COMMAND_ERROR.
+ assert_eq!(
+ result_text(&result).contains("REDIS_COMMAND_ERROR"),
+ revocation == "none",
+ "{revocation}: {}",
+ result_text(&result)
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn redis_database_permissions_follow_saved_settings_and_recheck_revocations() {
+ for (global_read, database_read, revoke) in
+ [(false, true, false), (false, false, false), (true, false, false), (false, false, true)]
+ {
+ let policy = McpGlobalPolicy {
+ read_only: global_read,
+ allow_dangerous_sql: !global_read,
+ prompt_high_risk_sql: true,
+ connection_policies: vec![serde_json::from_value(json!({
+ "connectionId": "redis",
+ "executionModeConfigured": false,
+ "executionModePolicyVersion": 1,
+ "databaseScope": "selected",
+ "allowedDatabases": ["0"],
+ "databasePolicies": [{
+ "databaseName": "0", "readOnly": database_read, "allowDangerousSql": false
+ }]
+ }))
+ .unwrap()],
+ ..Default::default()
+ };
+ let mut after = dbx_core::mcp_access::McpAccessPolicy::from_v1(&policy);
+ after
+ .rules
+ .get_mut(&dbx_core::mcp_access::McpRuleTarget::Scope {
+ connection_id: "redis".into(),
+ scope: "database".into(),
+ value: "0".into(),
+ })
+ .unwrap()
+ .access = Some(dbx_core::mcp_access::McpAccessLevel::Read);
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("redis", "redis", "redis", "0")],
+ policy,
+ access_after_approval: revoke.then_some(after),
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let result = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false)
+ .execute_redis_command(Parameters(ExecuteRedisCommandRequest {
+ selector: selector("redis"),
+ db: Some(0),
+ command: if revoke { "FLUSHDB" } else { "SET key value" }.into(),
+ }))
+ .await;
+ let output = result_text(&result);
+ if database_read {
+ assert!(output.contains("MCP_READ_ONLY"), "{output}");
+ } else if revoke {
+ assert!(output.contains("approval was revoked"), "{output}");
+ } else {
+ // Reaching the fake Redis adapter proves the saved selected
+ // database and its explicit write override were admitted.
+ assert!(output.contains("REDIS_COMMAND_ERROR"), "{output}");
+ }
+ assert_eq!(backend.tool_approvals.lock().unwrap().len(), usize::from(revoke));
+ }
+ }
+
+ #[test]
+ fn redis_scope_aliases_preserve_selected_visibility_and_strictest_level() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget, McpSubScopeMode};
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ access.rules.insert(
+ McpRuleTarget::Connection { id: "redis".into() },
+ McpAccessRule { sub_scope: Some(McpSubScopeMode::Selected), ..Default::default() },
+ );
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "redis".into(), scope: "dbIndex".into(), value: "0".into() },
+ McpAccessRule { visible: Some(true), access: Some(McpAccessLevel::Write), ..Default::default() },
+ );
+ assert!(redis_database_access(&access, &[], "redis", 0).visible);
+ assert!(!redis_database_access(&access, &[], "redis", 1).visible);
+ access.rules.insert(
+ McpRuleTarget::Scope { connection_id: "redis".into(), scope: "database".into(), value: "0".into() },
+ McpAccessRule { visible: Some(true), ceiling: Some(McpAccessLevel::Read), ..Default::default() },
+ );
+ let resolved = redis_database_access(&access, &[], "redis", 0);
+ assert!(resolved.visible);
+ assert_eq!(resolved.level, McpAccessLevel::Read);
+ }
+
+ #[tokio::test]
+ async fn redis_toolset_ceiling_blocks_write_commands() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ let mut rule = McpAccessRule::default();
+ rule.toolset_ceilings.insert("redis".into(), McpAccessLevel::Read);
+ access.rules.insert(McpRuleTarget::Connection { id: "redis".into() }, rule);
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("redis", "redis", "redis", "0")],
+ policy: McpGlobalPolicy { read_only: false, allow_dangerous_sql: true, ..Default::default() },
+ access_policy: Some(access),
+ tool_approval_answer: Some(true),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = server
+ .execute_redis_command(Parameters(ExecuteRedisCommandRequest {
+ selector: ConnectionSelector { connection_name: None, connection_id: Some("redis".into()) },
+ db: Some(0),
+ command: "SET key value".into(),
+ }))
+ .await;
+ assert!(result_text(&result).contains("MCP_READ_ONLY"), "{}", result_text(&result));
+ assert!(backend.tool_approvals.lock().unwrap().is_empty());
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty());
+ }
+
#[test]
fn configured_database_allowlist_blocks_qualified_sql_references() {
let connection = connection("sql", "sql", "mysql", "reporting");
@@ -7325,6 +11046,37 @@ mod tests {
assert!(!is_database_discovery_sql("show tables"));
}
+ #[tokio::test]
+ async fn v2_none_access_blocks_cached_connection_tools_and_connection_listing() {
+ let mut access = dbx_core::mcp_access::McpAccessPolicy {
+ default_access: dbx_core::mcp_access::McpAccessLevel::Read,
+ ..Default::default()
+ };
+ access.rules.insert(
+ dbx_core::mcp_access::McpRuleTarget::Connection { id: "sql".into() },
+ dbx_core::mcp_access::McpAccessRule {
+ access: Some(dbx_core::mcp_access::McpAccessLevel::None),
+ ..Default::default()
+ },
+ );
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("sql", "sql", "mysql", "app")],
+ access_policy: Some(access),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+
+ // A client may retain a schema tool from an earlier tools/list response;
+ // connection resolution must still enforce the v2 access floor.
+ let databases = server.list_databases(Parameters(ListDatabasesRequest { selector: selector("sql") })).await;
+ assert!(result_text(&databases).contains("MCP_READ_ONLY"), "{}", result_text(&databases));
+
+ // Discovery must apply the same v2 floor, otherwise it would disclose
+ // connections that the policy has made inaccessible.
+ let connections = server.list_connections(Parameters(ListConnectionsRequest {})).await;
+ assert_eq!(result_text(&connections), "No connections configured in DBX.");
+ }
+
#[test]
fn schema_scope_is_a_hard_bound() {
let dameng = connection("dameng-1", "Dameng", "dameng", "APPDB");
@@ -7855,6 +11607,147 @@ mod tests {
assert_eq!(backend.transaction_owner_sql.lock().unwrap().as_slice(), ["START TRANSACTION", "ROLLBACK"]);
}
+ async fn check_queued_transaction_call(
+ batch: bool,
+ initial: McpGlobalPolicy,
+ current: McpGlobalPolicy,
+ revoke_token: bool,
+ expected_error: Option<&str>,
+ ) {
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("mysql", "mysql", "mysql", "app")],
+ policy: initial,
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let opened = server
+ .open_session(Parameters(OpenSessionRequest {
+ selector: selector("mysql"),
+ database: None,
+ enable_transactions: true,
+ }))
+ .await;
+ let session_id = opened_session_id(&opened);
+ let begun =
+ server.begin_transaction(Parameters(TransactionSessionRequest { session_id: session_id.clone() })).await;
+ assert!(!begun.is_error.unwrap_or(false), "{}", result_text(&begun));
+ let (session, _) = server.sessions.resolve(&session_id).await.into_parts();
+ let owner = session.unwrap().transaction_owner.clone().unwrap();
+ let lease = owner.acquire().await.unwrap();
+ let sql = if batch { "DELETE FROM accounts; SELECT 1" } else { "DELETE FROM accounts" };
+ let queued = async {
+ if batch {
+ server
+ .execute_batch(Parameters(ExecuteBatchQueryRequest {
+ selector: selector("mysql"),
+ database: None,
+ sql: sql.into(),
+ session_id: Some(session_id.clone()),
+ cell_window: CellWindowArgs::default(),
+ continue_on_error: None,
+ use_transaction: None,
+ }))
+ .await
+ } else {
+ server
+ .execute_query(Parameters(ExecuteQueryRequest {
+ selector: selector("mysql"),
+ database: None,
+ sql: sql.into(),
+ session_id: Some(session_id.clone()),
+ max_rows: None,
+ cell_char_offset: None,
+ cell_char_limit: None,
+ }))
+ .await
+ }
+ };
+ futures::pin_mut!(queued);
+ // Poll to the occupied lease, rather than relying on a sleep or task
+ // scheduling to put the request in the queue before changing policy.
+ assert!(futures::poll!(&mut queued).is_pending());
+ assert!(backend.consumed_sql.lock().unwrap().is_empty(), "approval must remain revocable while queued");
+ *backend.policy_override.lock().unwrap() = Some(current);
+ backend.sql_approval_revoked.store(revoke_token, std::sync::atomic::Ordering::SeqCst);
+ drop(lease);
+ let result = tokio::time::timeout(Duration::from_secs(2), queued).await.expect("queued call finishes");
+ if let Some(error) = expected_error {
+ assert_eq!(result.is_error, Some(true), "{}", result_text(&result));
+ assert!(result_text(&result).contains(error), "{}", result_text(&result));
+ assert_eq!(backend.transaction_owner_sql.lock().unwrap().as_slice(), ["START TRANSACTION"]);
+ assert!(backend.consumed_sql.lock().unwrap().is_empty());
+ } else {
+ assert!(!result.is_error.unwrap_or(false), "{}", result_text(&result));
+ let expected = if batch {
+ vec!["START TRANSACTION", "DELETE FROM accounts", "SELECT 1"]
+ } else {
+ vec!["START TRANSACTION", sql]
+ };
+ assert_eq!(*backend.transaction_owner_sql.lock().unwrap(), expected);
+ assert_eq!(backend.approved_sql.lock().unwrap().as_slice(), [sql]);
+ assert_eq!(backend.consumed_sql.lock().unwrap().as_slice(), [sql]);
+ }
+ server.close_session(Parameters(CloseSessionRequest { session_id: session_id.clone() })).await;
+ }
+
+ #[tokio::test]
+ async fn queued_transaction_calls_reject_confirmation_policy_changes() {
+ let off = McpGlobalPolicy { allow_dangerous_sql: true, ..Default::default() };
+ let high_risk = call_safety_policy(true);
+ let legacy = McpGlobalPolicy { prompt_high_risk_sql: true, ..Default::default() };
+ for batch in [false, true] {
+ for (before, after) in [
+ (off.clone(), high_risk.clone()),
+ (high_risk.clone(), off.clone()),
+ (high_risk.clone(), legacy.clone()),
+ (legacy.clone(), high_risk.clone()),
+ ] {
+ check_queued_transaction_call(batch, before, after, false, Some("confirmation policy changed")).await;
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn queued_transaction_calls_consume_valid_approval_only_after_lease() {
+ for batch in [false, true] {
+ for policy in
+ [call_safety_policy(true), McpGlobalPolicy { prompt_high_risk_sql: true, ..Default::default() }]
+ {
+ check_queued_transaction_call(batch, policy.clone(), policy, false, None).await;
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn queued_transaction_calls_reject_revoked_approvals_with_unchanged_policy() {
+ for batch in [false, true] {
+ for policy in
+ [call_safety_policy(true), McpGlobalPolicy { prompt_high_risk_sql: true, ..Default::default() }]
+ {
+ check_queued_transaction_call(
+ batch,
+ policy.clone(),
+ policy,
+ true,
+ Some("Invalid or replayed approval"),
+ )
+ .await;
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn queued_transaction_calls_cannot_use_confirmation_to_override_permission_downgrades() {
+ for batch in [false, true] {
+ for (after, error) in [
+ (call_safety_policy(false), "High-risk SQL is disabled"),
+ (McpGlobalPolicy { read_only: true, ..call_safety_policy(true) }, "MCP_READ_ONLY"),
+ ] {
+ check_queued_transaction_call(batch, call_safety_policy(true), after, false, Some(error)).await;
+ }
+ }
+ }
+
#[tokio::test]
async fn queued_transaction_query_rechecks_revoked_policy_before_io() {
let policy = McpGlobalPolicy { allow_dangerous_sql: true, ..Default::default() };
@@ -8706,7 +12599,12 @@ mod tests {
assert_eq!(history[0].database, "app");
assert_eq!(history[0].sql, "SELECT 1");
assert!(history[0].success);
- assert_eq!(history[0].details_json.as_deref(), Some(r#"{"source":"mcp"}"#));
+ let details: serde_json::Value = serde_json::from_str(history[0].details_json.as_deref().unwrap()).unwrap();
+ assert_eq!(details["source"], "mcp");
+ assert_eq!(details["transport"], "stdio");
+ assert_eq!(details["accessLevel"], "full");
+ assert_eq!(details["accessMode"], "classified");
+ assert_eq!(details["confirmation"], "not_required");
assert!(!history[1].success);
assert!(history[1].error.as_deref().unwrap_or_default().contains("query failed"));
}
@@ -9502,6 +13400,44 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn salesforce_toolset_ceiling_blocks_dml_even_when_legacy_opt_in_is_on() {
+ use dbx_core::mcp_access::{McpAccessLevel, McpAccessPolicy, McpAccessRule, McpRuleTarget};
+
+ let mut access = McpAccessPolicy { default_access: McpAccessLevel::Full, ..Default::default() };
+ let mut rule = McpAccessRule::default();
+ rule.toolset_ceilings.insert(dbx_core::mcp_access::SALESFORCE_WRITE_TOOLSET.to_string(), McpAccessLevel::Read);
+ access.rules.insert(McpRuleTarget::Connection { id: "sfdc".into() }, rule);
+ let backend = Arc::new(FakeBackend {
+ connections: vec![salesforce_connection()],
+ policy: salesforce_dml_policy(true, false),
+ access_policy: Some(access),
+ salesforce_identity: Some(salesforce_identity(Some(true))),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let result = server
+ .salesforce_prepare_write(prepare_request(
+ "update",
+ "Account",
+ Some("001x"),
+ Some(json!({ "Name": "Acme" })),
+ ))
+ .await;
+ assert!(result_text(&result).contains("SALESFORCE_DML_DISABLED"), "{}", result_text(&result));
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty());
+
+ let names = server
+ .policy_filtered_tools()
+ .await
+ .into_iter()
+ .map(|tool| tool.name.to_string())
+ .collect::<std::collections::BTreeSet<_>>();
+ assert!(names.contains("dbx_salesforce_current_user"), "{names:?}");
+ assert!(!names.contains("dbx_salesforce_prepare_write"), "{names:?}");
+ assert!(!names.contains("dbx_salesforce_apply_write"), "{names:?}");
+ }
+
#[tokio::test]
async fn salesforce_prepare_write_summarises_the_write_and_the_identity() {
let backend = salesforce_server(salesforce_dml_policy(true, false), Some(salesforce_identity(Some(true))));
diff --git a/crates/dbx-mcp/tests/plugin_tools_server.rs b/crates/dbx-mcp/tests/plugin_tools_server.rs
index 132737e170..b7c787ab5a 100644
--- a/crates/dbx-mcp/tests/plugin_tools_server.rs
+++ b/crates/dbx-mcp/tests/plugin_tools_server.rs
@@ -1,7 +1,8 @@
//! End-to-end external plugin-tools test against a real `.dbxp` package:
//! install → opt-in-filtered discovery → merged `tools/list` → server
//! dispatch of a connection-less tool through the real sidecar. The packaged
-//! plugin must declare `external_tools: true` to be exposed here.
+//! plugin must declare `external_tools: true` and the tool's access level in
+//! its `mcp.tools` map, and the user grant is saved below.
//!
//! The mechanism under test is plugin-agnostic; the ssh plugin is only the
//! concrete vehicle available here (mirroring `plugin_tools_bridge.rs`).
@@ -28,6 +29,21 @@ async fn ssh_package_tools_are_detected_listed_and_dispatched() {
let database_path = data_dir.path().join("dbx.db");
let storage = dbx_core::storage::Storage::open(&database_path).await.unwrap();
+ // Nothing is exposed before the user authorizes the plugin. The packaged
+ // manifest must declare `ssh_list_known_hosts` with an access level.
+ storage
+ .save_plugin_mcp_grant(
+ "io.dbx.ssh",
+ dbx_core::storage::PluginMcpGrant {
+ external: true,
+ ceiling: dbx_core::storage::PluginMcpAccessLevel::Full,
+ approved_tools: [("ssh_list_known_hosts".to_string(), dbx_core::storage::PluginMcpAccessLevel::Full)]
+ .into(),
+ disabled_tools: Vec::new(),
+ },
+ )
+ .await
+ .unwrap();
drop(storage);
// No saved connections: every tool below must bind connection-less.
let backend = LocalBackend::open_with_app_version(&database_path, "0.7.0").await.unwrap();
diff --git a/crates/dbx-mcp/tests/protocol.rs b/crates/dbx-mcp/tests/protocol.rs
index 30b99117c3..1f68a7d61b 100644
--- a/crates/dbx-mcp/tests/protocol.rs
+++ b/crates/dbx-mcp/tests/protocol.rs
@@ -2,7 +2,9 @@ use std::{collections::HashMap, sync::Arc, sync::Mutex};
use async_trait::async_trait;
use dbx_core::{
- agent_events::ToolResult, agent_tools::AgentSqlPermissions, models::connection::ConnectionConfig,
+ agent_events::ToolResult,
+ agent_tools::AgentSqlPermissions,
+ models::connection::{ConnectionConfig, DatabaseType},
storage::McpGlobalPolicy,
};
use dbx_mcp::{with_legacy_discovery_fallback, DbxBackend, DbxMcpServer, McpScope};
@@ -13,53 +15,6 @@ use rmcp::{
use serde_json::{json, Map, Value};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream};
-struct EmptyBackend;
-
-#[async_trait]
-impl DbxBackend for EmptyBackend {
- async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String> {
- Ok(McpGlobalPolicy::default())
- }
-
- async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {
- Ok(Vec::new())
- }
-
- async fn execute_agent_tool(
- &self,
- _connection: &ConnectionConfig,
- _database: &str,
- tool_name: &str,
- _arguments: Value,
- _permissions: AgentSqlPermissions,
- ) -> ToolResult {
- ToolResult {
- tool_call_id: "protocol-test".to_string(),
- tool_name: tool_name.to_string(),
- content: "ok".to_string(),
- is_error: false,
- explain_data: None,
- }
- }
-
- async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result<ConnectionConfig, String> {
- Ok(config)
- }
-
- async fn duplicate_connection_for_mcp(
- &self,
- _source_id: &str,
- _copy_id: &str,
- _copy_name: &str,
- ) -> Result<ConnectionConfig, String> {
- Err("not exercised".to_string())
- }
-
- async fn remove_connection_for_mcp(&self, _connection_id: &str) -> Result<bool, String> {
- Ok(true)
- }
-}
-
struct PolicyBackend {
policy: McpGlobalPolicy,
connections: Vec<ConnectionConfig>,
@@ -328,6 +283,27 @@ fn test_connection(id: &str, name: &str) -> ConnectionConfig {
.expect("test connection")
}
+fn catalog_connections() -> Vec<ConnectionConfig> {
+ DatabaseType::ALL
+ .iter()
+ .enumerate()
+ .map(|(index, db_type)| {
+ serde_json::from_value(json!({
+ "id": format!("catalog-{index}"),
+ "name": format!("catalog-{db_type:?}"),
+ "db_type": db_type,
+ "host": "",
+ "port": 0,
+ "username": "",
+ "password": "",
+ "database": "",
+ "ssl": false
+ }))
+ .expect("catalog test connection")
+ })
+ .collect()
+}
+
fn mysql_connection(id: &str, name: &str) -> ConnectionConfig {
serde_json::from_value(json!({
"id": id,
@@ -382,7 +358,7 @@ async fn list_results_include_complete_discriminator_for_modern_stdio_clients()
for hide_tools in [false, true] {
let backend = PolicyBackend {
policy: McpGlobalPolicy { allowed_tool_names: hide_tools.then(Vec::new), ..Default::default() },
- connections: Vec::new(),
+ connections: hide_tools.then(Vec::new).unwrap_or_else(|| vec![test_connection("local", "local-db")]),
group_paths: Ok(HashMap::new()),
};
let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
@@ -418,7 +394,15 @@ async fn list_results_include_complete_discriminator_for_modern_stdio_clients()
async fn list_results_preserve_legacy_stdio_shapes_after_initialize() {
for requested_version in ["2025-03-26", "2025-06-18", "2025-11-25", "2026-07-28"] {
let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
- let server = DbxMcpServer::with_runtime_options(Arc::new(EmptyBackend), McpScope::default(), false);
+ let server = DbxMcpServer::with_runtime_options(
+ Arc::new(PolicyBackend {
+ policy: McpGlobalPolicy::default(),
+ connections: vec![test_connection("local", "local-db")],
+ group_paths: Ok(HashMap::new()),
+ }),
+ McpScope::default(),
+ false,
+ );
let server_task =
tokio::spawn(async move { server.serve(with_legacy_discovery_fallback(server_transport)).await });
let mut client = BufReader::new(client_transport);
@@ -459,17 +443,41 @@ async fn list_results_preserve_legacy_stdio_shapes_after_initialize() {
#[tokio::test]
async fn initializes_lists_tools_and_calls_a_tool() {
+ let connections = catalog_connections();
+ // The full catalog includes Salesforce writes only after an explicit
+ // per-connection DML opt-in; the global SQL ceiling is not that consent.
+ let connection_policies = connections
+ .iter()
+ .filter(|connection| connection.db_type == DatabaseType::Salesforce)
+ .map(|connection| {
+ serde_json::from_value(json!({
+ "connectionId": connection.id,
+ "executionModeConfigured": false,
+ "allowSalesforceDml": true
+ }))
+ .expect("Salesforce catalog policy")
+ })
+ .collect();
let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
- let server = DbxMcpServer::with_runtime_options(Arc::new(EmptyBackend), McpScope::default(), false);
+ let server = DbxMcpServer::with_runtime_options(
+ Arc::new(PolicyBackend {
+ policy: McpGlobalPolicy { allow_dangerous_sql: true, connection_policies, ..Default::default() },
+ connections,
+ group_paths: Ok(HashMap::new()),
+ }),
+ McpScope::default(),
+ false,
+ );
let server_task = tokio::spawn(async move { server.serve(server_transport).await });
let client = ().serve(client_transport).await.expect("initialize MCP client");
let tools = client.peer().list_tools(None).await.expect("list tools");
let names = tools.tools.iter().map(|tool| tool.name.as_ref()).collect::<Vec<_>>();
+ // Includes the 22 product-provider tools (14 Nacos + 8 Consul).
#[cfg(feature = "mq-admin")]
- assert_eq!(names.len(), 25);
+ assert_eq!(names.len(), 47);
#[cfg(not(feature = "mq-admin"))]
- assert_eq!(names.len(), 23);
+ assert_eq!(names.len(), 45);
#[cfg(feature = "mq-admin")]
assert!(names.contains(&"dbx_peek_messages"));
#[cfg(not(feature = "mq-admin"))]
@@ -513,11 +521,58 @@ async fn initializes_lists_tools_and_calls_a_tool() {
panic!("connections resource should be text");
};
assert_eq!(mime_type.as_deref(), Some("text/markdown"));
- assert_eq!(text, "No connections configured in DBX.");
+ assert!(text.contains("catalog-"), "{text}");
let result = client.peer().call_tool(CallToolRequestParams::new("dbx_list_connections")).await.expect("call tool");
let response = result.content[0].as_text().expect("text response");
- assert_eq!(response.text, "No connections configured in DBX.");
+ assert!(response.text.contains("catalog-"), "{}", response.text);
+
+ client.cancel().await.expect("close MCP client");
+ server_task.abort();
+}
+
+#[tokio::test]
+async fn salesforce_write_tools_require_explicit_connection_opt_in() {
+ let connection = catalog_connections()
+ .into_iter()
+ .find(|connection| connection.db_type == DatabaseType::Salesforce)
+ .expect("Salesforce catalog connection");
+ let connection_id = connection.id.clone();
+ let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
+ let server = DbxMcpServer::with_runtime_options(
+ Arc::new(PolicyBackend {
+ policy: McpGlobalPolicy { allow_dangerous_sql: true, ..Default::default() },
+ connections: vec![connection],
+ group_paths: Ok(HashMap::new()),
+ }),
+ McpScope::default(),
+ false,
+ );
+ let server_task = tokio::spawn(async move { server.serve(server_transport).await });
+ let client = ().serve(client_transport).await.expect("initialize MCP client");
+
+ let tools = client.peer().list_tools(None).await.expect("list tools");
+ let names = tools.tools.iter().map(|tool| tool.name.as_ref()).collect::<Vec<_>>();
+ assert!(names.contains(&"dbx_salesforce_current_user"));
+ assert!(names.contains(&"dbx_execute_query"));
+ assert!(!names.contains(&"dbx_salesforce_prepare_write"));
+ assert!(!names.contains(&"dbx_salesforce_apply_write"));
+
+ // Hiding tools is not sufficient: a client that already knows the name
+ // must still be denied when it sends a valid write request directly.
+ let result = client
+ .peer()
+ .call_tool(CallToolRequestParams::new("dbx_salesforce_prepare_write").with_arguments(
+ json!({"connection_id": connection_id, "op": "insert", "object": "Account", "fields": {"Name": "Acme"}})
+ .as_object()
+ .unwrap()
+ .clone(),
+ ))
+ .await
+ .expect("receive denied write result");
+ assert_eq!(result.is_error, Some(true));
+ let response = result.content[0].as_text().expect("text response");
+ assert!(response.text.contains("SALESFORCE_DML_DISABLED"), "{}", response.text);
client.cancel().await.expect("close MCP client");
server_task.abort();
diff --git a/crates/dbx-plugin-runtime/src/plugins.rs b/crates/dbx-plugin-runtime/src/plugins.rs
index 390cc0f31c..8648f825e4 100644
--- a/crates/dbx-plugin-runtime/src/plugins.rs
+++ b/crates/dbx-plugin-runtime/src/plugins.rs
@@ -50,7 +50,8 @@ pub use manifest::{
PluginDriverManifest, PluginEngines, PluginEntrypoints, PluginFieldCondition, PluginFieldConditionClause,
PluginFieldConditionLiteral, PluginFilesystemCapability, PluginFilesystemProviderContribution,
PluginFormFieldBinding, PluginFormFieldDefinition, PluginFormFieldOption, PluginFormFieldPicker,
- PluginFormFieldPickerKind, PluginFormFieldType, PluginManifest, PluginUiEntrypoint, PluginWorkbenchContribution,
+ PluginFormFieldPickerKind, PluginFormFieldType, PluginManifest, PluginMcpAccess, PluginMcpContribution,
+ PluginMcpScope, PluginMcpToolDeclaration, PluginMcpToolset, PluginUiEntrypoint, PluginWorkbenchContribution,
PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD, PLUGIN_CONNECTION_DISCONNECT_METHOD,
PLUGIN_CONNECTION_TEST_METHOD, SUPPORTED_PLUGIN_HOST_API_VERSION, SUPPORTED_PLUGIN_HOST_FEATURES,
SUPPORTED_PLUGIN_MANIFEST_VERSION, SUPPORTED_PLUGIN_PERMISSIONS, SUPPORTED_PLUGIN_PROTOCOL_VERSION,
diff --git a/crates/dbx-plugin-runtime/src/plugins/manifest.rs b/crates/dbx-plugin-runtime/src/plugins/manifest.rs
index 181f93f79b..874d8c8bfe 100644
--- a/crates/dbx-plugin-runtime/src/plugins/manifest.rs
+++ b/crates/dbx-plugin-runtime/src/plugins/manifest.rs
@@ -309,6 +309,81 @@ pub struct PluginMcpContribution {
/// `false`; set to `true` to opt in to that surface.
#[serde(default, skip_serializing_if = "is_false")]
pub external_tools: bool,
+ /// Optional grouping of the plugin's tools for the MCP settings UI. A
+ /// plugin without toolsets shows as one group.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub toolsets: Vec<PluginMcpToolset>,
+ /// Per-tool declarations keyed by the tool name `mcp/tools` returns. On
+ /// the external `dbx` MCP server only tools declared here with an
+ /// `access` level can be exposed; MCP annotations are not a substitute.
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub tools: BTreeMap<String, PluginMcpToolDeclaration>,
+ /// Optional sub-scope below a connection (a Kubernetes namespace, a
+ /// directory, …) that users can allow or restrict per connection, like
+ /// databases for SQL connections. The host reads the declared argument
+ /// from each call and enforces the access policy before forwarding.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub scope: Option<PluginMcpScope>,
+}
+
+/// A plugin-declared sub-scope kind.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginMcpScope {
+ /// Scope kind id, e.g. `namespace`. Must not be `database` (reserved for
+ /// the built-in database scope).
+ pub kind: String,
+ /// Display name in the access-control tree, e.g. "Namespace".
+ pub title: String,
+ /// Tool argument that carries the scope value. When a connection uses
+ /// selected or none sub-scope admission, the host requires this argument
+ /// on every scope-bound call; only an all-scopes connection may evaluate a
+ /// missing argument at connection level.
+ pub argument: String,
+ /// Optional sidecar method listing a connection's scope values
+ /// (`{ connectionId } → { values: [string] }`), for the settings picker.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub list_method: Option<String>,
+}
+
+/// One group of plugin MCP tools.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginMcpToolset {
+ pub id: String,
+ pub title: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+}
+
+/// Highest access a plugin MCP tool can reach, declared by its author.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum PluginMcpAccess {
+ Read,
+ Write,
+ Full,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginMcpToolDeclaration {
+ /// Toolset id from `toolsets`; omitted tools join the default group.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub toolset: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub access: Option<PluginMcpAccess>,
+}
+
+impl PluginMcpContribution {
+ /// The declared access of `tool`, if the author declared one.
+ pub fn declared_access(&self, tool: &str) -> Option<PluginMcpAccess> {
+ self.tools.get(tool).and_then(|declaration| declaration.access)
+ }
+
+ pub fn declared_toolset(&self, tool: &str) -> Option<&str> {
+ self.tools.get(tool).and_then(|declaration| declaration.toolset.as_deref())
+ }
}
fn default_true() -> bool {
@@ -1058,6 +1133,14 @@ impl PluginManifest {
})
}
+ /// Whether the plugin carries the "provides MCP tools" mark: a backend plus
+ /// an `mcp` contribution. Only marked plugins appear in the MCP settings
+ /// (capability tab) and the Plugin Center's MCP filter; a plugin without
+ /// the mark has no MCP surface at all.
+ pub fn provides_mcp_tools(&self) -> bool {
+ self.backend_entrypoint().is_some() && self.mcp_contribution().is_some()
+ }
+
/// Whether the optional `mcp` declaration keeps the sidecar tools off the
/// built-in AI agent (`ai_tools: false`) even when the user opts in via
/// the Plugin Center. Without it the tools participate once opted in.
@@ -1158,6 +1241,16 @@ impl PluginManifest {
plugin_dir,
&mut errors,
);
+ // Missing external access declarations must not disable an older
+ // plugin's drivers or AI tools. The MCP exposure gate hides those tools.
+ if let Some(mcp) = self.mcp_contribution() {
+ if mcp.external_tools && !mcp.tools.values().any(|declaration| declaration.access.is_some()) {
+ warnings.push(format!(
+ "Mcp contribution '{}' sets external_tools but declares no tool access level; external tools remain hidden until declared under `tools` with `access`",
+ mcp.id
+ ));
+ }
+ }
let target = current_plugin_target();
let backend_executable = self.backend_entrypoint().and_then(|backend| {
@@ -1572,6 +1665,53 @@ fn validate_contributions(
if !has_backend {
errors.push(format!("Mcp contribution '{id}' requires a backend entrypoint"));
}
+ let mut toolset_ids = HashSet::new();
+ for toolset in &mcp.toolsets {
+ if !is_plugin_mcp_identifier(&toolset.id) {
+ errors.push(format!("Mcp contribution '{id}' toolset id '{}' is invalid", toolset.id));
+ }
+ if !toolset_ids.insert(toolset.id.as_str()) {
+ errors
+ .push(format!("Mcp contribution '{id}' declares toolset '{}' more than once", toolset.id));
+ }
+ validate_required_text(&toolset.title, &format!("Mcp toolset '{}' title", toolset.id), errors);
+ validate_optional_text(
+ toolset.description.as_deref(),
+ &format!("Mcp toolset '{}' description", toolset.id),
+ errors,
+ );
+ }
+ if mcp.tools.len() > MAX_PLUGIN_MCP_TOOL_DECLARATIONS {
+ errors.push(format!(
+ "Mcp contribution '{id}' declares {} tools; at most {MAX_PLUGIN_MCP_TOOL_DECLARATIONS} are allowed",
+ mcp.tools.len()
+ ));
+ }
+ if let Some(scope) = &mcp.scope {
+ if !is_plugin_mcp_identifier(&scope.kind) || scope.kind == "database" {
+ errors.push(format!(
+ "Mcp contribution '{id}' scope kind '{}' is invalid or reserved",
+ scope.kind
+ ));
+ }
+ validate_required_text(&scope.title, &format!("Mcp contribution '{id}' scope title"), errors);
+ if scope.argument.trim().is_empty() || scope.argument.chars().count() > 64 {
+ errors.push(format!("Mcp contribution '{id}' scope argument '{}' is invalid", scope.argument));
+ }
+ if scope.list_method.as_deref().is_some_and(|method| method.trim().is_empty()) {
+ errors.push(format!("Mcp contribution '{id}' scope list_method cannot be empty when present"));
+ }
+ }
+ for (tool, declaration) in &mcp.tools {
+ if tool.trim().is_empty() || tool.chars().count() > 128 {
+ errors.push(format!("Mcp contribution '{id}' declares an invalid tool name '{tool}'"));
+ }
+ if let Some(toolset) = &declaration.toolset {
+ if !toolset_ids.contains(toolset.as_str()) {
+ errors.push(format!("Mcp tool '{tool}' references missing toolset '{toolset}'"));
+ }
+ }
+ }
}
}
}
@@ -1985,6 +2125,17 @@ fn validate_optional_reference(value: Option<&str>, label: &str, contribution_id
}
}
+/// Upper bound for per-tool declarations in one `mcp` contribution; matches
+/// the host's per-plugin tool cap (`MAX_TOOLS_PER_PLUGIN` in dbx-core).
+const MAX_PLUGIN_MCP_TOOL_DECLARATIONS: usize = 64;
+
+fn is_plugin_mcp_identifier(value: &str) -> bool {
+ let mut chars = value.chars();
+ value.len() <= 64
+ && chars.next().is_some_and(|first| first.is_ascii_lowercase() || first.is_ascii_digit())
+ && chars.all(|char| char.is_ascii_lowercase() || char.is_ascii_digit() || matches!(char, '.' | '_' | '-'))
+}
+
fn validate_required_text(value: &str, label: &str, errors: &mut Vec<String>) {
if value.trim().is_empty() {
errors.push(format!("{label} cannot be empty"));
@@ -2054,13 +2205,15 @@ fn valid_locale_tag(value: &str) -> bool {
#[cfg(test)]
mod tests {
+ use std::collections::BTreeMap;
+
use super::{
parse_host_network_permission, resolve_safe_plugin_path, validate_connection_actions, validate_contributions,
PluginCommandAction, PluginCommandContribution, PluginCommandPresentation, PluginCommandRestore,
PluginCommandReuse, PluginConnectionActionContribution, PluginConnectionProviderContribution,
- PluginContribution, PluginFormFieldBinding, PluginManifest, PluginMcpContribution, PluginMenuItem,
- PluginMenuLocation, PluginMenusContribution, PluginOpenWorkbenchAction, SUPPORTED_PLUGIN_HOST_API_VERSION,
- SUPPORTED_PLUGIN_PERMISSIONS,
+ PluginContribution, PluginFormFieldBinding, PluginManifest, PluginMcpAccess, PluginMcpContribution,
+ PluginMcpToolDeclaration, PluginMenuItem, PluginMenuLocation, PluginMenusContribution,
+ PluginOpenWorkbenchAction, SUPPORTED_PLUGIN_HOST_API_VERSION, SUPPORTED_PLUGIN_PERMISSIONS,
};
fn context_menu_manifest(menu: &str) -> Result<(tempfile::TempDir, PluginManifest), Box<dyn std::error::Error>> {
@@ -2125,6 +2278,12 @@ mod tests {
description: None,
ai_tools: true,
external_tools: true,
+ toolsets: Vec::new(),
+ scope: None,
+ tools: BTreeMap::from([(
+ "ping".to_string(),
+ PluginMcpToolDeclaration { toolset: None, access: Some(PluginMcpAccess::Read) },
+ )]),
});
let mut errors = Vec::new();
validate_contributions(std::slice::from_ref(&mcp), false, false, &plugin_dir, &mut errors);
@@ -2134,12 +2293,112 @@ mod tests {
validate_contributions(std::slice::from_ref(&mcp), true, false, &plugin_dir, &mut errors);
assert!(errors.is_empty(), "{errors:?}");
+ // Missing external declarations do not invalidate the whole plugin.
+ let PluginContribution::Mcp(undeclared) = &mcp else { unreachable!() };
+ let undeclared =
+ PluginContribution::Mcp(PluginMcpContribution { tools: BTreeMap::new(), ..undeclared.clone() });
+ let mut errors = Vec::new();
+ validate_contributions(std::slice::from_ref(&undeclared), true, false, &plugin_dir, &mut errors);
+ assert!(errors.is_empty(), "{errors:?}");
+
let two = vec![mcp.clone(), mcp];
let mut errors = Vec::new();
validate_contributions(&two, true, false, &plugin_dir, &mut errors);
assert!(errors.iter().any(|error| error.contains("at most one")), "{errors:?}");
}
+ #[test]
+ fn mcp_contribution_declares_toolsets_and_tool_access() {
+ let mcp: PluginContribution = serde_json::from_value(serde_json::json!({
+ "type": "mcp",
+ "id": "io.dbx.example.mcp",
+ "external_tools": true,
+ "toolsets": [
+ { "id": "files", "title": "Files" },
+ { "id": "shell", "title": "Remote shell", "description": "Run commands" }
+ ],
+ "tools": {
+ "sftp_list_dir": { "toolset": "files", "access": "read" },
+ "ssh_exec": { "toolset": "shell", "access": "full" },
+ "sftp_upload": { "access": "write" }
+ }
+ }))
+ .unwrap();
+ let PluginContribution::Mcp(parsed) = &mcp else { unreachable!() };
+ assert_eq!(parsed.declared_access("ssh_exec"), Some(PluginMcpAccess::Full));
+ assert_eq!(parsed.declared_toolset("sftp_list_dir"), Some("files"));
+ assert_eq!(parsed.declared_toolset("sftp_upload"), None);
+ assert_eq!(parsed.declared_access("unknown"), None);
+ let plugin_dir = std::env::temp_dir();
+ let mut errors = Vec::new();
+ validate_contributions(std::slice::from_ref(&mcp), true, false, &plugin_dir, &mut errors);
+ assert!(errors.is_empty(), "{errors:?}");
+
+ // Unknown access levels and unknown fields reject at parse time.
+ assert!(serde_json::from_value::<PluginContribution>(serde_json::json!({
+ "type": "mcp", "id": "x", "tools": { "t": { "access": "admin" } }
+ }))
+ .is_err());
+ assert!(serde_json::from_value::<PluginContribution>(serde_json::json!({
+ "type": "mcp", "id": "x", "toolsets": [{ "id": "a", "title": "A", "icon": "x" }]
+ }))
+ .is_err());
+ }
+
+ #[test]
+ fn mcp_contribution_declares_a_scope() {
+ let mcp: PluginContribution = serde_json::from_value(serde_json::json!({
+ "type": "mcp",
+ "id": "io.dbx.k8s.mcp",
+ "external_tools": true,
+ "tools": { "get_pods": { "access": "read" } },
+ "scope": { "kind": "namespace", "title": "Namespace", "argument": "namespace", "list_method": "mcp/scopes" }
+ }))
+ .unwrap();
+ let PluginContribution::Mcp(parsed) = &mcp else { unreachable!() };
+ let scope = parsed.scope.as_ref().unwrap();
+ assert_eq!((scope.kind.as_str(), scope.argument.as_str()), ("namespace", "namespace"));
+ let mut errors = Vec::new();
+ validate_contributions(std::slice::from_ref(&mcp), true, false, &std::env::temp_dir(), &mut errors);
+ assert!(errors.is_empty(), "{errors:?}");
+
+ let reserved: PluginContribution = serde_json::from_value(serde_json::json!({
+ "type": "mcp", "id": "x", "scope": { "kind": "database", "title": " ", "argument": "" }
+ }))
+ .unwrap();
+ let mut errors = Vec::new();
+ validate_contributions(std::slice::from_ref(&reserved), true, false, &std::env::temp_dir(), &mut errors);
+ let joined = errors.join("\n");
+ assert!(
+ joined.contains("invalid or reserved")
+ && joined.contains("scope title")
+ && joined.contains("scope argument"),
+ "{joined}"
+ );
+ }
+
+ #[test]
+ fn mcp_contribution_rejects_broken_toolset_references() {
+ let mcp: PluginContribution = serde_json::from_value(serde_json::json!({
+ "type": "mcp",
+ "id": "io.dbx.example.mcp",
+ "toolsets": [
+ { "id": "files", "title": "Files" },
+ { "id": "files", "title": "Again" },
+ { "id": "Bad Id", "title": " " }
+ ],
+ "tools": { "ssh_exec": { "toolset": "shell" } }
+ }))
+ .unwrap();
+ let mut errors = Vec::new();
+ validate_contributions(std::slice::from_ref(&mcp), true, false, &std::env::temp_dir(), &mut errors);
+ let joined = errors.join("\n");
+ assert!(joined.contains("declares toolset 'files' more than once"), "{joined}");
+ assert!(joined.contains("toolset id 'Bad Id' is invalid"), "{joined}");
+ assert!(joined.contains("title cannot be empty"), "{joined}");
+ assert!(joined.contains("references missing toolset 'shell'"), "{joined}");
+ }
+
#[test]
fn full_manifest_parses_the_mcp_declaration() {
let dir = tempfile::tempdir().unwrap();
@@ -2160,10 +2419,35 @@ mod tests {
}]
}))
.unwrap();
+ assert!(manifest.provides_mcp_tools(), "backend + mcp contribution carries the MCP mark");
assert!(!manifest.ai_tools_excluded(), "ai_tools defaults to participating");
assert!(manifest.external_tools_excluded(), "external_tools defaults to off");
let compatibility = manifest.compatibility(dir.path(), "0.6.0");
assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ assert!(compatibility.warnings.is_empty(), "{:?}", compatibility.warnings);
+
+ let mut manifest = manifest;
+ let PluginContribution::Mcp(mcp) = &mut manifest.contributions[0] else { unreachable!() };
+ mcp.external_tools = true;
+ for tools in [BTreeMap::new(), BTreeMap::from([("ping".to_string(), PluginMcpToolDeclaration::default())])] {
+ let PluginContribution::Mcp(mcp) = &mut manifest.contributions[0] else { unreachable!() };
+ mcp.tools = tools;
+ let compatibility = manifest.compatibility(dir.path(), "0.6.0");
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ assert!(
+ compatibility.warnings.iter().any(|warning| warning.contains("external tools remain hidden")),
+ "{:?}",
+ compatibility.warnings
+ );
+ assert!(!manifest.ai_tools_excluded());
+ assert!(manifest.provides_mcp_tools());
+ }
+
+ let PluginContribution::Mcp(mcp) = &mut manifest.contributions[0] else { unreachable!() };
+ mcp.tools.get_mut("ping").unwrap().access = Some(PluginMcpAccess::Read);
+ let compatibility = manifest.compatibility(dir.path(), "0.6.0");
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ assert!(compatibility.warnings.is_empty(), "{:?}", compatibility.warnings);
}
#[test]
diff --git a/crates/dbx-plugin-runtime/src/plugins/marketplace.rs b/crates/dbx-plugin-runtime/src/plugins/marketplace.rs
index bb20ade844..1c9e281fbd 100644
--- a/crates/dbx-plugin-runtime/src/plugins/marketplace.rs
+++ b/crates/dbx-plugin-runtime/src/plugins/marketplace.rs
@@ -112,6 +112,10 @@ pub struct PluginMarketplacePlugin {
pub tags: Vec<String>,
#[serde(default)]
pub permissions: Vec<String>,
+ /// The plugin provides MCP tools (its manifest declares an `mcp`
+ /// contribution). Lets the store show the MCP mark before install.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub mcp_tools: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -843,6 +847,7 @@ mod tests {
icon: Some("../assets/icon.svg".to_string()),
tags: vec!["hello".to_string()],
permissions: vec!["host.events".to_string()],
+ mcp_tools: false,
source: None,
homepage: None,
license: Some("Apache-2.0".to_string()),
@@ -1119,6 +1124,7 @@ mod tests {
icon: None,
tags: vec![],
permissions: vec![],
+ mcp_tools: false,
source: None,
homepage: None,
license: None,
diff --git a/crates/dbx-types/src/database_manifest.rs b/crates/dbx-types/src/database_manifest.rs
index 21f51a8553..450ff384cf 100644
--- a/crates/dbx-types/src/database_manifest.rs
+++ b/crates/dbx-types/src/database_manifest.rs
@@ -69,6 +69,48 @@ pub struct ManagedDriverEntry {
pub store_order: Option<u32>,
}
+#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum DatabaseSupportLevel {
+ Connect,
+ Browse,
+ Understand,
+ Operate,
+}
+
+/// Product capabilities a connection type advertises. Flags the descriptor
+/// omits fall back to its support level's defaults (see [`DatabaseManifestEntry::capability`]),
+/// matching the frontend's `databaseDriverManifest.ts`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum DatabaseCapability {
+ QueryExecution,
+ MetadataBrowse,
+ ObjectBrowser,
+ ObjectSource,
+ SchemaSearch,
+ TableDataEdit,
+ SqlFileExecution,
+}
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DatabaseCapabilityFlags {
+ #[serde(default)]
+ pub query_execution: Option<bool>,
+ #[serde(default)]
+ pub metadata_browse: Option<bool>,
+ #[serde(default)]
+ pub object_browser: Option<bool>,
+ #[serde(default)]
+ pub object_source: Option<bool>,
+ #[serde(default)]
+ pub schema_search: Option<bool>,
+ #[serde(default)]
+ pub table_data_edit: Option<bool>,
+ #[serde(default)]
+ pub sql_file_execution: Option<bool>,
+}
+
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseManifestEntry {
@@ -106,6 +148,37 @@ pub struct DatabaseManifestEntry {
pub local_file: bool,
#[serde(default)]
pub specialized_surface: bool,
+ pub support_level: DatabaseSupportLevel,
+ #[serde(default)]
+ pub capabilities: DatabaseCapabilityFlags,
+}
+
+impl DatabaseManifestEntry {
+ pub fn capability(&self, capability: DatabaseCapability) -> bool {
+ let flags = &self.capabilities;
+ let explicit = match capability {
+ DatabaseCapability::QueryExecution => flags.query_execution,
+ DatabaseCapability::MetadataBrowse => flags.metadata_browse,
+ DatabaseCapability::ObjectBrowser => flags.object_browser,
+ DatabaseCapability::ObjectSource => flags.object_source,
+ DatabaseCapability::SchemaSearch => flags.schema_search,
+ DatabaseCapability::TableDataEdit => flags.table_data_edit,
+ DatabaseCapability::SqlFileExecution => flags.sql_file_execution,
+ };
+ explicit.unwrap_or_else(|| support_level_default(self.support_level, capability))
+ }
+}
+
+fn support_level_default(level: DatabaseSupportLevel, capability: DatabaseCapability) -> bool {
+ use DatabaseCapability::*;
+ match capability {
+ QueryExecution => level == DatabaseSupportLevel::Connect,
+ SqlFileExecution => true,
+ MetadataBrowse | ObjectBrowser => level != DatabaseSupportLevel::Connect,
+ SchemaSearch => matches!(level, DatabaseSupportLevel::Understand | DatabaseSupportLevel::Operate),
+ TableDataEdit => level == DatabaseSupportLevel::Operate,
+ ObjectSource => false,
+ }
}
static DATABASE_MANIFEST: OnceLock<DatabaseManifestFile> = OnceLock::new();
@@ -148,6 +221,10 @@ pub fn supports_compare_mode(db_type: &DatabaseType, mode: DatabaseCompareMode)
entry(db_type).is_some_and(|candidate| candidate.compare_modes.contains(&mode))
}
+pub fn supports_capability(db_type: &DatabaseType, capability: DatabaseCapability) -> bool {
+ entry(db_type).is_some_and(|candidate| candidate.capability(capability))
+}
+
pub fn is_agent_runtime(db_type: &DatabaseType) -> bool {
entry(db_type).is_some_and(|candidate| candidate.runtime_mode == DatabaseRuntimeMode::Agent)
}
@@ -177,6 +254,16 @@ mod tests {
}
}
+ #[test]
+ fn capabilities_fall_back_to_support_level_defaults() {
+ assert!(supports_capability(&DatabaseType::Mysql, DatabaseCapability::ObjectSource));
+ assert!(!supports_capability(&DatabaseType::Sqlite, DatabaseCapability::ObjectSource));
+ assert!(supports_capability(&DatabaseType::Sqlite, DatabaseCapability::QueryExecution));
+ assert!(!supports_capability(&DatabaseType::Nacos, DatabaseCapability::QueryExecution));
+ assert!(!support_level_default(DatabaseSupportLevel::Operate, DatabaseCapability::QueryExecution));
+ assert!(support_level_default(DatabaseSupportLevel::Browse, DatabaseCapability::MetadataBrowse));
+ }
+
#[test]
fn manifest_contains_connection_runtime_defaults() {
assert_eq!(entry(&DatabaseType::Mysql).map(|entry| entry.default_port), Some(Some(3306)));
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index d770b97eca..7c62c0adf4 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -1496,6 +1496,14 @@ async fn serve() -> Result<(), String> {
"/app-settings/mcp-policy",
get(routes::app_settings::load_mcp_global_policy).put(routes::app_settings::save_mcp_global_policy),
)
+ .route("/app-settings/mcp-tool-catalog", get(routes::app_settings::load_mcp_tool_catalog))
+ .route("/app-settings/mcp-access-policy", get(routes::app_settings::load_mcp_access_policy))
+ .route("/app-settings/mcp-access-policy/recover", post(routes::app_settings::reset_invalid_mcp_access_policy))
+ .route("/app-settings/mcp-access-policy/plugin-scope", put(routes::app_settings::set_mcp_plugin_scope_rule))
+ .route("/app-settings/plugin-mcp", get(routes::app_settings::list_plugin_mcp_views))
+ .route("/app-settings/plugin-mcp/view", post(routes::app_settings::load_plugin_mcp_view))
+ .route("/app-settings/plugin-mcp/scopes", post(routes::app_settings::list_plugin_mcp_scopes))
+ .route("/app-settings/plugin-mcp/grant", put(routes::app_settings::save_plugin_mcp_grant))
.route("/app-settings/mcp-http-status", get(routes::app_settings::load_web_mcp_http_status))
.route("/app-settings/mcp-http", put(routes::app_settings::save_web_mcp_http_settings))
.route("/app-settings/mcp-http/rotate-token", post(routes::app_settings::rotate_web_mcp_token))
diff --git a/crates/dbx-web/src/routes/app_settings.rs b/crates/dbx-web/src/routes/app_settings.rs
index 0845a8eb40..85ac2f7270 100644
--- a/crates/dbx-web/src/routes/app_settings.rs
+++ b/crates/dbx-web/src/routes/app_settings.rs
@@ -61,6 +61,149 @@ pub async fn load_mcp_global_policy(
state.app.storage.load_mcp_global_policy().await.map(Json).map_err(AppError::from)
}
+pub async fn load_mcp_tool_catalog() -> Json<dbx_core::mcp_catalog::McpToolCatalog> {
+ Json(dbx_mcp::DbxMcpServer::tool_catalog())
+}
+
+pub async fn list_plugin_mcp_views(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<Vec<dbx_core::plugin_mcp::PluginMcpView>>, AppError> {
+ dbx_core::plugin_mcp::list_plugin_views(&state.app).await.map(Json).map_err(AppError::from)
+}
+
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginMcpViewRequest {
+ pub plugin_id: String,
+}
+
+pub async fn load_plugin_mcp_view(
+ State(state): State<Arc<WebState>>,
+ Json(body): Json<PluginMcpViewRequest>,
+) -> Result<Json<dbx_core::plugin_mcp::PluginMcpView>, AppError> {
+ dbx_core::plugin_mcp::plugin_view_for(&state.app, &body.plugin_id).await.map(Json).map_err(AppError::bad_request)
+}
+
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListPluginMcpScopesRequest {
+ pub plugin_id: String,
+ pub connection_id: String,
+}
+
+pub async fn list_plugin_mcp_scopes(
+ State(state): State<Arc<WebState>>,
+ Json(body): Json<ListPluginMcpScopesRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let manifest = state
+ .app
+ .plugins
+ .list_installed()
+ .map_err(AppError::from)?
+ .into_iter()
+ .find(|plugin| plugin.manifest.id == body.plugin_id)
+ .ok_or_else(|| AppError::bad_request("Plugin is not installed."))?
+ .manifest;
+ let method = manifest
+ .mcp_contribution()
+ .and_then(|mcp| mcp.scope.as_ref())
+ .and_then(|scope| scope.list_method.as_deref())
+ .ok_or_else(|| AppError::bad_request("This plugin does not declare a scope list method."))?;
+ let (policy, group_paths) = crate::routes::mcp_policy::load_policy_context(&state).await?;
+ let connection = state
+ .app
+ .storage
+ .load_connections()
+ .await
+ .map_err(AppError::from)?
+ .into_iter()
+ .find(|connection| connection.id == body.connection_id)
+ .ok_or_else(|| AppError::bad_request("CONNECTION_NOT_FOUND: connection is not available."))?;
+ if connection.plugin_id.as_deref() != Some(body.plugin_id.as_str()) {
+ return Err(AppError::bad_request("CONNECTION_OUT_OF_SCOPE: connection is not owned by this plugin."));
+ }
+ crate::routes::mcp_policy::ensure_allowed(&policy, group_paths.get(&connection.id), &connection.id)?;
+ let value = state
+ .app
+ .plugin_host
+ .invoke::<serde_json::Value>(
+ &body.plugin_id,
+ method,
+ serde_json::json!({ "connectionId": connection.id }),
+ None,
+ Some(std::time::Duration::from_secs(8)),
+ )
+ .await
+ .map_err(AppError::bad_request)?;
+ let values: Vec<String> = serde_json::from_value(
+ value
+ .get("values")
+ .cloned()
+ .ok_or_else(|| AppError::bad_request("Plugin scope list must return { values: string[] }."))?,
+ )
+ .map_err(|_| AppError::bad_request("Plugin scope list must return { values: string[] }."))?;
+ Ok(Json(serde_json::json!({ "values": values })))
+}
+
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SavePluginMcpGrantRequest {
+ pub plugin_id: String,
+ pub grant: dbx_core::storage::PluginMcpGrant,
+ #[serde(default)]
+ pub approve_current: bool,
+}
+
+pub async fn save_plugin_mcp_grant(
+ State(state): State<Arc<WebState>>,
+ Json(body): Json<SavePluginMcpGrantRequest>,
+) -> Result<Json<dbx_core::plugin_mcp::PluginMcpView>, AppError> {
+ dbx_core::plugin_mcp::save_plugin_grant(&state.app, &body.plugin_id, body.grant, body.approve_current)
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn load_mcp_access_policy(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<dbx_core::mcp_access::McpAccessPolicy>, AppError> {
+ state.app.storage.load_mcp_access_policy().await.map(Json).map_err(AppError::from)
+}
+
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SetMcpPluginScopeRuleRequest {
+ pub connection_id: String,
+ pub kind: String,
+ #[serde(default)]
+ pub value: Option<String>,
+ #[serde(default)]
+ pub rule: Option<dbx_core::mcp_access::McpAccessRule>,
+ #[serde(default)]
+ pub sub_scope: Option<dbx_core::mcp_access::McpSubScopeMode>,
+}
+
+pub async fn set_mcp_plugin_scope_rule(
+ State(state): State<Arc<WebState>>,
+ Json(body): Json<SetMcpPluginScopeRuleRequest>,
+) -> Result<Json<dbx_core::mcp_access::McpAccessPolicy>, AppError> {
+ dbx_core::plugin_mcp::set_scope_rule(
+ &state.app,
+ &body.connection_id,
+ &body.kind,
+ body.value.as_deref(),
+ body.rule,
+ body.sub_scope,
+ )
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn reset_invalid_mcp_access_policy(State(state): State<Arc<WebState>>) -> Result<Json<()>, AppError> {
+ state.app.storage.reset_invalid_mcp_access_policy().await.map(Json).map_err(AppError::bad_request)
+}
+
pub async fn save_mcp_global_policy(
State(state): State<Arc<WebState>>,
Json(policy): Json<McpGlobalPolicy>,
diff --git a/crates/dbx-web/src/routes/mcp_policy.rs b/crates/dbx-web/src/routes/mcp_policy.rs
index 2e8ca8bf64..36fa15cf6d 100644
--- a/crates/dbx-web/src/routes/mcp_policy.rs
+++ b/crates/dbx-web/src/routes/mcp_policy.rs
@@ -228,11 +228,11 @@ fn mongo_field_predicate_is_exists_true(value: &serde_json::Value) -> bool {
})
}
-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)
+pub(crate) async fn load_policy(state: &Arc<WebState>) -> Result<McpGlobalPolicy, AppError> {
+ state.app.storage.load_enforced_mcp_policy().await.map(|state| state.policy()).map_err(AppError::from)
}
-async fn load_policy_context(
+pub(crate) async fn load_policy_context(
state: &Arc<WebState>,
) -> Result<(McpGlobalPolicy, HashMap<String, McpConnectionGroupPath>), AppError> {
let policy = load_policy(state).await?;
@@ -250,7 +250,7 @@ async fn load_policy_context(
}
}
-fn ensure_allowed(
+pub(crate) fn ensure_allowed(
policy: &McpGlobalPolicy,
group_path: Option<&McpConnectionGroupPath>,
connection_id: &str,
diff --git a/docs/content/docs/mcp.cn.mdx b/docs/content/docs/mcp.cn.mdx
index 5cb90fc7c3..b7adcdf569 100644
--- a/docs/content/docs/mcp.cn.mdx
+++ b/docs/content/docs/mcp.cn.mdx
@@ -148,6 +148,42 @@ DBX MCP 当前提供以下工具(具体可用工具取决于构建功能及权
| `dbx_open_table` | 在运行中的 DBX 桌面端打开表 |
| `dbx_execute_and_show` | 执行查询并在 DBX 中展示结果 |
+
+### Nacos 与 Consul 工具级别
+
+Nacos 和 Consul 按产品提供工具集。客户端工具列表会按连接类型覆盖、工具开关和权限筛选;每次调用仍会根据目标连接及其子范围重新校验可见范围和生效权限,工具出现在列表中不代表任意目标都可调用。
+
+| 工具 | 级别 | 说明 |
+| --- | --- | --- |
+| `dbx_nacos_list_namespaces` | 只读 | 列出当前连接可见的 Nacos 命名空间 |
+| `dbx_nacos_list_configs` | 只读 | 按命名空间列出配置,可按 dataId、group、文本和分页筛选 |
+| `dbx_nacos_get_config` | 只读 | 读取配置内容及元数据 |
+| `dbx_nacos_config_history` | 只读 | 查看配置发布历史 |
+| `dbx_nacos_publish_config` | 读写 | 创建或覆盖一条配置,可用 CAS MD5 防止覆盖并发修改 |
+| `dbx_nacos_delete_config` | 高危 | 删除一条配置 |
+| `dbx_nacos_list_services` | 只读 | 列出命名空间中的服务 |
+| `dbx_nacos_list_instances` | 只读 | 查看服务实例的健康、权重和启用状态 |
+| `dbx_nacos_update_instance` | 读写 | 调整实例上下线状态或权重 |
+| `dbx_nacos_search_configs` | 只读 | 在当前或全部允许的命名空间中搜索配置内容 |
+| `dbx_nacos_rollback_config` | 读写 | 从发布历史恢复一条配置 |
+| `dbx_nacos_get_service` | 只读 | 读取服务详情 |
+| `dbx_nacos_register_instance` | 读写 | 注册一个服务实例 |
+| `dbx_nacos_deregister_instance` | 高危 | 注销一个服务实例 |
+| `dbx_consul_kv_list` | 只读 | 按前缀分页列出 Consul KV |
+| `dbx_consul_kv_get` | 只读 | 读取一个 KV 及其 ModifyIndex |
+| `dbx_consul_kv_put` | 读写 | 写入一个 KV,可用 CAS 防止覆盖并发修改 |
+| `dbx_consul_kv_delete` | 高危 | 删除一个 KV |
+| `dbx_consul_list_services` | 只读 | 列出 Consul 目录中的服务和标签 |
+| `dbx_consul_list_nodes` | 只读 | 列出目录节点 |
+| `dbx_consul_service_health` | 只读 | 查看服务实例及健康检查 |
+| `dbx_consul_set_maintenance` | 读写 | 设置或取消 Consul Agent 服务维护模式 |
+
+Nacos 的子范围是 **命名空间**。在 **权限管理** 的访问控制树展开 Nacos 连接,选择“全部命名空间”“指定命名空间”或“不开放任何命名空间”;`dbx_nacos_list_namespaces` 也只返回可见命名空间。Consul 连接本身已经绑定一个 datacenter,当前不再在树中拆分 datacenter,也没有 KV 前缀子范围设置。
+
+Nacos 公共命名空间在权限规则中使用 `public`;连接默认命名空间为空时,省略参数或传入空字符串都会按同一个公共命名空间判断权限。
+
+Nacos 的用户、角色、命名空间增删改等管理工具,以及 Consul 的 ACL、Intentions 等管理工具默认不开放。快照恢复、Raft/集群成员变更、License 写入和其他无法可靠判定风险的集群操作不会作为 MCP 工具提供。
+
`dbx_list_connections` 和 `dbx://connections` 会返回已保存的连接备注,不受侧边栏显示开关影响。可访问该连接的 MCP 客户端也能看到备注,请勿在备注中保存密码或其他敏感信息。
`dbx_execute_query` 返回行数:
@@ -163,12 +199,12 @@ DBX MCP 当前提供以下工具(具体可用工具取决于构建功能及权
- 工具名为 `dbx_<插件前缀>__<工具名>`,前缀取插件 id 的最后一段:`io.dbx.ssh` → `dbx_ssh__sftp_list_dir`,`io.dbx.kafka` → `dbx_kafka__kafka_topics_list`;
- 连接由宿主绑定:工具 schema 中的 `connectionId` / `connectionName` 会被移除,改由可选的 `dbx_connection` 参数选择该插件**已保存且被 MCP 设置放行**的连接;只有一个可用连接时省略该参数即可自动绑定;凭据由宿主从保存的连接生成 lifecycle 注入,永不经过模型或客户端;
- 作用域会话(`DBX_MCP_SCOPE_*`)与全局 MCP 设置(工具 allowlist、连接 allowlist)同样约束插件工具;
-- 工具白名单按精确名称匹配:启用插件工具后,请把要暴露的 `dbx_<前缀>__<工具名>` 逐个加入白名单(或清空白名单以全部放行);
+- 工具白名单支持精确名称和插件通配符:`dbx_<前缀>__<工具名>` 放行单个工具,`dbx_<前缀>__*` 放行一个插件,`dbx_*__*` 放行所有插件;
- Web / Docker 后端不提供插件工具。
### 懒发现(`DBX_MCP_PLUGIN_TOOLS`)
-插件较多时,平铺的 `tools/list` 会在参数 schema 上消耗大量上下文。设置 `DBX_MCP_PLUGIN_TOOLS=lazy` 只暴露三个元工具——`dbx_plugin_list`(可过滤的插件目录)、`dbx_plugin_tools`(按**插件 id** 查看某插件的工具与 schema)、`dbx_plugin_call`(按插件 id + 工具名调用)——schema 在需要时才进入上下文。`both` 同时平铺与元工具。默认仍为 `flat`。
+插件较多时,平铺的 `tools/list` 会在参数 schema 上消耗大量上下文。设置 `DBX_MCP_PLUGIN_TOOLS=lazy` 只暴露三个元工具——`dbx_plugin_list`(可过滤的插件目录)、`dbx_plugin_tools`(按**插件 id** 查看某插件的工具与 schema)、`dbx_plugin_call`(按插件 id + 工具名调用)——schema 在需要时才进入上下文。`both` 同时平铺与元工具。未设置环境变量时,新配置默认直接列出;已保存的模式保持不变。“自动(兼容模式)”保留插件工具总数不超过 40 个时直接列出、更多时按需发现的行为。
## Resources
@@ -369,25 +405,76 @@ DBX 在 **设置 → MCP** 中保存一份权威策略,并在每次请求时
同一页面还可只暴露选定的 MCP 工具。这项限制在服务端的每一次调用中都会强制执行,不只是客户端的展示偏好;即使客户端缓存了旧工具列表,也会在服务端 allowlist 更新后被拒绝。
-### 按顺序配置授权范围
+### MCP 设置页签
+
+MCP 设置页的三个页签使用界面中的名称:**接入方式**、**能力**和**权限管理**。它们共用一份策略,修改会对所有 MCP 客户端生效。
+
+#### 接入方式
+
+**接入方式**负责安装、升级和卸载 MCP Server,生成 stdio/HTTP 客户端配置,并提供运行参数。这里可以设置查询超时。插件工具对外提供方式位于**能力 → 高级配置**。客户端配置只包含启动 MCP Server 所需的运行信息,不包含权限或连接范围变量。
+
+#### 能力
+
+**能力**页默认使用**分类管理**:左侧选择数据库、Nacos、Consul、消息队列、Salesforce 或 DBX 通用,右侧配置工具集;切换到**全局总览**可以同时查看全部分类。插件使用带来源标识的独立入口。搜索覆盖分类、工具集、工具名称/ID 和插件;**仅显示已开启**按配置筛选,不会改变当前分类。分类批量操作包括被筛选隐藏的工具,点击**应用**后生效。共享连接发现属于 DBX 通用,关闭数据库分类不会关闭其他产品的连接发现。
+
+工具集显示开启数量、**读 / 写 / 高危**徽标和按连接类型统计的覆盖摘要。徽标描述工具风险,不等于授予权限;暂无适用连接时仍可提前配置。内置配置使用底部**应用 / 取消**,插件授权立即保存。自定义工具白名单位于**高级配置**。
+
+点击卡片可查看工具详情。详情包括工具 ID、给模型的说明、权限级别、适用的数据库类型,以及每个参数的名称、类型、是否必填、说明和默认值;逐次判定的工具会标明每次调用会按语句判为读、写或高危。工具详情中的开关可以单独关闭某个内置工具。弹窗底部的**应用本工具集**只保存当前工具集的开关,其他工具集、权限和运行参数的未保存修改继续保留为草稿;保存成功后弹窗保持打开。关闭详情也会保留草稿,仍可在设置页统一应用或放弃;已在详情中应用的修改不会随其他草稿一起放弃。保存失败会在弹窗内显示原因并允许重试。
+
+插件卡片显示插件名称、版本、插件 ID、工具级别徽标和 **MCP 工具**标识。卡片会明确显示插件作者是否开放外部 MCP、外部 MCP 总开关、**授权上限**(只读 / 读写 / 完全)和已暴露数量。第一次开启插件会弹出授权窗口;只会接受 manifest 已声明的工具和级别。插件新增的只读工具可自动使用;新增读写或高危工具,以及已有工具的声明级别升高时,需再次确认,即使级别未超过现有授权上限。超过授权上限的工具保持隐藏,提高上限也不能代替新工具确认。插件详情可以按工具集查看工具、参数、声明级别并单独关闭某个工具;manifest 未声明权限级别的工具始终不开放,即使 sidecar 的 MCP 标注声称它是只读。
+
+插件工具条目是全局 MCP 工具白名单的另一层过滤:`dbx_<前缀>__<工具名>` 精确放行一个工具,`dbx_<前缀>__*` 放行一个插件的全部工具,`dbx_*__*` 放行所有插件工具。使用显式白名单时,没有匹配条目的插件工具不会出现;选择全部工具时无需逐个添加条目。插件卡片开关、授权上限和单工具开关始终生效。
+
+在**能力 → 高级配置**展开**插件工具对外提供方式**,设置 DBX 如何向 MCP 客户端提供已授权的插件工具,点击底部**应用**后生效。新配置默认**直接列出**(`flat`),把已授权工具逐个放进 `tools/list`;**按需发现**(`lazy`)提供 `dbx_plugin_list`、`dbx_plugin_tools` 和 `dbx_plugin_call` 三个统一入口,需要开启 **DBX 通用 → 插件发现与调用**。两种方式都执行原有授权与资源权限检查。已有配置原样保留,旧配置缺少该字段时继续使用原有自动行为;**自动(兼容模式)**在插件工具总数不超过 40 个时直接列出,更多时按需发现。环境变量 `DBX_MCP_PLUGIN_TOOLS` 优先于页面设置,可设为 `flat`、`lazy` 或 `both`;`both` 同时提供平铺工具和发现工具。
+
+#### 权限管理
+
+**权限管理**提供**全局默认权限**、**访问控制**,以及独立的**调用安全**。不再提供快速预设或“自定义”模式;调整权限不会修改“能力”页的工具开关。
+
+**全局默认权限**用于没有更具体权限设置的资源,可选只读、数据读写和完全访问。修改默认值后,继承它的资源同步更新生效预览;单独设置的分组、连接和数据库保留自己的权限。权限对照表默认收起在“权限说明”中,表格描述的是权限级别,工具仍需在“能力”页启用。
+
+调用安全独立于权限继承和工具启停;切换默认权限不会修改确认策略。将默认、分组、连接或库设为完全访问时,仍先在应用内确认权限变更,取消则保留原设置。这与实际工具调用时的人工确认分别生效。
+
+全局默认权限与分组、连接、数据库权限先写入草稿,点击底部**应用**后保存生效;切换页签保留草稿,关闭并放弃修改会恢复已保存的配置。
+
+访问控制树把分组、连接和子范围放在同一张表中。可以选择**全部连接**(自动包含以后新增的连接)或**仅选中的**,并在树中为分组和连接设置可见性。连接下方显示库范围摘要,点击**配置库权限**打开穿梭框弹窗,选择**全部库**、**指定库**或**不开放任何库**。指定库时从左侧选择库并移入右侧,在右侧为每个库设置继承、只读、数据读写或完全访问;移除库也会移除该库的独立权限。
+
+分组内已有单独授权的连接或子分组时,外层分组显示半选,并汇总完整分组中可见连接的数量,折叠或筛选不会改变统计。即使当前连接全部可见,只要没有整组授权,仍保留半选,避免把未来新增连接误认为已授权。点击半选框将开放整个分组;分组默认权限可供未单独设置权限的子项继承,不改变可见范围。
+
+在右侧勾选多个库后,可通过**批量设置权限**统一修改,未勾选的库不受影响;选择完全访问时统一确认一次。**选择当前搜索结果**包含尚未展开显示的匹配库,改变搜索条件会清空勾选。批量修改仍需点击**应用本连接库权限**才会保存。每行的提示图标可查看权限来源及未发现库的说明。
+
+列表完整获取当前数据库账号可见的库,支持搜索、刷新和手动添加精确库名;超过 100 项时分批展示,搜索和“选择当前搜索结果”仍覆盖完整列表。未在本次发现的已选库不会被自动移除。**全部库**包含未来新增库,把当前库全部选入**指定库**则不会自动包含新库。未选中的库和跨库请求会被拒绝。
+
+**应用本连接库权限**只保存该连接的库范围及单库权限,其他连接、上级权限、工具和运行参数草稿保持不变。保存成功后弹窗保持打开,失败可直接重试;关闭弹窗保留草稿,放弃其他草稿不会撤销已应用的库权限。若上级权限仍有未应用修改,弹窗同时提示当前已保存的继承权限。
+
+权限按最具体的范围继承:**库 → 连接 → 最近的分组 → 上级分组 → 全局默认**。表格的“权限”列是当前行的设置,“生效”列显示最终级别和来源。搜索框可搜索分组、连接和库;勾选**仅显示单独设置**可隐藏只继承默认值的行。旧版本保存的行会标为**旧规则**,它只能收紧连接继承的权限;重新选择一次权限后才会成为普通设置。Salesforce 连接额外提供**允许 DML**开关;它默认关闭,只读级别下不可开启,连接和生产保护仍是硬上限。
+
+插件连接可以在同一棵树中展开插件声明的子范围(例如 namespace 或目录),从插件读取可选值,再选择全部、指定或不开放。Nacos 连接使用同样的子范围编辑器管理命名空间;Consul 的 datacenter 已由连接固定。命名空间等子范围的修改会立即保存,编辑器会明确提示;它们不受底部“应用 / 取消”影响。保存失败时显示错误并保留原配置。
+
+#### 调用安全
+
+开启“高危工具调用执行前,请求人工确认”后,先校验资源权限,权限不足直接拒绝;已获得完全访问权限的高危调用也须逐次确认。适用于高危 SQL、MongoDB 高危命令或无有效条件的修改、危险 Redis 命令、声明为 `full` 的插件工具、Nacos/Consul 删除及连接删除。普通读取和范围可验证的普通写入不额外询问。工具仍须开启,插件授权上限、连接可见范围、连接只读和生产保护始终有效。
+
+确认在 DBX 桌面端显示工具、目标和操作内容;仅批准当前调用,不提升权限、不生成限时放行。拒绝、超时或无法使用桌面确认时不执行。批准后重新检查权限,确认期间撤权会阻止执行。该策略同时适用于 stdio 和 HTTP,Web 后端不提供桌面确认。
+
+**旧配置兼容:** 原 `promptHighRiskSql=true` 或 v2 `confirm="full"` 保留为“旧版临时授权”:数据读写权限可确认执行部分高危操作,完全访问不询问;原有 SQL 一次、1 小时、1 天授权仍属于这个旧模式。界面明确显示其含义,只有主动选择“改用新的确认策略”或“关闭旧版临时授权”并点击“应用”才会转换。新策略使用 `callConfirmation="high_risk"` / v2 `confirm="high_risk"`;不会复用旧布尔值改变含义。没有旧授权的新配置默认不额外确认,可自行开启。旧版 MCP 程序不理解新策略,测试和使用时须让桌面与独立 MCP 程序保持配套版本。
+
+#### MCP 调用记录
-在 **设置 → MCP** 中建议按以下顺序定义最终权限范围:
+**接入方式**页的接入类型切换行右侧提供**查看 MCP 调用记录**,窄窗口下显示为历史图标。点击后关闭设置页并打开历史面板的 MCP 视图;有未保存修改时先询问是否放弃,选择继续编辑不会打开历史面板。记录包括时间、接入方式(stdio 或 HTTP)、MCP 客户端名称和版本、工具、目标连接/库或其他资源、判定级别、是否经过确认、耗时、请求/响应摘要和成功或失败原因;客户端名称只用于记录,不参与权限判定。调用历史有独立的保留和清理设置。
-1. 选择 MCP 可见的是**所有连接**(包括以后新增的连接),还是仅**指定连接**。
-2. 为每个已暴露连接选择**全部数据库**、**仅指定数据库**或**不允许访问**。指定数据库名按精确名称匹配;可先调用 `dbx_list_databases` 获取当前允许使用的名称,并为选中的数据库按需设置执行权限。
-3. 为每个连接设置默认执行权限。未配置单库覆盖、或选择全部数据库时,该默认值就是连接内数据库的执行权限。
-4. 仅选择客户端实际需要的 MCP 工具,再设置全局默认执行权限模式。
+最具体的执行设置优先,但已允许的工具仍不能绕过隐藏连接、数据库范围、连接只读、生产库保护或数据库账号本身的权限。请求未被选中的数据库时,服务会返回 `DATABASE_OUT_OF_SCOPE`;配置单库执行权限时,跨库 SQL 和 MongoDB 聚合写入会被拒绝,避免绕过数据库级限制。
-执行权限由最具体的设置决定,但已允许的工具仍不能绕过隐藏连接、数据库范围、连接只读、生产库保护或数据库账号本身的权限。请求未被选中数据库时,服务会返回 `DATABASE_OUT_OF_SCOPE`;配置单库执行权限时,跨库 SQL 和 MongoDB 聚合写入会被拒绝,避免绕过数据库级限制。
升级时,未带执行策略版本的已保存连接规则继续使用旧的权限上限语义,不会放大全局权限。只有当前设置页面保存的规则会标记为范围覆盖语义;编辑旧规则时,系统会先固化其实际生效的权限上限,再启用新的覆盖行为。
-新版 Server 不允许 `DBX_MCP_ALLOW_WRITES` 或 `DBX_MCP_ALLOW_DANGEROUS_SQL` 放宽 DBX 中央策略。为兼容升级,在中央策略首次保存前,旧配置中的 `DBX_MCP_ALLOW_WRITES=0`(或 `false`)仍会保持 MCP 只读;策略保存后仅以中央策略为准,并忽略旧权限变量。旧连接 scope 变量只能进一步收窄 DBX allowlist。
+新版 Server 不允许 `DBX_MCP_ALLOW_WRITES` 或 `DBX_MCP_ALLOW_DANGEROUS_SQL` 放宽 DBX 中央策略。`DBX_MCP_ALLOW_WRITES=0`(或 `false`)是本次运行的只读限制:即使中央策略已经保存,或分组、连接、单库配置了完全访问,也只能读取。此限制同时适用于本地和 Web 后端,不修改已保存的配置。设为 `1`、`true` 或不设置时,仍以中央策略授权为准。旧连接 scope 变量只能进一步收窄 DBX allowlist。
| 变量 | 用途 |
| --- | --- |
| `DBX_DATA_DIR` | 覆盖本地 DBX 数据目录 |
| `DBX_SESSION_IDLE_TTL_SECS` | 有状态会话空闲超时,单位为正整数秒,默认 `1800`。非法值、零、负数或无法表示的时长回退默认值;同样适用于事务专属连接。修改后需重启 MCP 宿主进程。 |
+| `DBX_MCP_PLUGIN_TOOLS` | 覆盖高级配置中的插件工具对外提供方式:`flat`、`lazy` 或 `both`;环境变量优先。 |
| `DBX_WEB_URL` | 使用 DBX Web/Docker 后端 |
| `DBX_WEB_PASSWORD` | 登录 DBX Web |
| `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` | DBX Web 请求的标准系统代理变量;空值表示不走代理。认证格式 `http://user:pass@host:port` |
@@ -399,7 +486,7 @@ DBX 在 **设置 → MCP** 中保存一份权威策略,并在每次请求时
| `DBX_WEB_MCP_TOKEN_FILE` | 从文件读取原生 Web MCP Token;不能与 `DBX_WEB_MCP_TOKEN` 同时设置 |
| `DBX_WEB_MCP_ALLOWED_HOSTS` | 原生 Web MCP 必填:允许的公网 Host authority,逗号分隔 |
| `DBX_WEB_MCP_ALLOWED_ORIGINS` | 原生 Web MCP 的浏览器 Origin allowlist,逗号分隔 |
-| `DBX_MCP_ALLOW_WRITES` | 仅用于升级兼容:`0`/`false` 使尚未配置的策略保持只读 |
+| `DBX_MCP_ALLOW_WRITES` | `0`/`false` 强制本次运行只读,包括已配置的分组、连接和单库权限;`1`/`true` 不会扩大中央策略授权。适用于本地和 Web 后端。 |
| `DBX_MCP_SCOPE_CONNECTION_ID` | 兼容旧配置:限制为一个连接 ID |
| `DBX_MCP_SCOPE_CONNECTION_IDS` | 兼容旧配置:限制为多个连接 ID |
| `DBX_MCP_SCOPE_CONNECTION_NAME` | 限制为一个连接名称 |
diff --git a/docs/content/docs/mcp.mdx b/docs/content/docs/mcp.mdx
index e11b78167b..53d96ec5be 100644
--- a/docs/content/docs/mcp.mdx
+++ b/docs/content/docs/mcp.mdx
@@ -148,6 +148,42 @@ DBX MCP provides the following tools (availability depends on build features and
| `dbx_open_table` | Open a table in the running DBX desktop app |
| `dbx_execute_and_show` | Execute a query and display the result in DBX |
+
+### Nacos and Consul tool levels
+
+Nacos and Consul expose product-specific toolsets. The client tool list is filtered by connection-type coverage, enabled tools, and permissions. Each call still rechecks visibility and effective permissions for the target connection and sub-scope; a listed tool is not authorized for every target.
+
+| Tool | Level | Description |
+| --- | --- | --- |
+| `dbx_nacos_list_namespaces` | Read | List the Nacos namespaces visible for the connection |
+| `dbx_nacos_list_configs` | Read | List configurations in a namespace, with dataId, group, text, and paging filters |
+| `dbx_nacos_get_config` | Read | Read configuration content and metadata |
+| `dbx_nacos_config_history` | Read | Read the publish history of a configuration |
+| `dbx_nacos_publish_config` | Write | Create or overwrite one configuration, with an optional CAS MD5 |
+| `dbx_nacos_delete_config` | Full | Delete one configuration |
+| `dbx_nacos_list_services` | Read | List services in a namespace |
+| `dbx_nacos_list_instances` | Read | Read instance health, weight, and enabled state |
+| `dbx_nacos_update_instance` | Write | Change an instance's online state or weight |
+| `dbx_nacos_search_configs` | Read | Search configuration content in one or all allowed namespaces |
+| `dbx_nacos_rollback_config` | Write | Restore one configuration from its publish history |
+| `dbx_nacos_get_service` | Read | Read service details |
+| `dbx_nacos_register_instance` | Write | Register one service instance |
+| `dbx_nacos_deregister_instance` | Full | Deregister one service instance |
+| `dbx_consul_kv_list` | Read | List Consul KV keys by prefix, one page at a time |
+| `dbx_consul_kv_get` | Read | Read one KV and its ModifyIndex |
+| `dbx_consul_kv_put` | Write | Write one KV, with optional CAS protection |
+| `dbx_consul_kv_delete` | Full | Delete one KV |
+| `dbx_consul_list_services` | Read | List services and tags in the Consul catalog |
+| `dbx_consul_list_nodes` | Read | List catalog nodes |
+| `dbx_consul_service_health` | Read | Read service instances and health checks |
+| `dbx_consul_set_maintenance` | Write | Put a Consul Agent service into or out of maintenance mode |
+
+Nacos uses **namespace** as its sub-scope. In the access-control tree under **Permission management**, expand a Nacos connection and choose all namespaces, selected namespaces, or no namespaces. `dbx_nacos_list_namespaces` also returns only namespaces that are visible to MCP. A Consul connection is already bound to one datacenter, so the tree does not split datacenters and currently has no KV-prefix sub-scope.
+
+The public Nacos namespace uses `public` in permission rules; an omitted or empty namespace resolves to the same public scope when the connection default is empty.
+
+Nacos user, role, and namespace administration, and Consul ACL and Intentions administration, are not exposed by default. Snapshot restore, Raft or cluster-member changes, License writes, and other cluster operations whose risk cannot be reliably classified are not provided as MCP tools.
+
`dbx_list_connections` and `dbx://connections` include saved connection notes regardless of the sidebar display setting. Notes are visible to MCP clients that can access the connection; do not store passwords or other secrets in notes.
`dbx_execute_query` row controls:
@@ -163,12 +199,12 @@ DBX plugins whose sidecar implements the `mcp/tools` bridge can be served by the
- Tools are exposed as `dbx_<prefix>__<tool>`, with the prefix derived from the plugin id's last segment: `io.dbx.ssh` → `dbx_ssh__sftp_list_dir`, `io.dbx.kafka` → `dbx_kafka__kafka_topics_list`.
- Connections stay host-bound: the plugin schema's `connectionId` / `connectionName` are removed and replaced by an optional `dbx_connection` argument that selects among the plugin's **saved connections allowed by the DBX MCP settings**. With exactly one allowed connection you can omit it. The host generates the lifecycle payload (credentials, runtime endpoint) from the saved connection — credentials never reach the model or client.
- Scoped sessions (`DBX_MCP_SCOPE_*`), the global tool allowlist, and the connection allowlist constrain plugin tools exactly like the `dbx_*` tools.
-- The tool allowlist matches exact names: after enabling plugin tools, add each `dbx_<prefix>__<tool>` you want exposed (or clear the allowlist to allow everything).
+- The tool allowlist supports exact names and plugin wildcards: `dbx_<prefix>__<tool>` allows one tool, `dbx_<prefix>__*` one plugin, and `dbx_*__*` every plugin.
- The Web / Docker backend does not serve plugin tools.
### Lazy discovery (`DBX_MCP_PLUGIN_TOOLS`)
-With many plugins, one flat `tools/list` spends a lot of context on argument schemas. Set `DBX_MCP_PLUGIN_TOOLS=lazy` to expose only three meta tools — `dbx_plugin_list` (filterable plugin catalog), `dbx_plugin_tools` (one plugin's tools and schemas), and `dbx_plugin_call` (call by **plugin id** + tool) — so schemas enter the context on demand. `both` advertises the flat tools and the meta tools at once. The default stays `flat`.
+With many plugins, one flat `tools/list` spends a lot of context on argument schemas. Set `DBX_MCP_PLUGIN_TOOLS=lazy` to expose only three meta tools — `dbx_plugin_list` (filterable plugin catalog), `dbx_plugin_tools` (one plugin's tools and schemas), and `dbx_plugin_call` (call by **plugin id** + tool) — so schemas enter the context on demand. `both` advertises the flat tools and the meta tools at once. Without the environment variable, new configurations list tools directly and saved modes remain unchanged. **Automatic (compatibility)** preserves the existing threshold: list directly with up to 40 plugin tools in total, otherwise use on-demand discovery.
## Resources
@@ -369,25 +405,76 @@ For connections exposed to MCP, **Settings → MCP** can set a default execution
The same page can also expose only selected MCP tools. This is enforced at every call, rather than being only a client-side display preference; a client that retained an old tool list is denied once the server-side allowlist changes.
-### Configure access in order
+### MCP settings tabs
+
+The MCP settings page uses the three labels shown in the UI: **Access methods**, **Capabilities**, and **Permission management**. They share one policy, so changes apply to every MCP client.
+
+#### Access methods
+
+**Access methods** handles MCP Server installation, upgrades and removal, generates stdio/HTTP client configurations, and exposes runtime settings. Query timeout remains here; **External plugin tool delivery** is under **Capabilities → Advanced settings**. Generated client configurations contain only the runtime information needed to start MCP Server; they do not contain permission or connection-scope variables.
+
+#### Capabilities
+
+The **Capabilities** tab defaults to **Category management**: choose Database, Nacos, Consul, Message queues, Salesforce, or DBX General on the left and configure its toolsets on the right. **Global overview** displays all categories together. Plugins have separate entries marked with their source. Search covers categories, toolsets, tool names/IDs and plugins; **Only show enabled** filters by configuration without changing the selected category. Category batch actions include tools hidden by filters and take effect after **Apply**. Shared connection discovery belongs to DBX General, so disabling Database does not disable discovery for other products.
+
+Each toolset shows enabled counts, **Read / Write / High risk** badges and connection coverage by type. Badges describe tool risk and do not grant access. Toolsets without matching connections remain configurable. Built-in changes use **Apply / Cancel**; plugin grants save immediately. Custom tool allowlists are under **Advanced configuration**.
+
+Open a card to inspect its tools. Tool details include the tool ID, model-facing description, access level, supported database types, and every parameter's name, type, required flag, description, and default. Classified tools say that each call is classified as read, write, or high risk from its statement. A switch in the detail view can disable one built-in tool. **Apply this toolset** saves only the switches in the current toolset and keeps the dialog open. Unsaved changes to other toolsets, permissions, and runtime settings remain drafts. Closing the detail also keeps its draft for Apply or Discard in Settings; discarding other drafts does not undo a toolset already applied from its details. Save failures appear inside the dialog and can be retried.
+
+Plugin cards show the plugin name, version, plugin ID, level badges, and the **MCP tools** mark. They show whether the author opened external MCP, the external MCP switch, an **authorization ceiling** (read only / read & write / full), and the exposed count. The first time you enable a plugin, an authorization dialog appears; only tools and levels declared in the manifest are accepted. New read-only tools can become available automatically. New write or full tools, and existing tools whose declared level rises, require confirmation even when they are within the existing ceiling. Tools above the ceiling remain hidden; raising the ceiling does not replace confirmation of new tools. Plugin details group tools by toolset, show parameters and declared levels, and allow a single tool to be switched off. A tool with no manifest access declaration is never exposed, even when the sidecar marks it read-only.
+
+Plugin tool entries add another layer to the global MCP tool allowlist: `dbx_<prefix>__<tool>` allows one exact tool, `dbx_<prefix>__*` allows every tool from one plugin, and `dbx_*__*` allows every plugin tool. When an explicit allowlist is active, plugin tools without a matching entry stay hidden. Selecting all tools requires no individual entries. The plugin switch, ceiling, and per-tool switch always apply.
+
+Expand **External plugin tool delivery** under **Capabilities → Advanced settings** to choose how DBX provides authorized plugin tools to MCP clients. Click **Apply** at the bottom to save. New configurations default to **List directly** (`flat`), which lists each authorized tool in `tools/list`. **Lazy discovery** (`lazy`) provides the shared `dbx_plugin_list`, `dbx_plugin_tools`, and `dbx_plugin_call` entry points; enable **Plugin discovery and invocation** under **DBX general**. Both paths enforce the same plugin grants and resource permissions. Saved modes remain unchanged, and legacy saved policies without this field retain their previous automatic behavior. **Automatic (compatibility)** lists directly with up to 40 plugin tools in total and uses on-demand discovery above that. The `DBX_MCP_PLUGIN_TOOLS` environment variable takes priority over the page setting and accepts `flat`, `lazy`, or `both`; `both` advertises both the flat tools and the discovery tools.
+
+#### Permission management
-Use **Settings → MCP** to define the effective scope in this order:
+**Permission management** provides **Global default permission**, **Access control**, and independent **Call safety**. There are no quick presets or Custom mode. Permission changes do not change tool switches in Capabilities.
-1. Choose whether MCP can see **all connections** (including future connections) or only **specified connections**.
-2. For every exposed connection, choose **all databases**, **specified databases**, or **no access**. Specified database names are exact matches; use `dbx_list_databases` to discover the names that are currently allowed, then optionally set execution permissions for those databases.
-3. Set each connection's default execution permission. It applies to every database when all databases are exposed, and to selected databases that do not have an override.
-4. Select only the MCP tools that the client needs, then choose the global default execution permission.
+**Global default permission** applies to resources without a more specific permission. Choose read only, data read/write, or full access. Changing the default updates the effective preview for resources that inherit it; groups, connections, and databases with their own permissions keep those settings. The comparison table is collapsed under **Permission details**. It describes permission levels; tools must also be enabled in Capabilities.
+
+Call safety is independent of permission inheritance and tool switches. Changing the global default does not alter the confirmation policy. Granting full access to a default, group, connection or database still asks for confirmation of that settings change; cancelling retains the previous value. This is separate from confirming a tool invocation.
+
+The global default and group, connection, and database permissions are staged until you click **Apply**. Switching tabs keeps the draft; closing and discarding changes restores the saved configuration.
+
+The access-control tree puts groups, connections, and sub-scopes in one table. Choose **All connections** (including future connections) or **Selected only**, then set group and connection visibility. Each connection shows a database scope summary. **Configure database access** opens a transfer dialog with **All databases**, **Selected**, and **No databases** modes. Move databases to the right and set each to inherit, read only, data read/write, or full access. Removing a database also removes its override.
+
+When individual connections or child groups are authorized, their ancestor group shows a mixed checkbox and the number of visible connections across the full group, regardless of collapsing or filtering. Even if all current connections are visible, the checkbox stays mixed until the whole group is authorized; future connections are not implicitly included. Clicking the mixed checkbox authorizes the entire group. Group permission defaults apply to child items without their own permission setting and do not change visibility.
+
+Check multiple databases on the right and use **Set access for checked** to update their permissions together. Unchecked databases are unchanged, and full access requires one confirmation for the batch. **Select current search results** includes matching databases beyond the currently rendered rows; changing the search clears the checkmarks. Batch changes are saved only when you click **Apply database access**. Each row's help icon explains the permission source and whether the database was found during discovery.
+
+Discovery loads every database visible to the database account. Both lists support search; refresh and manual entry of exact names are available. Lists over 100 entries render in batches, while search and **Select current search results** cover the entire list. Selected databases missing from discovery are retained. **All databases** includes future databases; selecting every currently discovered database does not. Unselected databases and cross-database requests are rejected.
+
+**Apply database access** saves only this connection’s database scope and individual permissions. Drafts for other connections, parent permissions, tools and runtime settings remain unchanged. Success keeps the dialog open; failures can be retried. Closing retains drafts, and discarding other drafts does not undo database permissions already applied. Pending parent changes are distinguished from currently saved inherited permissions.
+
+Permissions inherit from the most specific scope: **database → connection → nearest group → parent group → global default**. The **Permission** column is the row's setting; **Effective** shows the final level and its source. Search covers groups, connections, and databases, and **Only show individual settings** hides rows that only inherit their default. Rows saved by an older version are marked **legacy** and can only narrow the connection's inherited permission; choose a permission again to make the row a regular setting. Salesforce connections also have an **Allow DML** switch; it is off by default and unavailable at read-only level, while connection and production protections remain hard limits.
+
+Plugin connections can expose a plugin-declared sub-scope (for example, a namespace or directory) in the same tree. Load the values from the plugin and choose all, selected, or none. Nacos connections use the same editor for namespaces; Consul's datacenter is fixed by the connection. Sub-scope changes save immediately, as noted in their editor, and are unaffected by Apply or Cancel at the bottom. A failed save displays an error and keeps the previous configuration.
+
+#### Call safety
+
+Enable **Request human confirmation before high-risk tool calls** to check permissions first and reject insufficient access. Authorized high-risk calls also require confirmation at full access. This covers high-risk SQL, dangerous or unbounded MongoDB mutations, dangerous Redis commands, plugin tools declared `full`, Nacos/Consul deletion and connection removal. Ordinary reads and bounded ordinary writes do not prompt. Enabled tools, plugin grants, resource visibility, read-only connections and production protections remain mandatory.
+
+DBX Desktop shows the tool, target and operation. Each approval is for the current call only, without elevating permissions or granting a timed exemption. Denial, timeout or unavailable desktop confirmation prevents execution. Permissions are rechecked after approval; revocation wins. The policy applies to both stdio and HTTP; Web backends cannot provide desktop confirmation.
+
+**Compatibility:** Existing `promptHighRiskSql=true` or v2 `confirm="full"` remains **Legacy temporary authorization**: data-write access can confirm supported high-risk calls, while full access does not prompt. SQL's once/hour/day choices remain exclusive to that legacy mode. The UI explains the difference. Only explicitly choosing the new policy or disabling legacy authorization, then clicking Apply, changes the behavior. The new policy uses `callConfirmation="high_risk"` / v2 `confirm="high_risk"`, never a reinterpretation of the old boolean. Fresh configurations start without additional confirmation and can opt in. Older standalone MCP programs do not understand the new policy; use matching desktop and standalone MCP versions.
+
+#### MCP call history
+
+The **View MCP call history** button is on the right of the transport selector row in **Access methods**, displayed as a history icon in narrow layouts. It closes Settings and opens the history panel on its MCP view. If there are unsaved changes, you must first confirm discarding them; choosing to keep editing leaves the history panel closed. Entries include the time, transport (stdio or HTTP), MCP client name and version, tool, target connection/database or other resource, classified level, whether confirmation was used, duration, request/response summaries, and the success or failure reason. The client name is recorded only for auditing and does not affect authorization. MCP history has its own retention and cleanup settings.
The most specific execution setting wins, but an allowed tool still cannot bypass a hidden connection, database scope, connection read-only status, production protection, or the database account's own privileges. Requests for a database outside the selected scope are rejected with `DATABASE_OUT_OF_SCOPE`. When database-specific execution permissions exist, cross-database SQL and MongoDB aggregation writes are rejected to prevent bypassing those limits.
+
During upgrade, saved connection rules without an execution policy version keep the previous ceiling semantics and cannot widen the global permission. Only a rule saved by the current Settings UI is marked for scoped override semantics; editing an existing legacy rule first carries its effective ceiling forward before enabling the new behavior.
-Updated servers do not let `DBX_MCP_ALLOW_WRITES` or `DBX_MCP_ALLOW_DANGEROUS_SQL` widen the DBX policy. For upgrade compatibility, `DBX_MCP_ALLOW_WRITES=0` (or `false`) still keeps MCP read-only until a central policy is saved for the first time. After that, the central policy is authoritative and the legacy permission variables are ignored. Legacy connection-scope variables can only narrow the DBX allowlist.
+Updated servers do not let `DBX_MCP_ALLOW_WRITES` or `DBX_MCP_ALLOW_DANGEROUS_SQL` widen the DBX policy. `DBX_MCP_ALLOW_WRITES=0` (or `false`) enforces read-only access for the current run, even after the central policy is saved and even when a group, connection, or database grants full access. This restriction applies to both local and Web backends without modifying saved settings. A value of `1`, `true`, or an unset variable still requires authorization from the central policy. Legacy connection-scope variables can only narrow the DBX allowlist.
| Variable | Purpose |
| --- | --- |
| `DBX_DATA_DIR` | Override the local DBX data directory |
| `DBX_SESSION_IDLE_TTL_SECS` | Stateful session idle timeout in positive whole seconds (default: `1800`). Invalid, zero, negative or unrepresentable values use the default. Applies to transaction-owned connections too; restart the MCP host after changing it. |
+| `DBX_MCP_PLUGIN_TOOLS` | Override External plugin tool delivery in Advanced settings with `flat`, `lazy`, or `both`; the environment variable takes priority. |
| `DBX_WEB_URL` | Use a DBX Web/Docker backend |
| `DBX_WEB_PASSWORD` | Authenticate to DBX Web |
| `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` | Standard system proxy variables for DBX Web requests; empty value means no proxy. Auth via `http://user:pass@host:port` |
@@ -399,7 +486,7 @@ Updated servers do not let `DBX_MCP_ALLOW_WRITES` or `DBX_MCP_ALLOW_DANGEROUS_SQ
| `DBX_WEB_MCP_TOKEN_FILE` | Read the native Web MCP token from a file; cannot be combined with `DBX_WEB_MCP_TOKEN` |
| `DBX_WEB_MCP_ALLOWED_HOSTS` | Required comma-separated public Host authorities for native Web MCP |
| `DBX_WEB_MCP_ALLOWED_ORIGINS` | Comma-separated browser Origins allowed for native Web MCP |
-| `DBX_MCP_ALLOW_WRITES` | Upgrade compatibility only: `0`/`false` keeps an unconfigured policy read-only |
+| `DBX_MCP_ALLOW_WRITES` | `0`/`false` forces the current run to be read-only, including saved group, connection, and database overrides; `1`/`true` never widens the central policy. Applies to local and Web backends. |
| `DBX_MCP_SCOPE_CONNECTION_ID` | Compatibility scope for one connection ID |
| `DBX_MCP_SCOPE_CONNECTION_IDS` | Compatibility scope for multiple connection IDs |
| `DBX_MCP_SCOPE_CONNECTION_NAME` | Restrict the session to one connection name |
diff --git a/docs/mcp-capability-navigation-validation.md b/docs/mcp-capability-navigation-validation.md
new file mode 100644
index 0000000000..a65784b968
--- /dev/null
+++ b/docs/mcp-capability-navigation-validation.md
@@ -0,0 +1,75 @@
+# MCP 能力分类:实现与验证
+
+## 实现边界
+
+能力页使用「分类导航 → 工具集 → 工具详情」,保持现有 Neutral Modern 主题、shadcn 控件和 Lucide 图标。分类由前端目录元数据决定,不修改后端 API、工具名称或策略结构。
+
+| 分类 | 工具集 ID |
+| --- | --- |
+| 数据库 | `sql.query`、`sql.session`、`sql.schema`、`redis` |
+| Nacos | `nacos.config`、`nacos.service` |
+| Consul | `consul.kv`、`consul.service` |
+| 消息队列 | `mq` |
+| Salesforce | `salesforce` |
+| DBX 通用 | `core.discovery`、`workbench`、`admin.connections`、`plugin.router` |
+| 其他能力 | 不在上述映射中的工具集 |
+
+插件按真实名称独立展示,带来源和待确认徽标。高级配置提供自定义工具白名单。内置工具、工具集、分类和高级白名单的修改都进入原有策略草稿;插件授权即时保存。插件白名单放行操作明确提示需要应用。
+
+分类批量操作使用完整后端目录,包含筛选隐藏的工具。将 `null`(全部允许)转换成显式名单时,保留全部其他内置工具和插件通配符;显式名单保留已有自定义条目。共享发现位于 DBX 通用,因此关闭数据库分类不会影响其他产品的连接发现。
+
+界面按能力区域实际宽度响应:600px 以下使用分类选择器,600–759px 使用 144px 导航,760px 以上使用 184px 导航。搜索不改变原分类;详情不依赖过滤结果,关闭详情时恢复触发位置,触发元素消失时返回搜索框。
+
+## 自动化验证
+
+在仓库根目录执行:
+
+```bash
+pnpm exec vitest run \
+ apps/desktop/src/components/settings/__tests__ \
+ apps/desktop/src/lib/__tests__/mcp \
+ apps/desktop/src/i18n/__tests__ \
+ apps/desktop/src/components/editor/__tests__/EditorSettingsDialog*.spec.ts
+
+NODE_OPTIONS=--max-old-space-size=8192 pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
+git diff --check
+```
+
+主要新增测试覆盖分类唯一性和兜底、批量隔离、完整目录物化、跨来源搜索、分类恢复、加载和重试、插件失败及保存锁定、详情和焦点稳定、内置草稿的应用/取消、插件授权与取消独立,以及 13 种语言文案。
+
+插件并发回归覆盖:旧目录刷新不得覆盖期间保存的新授权;不同插件可独立保存;同插件保存中重复提交被拦截;切换页签后重新挂载仍保持保存锁;成功或失败后正确解锁。启用筛选下关闭已展开工具时,说明仍保留,收起后再按筛选条件隐藏。
+
+父级集成测试运行从设置组件提取的真实处理函数及应用/取消路径,替换后端持久化和无关设置依赖;它不等同于真实后端落盘测试。
+
+本轮执行结果:50 个测试文件、1768 项测试全部通过;完整 Vue/TypeScript 类型检查通过;定向 lint 无错误(设置组件有两条 HEAD 已存在的 `no-useless-fallback-in-spread` 警告);`git diff --check` 通过。
+
+## 桌面验收步骤
+
+1. 打开「设置 → MCP → 能力」。确认默认数据库分类、各分类顺序、实际工具数量和启用数;切换分类后先前草稿仍在。
+2. 关闭数据库分类,检查 Nacos、Consul、DBX 通用的启用状态保持原值。取消设置并重新打开,确认内置草稿撤销;再次修改并应用,重新打开应保持修改。
+3. 仅开启某个工具,勾选「仅显示已开启」,再执行本分类全部开启;被隐藏的工具也应开启。关闭最后一个工具后停留原分类并显示空状态,导航仍保留。
+4. 搜索分类名、工具集名、工具名称/ID、插件名/ID。结果应标明路径与来源,不显示分类批量按钮;点击具体工具直接展开,清空搜索恢复原分类。
+5. 在仅显示已开启的搜索结果中打开工具并关闭它。详情应继续显示;关闭详情后,若原结果消失,键盘焦点应返回搜索框。
+6. 选择插件,检查总开关、上限、工具集和待确认状态。首次开启和确认新增工具应进入授权流程;保存期间禁用对应控件。模拟保存失败时显示错误且保留旧状态。插件保存成功后取消设置,授权应仍然保留。
+7. 如果全局白名单限制插件,点击放行后应看到需要应用的提示;此操作可被取消撤销。高级配置添加自定义条目不能改变其他分类或移除插件通配符。
+8. 验证空连接、空插件、作者未开放、发现失败、目录加载失败及刷新/重试。暂无适用连接的内置工具仍可配置;已开启但无可暴露工具的插件保留原因。
+9. 在普通设置弹窗和宽页面,分别检查能力区域小于 600px、600–759px、至少 760px 的布局;切换明暗主题,并检查英文和长名称换行、参数局部滚动。
+10. 使用 Tab、Enter、Space、Escape 完成分类切换、搜索、开关、详情打开/关闭,确认焦点可见,详情关闭后回到触发按钮或搜索框。
+
+## 本次渲染验证范围
+
+使用隔离样例数据渲染实际 Vue 组件,检查数据库、Nacos、插件授权和搜索状态,以及宽版、紧凑双栏、窄版选择器、明暗主题、中英文、批量空状态、保存失败、工具直达及焦点恢复。样例页不调用真实插件或数据库,临时预览文件在验证后移除。
+
+真实桌面后端的持久化、插件进程发现和 MCP 客户端调用,应按上述桌面步骤做最终联调。
+
+## 本轮复查
+
+本轮设计和代码复查未发现剩余 P0、P1 或 P2 问题。修复了插件目录刷新覆盖新授权、切换页签丢失保存锁、筛选隐藏当前详情,以及工具直达和焦点恢复问题。
+
+| 设计维度 | 评分 | 依据 |
+| --- | --- | --- |
+| 设计理念 | 4/5 | 按产品与配置任务组织能力,批量操作范围明确 |
+| 信息层级 | 4/5 | 分类、工具集、工具三级清晰,搜索保留归属路径 |
+| DBX 适配度 | 4/5 | 复用现有组件、主题变量和权限模型,按能力区域宽度布局 |
+| 克制程度 | 4/5 | 移除重复筛选,参数和覆盖详情按需展开 |
+| 执行质量 | 4/5 | 草稿、即时保存、并发保护和焦点路径均有验证;真实后端联调待验收 |
diff --git a/docs/mcp-capability-platform-design.md b/docs/mcp-capability-platform-design.md
new file mode 100644
index 0000000000..b5f8313316
--- /dev/null
+++ b/docs/mcp-capability-platform-design.md
@@ -0,0 +1,580 @@
+# MCP 能力平台化设计方案
+
+> 状态:方向已确认(见 §10),P0–P4 已完成,收尾验证记录见 §9
+> 范围:MCP 的接入、能力(工具)注册与管理、权限模型、管理界面
+> 前置文档:[mcp-management-layout-redesign.md](./mcp-management-layout-redesign.md)(接入方式 / 权限管理两 Tab 布局)
+
+## 1. 背景与问题
+
+DBX 的 MCP Server 最初只服务 SQL 类数据库,现在已经覆盖 Redis、MongoDB、消息队列、Salesforce、连接管理、工作台联动和插件工具。后续还会陆续接入 Nacos、Consul、etcd、ZooKeeper、Elasticsearch、MQTT、向量库等各类非 SQL 产品,以及更多插件。现有设计是围绕 SQL 长出来的,继续堆功能会遇到下面这些问题。
+
+### 1.1 现状盘点
+
+| 维度 | 现状 | 代码位置 |
+|---|---|---|
+| 接入 | stdio(独立二进制 `dbx-mcp`)+ Streamable HTTP(单 Bearer Token),已经稳定 | `crates/dbx-mcp/src/{transport,http,http_auth}.rs` |
+| 内置工具 | 28 个静态工具,平铺在一个列表里 | `crates/dbx-mcp/src/server.rs` 的 `#[tool(name = ...)]` |
+| 工具开关 | `allowed_tool_names: Option<Vec<String>>` 扁平白名单;插件靠 `dbx_<prefix>__*` 通配符 | `server.rs::policy_allows_tool` |
+| 执行权限 | `read_only` + `allow_dangerous_sql` 两个布尔值,按 全局 → 分组 → 连接 → 单库 逐级覆盖 | `dbx-core/src/ai/mcp_policy.rs` |
+| 资源范围 | 分组/连接白名单 + 连接下的 `database_scope`(All/Selected/None) | `persistence/storage.rs::McpConnectionPolicy` |
+| 特例开关 | `allow_salesforce_dml` 直接挂在连接策略上 | `storage.rs`、`mcp_policy.rs::connection_allows_salesforce_dml` |
+| 插件工具 | 插件作者在 manifest 里声明 `mcp.external_tools: true` 才会对外暴露;只读判定只看 `readOnlyHint`;暴露方式由环境变量 `DBX_MCP_PLUGIN_TOOLS=flat/lazy/both` 控制 | `dbx-mcp/src/plugin_tools.rs`、`plugin-runtime/.../manifest.rs` |
+| 插件 AI 开关 | 插件中心里有“内置 AI 可用”的用户开关(`ai_plugin_tool_plugins`);**外部 MCP 没有用户侧开关** | `PluginAiAccessSection.vue` |
+| 确认 | `prompt_high_risk_sql`:安全写模式下,高危 SQL 需要桌面端确认 | `McpSqlApprovalDialog.vue` |
+| 非 SQL 产品 | Redis、MQ、Salesforce 各自零散地加了专用工具,没有统一规范;Nacos、Consul 等已有完整管理能力(`dbx-core/src/admin/*`),**MCP 还没接** | — |
+
+### 1.2 核心问题
+
+1. **权限语义只适用于 SQL。** `read_only` / `allow_dangerous_sql` 套在 Nacos(发布配置、下线实例)、Consul(写 KV、改 ACL)、MQ(发消息、清队列)、插件(SSH 执行命令)上都不准确。每接一种新能力,就会多一个 `allow_salesforce_dml` 这样的专用字段,策略结构会越来越碎。
+2. **“数据库范围”这一层没有抽象。** 在 Nacos 里是 namespace/group,在 Consul 里是 datacenter/KV 前缀,在 Kafka 里是 topic,在插件里可能是 K8s namespace,但现在只有 `database_name` 一种表达。
+3. **工具列表平铺,而且跟连接类型无关。** 用户没有任何 Salesforce 连接,界面上照样出现 3 个 Salesforce 勾选项;28 个工具加上插件工具(上限 512 个),既让界面变得复杂,也会浪费客户端的上下文。
+4. **插件管理分散在两处。** 内置 AI 的开关在插件中心,外部 MCP 只能靠作者声明加上权限页里的通配符白名单,用户没法以插件为单位清楚地控制“这个插件对 MCP 是否开放、开放到什么程度”。
+5. **插件工具的风险只能二选一。** 只有“是否只读”,无法区分普通写入和破坏性操作,确认机制也只覆盖 SQL。
+6. **独立二进制存在版本差。** `dbx-mcp` 和桌面端分别升级,策略文件的格式一旦变化,老版本二进制必须仍然安全(不能因为看不懂新字段而放宽权限)。
+
+## 2. 设计目标与原则
+
+- **一个统一的权限心智模型**:不管是 SQL、Nacos 还是插件,用户面对的都是“这个资源能 不可访问 / 只读 / 读写 / 完全访问”。
+- **能力按“提供方 → 工具集 → 工具”三层组织**:界面默认只操作到工具集(或插件)这一层,单个工具的开关作为高级选项。
+- **权限 = 资源 × 级别**,工具只声明“我需要什么级别”。用户不需要把每个工具和每个连接一一配对。
+- **内置和插件同构**:内置的 SQL、各产品能力和插件能力走同一套描述符、同一套判定、同一个界面。
+- **按产品接入,规范统一**:每个非 SQL 产品作为独立的提供方,工具贴合产品自身模型;所有产品遵守同一份接入规范(§5),Nacos、Consul 只是首批示例,后续产品一律照此执行。
+- **只有一份全局策略**:所有 MCP 客户端共用 DBX 当前的权限管理,不引入按客户端区分的多套策略。
+- **默认简单**:全局默认权限负责统一默认值;需要单独权限时在访问控制树中设置。
+- **默认安全、失败时拒绝**:没有声明的视为写入;新出现的高级别工具默认不开放;老版本二进制只读取一份“不会比新策略更宽”的投影。
+- **兼容平滑**:现有策略能无损映射到新模型,迁移后行为不变。
+
+## 3. 核心抽象
+
+### 3.1 三层能力模型
+
+```text
+能力提供方 Provider 工具集 Toolset 工具 Tool
+──────────────────── ───────────────────── ───────────────────────────
+builtin:core 发现与上下文 list_connections / list_databases / get_schema_context ...
+builtin:sql SQL 查询 execute_query / execute_batch
+ 会话与事务 open_session / begin / commit / rollback / close
+ 对象结构 list_tables / describe_table / list_routines / get_routine_source
+builtin:redis Redis execute_redis_command
+builtin:mq 消息队列 peek_messages / send_message
+builtin:salesforce Salesforce salesforce_current_user / prepare_write / apply_write
+builtin:<product> (新) 按 §5 规范,每个产品一个提供方 dbx_<product>_* ……
+ 例 builtin:nacos Nacos 配置 / Nacos 服务 / Nacos 管理(默认关闭)
+ 例 builtin:consul Consul KV / Consul 服务 / Consul 管理(默认关闭)
+ 后续 etcd / zookeeper / elasticsearch / mqtt / milvus …… 同样方式接入
+builtin:workbench 工作台联动 open_table / execute_and_show
+builtin:admin 连接管理 add_connection / duplicate_connection / remove_connection
+plugin:<pluginId> 由插件声明(默认一个工具集) 由插件 mcp/tools 返回
+```
+
+- **Provider(提供方)**:权限和启停的归属单位。内置提供方随 DBX 版本发布;每个插件就是一个提供方。
+- **Toolset(工具集)**:界面上的开关单位,也是 `tools/list` 裁剪的单位。
+- **Tool(工具)**:协议层的实际工具,带一份静态描述符。
+
+### 3.2 工具描述符(Tool Descriptor)
+
+内置工具不再只在 UI 里写死名称,而是在后端集中注册一份描述符表,UI 通过接口拉取:
+
+```rust
+pub struct ToolDescriptor {
+ pub name: &'static str, // dbx_execute_query
+ pub provider: ProviderId, // builtin:sql / plugin:io.dbx.ssh
+ pub toolset: &'static str, // sql.query
+ /// 工具可能触及的最高访问级别。
+ pub access: AccessLevel, // Read | Write | Full
+ /// 级别是静态的,还是由运行时分类器逐次判定(例如 SQL 风险分析)。
+ pub access_mode: AccessMode, // Static | Classified
+ /// 工具作用于哪类资源;None 表示不绑定连接(例如 add_connection)。
+ pub resource: Option<ResourceKind>,// Connection { kinds: &[ConnectionKind] }
+ /// 是否接受子范围参数,例如 database / namespace / topic。
+ pub scope_kind: Option<ScopeKind>,
+ /// 适用连接类型的计算方式(用于界面上的“覆盖范围”说明,见 §5.5)。
+ pub coverage: Coverage, // Static(&[DatabaseType]) | Capability(CapabilityKey)
+}
+```
+
+- `access_mode = Classified`:工具本身声明最高级别为 Full,每次调用时由分类器给出实际级别。`execute_query` 继续复用 `sql_risk`:SELECT 判为 Read,普通 DML 判为 Write,DDL/DROP/TRUNCATE 判为 Full。`dbx_nacos_publish_config` 是静态的 Write,`dbx_nacos_delete_config` 是静态的 Full。
+- `resource.kinds` 声明适用的连接类型。如果当前**没有任何可见连接**属于这些类型,这个工具集就在 `tools/list` 和界面里自动隐藏(界面上灰显,并提示“无可用连接”)。这样同时解决了“Salesforce 勾选项常驻”和“工具太多”这两个问题。
+- `coverage = Capability(...)`:适用类型不写死,而是从驱动清单 `crates/dbx-core/assets/database-drivers.manifest.json` 中按能力位计算(例如 `queryExecution`、`objectSource`、`metadataBrowse`)。新增或调整一个驱动时,工具的覆盖范围和界面说明自动更新,不需要改 MCP 代码。
+
+### 3.3 统一访问级别
+
+| 级别 | 含义 | SQL | MongoDB | Redis | MQ | 其他产品(以 Nacos / Consul 为例) | 插件 |
+|---|---|---|---|---|---|---|---|
+| 不可访问 | 对 MCP 不可见 | — | — | — | — | — | — |
+| 只读 Read | 不改变状态 | SELECT / EXPLAIN | find / aggregate(无 `$out`) | GET 类命令 | peek | 查询配置、服务、KV | `access = read` |
+| 读写 Write | 可逆或常规的变更 | INSERT / UPDATE / DELETE(带条件) | insert / update | SET 类命令 | send | 发布配置、注册/修改实例、写 KV | `access = write` |
+| 完全 Full | 破坏性、批量或结构变更 | DDL、DROP、TRUNCATE、无 WHERE 的 DML | drop、`$out` 跨库 | FLUSH*、DEL 模式匹配 | 删除 topic、清空队列 | 删除配置/命名空间、ACL 变更 | `access = full` |
+
+**与现有字段无损映射:**
+
+| 现有 `(read_only, allow_dangerous_sql)` | 新级别 |
+|---|---|
+| `(true, *)` | Read |
+| `(false, false)` | Write |
+| `(false, true)` | Full |
+
+`allow_salesforce_dml` 等专用字段会被收编:Salesforce 写入在描述符里声明为 Write,由连接的访问级别控制,不再需要单独字段。迁移时,连接上的 `allow_salesforce_dml=false` 会被转成一条“该连接上 Salesforce 写入工具的上限为 Read”的规则,保证迁移后行为不变(详见 §6)。
+
+### 3.4 资源与子范围
+
+```text
+全局默认
+└── 分组(可嵌套,沿用侧边栏分组 id)
+ └── 连接(内置类型或插件连接,plugin_id 区分)
+ └── 子范围 Scope(由连接类型声明种类)
+ SQL / Mongo → database(可选 schema)
+ Redis → db index
+ 其他产品 → 由产品提供方按 §5 声明,例如 Nacos → namespace,Consul → datacenter / KV 前缀
+ Kafka 等 → topic / queue 模式
+ 插件 → 插件在 manifest 中声明的 scope kind,由插件提供列举方法
+```
+
+每个节点上可以配置:
+
+- **可见性**:继承 / 可见 / 不可见。
+- **访问级别**:继承 / 不可访问 / 只读 / 读写 / 完全。
+
+继承顺序与现有规则一致:**子范围 > 连接 > 最近的分组 > 上级分组 > 全局默认**。
+
+**调用安全**独立于资源继承,由全局策略统一决定高危调用是否逐次确认。节点权限不能关闭这项确认要求;旧版临时授权仅为兼容保留,详见文末“调用安全语义与兼容”。
+
+### 3.5 判定公式
+
+一次工具调用最终是否被允许:
+
+```text
+allowed =
+ provider.enabled // 插件或内置能力已开启
+ AND toolset.enabled AND tool.enabled // 工具层开关
+ AND resource.visible // 连接 / 子范围可见
+ AND call_level ≤ effective_level(resource) // 级别比较
+ AND call_level ≤ provider.ceiling // 插件授权上限(§4.3)
+ AND hard_protections(resource, call_level) // 连接只读保护、生产保护、跨库校验等,永远是上限
+
+call_level = tool.access_mode == Classified ? classify(call) : tool.access
+
+needs_confirm = allowed AND confirm == high_risk AND is_high_risk(call)
+```
+
+以上为新策略:先授权,再确认;批准后重新校验权限和硬保护。旧 `confirm=full` 不采用新的语义,继续保留原先 Write 经确认临时执行部分 Full 操作的行为,直到用户主动迁移。
+
+- **不绑定连接的工具**(`add_connection`、插件中与连接无关的工具):`resource` 取“提供方自身”,级别和全局默认比较。另外延续现有规则:在有作用域的会话里,没有任何可见连接的插件,它的无连接工具也不可用,避免成为绕过限制的侧门。
+- **跨资源调用**(SQL 引用其他库、Mongo 的 `$out`/`$merge`):延续现有 `ensure_*_database_execution_scope`,推广成“分类器必须返回调用触及的所有子范围”,每个子范围都单独判定。
+- **`tools/list` 裁剪**:工具只有在至少一个可见资源的生效级别 ≥ 该工具的最低可用级别时才会出现。例如全部资源都是只读时,`commit_transaction`、`send_message` 之类的工具不会出现在列表里,减少客户端上下文;但调用时的判定仍是权威的。
+
+## 4. 插件 MCP 能力
+
+### 4.1 Manifest 扩展
+
+在现有 `mcp.ai_tools` / `mcp.external_tools` 基础上扩展,所有新字段都可选:
+
+```toml
+[mcp]
+ai_tools = true # 内置 AI 是否可以使用(作者上限)
+external_tools = true # 外部 MCP 是否可以使用(作者上限)
+
+# 可选:工具分组。不声明时整个插件就是一个工具集。
+[[mcp.toolsets]]
+id = "files"
+title = "文件浏览"
+[[mcp.toolsets]]
+id = "shell"
+title = "远程命令"
+
+# 可选:逐个工具声明级别与分组。不声明时根据 MCP annotations 推断。
+[mcp.tools.sftp_list_dir]
+toolset = "files"
+access = "read"
+[mcp.tools.ssh_exec]
+toolset = "shell"
+access = "full"
+
+# 可选:子范围。插件可以让用户按 K8s namespace、目录等进一步限定。
+[mcp.scope]
+kind = "namespace"
+title = "命名空间"
+list_method = "mcp/scopes" # sidecar 方法,返回某个连接下可选的范围
+argument = "namespace" # 工具调用里承载范围的参数,由宿主校验
+```
+
+**级别推断(未声明时)**:`readOnlyHint = true` → Read;`destructiveHint = true` → Full;其他情况一律视为 Write。这和现有“只读模式下拒绝未声明只读的插件工具”保持一致。
+
+`mcp/tools` 运行时返回的工具如果不在 manifest 声明里,就按推断处理,并在界面上标注“未声明级别”。
+
+### 4.2 以插件为单位管理(参考 uTools)
+
+- **一个插件对应一张卡片、一个总开关**:开关含义是“这个插件的工具对外部 MCP 开放”。作者的 `external_tools = false` 是硬上限,此时开关禁用,并显示“插件作者未开放”。
+- **内置 AI 和外部 MCP 共用一份存储**:存成 `plugin_capability_grants[pluginId] = { ai: bool, mcp: bool, ceiling, approvedTools, ... }`。插件中心和 MCP 设置编辑的是同一份数据,两边都能看到两个开关,避免出现两套状态。现有的 `ai_plugin_tool_plugins` 迁移到 `grants[*].ai`。
+- **首次开启时做一次授权确认**(类似 OAuth scope):弹窗列出插件的工具集和级别,用户选择授权上限(只读 / 读写 / 完全,默认取“插件声明的最高级别”和“读写”中较低的一个)。
+- **插件升级后的变化**:
+ - 新增只读工具在授权上限内可跟随插件开关自动可用;新增非只读工具仍需用户确认。
+ - 新增非只读工具,或已有工具的声明级别升高到非只读级别 → 默认不可用,卡片上显示待确认状态;工具超过授权上限时仍保持隐藏。
+- **插件的连接仍然走资源树**:插件连接本来就是 DBX 连接(`plugin_id` 非空),所以连接可见性、访问级别、子范围都在同一棵树里配置,不需要单独做一套。
+
+### 4.3 插件工具对外提供方式
+
+在“能力 → 高级配置”提供默认折叠的设置,控制 DBX 如何向 MCP 客户端提供已授权的插件工具,点击底部“应用”后生效:
+
+- **直接列出(新配置默认)**:逐个提供已授权工具,对应 `flat`。
+- **按需发现**:通过 `dbx_plugin_list` / `dbx_plugin_tools` / `dbx_plugin_call` 查询与调用,对应 `lazy`,需开启“DBX 通用 → 插件发现与调用”。
+- **自动(兼容模式)**:保留原有行为,插件工具总数 ≤ 40 时直接列出,超过时按需发现。已有模式不迁移;旧配置缺少该字段时保持原有自动行为。
+
+环境变量继续保留,用于覆盖设置。
+
+## 5. 产品能力接入规范
+
+> **适用范围:所有非 SQL 产品,包括现在已有的和以后新增的。** 下文的 Nacos、Consul 只是用来说明规范的首批示例,不是特例。etcd、ZooKeeper、Elasticsearch、MQTT、Milvus / Qdrant 等向量库、InfluxDB、Neo4j……以后任何产品接入 MCP,都必须按本节执行;Redis、MQ、Salesforce 这些已有的专用工具也逐步对齐到本规范。
+
+### 5.1 什么时候共用工具,什么时候按产品区分
+
+| 情况 | 做法 | 例子 |
+|---|---|---|
+| 多个产品共享一门 DBX 已经统一处理的查询语言 | 共用通用工具,由方言层处理差异 | 所有 SQL 数据库共用 `dbx_execute_query`、`dbx_describe_table` 等 |
+| 产品有自己的数据模型、命令或 API | **按产品单独提供工具**,不做跨产品抽象 | Nacos、Consul、Redis、Elasticsearch、MQTT …… |
+
+按产品区分的原因:各产品功能虽然相近,但细节差异大(Nacos 的 dataId + group + namespace 与配置回滚;Consul KV 的 CAS / ModifyIndex 与 datacenter;etcd 的 revision 与 lease)。强行统一要么丢能力,要么参数里塞满“仅某产品有效”的字段,模型调用时容易出错。
+
+### 5.2 接入清单
+
+每个产品作为一个内置提供方 `builtin:<product>`,接入时必须提供以下内容:
+
+| 项 | 要求 |
+|---|---|
+| 提供方 | id 为 `builtin:<product>`;声明适用的连接类型(`db_type`),默认一个连接类型对应一个提供方 |
+| 工具命名 | `dbx_<product>_<动作>_<对象>`,例如 `dbx_nacos_publish_config`。不得包含 `__`(`dbx_<prefix>__<tool>` 保留给插件) |
+| 工具集划分 | 按业务场景拆分,例如“配置”“服务”“KV”。日常场景的工具集默认开启;用户、角色、权限、命名空间增删等管理类操作统一放进“<产品> 管理”工具集,**默认关闭** |
+| 不暴露的操作 | 快照恢复、集群成员变更、License 写入、任意原始 API 透传等集群级或无法判定风险的操作,不提供 MCP 工具 |
+| 访问级别 | 每个工具在描述符里声明 Read / Write / Full(§3.3)。产品有自己的命令语言时(如 Redis),提供分类器逐次判定(`Classified`) |
+| 子范围 | 声明本产品的子范围种类(如 namespace、datacenter、db index、index、topic),并提供列举方法,供访问控制树懒加载;带子范围的工具必须把它作为显式参数,由宿主校验 |
+| 硬保护 | 复用连接只读保护、生产保护;产品自身已有的写保护(如 Consul 的 `ensure_writable_core`)继续生效 |
+| 实现位置 | 业务逻辑复用 `dbx-core/src/admin/<product>` 中已有的实现;MCP 层(`dbx-mcp/src/providers/<product>.rs`)只做参数映射、权限判定和结果整形,不重复实现业务 |
+| 确认预览 | Write / Full 工具需要给确认弹窗提供变更摘要:发布类给出前后 diff,批量删除类先预览影响范围 |
+| 界面与文案 | 工具集标题、说明和工具说明提供中英文 i18n;能力 Tab 自动生成卡片,不需要为产品单独写界面 |
+| 测试 | 描述符完整性测试(每个工具都有工具集、级别、适用连接类型);权限判定测试(各级别 × 子范围);至少一条正常调用的集成测试 |
+
+满足清单后,判定、`tools/list` 裁剪、能力 Tab、访问控制树、确认弹窗、调用记录全部自动复用,**不需要为单个产品改动框架或界面**。
+
+### 5.3 示例
+
+以下两个示例说明规范如何落到具体产品上。后续产品按同样的格式在本节补一张表即可。
+
+#### 示例一:Nacos
+
+实现复用 `crates/dbx-core/src/admin/nacos` 中已有的 `nacos_*_core` 函数。子范围:namespace。
+
+| 工具集 | 工具 | 级别 | 对应现有实现 |
+|---|---|---|---|
+| Nacos 配置(默认开启) | `dbx_nacos_list_configs` | Read | `nacos_list_configs_core` |
+| | `dbx_nacos_get_config` | Read | `nacos_get_config_core` |
+| | `dbx_nacos_search_configs` | Read | `nacos_search_config_content_core` |
+| | `dbx_nacos_config_history` | Read | `nacos_list_config_history_core` / `nacos_get_config_history_core` |
+| | `dbx_nacos_publish_config` | Write | `nacos_publish_config_core` |
+| | `dbx_nacos_rollback_config` | Write | `nacos_rollback_config_core` |
+| | `dbx_nacos_delete_config` | Full | `nacos_delete_config_core` |
+| Nacos 服务(默认开启) | `dbx_nacos_list_services` | Read | `nacos_list_services_core` |
+| | `dbx_nacos_get_service` | Read | `nacos_get_service_core` |
+| | `dbx_nacos_list_instances` | Read | `nacos_list_instances_core` |
+| | `dbx_nacos_update_instance` | Write | `nacos_update_instance_core`(上下线、权重、元数据) |
+| | `dbx_nacos_register_instance` / `dbx_nacos_deregister_instance` | Write / Full | `nacos_register_instance_core` / `nacos_deregister_instance_core` |
+| Nacos 管理(默认关闭) | `dbx_nacos_list_namespaces` | Read | `nacos_list_namespaces_core` |
+| | `dbx_nacos_create_namespace` / `update` / `delete` | Write / Write / Full | `nacos_*_namespace_core` |
+| | `dbx_nacos_list_users` / 用户与角色变更 | Read / Full | `nacos_*_user_core`、`nacos_assign_role_core` 等 |
+
+- 发布配置要求传入 `content` 和 `type`;如果当前配置存在,返回的结果里带上变更前后的摘要,方便确认弹窗展示 diff。
+- `dbx_nacos_list_namespaces` 在“管理”工具集关闭时,仍然会以只读方式出现在“Nacos 配置”工具集中(模型需要知道有哪些 namespace),但只列出访问控制树中可见的 namespace。
+
+#### 示例二:Consul
+
+实现复用 `crates/dbx-core/src/admin/consul` 中已有的 `consul_*_core` 函数。子范围:暂无——一个 Consul 连接本身就对应一个 datacenter,按 datacenter 细分没有意义;KV 前缀级授权留待需要时再加。
+
+| 工具集 | 工具 | 级别 | 对应现有实现 |
+|---|---|---|---|
+| Consul KV(默认开启) | `dbx_consul_kv_list` | Read | `consul_list_prefix_core` / `consul_list_recursive_core` |
+| | `dbx_consul_kv_get` | Read | `consul_get_core` |
+| | `dbx_consul_kv_put` | Write | `consul_put_core`(支持 `cas` ModifyIndex) |
+| | `dbx_consul_kv_delete` | Full | `consul_delete_core`;按前缀删除走 `consul_delete_prefix_preview_core` → `execute`,并强制确认 |
+| Consul 服务(默认开启) | `dbx_consul_list_services` | Read | `consul_catalog_services_core` |
+| | `dbx_consul_service_health` | Read | `consul_health_service_core` / `consul_health_checks_core` |
+| | `dbx_consul_list_nodes` | Read | `consul_catalog_nodes_core` |
+| | `dbx_consul_set_maintenance` | Write | `consul_agent_service_maintenance_core` |
+| Consul 管理(默认关闭) | `dbx_consul_acl_list` / `get` | Read | `consul_acl_list_core` / `consul_acl_get_core` |
+| | `dbx_consul_acl_apply` / `delete` | Full | `consul_acl_apply_core` / `consul_acl_delete_core` |
+| | `dbx_consul_intention_*` | Read / Full | `consul_mesh_intention_*_core` |
+
+- 快照恢复、Raft 操作、License 写入这类集群级危险操作**不暴露给 MCP**。
+- 已有的 `ensure_writable_core`(连接只读保护)继续作为硬保护生效。
+
+### 5.4 已有产品对齐与后续产品
+
+| 产品 | 现状 | 对齐方式 |
+|---|---|---|
+| Redis | `dbx_execute_redis_command` | 归入 `builtin:redis`;命令分类器给出级别;子范围为 db index |
+| 消息队列 | `dbx_peek_messages` / `dbx_send_message` | 归入 `builtin:mq`;子范围为 topic / queue;补充描述符 |
+| Salesforce | 3 个专用工具 + `allow_salesforce_dml` 字段 | 归入 `builtin:salesforce`;写入由访问级别控制,专用字段按 §6.2 迁移后移除 |
+| etcd、ZooKeeper、Elasticsearch、MQTT、向量库等 | 未接入 MCP | 按需排期,接入时按 §5.2 清单执行,并在 §5.3 补示例表 |
+
+插件提供的产品能力通过 manifest(§4.1)声明同样的信息:工具集、访问级别、子范围。内置产品和插件产品遵守同一份规范。
+
+### 5.5 SQL 类数据库与通用查询工具
+
+SQL 类数据库是 §5.1 中“共用通用工具”的情况,**不按数据库拆分工具**。现有工具、名字和行为全部保留,只纳入本方案的统一框架。
+
+#### 5.5.1 在新框架中的位置
+
+| 方面 | 处理方式 | 行为是否变化 |
+|---|---|---|
+| 工具 | 现有工具全部保留、名字不变,分成“SQL 查询”“会话与事务”“对象结构”三个工具集 | 不变 |
+| 发现类工具 | `list_connections` / `list_databases` / `get_schema_context` 归入“发现与上下文”,所有连接类型共用 | 不变 |
+| 访问级别 | 只读 → 只读;安全写 → 读写;允许高危 SQL → 完全访问 | 不变 |
+| 逐条判定 | 继续用 `sql_risk`:SELECT 为只读,普通 DML 为读写,DDL / DROP / TRUNCATE / 无条件 DML 为完全访问 | 不变 |
+| 继承 | 全局 → 分组 → 连接 → 单库;单库是子范围的一种(种类为 database) | 不变 |
+| 跨库校验 | SQL 引用其他库、Mongo `$out` / `$merge` 写到其他库的校验继续生效 | 不变 |
+| 确认 | 独立调用安全在授权后逐次确认高危调用,完全访问也遵循;旧 `prompt_high_risk_sql` 保留临时授权语义,主动切换才迁移 | 新策略与旧配置分别处理 |
+| 硬保护 | 连接只读保护、生产保护保持不变,永远是上限 | 不变 |
+
+**MongoDB**:现在也通过 `dbx_execute_query` 执行 shell 命令。近期保留这条路径以兼容现有配置,级别判定改用 MongoDB 命令分类;后续按 §5.2 新增 `builtin:mongodb` 提供专用工具,`dbx_execute_query` 对 MongoDB 的支持只保留兼容,不再扩展。
+
+#### 5.5.2 覆盖范围说明(界面提示)
+
+通用工具一次覆盖几十种数据库,但**不同工具覆盖的范围并不相同**。例如“存储过程源码”只有部分数据库支持,`execute_query` 则覆盖所有能执行查询的连接。用户需要在配置和使用时清楚知道每组工具对哪些数据库生效。
+
+**数据来源**:覆盖范围由描述符的 `coverage` 从驱动清单的能力位计算,不在界面上写死:
+
+| 工具集 / 工具 | 计算依据 | 当前覆盖(按 2026-10 驱动清单统计) |
+|---|---|---|
+| SQL 查询:`execute_query` | `capabilities.queryExecution` | 78 种:关系型、国产、轻量、分析型、时序、部分搜索/文档 |
+| SQL 查询:`execute_batch` | `capabilities.sqlFileExecution` | 64 种:关系型、国产、轻量、分析型等 |
+| 会话与事务 | 静态声明,与 `transaction_connection_supported` 保持一致 | 目前只有 MySQL(原生驱动);其他类型可以开会话,但不能开启事务 |
+| 对象结构:`list_tables` / `describe_table` | `capabilities.metadataBrowse` | 76 种 |
+| 对象结构:`list_routines` / `get_routine_source` | `capabilities.objectSource` | 31 种:MySQL、PostgreSQL、SQL Server、Oracle、DB2、达梦、金仓等 |
+
+不支持 MCP 的类型(清单中 `mcpMode = "unsupported"`,如 Nacos、Consul、MQ、MQTT)不计入通用工具的覆盖,它们按 §5.2 由各自的产品提供方覆盖。
+
+**界面上分三层展示,从简到详:**
+
+1. **卡片摘要**(能力 Tab 卡片第二行):一句话写明覆盖范围,并标出用户当前有多少连接会用到这组工具。
+
+ ```text
+ [≡] SQL 查询 execute_query · execute_batch 读 写 高危 2/2 [●]
+ 适用 78 种数据库 · 你有 6 个连接会用到 [查看覆盖]
+ [≡] 对象结构 4 个工具 读 4/4 [●]
+ 表结构适用 76 种 · 存储过程仅 31 种 · 你有 6 个连接会用到 [查看覆盖]
+ ```
+
+2. **覆盖详情**(点击“查看覆盖”或卡片抽屉中的“覆盖范围”页签):按连接分类分组列出数据库,分组沿用新建连接时的分类(关系型、国产、轻量、分析型、文档与搜索、时序、图与向量),用户熟悉。
+
+ ```text
+ 覆盖范围 · 对象结构 [搜索数据库…]
+ ┌─────────────────────────────────────────────────────────────────┐
+ │ 工具 关系型 国产 轻量 分析型 文档/搜索 时序 图/向量 │
+ │ 列出表 / 表结构 ✓ ✓ ✓ ✓ 部分 ✓ 部分 │
+ │ 存储过程列表/源码 ✓ ✓ 部分 — — — — │
+ └─────────────────────────────────────────────────────────────────┘
+ 关系型(9) MySQL ✓ PostgreSQL ✓ SQL Server ✓ Oracle ✓ DB2 ✓ …
+ 国产(16) 达梦 ✓ 金仓 ✓ 瀚高 ✓ GaussDB ✓ OceanBase Oracle ✓ …
+ ……
+ ● 你已有连接的类型高亮显示;“部分”可展开看到具体哪些支持、哪些不支持
+ ```
+
+3. **连接维度提示**(访问控制树):连接行悬停或展开时,显示“这个连接可用的 MCP 工具集”,例如 `local-mysql-v8:SQL 查询 · 会话与事务 · 对象结构(含存储过程)`;`local-redis-v7:Redis 命令`。用户在给连接授权时就能看到授权后实际能用哪些工具。
+
+**其他场景的提示:**
+
+- 用户有某种类型的连接,但**没有任何工具集覆盖它**(例如 Nacos 尚未接入时):在访问控制树该连接行显示“暂无 MCP 工具”,并在能力 Tab 顶部给出一条汇总提示:“有 2 个连接的类型暂不支持 MCP:dev-nacos、prod-consul”。
+- 工具集**部分覆盖**用户已有的连接(例如有 SQLite 连接,但存储过程工具不支持 SQLite):卡片摘要显示“你的 1 个连接不支持其中部分工具”,展开后列出具体连接与工具。
+- 发给 MCP 客户端的工具说明(`description`)末尾同样附上一句简短的覆盖说明,例如 “Supported on relational, analytical and time-series databases; not on Redis or MongoDB.”,让模型也知道不该对不支持的连接调用;调用不支持的连接时,返回的错误里列出该连接可用的工具。
+
+## 6. 策略数据模型 v2 与迁移
+
+### 6.1 结构
+
+```jsonc
+{
+ "version": 2,
+ "defaults": { "access": "read", "confirm": "full" },
+ "visibility": { "mode": "all" }, // 或 { "mode": "selected" },范围由 rules 的 visible 决定
+ "rules": [
+ { "target": { "group": "g-prod" }, "access": "read" },
+ { "target": { "connection": "c-mysql-dev" }, "access": "full", "visible": true },
+ { "target": { "scope": { "connection": "c-mysql-dev", "kind": "database", "value": "billing" } }, "access": "read" },
+ { "target": { "connection": "c-nacos" }, "toolsets": { "nacos.config": "read" } } // 可选:按工具集收紧级别
+ ],
+ "toolsets": {
+ "sql.batch": { "enabled": false },
+ "sql.tx": { "enabled": true, "tools": { "dbx_commit_transaction": false } }
+ },
+ "providers": {
+ "plugin:io.dbx.ssh": { "mcp": true, "ai": true, "ceiling": "write", "approvedTools": ["sftp_list_dir", "ssh_exec"] }
+ },
+ "runtime": { "queryTimeoutSecs": 0, "pluginToolsMode": "flat" }
+}
+```
+
+- `rules[].toolsets` 是**收紧**规则(只能降级,不能升级),用来表达“这个连接整体读写,但 Salesforce 写入只读”这类例外。`allow_salesforce_dml` 的迁移就落在这里。
+- 规则以目标为键做 upsert,避免同一个目标出现重复规则。
+
+### 6.2 迁移
+
+| v1 字段 | v2 |
+|---|---|
+| `read_only` / `allow_dangerous_sql` | `defaults.access` |
+| `prompt_high_risk_sql` | `defaults.confirm = "full"`(false 时为 `"off"`) |
+| `allowed_connection_ids` = None | `visibility.mode = all` |
+| `allowed_connection_ids` / `allowed_group_ids` | `visibility.mode = selected` + 对应 rules 设 `visible: true` |
+| `group_policies[]` | `rules[{group}]` |
+| `connection_policies[]`(v1 版本标记) | `rules[{connection}]` |
+| `connection_policies[]`(无版本标记的旧规则) | 按 `apply_ceiling` 计算出生效级别后写入,保持“只能收紧”的语义 |
+| `database_scope` + `allowed_databases` | `scope` 规则的 `visible` |
+| `database_policies[]` | `rules[{scope: database}]` |
+| `allow_salesforce_dml = false` | `rules[{connection}].toolsets["salesforce.write"] = "read"` |
+| `allowed_tool_names` | 反推出 `toolsets[*].enabled` 和单工具开关;插件通配符写到 `providers[*].mcp` |
+
+**迁移验证**:在迁移函数旁边加一个属性测试:对任意 v1 策略、任意(连接、库、工具、SQL 级别)组合,v1 判定结果 == v2 判定结果。
+
+### 6.3 独立二进制的版本差
+
+桌面端保存时**同时写入**:
+
+1. `mcp_policy_v2`:新格式,是权威数据。
+2. `mcp_global_policy`(v1):由 v2 **向下投影**得到,投影规则是“任何情况下都不比 v2 宽”。v1 表达不了的部分(例如按工具集收紧、新的 scope 种类)一律投影成更严的结果,例如直接关闭对应工具。
+
+新版二进制优先读 v2;老版二进制只认识 v1,因此仍然安全。再过两到三个版本后,可以在升级检查里提示用户更新 `dbx-mcp`,然后停写 v1。
+
+## 7. 确认与审计
+
+- **确认通用化**:`McpSqlApprovalDialog` 推广为 `McpToolApprovalDialog`。弹窗展示:客户端、工具、目标资源、判定级别;SQL 额外展示语句和风险原因;插件工具额外展示参数摘要。任何提供方的工具,只要 `needs_confirm` 为真,就走这个弹窗。
+- **桌面端不在线时(stdio 单独运行)**,需要确认的调用一律拒绝,并返回 `CONFIRMATION_UNAVAILABLE`,不会静默放行。
+- **审计**:在现有历史记录基础上增加“MCP 调用记录”视图:时间、接入方式(stdio / HTTP)与客户端名称(取自 MCP initialize 上报的 clientInfo,仅用于记录,不参与权限判定)、工具、资源、级别、结果、是否经过确认。权限预览里可以从某个资源直接跳到它的调用记录。
+
+## 8. 界面设计
+
+### 8.1 信息架构
+
+把现在的两个 Tab 调整为三个,每个 Tab 只回答一个问题:
+
+```text
+MCP Server [可用] [重新检查] [MCP 指南]
+
+[ 接入 ] [ 能力 ] [ 访问控制 ]
+ 怎么连 能用哪些工具 能碰哪些资源、到什么程度
+```
+
+| Tab | 内容 | 相对现状的变化 |
+|---|---|---|
+| 接入 | stdio / HTTP、版本、安装卸载、客户端配置、运行参数(超时) | 插件工具对外提供方式移入能力的高级配置 |
+| 能力 | 内置能力卡片 + 插件卡片,类似 uTools 插件列表,含高级配置 | 新增;取代现在“第 4 步”里平铺的 28 个勾选项 |
+| 权限管理 | 全局默认权限 + 访问控制树(含生效预览)+ 独立调用安全 | 默认值和局部覆盖分开配置 |
+
+### 8.2 能力 Tab
+
+```text
+搜索能力或工具… [全部] [内置] [插件] [仅显示已启用]
+
+内置能力
+┌─────────────────────────────────────────────────────────────────────────┐
+│ [≡] SQL 查询 execute_query · execute_batch 读 写 高危 2/2 [●] │
+│ [≡] 会话与事务 5 个工具 读 写 5/5 [●] │
+│ [≡] 对象结构 4 个工具 读 4/4 [●] │
+│ [≡] 消息队列 peek · send 读 写 1/2 [●] │
+│ [≡] Nacos 3 个工具集 · 2 个可用连接 读 写 高危 2/3 [●] │
+│ [≡] Consul 3 个工具集 · 1 个可用连接 读 写 高危 2/3 [●] │
+│ ……(每个按 §5 接入的产品自动生成一张卡片) │
+│ [≡] Salesforce 无可用连接 — [○] │ ← 灰显
+│ [≡] 工作台联动 2 个工具 读 2/2 [●] │
+│ [≡] 连接管理 3 个工具 高危 0/3 [○] │
+└─────────────────────────────────────────────────────────────────────────┘
+
+插件
+┌─────────────────────────────────────────────────────────────────────────┐
+│ [🖥] Terminal v1.4.0 io.dbx.ssh 6 个工具 · 3 个连接 读 写 高危 [●] │
+│ 上限:读写 ⚠ 1 个新工具待确认 │
+│ [☸] Kubernetes v0.3.1 作者未开放外部 MCP [—] │
+└─────────────────────────────────────────────────────────────────────────┘
+```
+
+- 级别徽标:读(中性色)/ 写(琥珀色)/ 高危(红色)。只表示“包含哪些级别的工具”,不是权限。
+- 点击卡片打开右侧抽屉:工具列表(名称、说明、级别、适用连接类型、单工具开关);插件还会显示授权上限选择、`内置 AI` / `外部 MCP` 两个开关和“预览工具”。
+- 卡片开关就是工具集或插件的开关,单工具开关放在抽屉里,属于高级操作。
+
+### 8.3 访问控制 Tab
+
+```text
+全局默认权限:[ 只读 ] [ 数据读写 ] [ 完全访问 ]
+调用安全独立控制授权后高危调用的逐次确认,完全访问也遵循;权限不足直接拒绝。权限说明默认收起。
+
+访问控制:连接可见范围 [全部连接 / 仅选中的]
+
+搜索连接、分组、库… [仅显示单独设置]
+┌──────────────────────────────────┬──────┬──────────┬──────────┬──────────┐
+│ 资源 │ 可见 │ 访问级别 │ 确认 │ 生效 │
+├──────────────────────────────────┼──────┼──────────┼──────────┼──────────┤
+│ ▾ 📁 生产环境 │ [✓] │ 只读 ▾ │ 继承 │ 只读 │
+│ ▸ 🐬 prod-mysql │ 继承 │ 继承 │ 继承 │ 只读 ·分组 │
+│ ▾ 📁 开发 │ [✓] │ 继承 │ 继承 │ 只读 ·全局 │
+│ ▾ 🐬 local-mysql-v8 │ 继承 │ 完全 ▾ │ 继承 │ 完全 ·连接 │
+│ 🗄 billing │ 继承 │ 只读 ▾ │ 继承 │ 只读 ·单库 │
+│ + 添加库例外 │ │ │ │ │
+│ 🧭 dev-nacos │ 继承 │ 读写 ▾ │ 写入以上 │ 读写 ·连接 │
+│ 🏷 namespace: public │ 继承 │ 继承 │ 继承 │ 读写 ·连接 │
+│ 🖥 jump-host (Terminal 插件) │ 继承 │ 继承 │ 继承 │ 只读 ·全局 │
+└──────────────────────────────────┴──────┴──────────┴──────────┴──────────┘
+```
+
+- **全局默认权限**用于没有更具体设置的资源;调整它只更新继承资源的生效预览,不改工具开关、连接范围或局部规则。
+- **访问控制**为分组、连接和库设置具体权限;选择“继承”时使用上级设置。隐藏资源显示不可访问及其状态。
+- 不再提供预设或“自定义”模式。调用安全使用独立可折叠区域;权限对照表默认收起为“权限说明”。
+- **一棵树完成现在四步向导的全部工作**:可见性(原第 2 步)、子范围(原第 3 步)、级别(原第 1 和第 3 步)、生效预览(原第 4 步)。和侧边栏同构,用户不用在步骤之间来回切换。
+- **子范围懒加载**:展开连接时才去请求库、namespace 等列表;默认只显示有例外的子范围,加上“+ 添加例外”入口,避免大实例一次展开几百个库。
+- **“生效”列**显示最终级别和来源(全局 / 分组 / 连接 / 单库),等价于现在的“权限预览”。悬停时显示完整的继承链和硬保护(例如“连接已开启只读保护”)。
+- 行内编辑后,在页面底部统一用“应用”保存,保留现有的保存交互。
+
+### 8.4 交互上的简化点
+
+- 权限管理包含全局默认权限、访问控制和独立调用安全;全局默认权限及分组、连接和库权限通过底部统一应用或放弃草稿。插件子范围沿用现有的即时保存提示。
+- 客户端配置继续只包含启动参数,不包含任何权限信息,这一点和现在一致。
+- 插件中心的插件详情页保留“AI 能力”一节,和 MCP 能力 Tab 编辑同一份数据,并互相提供跳转链接。
+
+## 9. 分阶段落地
+
+> P1 与原方案的差异(实现时调整,待评审):
+> - **子范围 `mcp.scope` 推迟到 P2**:它依赖 P2 的通用子范围规则,单独在 P1 落地没有判定入口。
+> - **内置 AI 与外部 MCP 没有合并成一份存储**:内置 AI 继续用插件中心原有开关(`ai_plugin_tool_plugins`),外部 MCP 用新的 `plugin_mcp_grants`。两者的确认机制不同(内置 AI 每次调用确认,外部 MCP 靠授权上限),强行合并会改变内置 AI 的现有行为;插件中心改为显示外部 MCP 状态并指向设置页。
+> - **插件工具暴露方式(flat / lazy)**:环境变量仍可强制覆盖,持久化策略和“能力 → 高级配置”提供 `flat|lazy|auto` 设置,新配置默认 `flat`。
+> - **已确认工具记录了确认时的级别**:插件升级后,即使工具名不变、但声明级别升高(如读 → 写),也会重新进入待确认。
+> - **插件的 MCP 工具标识**(2026-10-15 确认):manifest 声明了 `mcp` 贡献(且有后端)即带"MCP 工具"标识;插件中心、商店卡片显示标识并可筛选,商店目录用 `mcpTools: true` 标出;只有带标识的插件出现在 MCP 能力页。需要插件方适配的内容以文档说明为准(`plugins/README.md`)。
+> - **插件契约不兼容未适配的旧插件**(2026-10-15 确认):外部 MCP 只认 manifest 显式声明的工具级别,不再按 MCP 标注推断;没保存过授权的插件不再沿用"作者开放即全部暴露"。插件需要按新契约适配。
+
+
+| 阶段 | 内容 | 行为变化 | 主要改动 |
+|---|---|---|---|
+| **P0 工具描述符** ✅ 已实现并完成收尾 | 后端注册内置工具描述符表;新增 `mcp_tool_catalog` 接口;能力 Tab 按工具集展示(底层仍写 `allowed_tool_names`);从驱动清单计算每个工具的覆盖范围,卡片和抽屉展示覆盖说明(§5.5.2);能力页中没有适用连接的工具集仍可提前配置;客户端工具列表按连接覆盖情况裁剪;`tools/list` 对外说明追加覆盖范围,不支持的连接类型会列出可用工具 | 无(只是界面重组) | `mcp_catalog.rs`、`server.rs`、`McpCapabilitiesPanel.vue`、`McpPluginCapabilities.vue` |
+| **P1 插件能力** ✅ 已实现 | manifest 新增 `toolsets` / `tools{toolset, access}`,`external_tools: true` 必须声明工具级别;外部 MCP 授权存储 `plugin_mcp_grants`(开关、授权上限、已确认工具及其级别、单工具关闭);能力 Tab 插件卡片 + 首次授权弹窗 + 新增/升级工具待确认;插件中心显示外部 MCP 状态 | **严格契约**:未声明级别的工具永不暴露,未经用户授权的插件不暴露任何工具,声明级别覆盖 sidecar 自带标注 | `manifest.rs`、`plugin_mcp.rs`、`storage.rs`、`backend.rs`、`McpPluginCapabilities.vue` |
+| **P2 策略 v2** ✅ 已实现并完成收尾 | ① 全局默认权限(原快速预设已按简化方案移除);② v2 访问模型 `mcp_access.rs` + `decide()`;③ v1↔v2 映射与等价性 / "只会更严" / 精确往返测试;④ 存储 `mcp_access_policy`,v1/v2 同步写入,v1 保存不会抹掉 v2 独有的插件子范围规则;⑤ 访问控制树替换四步向导;⑥ 三端统一读取 v2 策略,WebBackend 不再回退到 v1;⑦ **通用确认**:声明为 `full` 的插件工具、高危 Redis 命令在"高危操作需确认"开启时弹窗一次性确认(桌面不在线一律拒绝),弹窗与 SQL 共用队列和失效机制;⑧ **插件子范围** `mcp.scope`:manifest 声明 kind/title/argument,服务端按 v2 规则校验调用参数里的值,访问控制树里可按连接编辑;⑨ 插件工具暴露方式持久化为 `pluginToolsMode: auto|flat|lazy`,环境变量优先,在“能力 → 高级配置”可设置,新配置默认 `flat`,保留已有模式;⑩ 插件 `scope.list_method` 提供桌面 Tauri / Web 读取值列表接口和复选编辑;⑪ 内置工具描述符向设置页传递 `resourceKinds` / `scopeKind` 元数据 | 判定输入来自 v2;新调用安全先授权再确认,不提升权限;旧 `confirm=full` 临时授权保留且明确标识 | `mcp_access.rs`、`storage.rs`、`approval.rs`、`mcp_bridge.rs`、`mcp_catalog.rs`、`McpSqlApprovalDialog.vue`、`McpPluginScopeEditor.vue`、`app_settings.rs` |
+| **P3 产品能力接入** ✅ Nacos / Consul | 新增 `dbx-mcp/src/products.rs`(按产品分发到 `dbx-core/admin/<product>`)+ 服务端统一门 `run_product_tool`(工具白名单 → 连接类型 → v2 子范围准入与级别 → 连接只读 / 生产保护 → `full` 级走高危确认)。Nacos 14 个已接入工具(命名空间、配置搜索/读写删/历史/回滚、服务、实例注册/注销/上下线),`dbx_nacos_list_namespaces` 按连接的 `namespace` 子范围过滤;子范围 = namespace,访问控制树可按命名空间授权;Consul 8 个工具(KV 读写删带 CAS、服务、节点、健康、维护模式)。管理类(用户 / 角色 / ACL / 命名空间增删)、快照恢复、Raft 未开放。⏳ Redis / MQ / Salesforce 尚未迁到 `products.rs`(行为已符合规范:独立工具、声明级别、确认机制) | 新增能力;Nacos/Consul 在能力 Tab 自动出现工具集卡片 | `products.rs`、`server.rs`、`mcp_catalog.rs`、`McpAccessTree.vue` |
+| **P4 审计** ✅ 已实现 | 调用记录本已存在(每次 MCP 调用写入历史,含工具、连接、耗时、请求/响应摘要、失败原因,历史面板有 MCP 视图和按工具筛选)。本期补充:① 记录发起调用的 **MCP 客户端名称和版本**、传输方式(stdio / HTTP)、声明访问级别及权限模式、确认状态(取自 MCP 调用生命周期,仅记录不参与判定),历史详情显示"MCP 客户端";② 设置页接入方式中,与接入类型同一行右侧的"查看 MCP 调用记录",一键打开历史面板并切到 MCP 视图(经设置页的关闭确认流程);③ 访问控制树的连接和库节点可以直接打开已按资源过滤的 MCP 历史 | 新增 | `server.rs`(call_tool)、`QueryHistory.vue`、`mcpCallHistory.ts`、`McpAccessTree.vue` |
+
+本轮按交接任务 T1→T8 完成收尾:补齐 Nacos 命名空间子范围过滤、只读资源下的静态写工具裁剪、覆盖范围说明和连接类型错误提示、插件工具暴露模式设置、能力页筛选、插件子范围值列表接口与复选编辑、授权文档重写及全部 13 种受支持语言文案。Rust 与前端验证均已执行;需要本地监听端口的既有测试在受限沙盒中会因 `Operation not permitted` 失败,详见 `tmp/codex-mcp-report.md`。
+
+P0 和 P1 可以并行;P3 依赖 P2 的 scope 抽象,如果要提前上线某个产品的只读工具,也可以在 P2 之前用现有 `read_only` 判定先做一个只读版本。
+
+## 10. 已确认的决策
+
+| # | 事项 | 结论 |
+|---|---|---|
+| 1 | Tab 结构 | 三个 Tab:接入 / 能力 / 访问控制 |
+| 2 | 四步向导 | 用访问控制树表替换 |
+| 3 | 插件升级后新增或提升级别的工具 | 新增非只读工具、已确认工具升至更高的非只读级别都需重新确认;新增只读工具可在上限内自动可用;超过授权上限的工具始终隐藏 |
+| 4 | 已开放外部 MCP 的现有插件 | 按 2026-10-15 确认的严格契约执行:必须声明工具级别并由用户授权,未保存授权时不暴露 |
+| 5 | 非 SQL 产品的工具粒度 | 按产品区分,每个产品是独立提供方;Nacos / Consul 只是示例,所有现有和后续产品都按 §5 接入规范执行 |
+| 6 | 客户端档案 | 不做。只维护 DBX 当前的一份全局权限策略,所有客户端共用 |
+| 7 | SQL 类数据库 | 沿用现有通用工具,不按数据库拆分,行为不变;MongoDB 后续单独成产品(§5.5.1) |
+| 8 | 通用工具的覆盖说明 | 界面分卡片摘要、覆盖详情、连接维度三层展示适用的数据库类型,数据从驱动清单计算(§5.5.2) |
+
+### 调用安全语义与兼容
+
+- `confirm=off`:按权限执行,不额外询问;权限不足直接拒绝。
+- `confirm=high_risk`:先授权,再对高危调用逐次确认;完全访问也确认。无桌面确认、拒绝或超时不执行,批准后重新检查授权。
+- `confirm=full`:仅为旧版兼容保留,Write 可临时授权部分 Full 操作,Full 不询问。旧 SQL 限时授权不能用于新策略。
+- v1 的可选 `callConfirmation` 显式值优先于旧 `promptHighRiskSql`;标准化后新策略保存为 `high_risk` 且旧布尔值为 false。缺失新字段时保持原行为,v1/v2 往返和局部保存保留该语义。
+- 设置页独立“调用安全”,旧模式默认展开说明;只有主动切换并应用才迁移。普通读取与普通写入不额外确认,高危判定由宿主目录/参数分类及插件声明决定。后续工具复用 `McpConfirmPolicy::decide`,先检查范围和硬保护,再询问、复核、执行。
diff --git a/plugins/README.md b/plugins/README.md
index 397d9dea12..8d0e174050 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -569,6 +569,8 @@ Mutation methods return `{ success, message?, entry? }` and are rejected unless
### `mcp`
+**The MCP tools mark.** Declaring this contribution (with a backend entrypoint) is what marks a plugin as *providing MCP tools*. Marked plugins get an "MCP tools" badge in the Plugin Center and the store, can be filtered there, and get a card in Settings → MCP → Capabilities where the user enables and authorizes their tools. A plugin without the contribution has no MCP surface and never appears in the MCP settings. Store catalogs should set `"mcpTools": true` on the plugin entry so the badge shows before install (see `marketplace.schema.json`).
+
A backend that implements the optional MCP tool bridge (`mcp/tools` + `mcp/call`, see "Tools for the built-in AI assistant" below) does not put its tools in front of anyone by itself: the built-in AI agent only sees a plugin after the user enabled it in the Plugin Center, and the external `dbx` MCP server (`dbx-mcp`) only sees plugins that opt in with `external_tools: true`. This optional contribution declares and tunes those surfaces:
```json
@@ -580,7 +582,54 @@ A backend that implements the optional MCP tool bridge (`mcp/tools` + `mcp/call`
}
```
-Only `id` is required; `ai_tools` defaults to `true` (set it to `false` to keep the tools off the AI surface even when the user opts in) and `external_tools` defaults to `false` (set it to `true` to expose the tools on the external server). At most one `mcp` contribution is allowed per manifest, and it requires a backend entrypoint. Declaring it makes the manifest unreadable to hosts that predate the contribution type, so plugins that must install on older hosts should stay undeclared. The runtime gates stay in force on every call regardless: open connections for the AI surface, the global MCP policy plus per-connection allowlist for the external surface, per-call approval for anything not `annotations.readOnlyHint: true`, and the Plugin Center switch (which always wins) to turn a plugin's AI tools off entirely.
+#### Tool declarations for the external server
+
+On the external server, users manage MCP tools per plugin in Settings → MCP → Capabilities: one switch per plugin, an access ceiling (read / read & write / full), and per-tool opt-outs. A plugin that sets `external_tools: true` must declare every tool it wants to expose there:
+
+```json
+{
+ "type": "mcp",
+ "id": "vendor.ssh.mcp",
+ "external_tools": true,
+ "toolsets": [
+ { "id": "files", "title": "Files" },
+ { "id": "shell", "title": "Remote shell", "description": "Run commands on the host" }
+ ],
+ "tools": {
+ "sftp_list_dir": { "toolset": "files", "access": "read" },
+ "sftp_upload": { "toolset": "files", "access": "write" },
+ "ssh_exec": { "toolset": "shell", "access": "full" }
+ }
+}
+```
+
+- `tools` (required to expose tools with `external_tools: true`) declares, per tool name returned by `mcp/tools`, the highest `access` it can reach — `read` (no state change), `write` (ordinary changes), `full` (destructive or bulk changes) — and optionally its `toolset`. Up to 64 entries. **A tool `mcp/tools` lists without a declaration is never exposed on the external server**; MCP annotations are client hints, not a substitute. The declared level is authoritative: the host rewrites `readOnlyHint` / `destructiveHint` from it. Each call remains subject to the effective resource permissions and allowed connection scope.
+- `toolsets` (optional) groups tools in the settings UI (`id` uses `[a-z0-9._-]`, `title` is required). Tools without a toolset join a default group.
+
+A legacy manifest with `external_tools: true` but no tool access declarations remains compatible and receives a warning. Its drivers and built-in AI tools remain available under their existing gates, but no undeclared tool is exposed on the external MCP server. Authors must add per-tool `access` declarations to enable external exposure.
+
+#### Sub-scopes (optional)
+
+A plugin whose connections contain their own resources (Kubernetes namespaces, directories, …) can declare one sub-scope kind, so users can allow or restrict values per connection in Settings → MCP → Permissions, like databases for SQL connections:
+
+```json
+"scope": { "kind": "namespace", "title": "Namespace", "argument": "namespace", "list_method": "mcp/scopes" }
+```
+
+- `kind` (`[a-z0-9._-]`, not `database`) and `title` name the scope in the access-control tree.
+- `argument` is the tool argument that carries the value. On every external call that includes it, the host checks scope admission and access for the bound connection before forwarding. Omitting it is allowed only when all sub-scopes are open and no named scope has a permission override or ceiling; otherwise the host returns `SCOPE_REQUIRED`. Full tools also follow the confirmation tier below.
+- The sidecar must interpret the scope argument consistently with the host policy. The host trims and compares the declared argument value; it cannot detect a sidecar interpreting `*`, an empty value, or a parent path as access to all resources. Do not expand an authorized value into a broader scope; reject ambiguous values or require an explicitly authorized scope instead.
+- `list_method` (optional) is a sidecar method returning `{ "values": [string] }` for a `connectionId`, used by the settings picker.
+
+#### High-risk tools
+
+Tools declared `"access": "full"` require full resource access. In Settings → MCP → Permissions → **Call safety**, users can require human confirmation for authorized high-risk calls, including calls at full access. With this policy, insufficient permissions are rejected before prompting; confirmation never elevates access. If confirmation is required but DBX Desktop is unavailable, the call is refused. Permissions and grants are checked again after confirmation.
+
+Existing **Legacy temporary authorization** settings (`promptHighRiskSql=true` or v2 `confirm="full"`) retain their previous behavior until the user explicitly changes them: read/write access can confirm a high-risk plugin call, while full access does not prompt. New call-safety settings use `callConfirmation="high_risk"` / v2 `confirm="high_risk"` instead of reinterpreting the legacy flag. Use matching DBX and standalone MCP versions so both understand this policy.
+
+Nothing is exposed until the user authorizes the plugin and picks a ceiling; tools above the ceiling stay hidden. After a plugin update, a tool that needs more than `read` and is new — or whose declared level rose since the user accepted it — stays hidden until the user confirms it, so an update cannot widen exposure silently.
+
+With the default `external_tools: false`, only `id` is required in addition to `type`; exposing external tools also requires the tool access declarations above, while missing declarations produce a compatibility warning rather than disabling the plugin. `ai_tools` defaults to `true` (set it to `false` to keep the tools off the AI surface even when the user opts in). At most one `mcp` contribution is allowed per manifest, and it requires a backend entrypoint. Declaring it makes the manifest unreadable to hosts that predate the contribution type, so plugins that must install on older hosts should stay undeclared. The runtime gates stay in force on every call: the AI surface requires open connections, per-call approval for tools not marked `annotations.readOnlyHint: true`, and the Plugin Center switch; the external surface uses the resource permissions, connection scope, plugin grants, and confirmation rules described above.
### Table Schema Metadata
@@ -932,7 +981,7 @@ Sidecars are shared per plugin process, not spawned per tab. Plugins own their i
- **Secret persistence:** plugin secrets are removed from connection JSON and stored through DBX's secret-store path. Ordinary cloud-sync snapshots always contain redacted placeholders. Secrets enter sync data only inside the encrypted payload when the user has configured a sync passphrase; without one, plugin secrets remain local and are not synchronized.
- **Native backend trust:** a native sidecar runs with the current OS user's privileges. A signature identifies the repository that approved and published the package; it is not an OS sandbox or proof that the author is harmless. Install only plugins whose backend code you trust.
- **Permission declarations:** privileged host bridge operations require declared permissions. Plugin UI network egress is fully blocked except for explicitly declared `host.network:` origins. Native process filesystem/network access cannot currently be completely mediated by DBX. `host.plans:read` grants reading host-generated estimated execution plans only; it never grants SQL execution, writes, DDL, or actual plans. `host.schema:read` grants only narrow metadata for a table on an already-open host connection; it never grants arbitrary SQL, writes, or reconnects. `host.storage` confines the workbench UI to a small JSON store inside its own `plugin-data/<id>` directory; it grants no other filesystem reach. `host.ai` lets a workbench open a built-in AI conversation seeded with a snapshot the plugin supplies and publish context-aware recommendation chips; the conversation API returns no model output or configuration. The optional text completion API returns sanitized model choices and generated text only after host confirmation; it never exposes credentials or SQL execution. `host.data:read` grants single read-only statements only on connections the user consented to, per plugin and connection, revocable in Plugin Center; it never grants writes, DDL, locking reads, database switches, or reconnects. `host.connections:read` grants read-only, secret-free summary metadata for all configured connections; it never grants passwords, credentials, or connection strings.
-- **AI tool exposure:** plugin MCP tools reach the built-in AI agent only after the user enabled the plugin in Plugin Center, only on open connections and — unless declared read-only — only after a per-call approval; visibility is revocable per plugin (a manifest `ai_tools: false` also opts out). The external `dbx` MCP server exposes a plugin's tools only when its manifest declares `external_tools: true`, and additionally applies the global MCP connection allowlist.
+- **AI tool exposure:** plugin MCP tools reach the built-in AI agent only after the user enabled the plugin in Plugin Center, only on open connections and — unless declared read-only — only after a per-call approval; visibility is revocable per plugin (a manifest `ai_tools: false` also opts out). The external `dbx` MCP server exposes a plugin's tools only when its manifest declares `external_tools: true` and the tool's access level, and only after the user authorized the plugin; it then applies the access ceiling, per-tool opt-outs, confirmation of new or escalated tools, and the global MCP policy (tool allowlist, execution mode, connection scope).
Custom repository public keys can be added or removed in Plugin Center. Obtain them through a channel independent from the downloaded package.
diff --git a/plugins/manifest.schema.json b/plugins/manifest.schema.json
index 30b5904d38..7c97820273 100644
--- a/plugins/manifest.schema.json
+++ b/plugins/manifest.schema.json
@@ -457,7 +457,46 @@
"id": { "$ref": "#/$defs/identifier" },
"description": { "type": "string" },
"ai_tools": { "type": "boolean", "default": true, "description": "Set false to keep the tools off the built-in AI agent." },
- "external_tools": { "type": "boolean", "default": false, "description": "Set true to expose the tools on the external dbx MCP server." }
+ "external_tools": { "type": "boolean", "default": false, "description": "Set true to expose the tools on the external dbx MCP server." },
+ "toolsets": {
+ "type": "array",
+ "description": "Optional grouping of the plugin's tools for the MCP settings UI. Without toolsets the plugin shows as one group.",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "title"],
+ "properties": {
+ "id": { "type": "string", "maxLength": 64, "pattern": "^[a-z0-9][a-z0-9._-]*$" },
+ "title": { "type": "string", "minLength": 1 },
+ "description": { "type": "string", "minLength": 1 }
+ }
+ }
+ },
+ "scope": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["kind", "title", "argument"],
+ "description": "Optional sub-scope below a connection (e.g. a Kubernetes namespace) that users can allow or restrict per connection.",
+ "properties": {
+ "kind": { "type": "string", "maxLength": 64, "pattern": "^[a-z0-9][a-z0-9._-]*$", "not": { "const": "database" } },
+ "title": { "type": "string", "minLength": 1 },
+ "argument": { "type": "string", "minLength": 1, "maxLength": 64, "description": "Tool argument carrying the scope value; the host enforces the policy on it." },
+ "list_method": { "type": "string", "minLength": 1, "description": "Sidecar method returning { values: [string] } for a connectionId." }
+ }
+ },
+ "tools": {
+ "type": "object",
+ "description": "Per-tool declarations keyed by the tool name mcp/tools returns. Required with external_tools: only tools declared here with an access level can be exposed on the external dbx MCP server.",
+ "maxProperties": 64,
+ "additionalProperties": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "toolset": { "type": "string", "description": "Toolset id from toolsets." },
+ "access": { "enum": ["read", "write", "full"], "description": "Highest access the tool can reach." }
+ }
+ }
+ }
}
},
"menuItem": {
diff --git a/plugins/marketplace.schema.json b/plugins/marketplace.schema.json
index faa04fb87d..4cdd5f7f69 100644
--- a/plugins/marketplace.schema.json
+++ b/plugins/marketplace.schema.json
@@ -93,6 +93,7 @@
"icon": { "type": "string", "format": "uri-reference" },
"tags": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
"permissions": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
+ "mcpTools": { "type": "boolean", "default": false, "description": "The plugin provides MCP tools (its manifest declares an mcp contribution)." },
"source": { "type": "string", "format": "uri" },
"homepage": { "type": "string", "format": "uri" },
"license": { "type": "string", "minLength": 1 },
diff --git a/src-tauri/src/commands/app_settings.rs b/src-tauri/src/commands/app_settings.rs
index d53dc21917..21983c9fb6 100644
--- a/src-tauri/src/commands/app_settings.rs
+++ b/src-tauri/src/commands/app_settings.rs
@@ -214,6 +214,123 @@ pub async fn load_mcp_global_policy(state: State<'_, Arc<AppState>>) -> Result<M
state.storage.load_mcp_global_policy().await
}
+#[tauri::command]
+pub fn load_mcp_tool_catalog() -> dbx_core::mcp_catalog::McpToolCatalog {
+ dbx_mcp::DbxMcpServer::tool_catalog()
+}
+
+/// Plugin cards of the MCP capability tab (probes plugin sidecars).
+#[tauri::command]
+pub async fn list_plugin_mcp_views(
+ state: State<'_, Arc<AppState>>,
+) -> Result<Vec<dbx_core::plugin_mcp::PluginMcpView>, String> {
+ dbx_core::plugin_mcp::list_plugin_views(state.inner()).await
+}
+
+#[tauri::command]
+pub async fn load_plugin_mcp_view(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+) -> Result<dbx_core::plugin_mcp::PluginMcpView, String> {
+ dbx_core::plugin_mcp::plugin_view_for(state.inner(), &plugin_id).await
+}
+
+#[tauri::command]
+pub async fn list_mcp_plugin_scopes(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ connection_id: String,
+) -> Result<serde_json::Value, String> {
+ let manifest = state
+ .plugins
+ .list_installed()?
+ .into_iter()
+ .find(|plugin| plugin.manifest.id == plugin_id)
+ .ok_or_else(|| format!("Plugin `{plugin_id}` is not installed."))?
+ .manifest;
+ let method = manifest
+ .mcp_contribution()
+ .and_then(|mcp| mcp.scope.as_ref())
+ .and_then(|scope| scope.list_method.as_deref())
+ .ok_or_else(|| "This plugin does not declare a scope list method.".to_string())?;
+ let policy = state.storage.load_enforced_mcp_policy().await?.policy();
+ let group_paths = match state.storage.load_sidebar_layout().await? {
+ Some(layout) => dbx_core::mcp_policy::connection_group_paths(&layout)
+ .map_err(|error| format!("MCP_POLICY_UNAVAILABLE: {error}"))?,
+ None => std::collections::HashMap::new(),
+ };
+ let connection = state
+ .storage
+ .load_connections()
+ .await?
+ .into_iter()
+ .find(|connection| connection.id == connection_id)
+ .ok_or_else(|| "CONNECTION_NOT_FOUND: connection is not available.".to_string())?;
+ if connection.plugin_id.as_deref() != Some(plugin_id.as_str()) {
+ return Err("CONNECTION_OUT_OF_SCOPE: connection is not owned by this plugin.".to_string());
+ }
+ if !dbx_core::mcp_policy::policy_allows_connection(&policy, group_paths.get(&connection.id), &connection.id) {
+ return Err("CONNECTION_OUT_OF_SCOPE: connection is not allowed by DBX MCP settings.".to_string());
+ }
+ let value = state
+ .plugin_host
+ .invoke::<serde_json::Value>(
+ &plugin_id,
+ method,
+ serde_json::json!({ "connectionId": connection.id }),
+ None,
+ Some(std::time::Duration::from_secs(8)),
+ )
+ .await?;
+ let values: Vec<String> = serde_json::from_value(
+ value
+ .get("values")
+ .cloned()
+ .ok_or_else(|| "Plugin scope list must return { values: string[] }.".to_string())?,
+ )
+ .map_err(|_| "Plugin scope list must return { values: string[] }.".to_string())?;
+ Ok(serde_json::json!({ "values": values }))
+}
+
+#[tauri::command]
+pub async fn save_plugin_mcp_grant(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ grant: dbx_core::storage::PluginMcpGrant,
+ approve_current: bool,
+) -> Result<dbx_core::plugin_mcp::PluginMcpView, String> {
+ dbx_core::plugin_mcp::save_plugin_grant(state.inner(), &plugin_id, grant, approve_current).await
+}
+
+#[tauri::command]
+pub async fn load_mcp_access_policy(
+ state: State<'_, Arc<AppState>>,
+) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {
+ state.storage.load_mcp_access_policy().await
+}
+
+#[tauri::command]
+pub async fn set_mcp_plugin_scope_rule(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: String,
+ value: Option<String>,
+ rule: Option<dbx_core::mcp_access::McpAccessRule>,
+ sub_scope: Option<dbx_core::mcp_access::McpSubScopeMode>,
+) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {
+ let access =
+ dbx_core::plugin_mcp::set_scope_rule(&state, &connection_id, &kind, value.as_deref(), rule, sub_scope).await?;
+ super::mcp_bridge::clear_mcp_sql_approvals();
+ Ok(access)
+}
+
+#[tauri::command]
+pub async fn reset_invalid_mcp_access_policy(state: State<'_, Arc<AppState>>) -> Result<(), String> {
+ state.storage.reset_invalid_mcp_access_policy().await?;
+ super::mcp_bridge::clear_mcp_sql_approvals();
+ Ok(())
+}
+
#[tauri::command]
pub async fn save_mcp_global_policy(state: State<'_, Arc<AppState>>, policy: McpGlobalPolicy) -> Result<(), String> {
state.storage.save_mcp_global_policy(&policy).await?;
diff --git a/src-tauri/src/commands/mcp_bridge.rs b/src-tauri/src/commands/mcp_bridge.rs
index 030fa86fb1..96b08245ee 100644
--- a/src-tauri/src/commands/mcp_bridge.rs
+++ b/src-tauri/src/commands/mcp_bridge.rs
@@ -1,3 +1,4 @@
+use dbx_core::mcp_access::{McpAccessLevel, McpCallDecision, McpConfirmPolicy};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -54,12 +55,41 @@ struct ConsumeSqlApprovalRequest {
#[derive(Clone, Serialize)]
struct SqlApprovalEvent {
+ allow_timed: bool,
id: String,
connection_name: String,
database: String,
sql: String,
}
+/// A high-risk non-SQL tool call awaiting confirmation (plugin tool declared
+/// `full`, dangerous Redis command). Mirrors `dbx_mcp::approval::ToolApprovalRequest`.
+#[derive(Deserialize)]
+struct ToolApprovalRequest {
+ kind: String,
+ tool: String,
+ #[serde(default)]
+ plugin: Option<String>,
+ #[serde(default)]
+ connection_id: Option<String>,
+ #[serde(default)]
+ database: Option<String>,
+ detail: String,
+}
+
+/// Payload of the `mcp-tool-approval` event. Tool confirmations are one-shot:
+/// unlike SQL there is no exact statement to bind a timed grant to.
+#[derive(Clone, Serialize)]
+struct ToolApprovalEvent {
+ id: String,
+ kind: String,
+ tool: String,
+ plugin: Option<String>,
+ connection_name: Option<String>,
+ database: Option<String>,
+ detail: String,
+}
+
#[derive(Clone, Copy)]
enum SqlApprovalDecision {
Once,
@@ -389,6 +419,8 @@ pub fn start(app_handle: AppHandle, state: Arc<AppState>, data_dir: PathBuf) {
handle_execute_query_data(&st, body, &mut stream).await;
} else if first_line.starts_with("POST /approve-high-risk-sql") {
handle_sql_approval(&app, &st, body, &mut stream).await;
+ } else if first_line.starts_with("POST /approve-high-risk-tool") {
+ handle_tool_approval(&app, &st, body, &mut stream).await;
} else if first_line.starts_with("POST /consume-high-risk-sql-approval") {
handle_consume_sql_approval(&st, body, &mut stream).await;
} else if first_line.starts_with("POST /execute-query") {
@@ -543,6 +575,93 @@ mod tests {
use std::sync::Arc;
use std::time::{Duration, Instant};
+ #[tokio::test]
+ async fn tool_approval_bridge_keeps_resource_overrides_under_global_read() {
+ let root = tempfile::tempdir().unwrap();
+ let storage = dbx_core::persistence::test_storage::open(&root.path().join("storage.db")).await.unwrap();
+ let config = mysql_config(false);
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+ let state = Arc::new(AppState::new_with_plugin_dir(storage, root.path().join("plugins")));
+ let mut policy = McpGlobalPolicy { read_only: true, prompt_high_risk_sql: true, ..Default::default() };
+ policy.connection_policies.push(serde_json::from_value(serde_json::json!({
+ "connectionId": config.id, "readOnly": false, "executionModeConfigured": true, "executionModePolicyVersion": 1
+ })).unwrap());
+ state.storage.save_mcp_global_policy(&policy).await.unwrap();
+ let mut request = super::ToolApprovalRequest {
+ kind: "product_tool".into(),
+ tool: "dbx_nacos_delete_config".into(),
+ plugin: None,
+ connection_id: Some(config.id.clone()),
+ database: Some("dev".into()),
+ detail: "test".into(),
+ };
+ // The server has checked the resource-level grant; the bridge must not
+ // replace that resolved decision with the unrelated global default.
+ assert_eq!(super::tool_approval_target(&state, &request).await.unwrap(), Some(config.name.clone()));
+ request.connection_id = None;
+ assert!(super::tool_approval_target(&state, &request).await.is_err());
+ request.connection_id = Some(config.id.clone());
+ let mut protected = config.clone();
+ protected.read_only = true;
+ state.storage.save_connections(std::slice::from_ref(&protected)).await.unwrap();
+ assert!(super::tool_approval_target(&state, &request).await.unwrap_err().contains("CONNECTION_READ_ONLY"));
+ protected.read_only = false;
+ protected.is_production = true;
+ state.storage.save_connections(std::slice::from_ref(&protected)).await.unwrap();
+ assert!(super::tool_approval_target(&state, &request).await.unwrap_err().contains("PRODUCTION_WRITE_BLOCKED"));
+ policy.prompt_high_risk_sql = false;
+ state.storage.save_mcp_global_policy(&policy).await.unwrap();
+ assert!(super::tool_approval_target(&state, &request).await.unwrap_err().contains("TOOL_BLOCKED"));
+ }
+
+ #[tokio::test]
+ async fn call_safety_bridge_requires_confirmation_without_elevating_permissions() {
+ use dbx_core::mcp_access::McpConfirmPolicy;
+ let root = tempfile::tempdir().unwrap();
+ let storage = dbx_core::persistence::test_storage::open(&root.path().join("storage.db")).await.unwrap();
+ let config = mysql_config(false);
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+ let state = Arc::new(AppState::new_with_plugin_dir(storage, root.path().join("plugins")));
+ for full in [false, true] {
+ for approved in [false, true] {
+ let policy = McpGlobalPolicy {
+ allow_dangerous_sql: full,
+ call_confirmation: Some(McpConfirmPolicy::HighRisk),
+ ..Default::default()
+ };
+ state.storage.save_mcp_global_policy(&policy).await.unwrap();
+ let result =
+ super::ensure_mcp_sql_allowed_with_approval(&state, &config, "app", "DROP TABLE items", approved)
+ .await;
+ assert_eq!(result.is_ok(), full && approved, "full={full} approved={approved}: {result:?}");
+ assert!(super::ensure_mcp_sql_allowed_with_approval(&state, &config, "app", "SELECT 1", false)
+ .await
+ .is_ok());
+ }
+ }
+ // The legacy boolean keeps its former meaning, including no prompt at Full.
+ for full in [false, true] {
+ state
+ .storage
+ .save_mcp_global_policy(&McpGlobalPolicy {
+ allow_dangerous_sql: full,
+ prompt_high_risk_sql: true,
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ assert!(super::ensure_mcp_sql_allowed_with_approval(&state, &config, "app", "DROP TABLE items", true)
+ .await
+ .is_ok());
+ assert_eq!(
+ super::ensure_mcp_sql_allowed_with_approval(&state, &config, "app", "DROP TABLE items", false)
+ .await
+ .is_ok(),
+ full
+ );
+ }
+ }
+
#[test]
fn sql_approval_token_is_single_use_and_bound_to_target_and_text() {
let token = uuid::Uuid::new_v4().to_string();
@@ -1154,7 +1273,7 @@ async fn resolve_connection(
async fn load_mcp_policy(state: &Arc<AppState>) -> Result<McpGlobalPolicy, String> {
state
.storage
- .load_mcp_global_policy()
+ .load_enforced_mcp_policy()
.await
.map(|state| state.policy())
.map_err(|error| mcp_policy_unavailable(error.to_string()))
@@ -1666,12 +1785,22 @@ async fn ensure_mcp_sql_allowed_with_approval(
"MCP_READ_ONLY: MCP execution permission for database '{database}' is read-only. SQL write blocked."
));
}
- if !allow_dangerous_sql
- && (risk == dbx_core::sql_risk::SqlRisk::Ddl
- || dbx_core::sql_risk::is_dangerous_sql_for_database(sql, config.db_type))
- && !(approved && policy.prompt_high_risk_sql && !read_only)
- {
- return Err("SQL_BLOCKED: High-risk SQL is disabled in DBX MCP settings.".to_string());
+ let high_risk = risk == dbx_core::sql_risk::SqlRisk::Ddl
+ || dbx_core::sql_risk::is_dangerous_sql_for_database(sql, config.db_type);
+ if high_risk {
+ match policy.confirmation_policy().decide(
+ McpAccessLevel::from_flags(read_only, allow_dangerous_sql),
+ McpAccessLevel::Full,
+ true,
+ ) {
+ McpCallDecision::Deny => {
+ return Err("SQL_BLOCKED: High-risk SQL is disabled in DBX MCP settings.".to_string())
+ }
+ McpCallDecision::Confirm if !approved => {
+ return Err("SQL_BLOCKED: This high-risk call requires confirmation.".to_string())
+ }
+ _ => {}
+ }
}
ensure_mcp_connection_sql_write_allowed(config, is_write)?;
if is_write && dbx_core::production_safety::targets_production_database(config, database, sql) {
@@ -1707,12 +1836,14 @@ async fn handle_sql_approval(app: &AppHandle, state: &Arc<AppState>, body: &str,
let group_ids = group_paths.get(&config.id).map(|path| path.ids.as_slice()).unwrap_or_default();
let (read_only, allow_dangerous) =
effective_database_execution_policy_with_groups(&policy, group_ids, &config.id, &req.database);
- if !policy.prompt_high_risk_sql
- || read_only
- || allow_dangerous
- || !(dbx_core::sql_risk::classify_sql_risk_for_database(&req.sql, config.db_type)
- .is_ok_and(|risk| risk == dbx_core::sql_risk::SqlRisk::Ddl)
- || dbx_core::sql_risk::is_dangerous_sql_for_database(&req.sql, config.db_type))
+ let high_risk = dbx_core::sql_risk::classify_sql_risk_for_database(&req.sql, config.db_type)
+ .is_ok_and(|risk| risk == dbx_core::sql_risk::SqlRisk::Ddl)
+ || dbx_core::sql_risk::is_dangerous_sql_for_database(&req.sql, config.db_type);
+ let confirmation = policy.confirmation_policy();
+ let allow_timed = confirmation == McpConfirmPolicy::Full;
+ if !high_risk
+ || confirmation.decide(McpAccessLevel::from_flags(read_only, allow_dangerous), McpAccessLevel::Full, true)
+ != McpCallDecision::Confirm
{
respond_error(stream, "403 Forbidden", "SQL_BLOCKED: High-risk SQL approval is unavailable.").await;
return;
@@ -1728,7 +1859,10 @@ async fn handle_sql_approval(app: &AppHandle, state: &Arc<AppState>, body: &str,
approvals
.timed
.retain(|grant_key, grant| grant.expires_at > now && (grant_key != &key || grant.valid_for(&config, now)));
- Ok::<_, ()>((approvals.timed.contains_key(&key).then_some(SqlApprovalDecision::Hour), approvals.generation))
+ Ok::<_, ()>((
+ (allow_timed && approvals.timed.contains_key(&key)).then_some(SqlApprovalDecision::Hour),
+ approvals.generation,
+ ))
})();
let (decision, generation) = match existing {
Ok(existing) => existing,
@@ -1756,6 +1890,7 @@ async fn handle_sql_approval(app: &AppHandle, state: &Arc<AppState>, body: &str,
return;
}
let event = SqlApprovalEvent {
+ allow_timed,
id: id.clone(),
connection_name: config.name.clone(),
database: req.database.clone(),
@@ -1776,7 +1911,8 @@ async fn handle_sql_approval(app: &AppHandle, state: &Arc<AppState>, body: &str,
}
}
};
- if matches!(decision, SqlApprovalDecision::Deny) {
+ if matches!(decision, SqlApprovalDecision::Deny) || (!allow_timed && !matches!(decision, SqlApprovalDecision::Once))
+ {
respond_error(stream, "403 Forbidden", "SQL_BLOCKED: MCP approval denied.").await;
return;
}
@@ -1832,6 +1968,95 @@ async fn handle_sql_approval(app: &AppHandle, state: &Arc<AppState>, body: &str,
respond_json(stream, &serde_json::json!({ "token": token })).await;
}
+/// The MCP server validates the exact tool/sub-scope level before requesting
+/// and after receiving confirmation. The bridge gates the shared switch and
+/// independent protections; a global read default cannot veto resource overrides.
+async fn tool_approval_target(state: &Arc<AppState>, req: &ToolApprovalRequest) -> Result<Option<String>, String> {
+ let policy = load_mcp_policy(state).await?;
+ if policy.confirmation_policy() == McpConfirmPolicy::Off || (req.connection_id.is_none() && policy.read_only) {
+ return Err("TOOL_BLOCKED: High-risk confirmation is unavailable in DBX MCP settings.".to_string());
+ }
+ let Some(id) = req.connection_id.as_deref() else { return Ok(None) };
+ let config = resolve_connection(state, Some(id), "").await?;
+ if config.read_only {
+ return Err("CONNECTION_READ_ONLY: The connection has read-only protection enabled.".to_string());
+ }
+ if dbx_core::production_safety::is_production_database(&config, req.database.as_deref().unwrap_or_default()) {
+ return Err("PRODUCTION_WRITE_BLOCKED: The target has production protection enabled.".to_string());
+ }
+ Ok(Some(config.name))
+}
+
+/// Shows a one-shot confirmation for a high-risk non-SQL tool call and answers
+/// once the person decided. Shares the pending queue (and its cap and policy
+/// generation) with SQL approvals, so a policy save cancels it too.
+async fn handle_tool_approval(app: &AppHandle, state: &Arc<AppState>, body: &str, stream: &mut tokio::net::TcpStream) {
+ let req: ToolApprovalRequest = match serde_json::from_str(body) {
+ Ok(req) => req,
+ Err(_) => {
+ respond_error(stream, "400 Bad Request", "Invalid tool approval request").await;
+ return;
+ }
+ };
+ let connection_name = match tool_approval_target(state, &req).await {
+ Ok(name) => name,
+ Err(error) => {
+ respond_error(stream, "403 Forbidden", &error).await;
+ return;
+ }
+ };
+ let id = uuid::Uuid::new_v4().to_string();
+ let (sender, receiver) = oneshot::channel();
+ let queued = (|| {
+ let mut approvals =
+ sql_approvals().lock().map_err(|_| ("500 Internal Server Error", "MCP approval state unavailable"))?;
+ if approvals.pending.len() >= 16 {
+ return Err(("429 Too Many Requests", "Too many pending MCP approvals"));
+ }
+ approvals.pending.insert(id.clone(), sender);
+ Ok::<_, (&str, &str)>(approvals.generation)
+ })();
+ let generation = match queued {
+ Ok(generation) => generation,
+ Err((status, message)) => {
+ respond_error(stream, status, message).await;
+ return;
+ }
+ };
+ let event = ToolApprovalEvent {
+ id: id.clone(),
+ kind: req.kind,
+ tool: req.tool,
+ plugin: req.plugin,
+ connection_name,
+ database: req.database,
+ detail: req.detail,
+ };
+ if app.emit_to("main", "mcp-tool-approval", event).is_err() {
+ sql_approvals().lock().ok().map(|mut approvals| approvals.pending.remove(&id));
+ respond_error(stream, "503 Service Unavailable", "DBX approval window unavailable").await;
+ return;
+ }
+ let answer = tokio::time::timeout(Duration::from_secs(90), receiver).await;
+ sql_approvals().lock().ok().map(|mut approvals| approvals.pending.remove(&id));
+ let approved = matches!(answer, Ok(Ok(decision)) if !matches!(decision, SqlApprovalDecision::Deny));
+ if !approved {
+ let message = if answer.is_err() {
+ "TOOL_BLOCKED: MCP confirmation timed out."
+ } else {
+ "TOOL_BLOCKED: MCP confirmation denied."
+ };
+ respond_error(stream, "403 Forbidden", message).await;
+ return;
+ }
+ let revoked = sql_approvals().lock().map(|approvals| approvals.generation != generation).unwrap_or(true);
+ if revoked {
+ respond_error(stream, "403 Forbidden", "TOOL_BLOCKED: Approval revoked by policy change.").await;
+ return;
+ }
+ respond_json(stream, &serde_json::json!({ "ok": true })).await;
+}
+
async fn handle_consume_sql_approval(state: &Arc<AppState>, body: &str, stream: &mut tokio::net::TcpStream) {
let req: ConsumeSqlApprovalRequest = match serde_json::from_str(body) {
Ok(req) => req,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 93988efbbd..b71cb6b0e2 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2367,6 +2367,14 @@ pub fn run() {
commands::app_settings::save_pinned_tree_node_ids,
commands::app_settings::load_mcp_global_policy,
commands::app_settings::save_mcp_global_policy,
+ commands::app_settings::load_mcp_tool_catalog,
+ commands::app_settings::load_mcp_access_policy,
+ commands::app_settings::reset_invalid_mcp_access_policy,
+ commands::app_settings::set_mcp_plugin_scope_rule,
+ commands::app_settings::list_plugin_mcp_views,
+ commands::app_settings::load_plugin_mcp_view,
+ commands::app_settings::list_mcp_plugin_scopes,
+ commands::app_settings::save_plugin_mcp_grant,
commands::mcp_bridge::respond_mcp_sql_approval,
commands::background_image::save_background_image,
commands::background_image::clear_background_image,