diff --git a/Cargo.lock b/Cargo.lock index ddba15accc..120764aa1b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -145,7 +145,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbb4e440d04be07da1f1bf44fb4495ebd58669372fe0cffa6e48595ac5bd88a3" dependencies = [ "android_log-sys", - "env_filter", + "env_filter 0.1.4", "log", ] @@ -158,6 +158,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -1469,6 +1519,12 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.7" @@ -2472,6 +2528,8 @@ dependencies = [ "chrono", "dbx-core", "dirs", + "env_logger", + "futures", "log", "mysql_async", "reqwest 0.12.28", @@ -2714,6 +2772,37 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror 2.0.19", +] + [[package]] name = "delegate" version = "0.13.5" @@ -3211,6 +3300,29 @@ dependencies = [ "regex", ] +[[package]] +name = "env_filter" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" +dependencies = [ + "anstream", + "anstyle", + "env_filter 2.0.0", + "jiff", + "log", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -4876,6 +4988,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.12.1" @@ -4914,6 +5032,43 @@ dependencies = [ "system-deps", ] +[[package]] +name = "jiff" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "jni" version = "0.21.1" @@ -6262,6 +6417,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "opaque-debug" version = "0.3.1" @@ -6902,6 +7063,15 @@ version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3" +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "portpicker" version = "0.1.1" @@ -10661,6 +10831,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utoipa" version = "5.5.0" diff --git a/apps/desktop/src/components/plugins/PluginAiAccessSection.vue b/apps/desktop/src/components/plugins/PluginAiAccessSection.vue index 1cf208fb01..aac289ba06 100644 --- a/apps/desktop/src/components/plugins/PluginAiAccessSection.vue +++ b/apps/desktop/src/components/plugins/PluginAiAccessSection.vue @@ -15,7 +15,9 @@ import type { PluginToolPreview } from "@/types/pluginAiTools"; /** * Plugin Center controls for what a plugin may reach beyond its own UI: * built-in AI access to its MCP tools, and the connections it may read - * through `host.data:read`. Both are off until the user turns them on. + * through `host.data:read`. AI tool access is opt-in — off until the user + * turns it on, and the choice survives restarts and plugin updates. Data + * reads are off until the user consents. */ const props = defineProps<{ plugin: InstalledPlugin }>(); diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts index 86eab58836..11dccf8c90 100644 --- a/apps/desktop/src/i18n/locales/az.ts +++ b/apps/desktop/src/i18n/locales/az.ts @@ -86,7 +86,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "Məlumat girişi sorğusu", aiTools: { title: "Daxili süni intellekt alətləri", - description: "DBX süni intellekt köməkçisinin (Agent rejimi) açıq olan plagin bağlantılarında bu plaginin alətlərini çağırmasına icazə verir. Yalnız oxuma kimi elan edilməyən alətlər hər çağırışdan əvvəl təsdiqinizi istəyir və alət nəticəsi süni intellekt modelinizə göndərilir.", + 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.", preview: "Alətləri göstər", previewHint: "Plagin işləmirsə, onu başladır.", previewFailed: "Alətlərin siyahısı alınmadı: {message}", @@ -8278,6 +8278,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "Əlaqəni çıxar", mcpToolOpenTable: "Cədvəli DBX-də aç", mcpToolExecuteAndShow: "İcra et və DBX-də göstər", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", supportInfoTitle: "Dəstək məlumatları", supportInfoDescription: "Problem bildirərkən və ya kömək istəyərkən bu mühit təfərrüatlarını kopyalayın.", supportInfoCopy: "Dəstək məlumatlarını kopyala", diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index 40928e1735..72aa9f8819 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -172,7 +172,7 @@ export default { dataAccessConsentTitle: "Data Access Request", aiTools: { title: "Built-in AI tools", - description: "Let the DBX AI assistant (Agent mode) call this plugin's tools on the plugin connections you have open. Tools that are not declared read-only ask for your approval before every call, and tool output is sent to your AI model.", + 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.", preview: "Show tools", previewHint: "Starts the plugin if it is not running.", previewFailed: "Could not list tools: {message}", @@ -9012,6 +9012,9 @@ export default { mcpToolRemoveConnection: "Remove connection", mcpToolOpenTable: "Open table in DBX", mcpToolExecuteAndShow: "Execute and show in DBX", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", 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 b6e43fe2e5..e921ce64a1 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -175,7 +175,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "Solicitud de acceso a datos", aiTools: { title: "Herramientas de IA integradas", - description: "Permite que el asistente de IA de DBX (modo Agent) use las herramientas de este plugin en las conexiones del plugin que tengas abiertas. Las herramientas no declaradas de solo lectura piden tu aprobación antes de cada llamada, y su resultado se envía a tu modelo de IA.", + 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.", preview: "Ver herramientas", previewHint: "Inicia el plugin si no está en ejecución.", previewFailed: "No se pudieron listar las herramientas: {message}", @@ -8301,6 +8301,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "Eliminar conexión", mcpToolOpenTable: "Abrir tabla en DBX", mcpToolExecuteAndShow: "Ejecutar y mostrar en DBX", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", supportInfoTitle: "Información de soporte", supportInfoDescription: "Copia estos datos del entorno al crear issues o pedir ayuda.", supportInfoCopy: "Copiar información", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 5c84d9529a..71ebf8d46e 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -174,8 +174,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "Richiesta di accesso ai dati", aiTools: { title: "Strumenti IA integrati", - description: - "Consente all'assistente IA di DBX (modalità Agent) di usare gli strumenti di questo plugin sulle connessioni del plugin che hai aperto. Gli strumenti non dichiarati di sola lettura chiedono la tua approvazione prima di ogni chiamata e il loro output viene inviato al tuo modello IA.", + 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.", preview: "Mostra strumenti", previewHint: "Avvia il plugin se non è in esecuzione.", previewFailed: "Impossibile elencare gli strumenti: {message}", @@ -8226,6 +8225,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "Rimuovi connessione", mcpToolOpenTable: "Apri tabella in DBX", mcpToolExecuteAndShow: "Esegui e mostra in DBX", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", supportInfoTitle: "Informazioni di supporto", supportInfoDescription: "Copia questi dettagli dell'ambiente quando apri issue o chiedi aiuto.", supportInfoCopy: "Copia informazioni", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 56adf0d963..2e5762dcf6 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -175,7 +175,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "データアクセスの要求", aiTools: { title: "組み込み AI ツール", - description: "DBX AI アシスタント(Agent モード)が、開いているこのプラグインの接続でプラグインのツールを呼び出せるようにします。読み取り専用と宣言されていないツールは呼び出しのたびに承認を求め、ツールの出力は設定した AI モデルに送信されます。", + description: "デフォルトはオフです:このスイッチが有効な間のみ、DBX AIアシスタント(Agentモード)が開いているこのプラグインの接続でツールを呼び出せます。読み取り専用以外のツールは毎回承認を求めます。", preview: "ツールを表示", previewHint: "プラグインが実行されていない場合は起動します。", previewFailed: "ツール一覧を取得できませんでした: {message}", @@ -8222,6 +8222,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "接続を削除", mcpToolOpenTable: "DBX でテーブルを開く", mcpToolExecuteAndShow: "DBX で実行して表示", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", updateDownloadSource: "アップデートのダウンロード元", updateDownloadSourceDescription: "アプリ内アップデートのインストーラーのダウンロード元を選択します。公式ソース推奨。中国本土ではCNBの方が高速な場合があります。", updateDownloadSourceOfficial: "公式ソース(推奨)", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index 425fb2908a..62ae43dadc 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -174,7 +174,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "데이터 액세스 요청", aiTools: { title: "내장 AI 도구", - description: "DBX AI 어시스턴트(Agent 모드)가 열려 있는 이 플러그인의 연결에서 플러그인 도구를 호출하도록 허용합니다. 읽기 전용으로 선언되지 않은 도구는 호출할 때마다 승인을 요청하며, 도구 출력은 설정한 AI 모델로 전송됩니다.", + description: "기본값은 꺼짐입니다: 이 스위치가 켜져 있는 동안에만 DBX AI 어시스턴트(Agent 모드)가 열려 있는 이 플러그인의 연결에서 도구를 호출할 수 있습니다. 읽기 전용이 아닌 도구는 호출할 때마다 승인을 요청합니다.", preview: "도구 보기", previewHint: "플러그인이 실행 중이 아니면 시작합니다.", previewFailed: "도구 목록을 가져올 수 없습니다: {message}", @@ -8009,6 +8009,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "연결 삭제", mcpToolOpenTable: "DBX에서 테이블 열기", mcpToolExecuteAndShow: "DBX에서 실행 및 표시", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", supportInfoTitle: "지원 정보", supportInfoDescription: "이슈를 등록하거나 도움을 요청할 때 이 환경 세부 정보를 복사하세요.", supportInfoCopy: "지원 정보 복사", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index c48808c7c3..d9f7a6a01a 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -175,7 +175,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "Solicitação de acesso a dados", aiTools: { title: "Ferramentas de IA integradas", - description: "Permite que o assistente de IA do DBX (modo Agent) use as ferramentas deste plugin nas conexões do plugin que você tem abertas. Ferramentas não declaradas como somente leitura pedem sua aprovação antes de cada chamada, e a saída delas é enviada ao seu modelo de IA.", + 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.", preview: "Ver ferramentas", previewHint: "Inicia o plugin se ele não estiver em execução.", previewFailed: "Não foi possível listar as ferramentas: {message}", @@ -8227,6 +8227,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "Remover conexão", mcpToolOpenTable: "Abrir tabela no DBX", mcpToolExecuteAndShow: "Executar e mostrar no DBX", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", supportInfoTitle: "Informações de suporte", supportInfoDescription: "Copie estes detalhes do ambiente ao abrir issues ou pedir ajuda.", supportInfoCopy: "Copiar informações", diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts index 989cca14e4..77cff903b3 100644 --- a/apps/desktop/src/i18n/locales/ru.ts +++ b/apps/desktop/src/i18n/locales/ru.ts @@ -122,7 +122,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "Запрос доступа к данным", aiTools: { title: "Встроенные инструменты ИИ", - description: "Разрешает ИИ-ассистенту DBX (режим Agent) вызывать инструменты этого плагина на открытых подключениях плагина. Инструменты, не объявленные как только для чтения, запрашивают ваше подтверждение перед каждым вызовом, а их вывод отправляется вашей модели ИИ.", + description: "По умолчанию выключено: ИИ-ассистент DBX (режим Agent) может вызывать инструменты этого плагина в открытых подключениях, только пока переключатель включён. Инструменты без признака «только чтение» по-прежнему требуют подтверждения каждого вызова.", preview: "Показать инструменты", previewHint: "Запускает плагин, если он не работает.", previewFailed: "Не удалось получить список инструментов: {message}", @@ -9499,6 +9499,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "Удалить подключение", mcpToolOpenTable: "Открыть таблицу в DBX", mcpToolExecuteAndShow: "Выполнить и показать в DBX", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", supportInfoTitle: "Информация для поддержки", supportInfoDescription: "Скопируйте эти сведения о среде при создании обращений или запросе помощи.", supportInfoCopy: "Скопировать информацию для поддержки", diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts index 61bf18950e..4657dbfcad 100644 --- a/apps/desktop/src/i18n/locales/tr.ts +++ b/apps/desktop/src/i18n/locales/tr.ts @@ -88,7 +88,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "Veri Erişim İsteği", aiTools: { title: "Yerleşik yapay zekâ araçları", - description: "DBX yapay zekâ asistanının (Agent modu) açık olan eklenti bağlantılarında bu eklentinin araçlarını çağırmasına izin verir. Salt okunur olarak bildirilmeyen araçlar her çağrıdan önce onayınızı ister ve araç çıktısı yapay zekâ modelinize gönderilir.", + 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.", preview: "Araçları göster", previewHint: "Eklenti çalışmıyorsa başlatılır.", previewFailed: "Araçlar listelenemedi: {message}", @@ -8176,6 +8176,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "Bağlantıyı kaldır", mcpToolOpenTable: "Tabloyu DBX'te aç", mcpToolExecuteAndShow: "Çalıştır ve DBX'te göster", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", supportInfoTitle: "Destek bilgileri", supportInfoDescription: "Sorun bildirirken ya da yardım isterken bu ortam ayrıntılarını kopyalayın.", supportInfoCopy: "Destek bilgilerini kopyala", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index 792623afad..6a30a373ed 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -97,7 +97,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "数据访问请求", aiTools: { title: "内置 AI 工具", - description: "允许 DBX AI 助手(Agent 模式)在你已打开的该插件连接上调用插件工具。未声明为只读的工具每次调用前都会请求你确认,工具输出会发送给你配置的 AI 模型。", + description: "默认关闭:仅在此开关开启期间,DBX AI 助手(Agent 模式)才能在你已打开的该插件连接上调用其工具。未声明为只读的工具每次调用前仍会请求你确认,工具输出会发送给你配置的 AI 模型。", preview: "查看工具", previewHint: "插件未运行时会先启动它。", previewFailed: "无法获取工具列表:{message}", @@ -8979,6 +8979,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "删除连接", mcpToolOpenTable: "在 DBX 中打开表", mcpToolExecuteAndShow: "在 DBX 中执行并展示", + mcpToolPluginList: "插件目录", + mcpToolPluginTools: "插件工具清单", + mcpToolPluginCall: "调用插件工具", 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 4cd26f3a62..b5bb357f3b 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -175,7 +175,7 @@ export default withEnglishFallback({ dataAccessConsentTitle: "資料存取請求", aiTools: { title: "內建 AI 工具", - description: "允許 DBX AI 助理(Agent 模式)在你已開啟的此外掛連線上呼叫外掛工具。未宣告為唯讀的工具每次呼叫前都會請求你確認,工具輸出會傳送給你設定的 AI 模型。", + description: "預設關閉:僅在此開關開啟期間,DBX AI 助理(Agent 模式)才能在你已開啟的此外掛連線上呼叫其工具。未宣告為唯讀的工具每次呼叫前仍會請求你確認,工具輸出會傳送給你設定的 AI 模型。", preview: "檢視工具", previewHint: "外掛未執行時會先啟動它。", previewFailed: "無法取得工具清單:{message}", @@ -7595,6 +7595,9 @@ export default withEnglishFallback({ mcpToolRemoveConnection: "刪除連線", mcpToolOpenTable: "在 DBX 中開啟資料表", mcpToolExecuteAndShow: "在 DBX 中執行並顯示", + mcpToolPluginList: "Plugin catalog", + mcpToolPluginTools: "Plugin tool listing", + mcpToolPluginCall: "Call plugin tools", updateDownloadSource: "更新下載來源", updateDownloadSourceDescription: "選擇應用程式內更新安裝程式的下載來源。建議使用官方來源;CNB 在中國大陸網路環境下可能更快。", updateDownloadSourceOfficial: "官方來源(建議)", diff --git a/apps/desktop/src/lib/mcp/mcpPolicySelection.ts b/apps/desktop/src/lib/mcp/mcpPolicySelection.ts index 4f87d054ea..c812d059f9 100644 --- a/apps/desktop/src/lib/mcp/mcpPolicySelection.ts +++ b/apps/desktop/src/lib/mcp/mcpPolicySelection.ts @@ -47,6 +47,9 @@ export const MCP_TOOL_OPTIONS = [ { name: "dbx_remove_connection", labelKey: "settings.mcpToolRemoveConnection" }, { name: "dbx_open_table", labelKey: "settings.mcpToolOpenTable" }, { name: "dbx_execute_and_show", labelKey: "settings.mcpToolExecuteAndShow" }, + { name: "dbx_plugin_list", labelKey: "settings.mcpToolPluginList" }, + { name: "dbx_plugin_tools", labelKey: "settings.mcpToolPluginTools" }, + { name: "dbx_plugin_call", labelKey: "settings.mcpToolPluginCall" }, ] as const; export interface McpExecutionPolicyFields { diff --git a/apps/desktop/src/lib/plugins/frontendPlugin.ts b/apps/desktop/src/lib/plugins/frontendPlugin.ts index ca71114067..3ffc671dcc 100644 --- a/apps/desktop/src/lib/plugins/frontendPlugin.ts +++ b/apps/desktop/src/lib/plugins/frontendPlugin.ts @@ -366,8 +366,13 @@ function localizePluginMetadata(plugin: InstalledPlugin, localization?: PluginMa function localizeContribution(contribution: PluginContribution, localization: PluginContributionLocalization | undefined, pluginName: string): PluginContribution { // Menus entries carry no display text of their own — labels come from the - // referenced commands, so they pass through localization untouched. + // referenced commands, so they pass through localization untouched. The + // `mcp` declaration is host-surface metadata without a label either; only + // its optional description localizes. if (contribution.type === "menus") return contribution; + if (contribution.type === "mcp") { + return { ...contribution, description: localizedOptionalText(contribution.description, localization?.description) }; + } const fallbackLabel = contribution.type === "connection-provider" ? optionalTrimmed(contribution.label) || optionalTrimmed(pluginName) || contribution.id : contribution.label; const localized = { ...contribution, diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts index 8feac2204c..039e65d201 100644 --- a/apps/desktop/src/types/database.ts +++ b/apps/desktop/src/types/database.ts @@ -582,6 +582,20 @@ export interface PluginMenusContribution { items: PluginMenuItem[]; } +/** + * Declares that the plugin sidecar speaks the optional MCP tool bridge + * (`mcp/tools` + `mcp/call`) and opts its tools into the host's automatic + * surfaces: the built-in AI agent and the external `dbx` MCP server. Both + * default to true; the Plugin Center switch still overrides the AI surface. + */ +export interface PluginMcpContribution { + type: "mcp"; + id: string; + description?: string; + ai_tools?: boolean; + external_tools?: boolean; +} + /** * Contribution types the host renders through the plugin's own UI entrypoint in * a plugin tab. A `workbench` is launched from the sidebar, the plugin center, @@ -592,7 +606,7 @@ export interface PluginMenusContribution { */ export type PluginUiContribution = PluginWorkbenchContribution | PluginResultViewContribution; -export type PluginContribution = PluginConnectionProviderContribution | PluginWorkbenchContribution | PluginFilesystemProviderContribution | PluginContextMenuContribution | PluginResultViewContribution | PluginCommandContribution | PluginMenusContribution; +export type PluginContribution = PluginConnectionProviderContribution | PluginWorkbenchContribution | PluginFilesystemProviderContribution | PluginContextMenuContribution | PluginResultViewContribution | PluginCommandContribution | PluginMenusContribution | PluginMcpContribution; export interface PluginEngines { dbx: string; diff --git a/crates/dbx-core/src/ai/plugin_tools.rs b/crates/dbx-core/src/ai/plugin_tools.rs index 92dc7a3c14..ba46ebaf94 100644 --- a/crates/dbx-core/src/ai/plugin_tools.rs +++ b/crates/dbx-core/src/ai/plugin_tools.rs @@ -4,9 +4,12 @@ //! and `mcp/call` (execution). This module turns them into agent tools under //! three host-owned rules: //! -//! * **Opt-in per plugin.** Only plugins the user enabled for the built-in AI -//! in the Plugin Center contribute tools, so a plugin cannot put its tools — -//! and whatever they read — in front of the model on install alone. +//! * **Detected plugins, revocable.** Every installed, compatible plugin with +//! a backend contributes tools automatically — implementing the optional +//! `mcp/tools` bridge is the author's declaration of intent (a manifest +//! `mcp` contribution with `ai_tools: false` narrows it). The Plugin Center +//! switch still turns a plugin off for good, and the opt-out outlives +//! restarts and plugin updates. //! * **Open connections only.** Tools run against plugin connections DBX //! already has open. The host binds the connection: the model picks among //! the open ones by DBX id, the lifecycle payload (credentials, runtime @@ -23,7 +26,10 @@ //! Tool definitions are reduced to a JSON-Schema subset every supported //! provider accepts (OpenAI, Anthropic, and Gemini's OpenAPI-style //! `parameters`), and exposed as `__` names that satisfy all of -//! their naming rules. +//! their naming rules. The naming, schema-reduction, and listing helpers are +//! shared with the external `dbx` MCP server +//! (`crates/dbx-mcp/src/plugin_tools.rs`) so one plugin tool surfaces under +//! the same exposed name on both automatic surfaces. use std::collections::{BTreeMap, HashMap, HashSet}; use std::future::Future; @@ -46,8 +52,10 @@ const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(8); /// task tools (e.g. SSH `ssh_run_bg`), not in one blocking call. const CALL_TIMEOUT: Duration = Duration::from_secs(120); const MAX_OPEN_CONNECTIONS: usize = 8; -const MAX_TOOLS_PER_PLUGIN: usize = 64; -const MAX_TOTAL_TOOLS: usize = 96; +/// Shared with the external `dbx` MCP server so one plugin tool keeps the +/// same bounds on both automatic surfaces. +pub const MAX_TOOLS_PER_PLUGIN: usize = 64; +pub const MAX_TOTAL_TOOLS: usize = 96; const MAX_DESCRIPTION_CHARS: usize = 1_500; const MAX_SCHEMA_PROPERTIES: usize = 64; const MAX_SCHEMA_DEPTH: usize = 6; @@ -62,7 +70,7 @@ const PLUGIN_PREFIX_MAX_CHARS: usize = 20; pub const CONNECTION_ARGUMENT: &str = "dbx_connection"; /// Plugin arguments the host fills from the bound connection; the model never /// supplies them, so it cannot address a connection the user did not open. -const HOST_BOUND_ARGUMENTS: &[&str] = &["connectionId", "connectionName"]; +pub const HOST_BOUND_ARGUMENTS: &[&str] = &["connectionId", "connectionName"]; /// An open plugin connection whose tools the agent may call. #[derive(Debug, Clone)] @@ -249,6 +257,53 @@ impl PluginToolBinding { } } +/// Plugin ids whose sidecar tools the built-in AI agent may use. +/// +/// Opt-in only: the Plugin Center list is the single source — a plugin +/// contributes AI tools only after the user enabled it there, so installing +/// alone never puts anything in front of the model. A manifest `mcp` +/// contribution with `ai_tools: false` keeps a plugin off this surface even +/// when opted in, the ids the user explicitly turned off always win, and an +/// opted-in plugin must still be installed, compatible, and backend-capable. +/// If the setting or the plugin registry cannot be read, the surface degrades +/// to empty so a transient failure never widens exposure. +pub async fn effective_ai_tool_plugin_ids(state: &AppState) -> HashSet { + let opted_in: HashSet = match state.storage.load_ai_plugin_tool_plugin_ids().await { + Ok(ids) if !ids.is_empty() => ids.into_iter().collect(), + Ok(_) => return HashSet::new(), + Err(error) => { + log::warn!("[agent][plugin-tools] cannot read AI plugin tool settings: {error}"); + return HashSet::new(); + } + }; + let installed = match state.plugins.list_installed() { + Ok(plugins) => plugins + .iter() + .filter(|plugin| { + plugin.compatibility.compatible + && plugin.manifest.backend_entrypoint().is_some() + && !plugin.manifest.ai_tools_excluded() + }) + .map(|plugin| plugin.manifest.id.clone()) + .collect::>(), + Err(error) => { + log::warn!("[agent][plugin-tools] cannot list installed plugins: {error}"); + return HashSet::new(); + } + }; + let disabled: HashSet = state + .storage + .load_ai_plugin_tool_disabled_plugin_ids() + .await + .unwrap_or_else(|error| { + log::warn!("[agent][plugin-tools] cannot read AI plugin opt-outs: {error}"); + Vec::new() + }) + .into_iter() + .collect(); + opted_in.into_iter().filter(|plugin_id| installed.contains(plugin_id) && !disabled.contains(plugin_id)).collect() +} + /// Collects the plugin tools the built-in agent may use right now. Any /// failure degrades to fewer (or no) plugin tools; it never fails the run. pub async fn discover_plugin_tools( @@ -256,14 +311,10 @@ pub async fn discover_plugin_tools( host_runtime: Option<&tokio::runtime::Handle>, connection_id: Option<&str>, ) -> PluginToolSet { - let enabled = match state.storage.load_ai_plugin_tool_plugin_ids().await { - Ok(ids) if !ids.is_empty() => ids.into_iter().collect::>(), - Ok(_) => return PluginToolSet::default(), - Err(error) => { - log::warn!("[agent][plugin-tools] cannot read AI plugin tool settings: {error}"); - return PluginToolSet::default(); - } - }; + let enabled = effective_ai_tool_plugin_ids(state).await; + if enabled.is_empty() { + return PluginToolSet::default(); + } let plugin_names = match tool_capable_plugins(state, &enabled) { Ok(names) if !names.is_empty() => names, Ok(_) => return PluginToolSet::default(), @@ -398,7 +449,7 @@ pub async fn execute_plugin_tool( prepared: &PreparedPluginToolCall, ) -> ToolResult { let outcome = async { - let enabled = state.storage.load_ai_plugin_tool_plugin_ids().await?; + let enabled = effective_ai_tool_plugin_ids(state).await; if !enabled.contains(&prepared.plugin_id) { return Err("Built-in AI access to this plugin has been disabled".to_string()); } @@ -568,15 +619,18 @@ impl Drop for AbortOnDrop { } #[derive(Debug, Clone, PartialEq)] -struct RawPluginTool { - name: String, - description: String, - input_schema: Value, - read_only: bool, +pub struct RawPluginTool { + pub name: String, + pub description: String, + pub input_schema: Value, + pub read_only: bool, + /// Raw MCP `annotations` object; the external `dbx` MCP server passes it + /// through on `tools/list`, the AI surface only reads `readOnlyHint`. + pub annotations: Value, } /// Parses an `mcp/tools` answer (`{ tools: [...] }` or a bare array). -fn parse_tool_list(value: &Value) -> Vec { +pub fn parse_tool_list(value: &Value) -> Vec { let tools = value.get("tools").and_then(Value::as_array).or_else(|| value.as_array()); let Some(tools) = tools else { return Vec::new(); @@ -600,6 +654,7 @@ fn parse_tool_list(value: &Value) -> Vec { description: tool.get("description").and_then(Value::as_str).unwrap_or_default().trim().to_string(), input_schema, read_only: tool.pointer("/annotations/readOnlyHint").and_then(Value::as_bool) == Some(true), + annotations: tool.get("annotations").cloned().unwrap_or_else(|| json!({})), }) }) .take(MAX_TOOLS_PER_PLUGIN) @@ -662,14 +717,62 @@ fn tool_description(plugin_name: &str, tool: &RawPluginTool, connections: &[Open } /// A short, stable, name-safe prefix per plugin (`io.dbx.ssh` → `ssh`). -/// Plugins that reduce to the same prefix are told apart by a counter, in -/// plugin-id order so the assignment is deterministic. -fn plugin_prefixes<'a>(plugin_ids: impl Iterator) -> HashMap { - let mut used = HashSet::new(); +/// +/// The prefix starts at the id's last segment and **extends leftward only +/// when two installed plugins reduce to the same candidate** (`a.files` → +/// `a_files`, `b.files` → `b_files`), so ordinary ids stay short while +/// same-named plugins remain distinguishable by their own id — not by an +/// install-order counter that would silently reassign names when plugins are +/// uninstalled. Sanitization can still collapse two distinct ids to the same +/// prefix (`a.b-c` vs `a.b_c`); those fall to a counter suffix, assigned in +/// plugin-id order so the result is deterministic for a given installed set. +pub fn plugin_prefixes<'a>(plugin_ids: impl Iterator) -> HashMap { + let mut ids = plugin_ids.into_iter().map(str::to_string).collect::>(); + ids.sort(); + + // Sanitized segments in original id order, without empties. + let segments_of = |id: &str| -> Vec { + let mut segments: Vec = + id.split('.').map(sanitize_identifier).filter(|segment| !segment.is_empty()).collect(); + if segments.is_empty() { + segments.push("plugin".to_string()); + } + segments + }; + let segment_lists: Vec> = ids.iter().map(|id| segments_of(id)).collect(); + // The prefix is the id's LAST `depth` segments in natural order, so the + // extension reads like the id itself (`a.files` → `a_files`). + let joined = |index: usize, depth: usize| -> String { + let list = &segment_lists[index]; + let start = list.len().saturating_sub(depth); + list[start..].join("_") + }; + + // Extend colliding plugins leftward until every prefix is unique. Full + // ids are unique, so the loop terminates; sanitization can still collapse + // distinct ids at full depth, which the counter fallback below resolves. + let mut depths = vec![1usize; ids.len()]; + for _ in 0..ids.iter().map(|id| id.split('.').count()).max().unwrap_or(1) { + let candidates: Vec = (0..ids.len()).map(|index| joined(index, depths[index])).collect(); + let mut extended = false; + for index in 0..ids.len() { + let collides = candidates.iter().enumerate().any(|(other, candidate)| { + other != index && candidate == &candidates[index] && depths[index] < segment_lists[index].len() + }); + if collides { + depths[index] += 1; + extended = true; + } + } + if !extended { + break; + } + } + let mut prefixes = HashMap::new(); - for plugin_id in plugin_ids { - let last_segment = plugin_id.rsplit('.').next().unwrap_or(plugin_id); - let mut base = sanitize_identifier(last_segment); + let mut used = HashSet::new(); + for (index, plugin_id) in ids.iter().enumerate() { + let mut base = joined(index, depths[index]); base.truncate(PLUGIN_PREFIX_MAX_CHARS); let base = base.trim_end_matches('_').to_string(); let base = if base.is_empty() { "plugin".to_string() } else { base }; @@ -679,14 +782,15 @@ fn plugin_prefixes<'a>(plugin_ids: impl Iterator) -> HashMap__`: starts with a letter, only `[A-Za-z0-9_]`, at most 64 /// characters. Truncated or colliding names get a hash of the original. -fn exposed_tool_name(prefix: &str, tool_name: &str, used: &mut HashSet) -> String { +/// Shared with the external `dbx` MCP server. +pub fn exposed_tool_name(prefix: &str, tool_name: &str, used: &mut HashSet) -> String { let sanitized = sanitize_identifier(tool_name); let mut name = format!("{prefix}__{sanitized}"); if name.chars().count() > MAX_EXPOSED_NAME_CHARS || used.contains(&name) { @@ -771,8 +875,9 @@ fn tool_parameters(input_schema: &Value, connections: &[OpenPluginConnection]) - /// Reduces a JSON Schema to keywords OpenAI, Anthropic, and Gemini's /// OpenAPI-style `parameters` all accept. Anything outside the subset is /// dropped rather than passed through: one unsupported keyword makes a -/// provider reject the whole request, not just this tool. -fn sanitize_schema(schema: &Value, depth: usize) -> Value { +/// provider reject the whole request, not just this tool. Shared with the +/// external `dbx` MCP server. +pub fn sanitize_schema(schema: &Value, depth: usize) -> Value { let Some(object) = schema.as_object() else { return json!({ "type": "string" }); }; @@ -947,6 +1052,26 @@ mod tests { } } + /// Writes a minimal installable plugin container: one manifest, one + /// backend executable. `contributions` carries extra entries such as the + /// `mcp` surface override. + fn write_fake_plugin(plugins_dir: &std::path::Path, plugin_id: &str, contributions: Value) { + let container = plugins_dir.join(plugin_id); + std::fs::create_dir_all(container.join("bin")).unwrap(); + std::fs::write(container.join("bin").join("backend"), b"backend").unwrap(); + let manifest = json!({ + "manifest_version": 1, + "id": plugin_id, + "name": plugin_id, + "version": "1.0.0", + "publisher": "test", + "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" }, + "entrypoints": { "backend": { "executable": "bin/backend" } }, + "contributions": contributions, + }); + std::fs::write(container.join("manifest.json"), serde_json::to_vec(&manifest).unwrap()).unwrap(); + } + fn tool_call(name: &str, arguments: Value) -> ToolCall { ToolCall { id: "call-1".to_string(), name: name.to_string(), arguments, provider_payload: None } } @@ -1127,9 +1252,20 @@ mod tests { } let prefixes = plugin_prefixes(["a.files", "b.files", "io.dbx.9lives"].into_iter()); - assert_eq!(prefixes["a.files"], "files"); - assert_eq!(prefixes["b.files"], "files2"); + assert_eq!(prefixes["a.files"], "a_files"); + assert_eq!(prefixes["b.files"], "b_files"); assert_eq!(prefixes["io.dbx.9lives"], "t9lives"); + + // Distinct last segments keep the short form. + let prefixes = plugin_prefixes(["io.dbx.ssh", "io.dbx.files"].into_iter()); + assert_eq!(prefixes["io.dbx.ssh"], "ssh"); + assert_eq!(prefixes["io.dbx.files"], "files"); + + // Sanitization collapses `a.b-c` and `a.b_c` even at full depth; + // the counter is the deterministic last resort. + let prefixes = plugin_prefixes(["a.b-c", "a.b_c"].into_iter()); + assert_eq!(prefixes["a.b-c"], "a_b_c"); + assert_eq!(prefixes["a.b_c"], "a_b_c2"); } #[test] @@ -1144,11 +1280,52 @@ mod tests { assert_eq!(structured, "{\"ok\":true}"); } + #[tokio::test] + async fn opt_in_gates_ai_tools_and_opt_outs_win() { + let root = tempfile::tempdir().unwrap(); + let storage = crate::persistence::test_storage::open(&root.path().join("dbx.db")).await.unwrap(); + let plugins_dir = root.path().join("plugins"); + write_fake_plugin(&plugins_dir, "io.test.ssh", serde_json::json!([])); + write_fake_plugin( + &plugins_dir, + "io.test.quiet", + serde_json::json!([{ "type": "mcp", "id": "io.test.quiet.mcp", "ai_tools": false }]), + ); + write_fake_plugin(&plugins_dir, "io.test.ui_only", serde_json::json!([])); + // Remove the backend from the UI-only plugin after writing it. + let backend = plugins_dir.join("io.test.ui_only").join("bin").join("backend"); + std::fs::remove_file(&backend).unwrap(); + + let state = Arc::new(AppState::new_with_plugin_dir(storage, plugins_dir)); + // Installing alone exposes nothing: the Plugin Center opt-in gates the AI surface. + let ids = effective_ai_tool_plugin_ids(&state).await; + assert!(ids.is_empty(), "nothing is exposed before the user opts in"); + + // Opting in enables a tool-capable plugin. + state.storage.set_ai_plugin_tool_plugin_enabled("io.test.ssh", true).await.unwrap(); + let ids = effective_ai_tool_plugin_ids(&state).await; + assert!(ids.contains("io.test.ssh"), "the opt-in enables the tool-capable plugin"); + + // The manifest declaration and the backend guard still bind opted-in plugins. + state.storage.set_ai_plugin_tool_plugin_enabled("io.test.quiet", true).await.unwrap(); + state.storage.set_ai_plugin_tool_plugin_enabled("io.test.ui_only", true).await.unwrap(); + let ids = effective_ai_tool_plugin_ids(&state).await; + assert!(!ids.contains("io.test.quiet"), "ai_tools:false excludes the AI surface even when opted in"); + assert!(!ids.contains("io.test.ui_only"), "plugins without a backend stay invisible"); + + // The Plugin Center opt-out always wins over the opt-in. + state.storage.set_ai_plugin_tool_plugin_enabled("io.test.ssh", false).await.unwrap(); + let ids = effective_ai_tool_plugin_ids(&state).await; + assert!(!ids.contains("io.test.ssh")); + } + #[tokio::test] async fn stale_tool_bindings_cannot_bypass_revoked_ai_access() { let root = tempfile::tempdir().unwrap(); let storage = crate::persistence::test_storage::open(&root.path().join("dbx.db")).await.unwrap(); - let state = Arc::new(AppState::new(storage)); + let plugins_dir = root.path().join("plugins"); + write_fake_plugin(&plugins_dir, "io.dbx.kafka", serde_json::json!([])); + let state = Arc::new(AppState::new_with_plugin_dir(storage, plugins_dir)); state.storage.set_ai_plugin_tool_plugin_enabled("io.dbx.kafka", true).await.unwrap(); let set = build_tool_set( &names(), diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs index 6e2b600907..2984e26200 100644 --- a/crates/dbx-core/src/persistence/storage.rs +++ b/crates/dbx-core/src/persistence/storage.rs @@ -60,8 +60,14 @@ const MAX_RETRIES_KEY: &str = "max_retries"; const HISTORY_RETENTION_LIMIT_KEY: &str = "history_retention_limit"; const MCP_HISTORY_RETENTION_LIMIT_KEY: &str = "mcp_history_retention_limit"; const SQL_FILE_UPLOAD_MAX_MB_KEY: &str = "sql_file_upload_max_mb"; -/// Plugin ids whose MCP tools the built-in AI agent may call. +/// Plugin ids whose MCP tools the built-in AI agent may call. The opt-in +/// list is the single source: a plugin contributes AI tools only after the +/// user enabled it in the Plugin Center. const AI_PLUGIN_TOOL_PLUGINS_KEY: &str = "ai_plugin_tool_plugins"; +/// Plugin ids the user explicitly turned off in the Plugin Center; they stay +/// 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: [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"; @@ -4347,9 +4353,19 @@ impl Storage { Ok(normalized_string_list(settings.get(AI_PLUGIN_TOOL_PLUGINS_KEY))) } + /// Plugin ids the user explicitly turned off for the built-in AI agent. + /// Only records explicit revocations; combined with the enabled list and + /// the manifest `mcp` declarations it yields the effective AI tool set. + pub async fn load_ai_plugin_tool_disabled_plugin_ids(&self) -> Result, String> { + let settings = self.load_app_settings_json().await?; + Ok(normalized_string_list(settings.get(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY))) + } + /// Enables or disables built-in AI access to one plugin's tools and returns /// the updated list. The read-modify-write runs inside one connection - /// closure so concurrent settings saves cannot drop the change. + /// closure so concurrent settings saves cannot drop the change. Disabling + /// also records the opt-out so a detection-enabled plugin (the default) + /// stays off across restarts and plugin updates. pub async fn set_ai_plugin_tool_plugin_enabled( &self, plugin_id: &str, @@ -4361,8 +4377,19 @@ impl Storage { let mut plugin_ids = normalized_string_list(settings.get(AI_PLUGIN_TOOL_PLUGINS_KEY)); plugin_ids.retain(|candidate| candidate != &plugin_id); if enabled { - plugin_ids.push(plugin_id); + plugin_ids.push(plugin_id.clone()); plugin_ids.sort(); + // Re-enable after an explicit opt-out of a manifest-declared plugin. + let mut disabled = normalized_string_list(settings.get(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY)); + disabled.retain(|candidate| candidate != &plugin_id); + settings.insert(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY.to_string(), serde_json::json!(disabled)); + } else { + let mut disabled = normalized_string_list(settings.get(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY)); + if !disabled.contains(&plugin_id) { + disabled.push(plugin_id.clone()); + disabled.sort(); + } + settings.insert(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY.to_string(), serde_json::json!(disabled)); } settings.insert(AI_PLUGIN_TOOL_PLUGINS_KEY.to_string(), serde_json::json!(plugin_ids)); write_app_settings_map(conn, &settings)?; @@ -4427,6 +4454,9 @@ impl Storage { let mut plugin_ids = normalized_string_list(settings.get(AI_PLUGIN_TOOL_PLUGINS_KEY)); plugin_ids.retain(|candidate| candidate != &plugin_id); settings.insert(AI_PLUGIN_TOOL_PLUGINS_KEY.to_string(), serde_json::json!(plugin_ids)); + let mut disabled = normalized_string_list(settings.get(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY)); + disabled.retain(|candidate| candidate != &plugin_id); + settings.insert(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY.to_string(), serde_json::json!(disabled)); if let Some(serde_json::Value::Object(grants)) = settings.get_mut(PLUGIN_DATA_GRANTS_KEY) { grants.remove(&plugin_id); } @@ -12019,6 +12049,9 @@ mod tests { assert_eq!(storage.set_plugin_data_grant("io.dbx.chart", "conn-b", false).await.unwrap(), ["conn-a"]); assert_eq!(storage.set_ai_plugin_tool_plugin_enabled("io.dbx.kafka", false).await.unwrap(), ["io.dbx.ssh"]); + // Disabling records an explicit opt-out (manifest-declared plugins are + // enabled by default, so the opt-out must persist separately). + assert_eq!(storage.load_ai_plugin_tool_disabled_plugin_ids().await.unwrap(), ["io.dbx.kafka"]); assert!(storage.set_plugin_data_grant("io.dbx.chart", " ", true).await.is_err()); storage.set_ai_plugin_tool_plugin_enabled("io.dbx.chart", true).await.unwrap(); @@ -12026,6 +12059,10 @@ mod tests { assert_eq!(storage.load_ai_plugin_tool_plugin_ids().await.unwrap(), ["io.dbx.ssh"]); assert!(storage.load_plugin_data_grants("io.dbx.chart").await.unwrap().is_empty()); assert_eq!(storage.load_plugin_data_grants("io.dbx.other").await.unwrap(), ["conn-a"]); + // Re-enabling clears the recorded opt-out again. + storage.set_ai_plugin_tool_plugin_enabled("io.dbx.kafka", true).await.unwrap(); + assert_eq!(storage.load_ai_plugin_tool_plugin_ids().await.unwrap(), ["io.dbx.kafka", "io.dbx.ssh"]); + assert!(storage.load_ai_plugin_tool_disabled_plugin_ids().await.unwrap().is_empty()); } #[tokio::test] diff --git a/crates/dbx-mcp/Cargo.toml b/crates/dbx-mcp/Cargo.toml index c2bf6c72b3..bdbf271b97 100644 --- a/crates/dbx-mcp/Cargo.toml +++ b/crates/dbx-mcp/Cargo.toml @@ -24,8 +24,10 @@ path = "src/main.rs" [dependencies] async-trait = "0.1" +futures = "0.3" dbx-core = { path = "../dbx-core", default-features = false } dirs = "6" +env_logger = "0.11" log = "0.4" mysql_async = { version = "0.37", default-features = false, features = ["default-rustls", "client_ed25519", "chrono", "rust_decimal"] } axum = "0.8" diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rs index a07492c687..9a4ca5f8df 100644 --- a/crates/dbx-mcp/src/backend.rs +++ b/crates/dbx-mcp/src/backend.rs @@ -424,6 +424,29 @@ pub trait DbxBackend: Send + Sync { let _ = (connection, database, options); Err("Documentation snapshots are not supported by this backend.".to_string()) } + /// Tool-capable plugins for the external `dbx` MCP surface, with their + /// discovered `mcp/tools` listings. Author opt-in: installed + + /// compatible + backend entrypoint + a manifest `external_tools: true` + /// declaration. An error means "no plugin tools on this backend" (e.g. + /// the web backend); the server degrades to the static tools. + async fn list_plugin_mcp_tools(&self) -> Result, String> { + let _ = self; + Err("Plugin tools are 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 + /// connection-less tools. + async fn call_plugin_mcp_tool( + &self, + plugin_id: &str, + tool: &str, + connection_id: Option<&str>, + arguments: &Value, + ) -> Result { + let _ = (self, plugin_id, tool, connection_id, arguments); + Err("Plugin tools are not supported by this backend.".to_string()) + } } pub struct LocalBackend { @@ -653,6 +676,11 @@ fn plugin_lacks_mcp_surface(err: &str) -> bool { lower.contains("unknown method") || lower.contains("method not found") || lower.contains("-32601") } +/// Probe budget for one plugin's `mcp/tools` during external discovery — +/// aligned with the AI surface's discovery timeout so one hung sidecar +/// cannot stall `tools/list` beyond a few seconds. +const PLUGIN_TOOLS_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8); + impl LocalBackend { fn spawn_connection_lifecycle_watcher( &self, @@ -812,7 +840,9 @@ impl LocalBackend { /// Call one plugin MCP tool through the host-managed sidecar session. /// When a saved connection is supplied, only its host-generated lifecycle - /// payload is sent to the plugin; credentials remain host-managed. + /// payload is sent to the plugin; credentials remain host-managed. The + /// saved config must still belong to the target plugin, so a connection + /// re-bound to another plugin can never leak its lifecycle here. pub async fn call_plugin_tool( &self, plugin_id: &str, @@ -830,6 +860,9 @@ impl LocalBackend { .get(connection_id) .cloned() .ok_or_else(|| format!("Connection not found: {connection_id}"))?; + if config.plugin_id.as_deref() != Some(plugin_id) { + return Err(format!("Connection \"{connection_id}\" is not bound to plugin \"{plugin_id}\"")); + } let lifecycle = self.state.plugin_host.connection_params_standalone(&config)?; params["lifecycle"] = lifecycle; } @@ -839,6 +872,55 @@ impl LocalBackend { .await } + /// 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`. + pub async fn detect_plugin_tool_providers(&self) -> Result, String> { + let plugins = self.state.plugins.list_installed()?; + let candidates: Vec<(String, String)> = plugins + .into_iter() + .filter(|plugin| { + plugin.compatibility.compatible + && plugin.manifest.backend_entrypoint().is_some() + && !plugin.manifest.external_tools_excluded() + }) + .map(|plugin| (plugin.manifest.id.clone(), plugin.manifest.name.clone())) + .collect(); + // Probe every candidate's sidecar concurrently; the probes share the + // plugin sidecar sessions, so repeated listings are cheap. + let probes = candidates.into_iter().map(|(plugin_id, plugin_name)| { + let state = Arc::clone(&self.state); + async move { + let listing = state + .plugin_host + .invoke::(&plugin_id, "mcp/tools", json!({}), None, Some(PLUGIN_TOOLS_PROBE_TIMEOUT)) + .await; + (plugin_id, plugin_name, listing) + } + }); + let mut providers = Vec::new(); + for (plugin_id, plugin_name, listing) in futures::future::join_all(probes).await { + match listing { + Ok(value) => { + let tools = 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 }); + } + } + Err(err) if plugin_lacks_mcp_surface(&err) => { + log::debug!("[mcp] plugin {plugin_id} exposes no MCP tool surface: {err}"); + } + Err(err) => { + log::warn!("[mcp] plugin {plugin_id} tool discovery failed: {err}"); + } + } + } + Ok(providers) + } + /// Sync the latest connection list from storage into the `AppState.configs` in-memory cache: /// upsert new/changed entries and remove connections deleted from storage. Only LocalBackend /// needs this — WebBackend talks HTTP and holds no local AppState, and the desktop mcp_bridge @@ -928,6 +1010,20 @@ impl DbxBackend for LocalBackend { self.state.storage.load_mcp_global_policy().await.map(effective_mcp_policy) } + async fn list_plugin_mcp_tools(&self) -> Result, String> { + self.detect_plugin_tool_providers().await + } + + async fn call_plugin_mcp_tool( + &self, + plugin_id: &str, + tool: &str, + connection_id: Option<&str>, + arguments: &Value, + ) -> Result { + self.call_plugin_tool(plugin_id, tool, connection_id, arguments).await + } + async fn load_connections(&self) -> Result, String> { let configs = self.state.storage.load_connections().await?; // Connections created/modified/deleted in the DBX desktop UI after this process started diff --git a/crates/dbx-mcp/src/lib.rs b/crates/dbx-mcp/src/lib.rs index 5d2717ee84..62cbd62c3a 100644 --- a/crates/dbx-mcp/src/lib.rs +++ b/crates/dbx-mcp/src/lib.rs @@ -5,6 +5,7 @@ pub mod diagnostics; pub mod http; pub mod http_auth; pub mod paths; +pub mod plugin_tools; pub mod runtime; pub mod server; pub mod session; diff --git a/crates/dbx-mcp/src/main.rs b/crates/dbx-mcp/src/main.rs index 994ae7e1bd..77a4746ed4 100644 --- a/crates/dbx-mcp/src/main.rs +++ b/crates/dbx-mcp/src/main.rs @@ -12,6 +12,10 @@ async fn main() -> Result<(), Box> { println!("dbx-mcp {}", env!("CARGO_PKG_VERSION")); return Ok(()); } + // Diagnostics (plugin-tool discovery, bridge fallbacks) go to stderr, + // which is safe under the stdio transport. RUST_LOG controls the level; + // warnings are on by default so silent degradation stays visible. + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init(); let runtime = RuntimeConfig::from_environment_and_args()?; let backend: Arc = if let Ok(base_url) = std::env::var("DBX_WEB_URL") { Arc::new( diff --git a/crates/dbx-mcp/src/plugin_tools.rs b/crates/dbx-mcp/src/plugin_tools.rs new file mode 100644 index 0000000000..f778f692fc --- /dev/null +++ b/crates/dbx-mcp/src/plugin_tools.rs @@ -0,0 +1,360 @@ +//! External exposure of plugin MCP tools on the `dbx` MCP server. +//! +//! Author opt-in: installed, compatible plugins with a backend contribute +//! their `mcp/tools` listing under `dbx___` names only when the +//! manifest declares `external_tools: true`. Naming, parsing, and schema +//! reduction are shared with the built-in AI agent +//! (`dbx_core::ai::plugin_tools`) so one plugin tool surfaces under the same +//! exposed name on both surfaces. +//! +//! Calls stay host-bound: the caller picks among the plugin's saved +//! connections that the global MCP policy allows through `dbx_connection` +//! (`connectionId` / `connectionName` are accepted as aliases), and the host +//! generates the lifecycle payload from the saved connection — credentials +//! 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::sync::Arc; + +use serde_json::{json, Value}; + +#[doc(hidden)] +pub use dbx_core::ai::plugin_tools::CONNECTION_ARGUMENT as PLUGIN_CONNECTION_ARGUMENT; +use dbx_core::ai::plugin_tools::{ + exposed_tool_name, plugin_prefixes, sanitize_schema, RawPluginTool, CONNECTION_ARGUMENT, HOST_BOUND_ARGUMENTS, +}; + +/// Upper bound for the merged tools/list. Higher than the AI surface's cap: +/// MCP clients paginate and let their users enable/disable tools themselves, +/// so the host does not need to ration as aggressively. +pub const MAX_TOTAL_PLUGIN_TOOLS: usize = 512; + +/// Plugin arguments the host resolves from the saved connection before the +/// call is forwarded. +pub const CONNECTION_SELECTOR_ARGUMENTS: &[&str] = &[CONNECTION_ARGUMENT, "connectionId", "connectionName"]; + +/// One plugin's discovered `mcp/tools` listing, keyed for exposure. +#[derive(Debug, Clone)] +pub struct PluginToolProvider { + pub plugin_id: String, + pub plugin_name: String, + pub tools: Vec, +} + +/// One externally exposed plugin tool. +#[derive(Debug, Clone)] +pub struct PluginToolEntry { + pub plugin_id: String, + pub plugin_name: String, + pub exposed_name: String, + pub tool: RawPluginTool, + /// The plugin schema declares `connectionId`, so the host injects the + /// bound connection's id into the forwarded arguments. + pub injects_connection_id: bool, +} + +/// Whether `name` sits in the plugin-tool namespace (`dbx___`). +/// The static `dbx_*` router tools never contain `__`, so this cannot swallow +/// one, and unknown plugin names simply fail resolution at call time. +pub fn is_plugin_tool_name(name: &str) -> bool { + let Some(rest) = name.strip_prefix("dbx_") else { return false }; + let Some((prefix, _)) = rest.split_once("__") else { return false }; + !prefix.is_empty() +} + +/// Builds the exposed entries from raw provider listings. Deterministic: +/// providers are ordered by plugin id (so prefix de-duplication is stable) +/// and each plugin keeps its listing order. Exposed names live in the +/// `dbx___` namespace: the shared AI-surface name plus the +/// `dbx_` router prefix, which static tools never use with a `__` separator. +pub fn build_catalog(providers: &[PluginToolProvider]) -> Vec { + let mut sorted: Vec<&PluginToolProvider> = providers.iter().collect(); + sorted.sort_by(|left, right| left.plugin_id.cmp(&right.plugin_id)); + let prefixes = plugin_prefixes(sorted.iter().map(|provider| provider.plugin_id.as_str())); + let mut entries = Vec::new(); + 'providers: for provider in sorted { + let prefix = &prefixes[&provider.plugin_id]; + let mut used = HashSet::new(); + for tool in &provider.tools { + if entries.len() >= MAX_TOTAL_PLUGIN_TOOLS { + log::warn!( + "[mcp][plugin-tools] tool limit {MAX_TOTAL_PLUGIN_TOOLS} reached; remaining plugin tools skipped" + ); + break 'providers; + } + entries.push(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(), + injects_connection_id: tool.input_schema.pointer("/properties/connectionId").is_some(), + tool: tool.clone(), + }); + } + } + entries +} + +/// The caller-facing parameter schema: the plugin schema reduced to the same +/// portable subset the AI surface uses, host-bound arguments removed, and an +/// optional connection selector added when the plugin has allowed +/// connections. The selector stays optional: with exactly one connection the +/// host binds it, and connection-less tools work without one. +pub fn external_tool_parameters(input_schema: &Value, connections: &[(String, String)]) -> Value { + let mut schema = sanitize_schema(input_schema, 0); + if schema.get("type").and_then(Value::as_str) != Some("object") { + schema = json!({ "type": "object", "properties": {} }); + } + let object = schema.as_object_mut().expect("object schema"); + let properties = object.entry("properties").or_insert_with(|| json!({})); + if let Some(properties) = properties.as_object_mut() { + for key in HOST_BOUND_ARGUMENTS { + properties.remove(*key); + } + } + let required = object + .get("required") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(Value::as_str) + .filter(|key| !HOST_BOUND_ARGUMENTS.contains(key)) + .map(str::to_string) + .collect::>() + }) + .unwrap_or_default(); + if !required.is_empty() { + object.insert("required".to_string(), json!(required)); + } else { + object.remove("required"); + } + if !connections.is_empty() { + let choices = connections.iter().map(|(id, name)| format!("{id} = {name}")).collect::>().join("; "); + let mut selector = json!({ + "type": "string", + "description": format!( + "DBX connection to run this tool on. Omit to use the only allowed connection. ({choices})" + ), + }); + if connections.len() > 1 { + selector["enum"] = json!(connections.iter().map(|(id, _)| id.clone()).collect::>()); + } + object["properties"][CONNECTION_ARGUMENT] = selector; + } + schema +} + +/// Caller-facing description, attributed to the owning plugin. +pub fn external_tool_description(plugin_name: &str, tool: &RawPluginTool) -> String { + let body = if tool.description.trim().is_empty() { tool.name.as_str() } else { tool.description.as_str() }; + format!("[{plugin_name} plugin] {body}").chars().take(1_500).collect() +} + +/// Resolves the connection binding for one external call. `selector` is the +/// trimmed `dbx_connection` / `connectionId` / `connectionName` value, when +/// the caller supplied one. Matching mirrors the AI surface: exact id first, +/// then an unambiguous name. +pub fn select_connection<'a>( + connections: &'a [(String, String)], + selector: Option<&str>, +) -> Result, String> { + let available = || connections.iter().map(|(id, name)| format!("{id} ({name})")).collect::>().join(", "); + let Some(selector) = selector.filter(|selector| !selector.trim().is_empty()) else { + return match connections { + [only] => Ok(Some(only)), + [] => Ok(None), + _ => Err(format!( + "Pass `{CONNECTION_ARGUMENT}` to choose the connection. Allowed connections: {}", + available() + )), + }; + }; + let requested = selector.trim(); + connections + .iter() + .find(|(id, _)| id == requested) + .or_else(|| { + let mut by_name = connections.iter().filter(|(_, name)| name == requested); + let first = by_name.next(); + // A name is only a valid selector when it is unambiguous. + first.filter(|_| by_name.next().is_none()) + }) + .map(Some) + .ok_or_else(|| { + format!("`{requested}` is not an allowed connection for this tool. Allowed connections: {}", available()) + }) +} + +/// Extracts the connection selector from raw call arguments (without +/// consuming them), preferring the canonical `dbx_connection` key. +pub fn connection_selector_from(arguments: &Value) -> Option<&str> { + CONNECTION_SELECTOR_ARGUMENTS.iter().find_map(|key| arguments.get(*key).and_then(Value::as_str)) +} + +/// Converts a plugin `mcp/call` answer (MCP `CallToolResult`-shaped JSON) +/// into the rmcp wire type, degrading to a plain text payload for plugins +/// that return something else. +pub fn call_result_to_rmcp(value: Value) -> rmcp::model::CallToolResult { + use rmcp::model::{CallToolResult, ContentBlock}; + if let Ok(result) = serde_json::from_value::(value.clone()) { + return result; + } + let text = if value.is_null() { "(the tool returned no output)".to_string() } else { value.to_string() }; + let mut result = CallToolResult::success(vec![ContentBlock::text(text)]); + result.is_error = None; + result +} + +/// The rmcp `Tool` for the external `tools/list` view. +pub fn to_rmcp_tool(entry: &PluginToolEntry, connections: &[(String, String)]) -> rmcp::model::Tool { + let annotations = + entry.tool.annotations.as_object().filter(|annotations| !annotations.is_empty()).and_then(|annotations| { + serde_json::from_value::(Value::Object(annotations.clone())).ok() + }); + let schema = external_tool_parameters(&entry.tool.input_schema, connections); + let mut tool = rmcp::model::Tool::new( + entry.exposed_name.clone(), + external_tool_description(&entry.plugin_name, &entry.tool), + Arc::new(schema.as_object().cloned().unwrap_or_default()), + ); + tool.annotations = annotations; + tool +} + +#[cfg(test)] +mod tests { + use super::*; + use dbx_core::ai::plugin_tools::parse_tool_list; + + fn provider(plugin_id: &str, plugin_name: &str, tools: Value) -> PluginToolProvider { + PluginToolProvider { + plugin_id: plugin_id.to_string(), + plugin_name: plugin_name.to_string(), + tools: parse_tool_list(&tools), + } + } + + fn ssh_listing() -> Value { + json!({ + "tools": [ + { + "name": "sftp_list_dir", + "description": "List a remote directory", + "annotations": { "readOnlyHint": true }, + "inputSchema": { + "type": "object", + "properties": { + "connectionId": { "type": "string" }, + "path": { "type": "string", "description": "Absolute path" } + }, + "required": ["connectionId", "path"] + } + }, + { + "name": "ssh_exec", + "description": "Run a command", + "inputSchema": { "type": "object", "properties": { "command": { "type": "string" } }, "required": ["command"] } + } + ] + }) + } + + #[test] + fn plugin_namespace_cannot_swallow_static_router_names() { + assert!(is_plugin_tool_name("dbx_ssh__sftp_list_dir")); + assert!(is_plugin_tool_name("dbx_ssh__x__y")); + assert!(!is_plugin_tool_name("dbx_list_connections")); + assert!(!is_plugin_tool_name("dbx_ssh_underscore")); + assert!(!is_plugin_tool_name("ssh__sftp_list_dir")); + assert!(!is_plugin_tool_name("dbx____")); + } + + #[test] + fn catalog_exposes_prefixed_names_in_provider_order() { + let providers = vec![ + provider("io.dbx.ssh", "Terminal", ssh_listing()), + provider("io.dbx.files", "Files", json!({ "tools": [{ "name": "files_list", "description": "List" }] })), + ]; + let entries = build_catalog(&providers); + let names = entries.iter().map(|entry| entry.exposed_name.as_str()).collect::>(); + assert_eq!(names, ["dbx_files__files_list", "dbx_ssh__sftp_list_dir", "dbx_ssh__ssh_exec"]); + let sftp = entries.iter().find(|entry| entry.exposed_name == "dbx_ssh__sftp_list_dir").unwrap(); + assert!(sftp.tool.read_only); + assert!(sftp.injects_connection_id, "the plugin schema declares connectionId"); + } + + #[test] + fn catalog_is_plugin_agnostic_and_disambiguates_prefix_clashes() { + // Any plugin id works; the prefix is the id's last segment, extended + // leftward only when two plugins share it — the distinguishing part + // of the id stays in the name instead of an install-order counter. + let providers = vec![ + provider("a.files", "Files A", json!({ "tools": [{ "name": "list", "description": "List" }] })), + provider("b.files", "Files B", json!({ "tools": [{ "name": "list", "description": "List" }] })), + provider("com.vendor.kubernetes", "K8s", json!({ "tools": [{ "name": "apply", "description": "Apply" }] })), + ]; + let entries = build_catalog(&providers); + let names = entries.iter().map(|entry| entry.exposed_name.as_str()).collect::>(); + assert_eq!(names, ["dbx_a_files__list", "dbx_b_files__list", "dbx_kubernetes__apply"]); + } + + #[test] + fn external_schema_strips_host_bound_arguments_and_adds_selector() { + let providers = vec![provider("io.dbx.ssh", "Terminal", ssh_listing())]; + let entries = build_catalog(&providers); + let sftp = entries.iter().find(|entry| entry.exposed_name == "dbx_ssh__sftp_list_dir").unwrap(); + let schema = external_tool_parameters( + &sftp.tool.input_schema, + &[("c1".to_string(), "prod".to_string()), ("c2".to_string(), "test".to_string())], + ); + assert!(schema.pointer("/properties/connectionId").is_none()); + assert_eq!(schema["required"], json!(["path"]), "connectionId leaves the required list"); + assert_eq!(schema["properties"][CONNECTION_ARGUMENT]["enum"], json!(["c1", "c2"])); + + let single = external_tool_parameters(&sftp.tool.input_schema, &[("c1".to_string(), "prod".to_string())]); + assert!(single.pointer(&format!("/properties/{CONNECTION_ARGUMENT}/enum")).is_none()); + assert!(single.pointer(&format!("/properties/{CONNECTION_ARGUMENT}")).is_some()); + + let none = external_tool_parameters(&sftp.tool.input_schema, &[]); + assert!(none.pointer(&format!("/properties/{CONNECTION_ARGUMENT}")).is_none()); + } + + #[test] + fn selector_resolution_mirrors_the_ai_surface() { + let connections = vec![("c1".to_string(), "prod".to_string()), ("c2".to_string(), "test".to_string())]; + // Multiple connections need an explicit selector. + assert!(select_connection(&connections, None).is_err()); + // Exact id, unique name, unknown. + assert_eq!(select_connection(&connections, Some("c2")).unwrap().unwrap().0, "c2"); + assert_eq!(select_connection(&connections, Some("prod")).unwrap().unwrap().0, "c1"); + assert!(select_connection(&connections, Some("c9")).is_err()); + + let single = vec![("c1".to_string(), "prod".to_string())]; + assert_eq!(select_connection(&single, None).unwrap().unwrap().0, "c1"); + let empty: Vec<(String, String)> = Vec::new(); + assert!(select_connection(&empty, None).unwrap().is_none(), "connection-less tools stay callable"); + } + + #[test] + fn selector_extraction_prefers_the_canonical_argument() { + let args = json!({ "connectionId": "k1", "path": "/" }); + assert_eq!(connection_selector_from(&args), Some("k1")); + let canonical = json!({ "dbx_connection": "k2", "connectionId": "k1" }); + assert_eq!(connection_selector_from(&canonical), Some("k2")); + assert_eq!(connection_selector_from(&json!({ "path": "/" })), None); + } + + #[test] + fn call_results_convert_with_a_text_fallback() { + let shaped = call_result_to_rmcp(json!({ + "content": [{ "type": "text", "text": "done" }], + "isError": true + })); + assert_eq!(shaped.content.len(), 1); + assert_eq!(shaped.is_error, Some(true)); + let fallback = call_result_to_rmcp(json!({ "unexpected": "shape" })); + assert_eq!(fallback.content.len(), 1); + assert_eq!(fallback.is_error, None); + } +} diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rs index a6f60fe595..9a845bb6c4 100644 --- a/crates/dbx-mcp/src/server.rs +++ b/crates/dbx-mcp/src/server.rs @@ -63,6 +63,34 @@ pub struct ListDatabasesRequest { pub selector: ConnectionSelector, } +#[derive(Debug, Deserialize, schemars::JsonSchema)] +pub struct PluginListRequest { + #[schemars(description = "Optional case-insensitive keyword matched against plugin ids and names")] + #[schemars(extend("type" = "string"))] + pub filter: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +pub struct PluginToolsRequest { + #[schemars(description = "Unique ID of the plugin, as returned by dbx_plugin_list")] + pub plugin_id: String, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +pub struct PluginCallRequest { + #[schemars(description = "Unique ID of the plugin, as returned by dbx_plugin_list")] + pub plugin_id: String, + #[schemars(description = "Tool name exactly as listed by dbx_plugin_tools")] + pub tool: String, + #[schemars(description = "Tool arguments object, matching the tool schema returned by dbx_plugin_tools")] + pub arguments: Option, + #[schemars( + description = "Optional DBX connection to run the tool on when the plugin has several allowed connections" + )] + #[schemars(extend("type" = "string"))] + pub dbx_connection: Option, +} + #[derive(Debug, Deserialize, schemars::JsonSchema)] pub struct ConnectionSelector { #[schemars(description = "Unique ID of the DBX connection")] @@ -662,11 +690,43 @@ fn bounded_history_response(value: &T) -> String { pub struct DbxMcpServer { backend: Arc, scope: McpScope, + plugin_tools_mode: PluginToolsMode, sessions: Arc, pending_salesforce_writes: Arc, tool_router: ToolRouter, } +/// How plugin tools appear on the external server (`DBX_MCP_PLUGIN_TOOLS`): +/// `flat` lists every plugin tool in `tools/list` (default, compatible), +/// `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] + Flat, + Lazy, + Both, +} + +impl PluginToolsMode { + pub fn from_env() -> 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(), + } + } + + pub fn advertise_flat(&self) -> bool { + matches!(self, Self::Flat | Self::Both) + } + + pub fn advertise_meta(&self) -> bool { + matches!(self, Self::Lazy | Self::Both) + } +} + #[derive(Clone, Debug, Default)] pub struct McpScope { pub connection_ids: Vec, @@ -732,6 +792,17 @@ impl DbxMcpServer { } pub fn with_runtime_options(backend: Arc, scope: McpScope, web_mode: bool) -> Self { + Self::with_plugin_tools_mode(backend, scope, web_mode, PluginToolsMode::from_env()) + } + + /// Same as [`with_runtime_options`], but pins the plugin-tools mode — + /// used by tests so parallel cases cannot observe each other's env. + pub fn with_plugin_tools_mode( + backend: Arc, + scope: McpScope, + web_mode: bool, + plugin_tools_mode: PluginToolsMode, + ) -> Self { // The workspace enables more than one rustls crypto feature through // transitive dependencies. Native MCP runs outside the desktop/web // startup paths, so select the same provider before any TLS tool call. @@ -752,9 +823,18 @@ 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() { + 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: McpSessionStore::new(), pending_salesforce_writes: PendingSalesforceWrites::new(SALESFORCE_WRITE_CONFIRM_TTL), tool_router, @@ -898,6 +978,161 @@ 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." + )] + async fn plugin_list(&self, Parameters(request): Parameters) -> 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, ¬e) { + (Some(_), _) => "No DBX plugin matches the filter.".to_string(), + (None, Some(note)) => note.clone(), + (None, None) => "No DBX plugin contributes MCP tools.".to_string(), + }); + } + text(format!( + "{} plugin(s) contribute MCP tools:\n{}\n\nInspect tools with dbx_plugin_tools (plugin_id), call them with dbx_plugin_call.{}", + lines.len(), + lines.join("\n"), + note.as_ref().map(|note| format!("\n{note}")).unwrap_or_default() + )) + } + + #[tool( + name = "dbx_plugin_tools", + description = "List the MCP tools of one DBX plugin by its plugin id (from dbx_plugin_list). Returns each tool's name, description, arguments schema, read-only hint, and whether a connection must be selected. Call the tool through dbx_plugin_call." + )] + async fn plugin_tools(&self, Parameters(request): Parameters) -> CallToolResult { + if let Err(error) = self.ensure_tool_allowed("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."); + } + let providers = match self.backend.list_plugin_mcp_tools().await { + Ok(providers) => providers, + Err(error) => return backend_tool_error("DBX_TOOL_ERROR", error), + }; + let entries = crate::plugin_tools::build_catalog(&providers); + // Disclose only what the flat surface would advertise: the per-tool + // 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 owned: Vec<&crate::plugin_tools::PluginToolEntry> = entries + .iter() + .filter(|entry| { + entry.plugin_id == plugin_id + && policy.as_ref().is_none_or(|policy| policy_allows_tool(policy, &entry.exposed_name)) + }) + .collect(); + let total = entries.iter().filter(|entry| entry.plugin_id == plugin_id).count(); + let hidden = total - owned.len(); + (owned, hidden) + }; + if owned.is_empty() { + let reason = if hidden > 0 { + format!("All {hidden} tool(s) of plugin \"{plugin_id}\" are hidden by the DBX MCP tool allowlist.") + } else { + format!("Plugin \"{plugin_id}\" does not contribute MCP tools. Use dbx_plugin_list to list plugins.") + }; + return tool_error("PLUGIN_NOT_FOUND", reason); + } + let allowed = match self.allowed_plugin_connections_for(plugin_id).await { + Ok(allowed) => allowed, + Err(error) => return error, + }; + let mut lines = Vec::new(); + for entry in &owned { + let mut line = format!( + "### {}\n{}", + entry.tool.name, + crate::plugin_tools::external_tool_description(&entry.plugin_name, &entry.tool) + ); + if entry.tool.read_only { + line.push_str("\nRead-only."); + } + let schema = crate::plugin_tools::external_tool_parameters(&entry.tool.input_schema, &allowed); + 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() { + 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), + _ => format!( + "Pass dbx_connection to choose among: {}", + allowed.iter().map(|(id, name)| format!("{id} = {name}")).collect::>().join("; ") + ), + }; + let hidden_note = (hidden > 0) + .then(|| format!("\n{} further tool(s) of this plugin are hidden by the DBX MCP tool allowlist.", 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(), + lines.join("\n\n"), + hidden_note.unwrap_or_default() + )) + } + + #[tool( + name = "dbx_plugin_call", + description = "Call one MCP tool of a DBX plugin by plugin id (from dbx_plugin_list) and tool name (from dbx_plugin_tools). The host binds the connection from DBX settings and generates the credentials payload; pass dbx_connection only when dbx_plugin_tools lists several allowed connections." + )] + async fn plugin_call(&self, Parameters(request): Parameters) -> CallToolResult { + if let Err(error) = self.ensure_tool_allowed("dbx_plugin_call").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."); + } + let tool = request.tool.trim(); + if tool.is_empty() { + return tool_error( + "TOOL_NAME_REQUIRED", + "tool is required; use dbx_plugin_tools to list this plugin's tools.", + ); + } + let mut arguments = request.arguments.clone().unwrap_or_else(|| json!({})); + if !arguments.is_object() { + return tool_error("INVALID_ARGUMENTS", "arguments must be a JSON object."); + } + if let Some(selector) = request.dbx_connection.as_deref().map(str::trim).filter(|value| !value.is_empty()) { + if let Some(object) = arguments.as_object_mut() { + object.insert(crate::plugin_tools::PLUGIN_CONNECTION_ARGUMENT.to_string(), json!(selector)); + } + } + let dispatched = match self.call_plugin_by_id(plugin_id, tool, arguments).await { + Ok(result) => result, + Err(error) => return error, + }; + self.postprocess_plugin_result(plugin_id, tool, &request.dbx_connection, dispatched).await + } + #[tool( name = "dbx_list_connections", description = "List database connections configured in DBX. Returns connection IDs, names, group paths, database types, endpoints, and selected databases." @@ -2902,19 +3137,25 @@ impl DbxMcpServer { } /// The advertised `tools/list` view: router-enabled tools narrowed to the - /// global policy's tool allowlist. When the policy cannot be loaded every + /// global policy's tool allowlist, plus the automatically exposed plugin + /// tools (`dbx___`). When the policy cannot be loaded every /// tool call already fails with `MCP_POLICY_UNAVAILABLE`, so fall back to /// the plain router view rather than adding a new failure mode here. - async fn policy_filtered_tools(&self) -> Vec { - match self.load_policy().await { - Ok(policy) => self + pub async fn policy_filtered_tools(&self) -> Vec { + let policy = self.load_policy().await.ok(); + let mut tools: Vec = match &policy { + Some(policy) => self .tool_router .list_all() .into_iter() - .filter(|tool| policy_allows_tool(&policy, tool.name.as_ref())) + .filter(|tool| policy_allows_tool(policy, tool.name.as_ref())) .collect(), - Err(_) => self.tool_router.list_all(), + None => self.tool_router.list_all(), + }; + if self.plugin_tools_mode.advertise_flat() { + tools.extend(self.plugin_tools_view(policy.as_ref()).await); } + tools } // CallToolResult is the rmcp wire response type; keeping it unboxed avoids conversions at every tool boundary. @@ -3064,6 +3305,275 @@ impl DbxMcpServer { _ => Err(tool_error("AMBIGUOUS_CONNECTION", ambiguous_connections(name, &allowed))), } } + /// Saved plugin connections the global MCP policy (and a scoped CLI/AI + /// session) allows, grouped per owning plugin. Used both to decorate the + /// exposed plugin tools with a connection selector and to bind calls. + /// Connections not in the map are unreachable through plugin tools. + #[allow(clippy::result_large_err)] + async fn allowed_plugin_connections( + &self, + ) -> Result>, CallToolResult> { + let policy = self.load_policy().await?; + let group_paths = self + .load_group_paths_for_policy(&policy) + .await + .map_err(|error| backend_tool_error("MCP_POLICY_UNAVAILABLE", error))?; + let connections = + self.backend.load_connections().await.map_err(|error| tool_error("CONNECTION_LOAD_ERROR", error))?; + let mut allowed: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for config in connections { + let Some(plugin_id) = config.plugin_id.as_deref().map(str::trim).filter(|id| !id.is_empty()) else { + continue; + }; + if self.scope.connection_scope_enabled() && !self.scope.matches(&config) { + continue; + } + if !policy_allows_connection(&policy, group_paths.get(&config.id), &config) { + continue; + } + allowed.entry(plugin_id.to_string()).or_default().push((config.id.clone(), config.name.clone())); + } + for list in allowed.values_mut() { + list.sort(); + } + Ok(allowed) + } + + /// The plugin portion of the advertised `tools/list`. Discovery failures + /// degrade to an empty view (the static tools keep working); the global + /// policy's tool allowlist narrows exposed plugin names exactly like the + /// static ones. In a scoped session only plugins with at least one + /// in-scope connection are listed, matching the scoped dbx_* behavior. + async fn plugin_tools_view(&self, policy: Option<&McpGlobalPolicy>) -> Vec { + let providers = match self.backend.list_plugin_mcp_tools().await { + Ok(providers) => providers, + Err(error) => { + log::debug!("[mcp][plugin-tools] no plugin tools on this backend: {error}"); + return Vec::new(); + } + }; + 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(); + 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| { + let connections = allowed.get(&entry.plugin_id).cloned().unwrap_or_default(); + crate::plugin_tools::to_rmcp_tool(&entry, &connections) + }) + .collect() + } + + /// Dispatches a plugin-tool call (`dbx___`): policy check, + /// name resolution over a fresh discovery pass, host-side connection + /// binding from the policy-allowed set, and lifecycle generation from the + /// saved connection in the backend — credentials never reach the caller. + #[allow(clippy::result_large_err)] + pub async fn call_plugin_tool_dispatch( + &self, + name: &str, + mut arguments: serde_json::Value, + ) -> Result { + if let Err(error) = self.ensure_tool_allowed(name).await { + return Ok(error); + } + let providers = match self.backend.list_plugin_mcp_tools().await { + Ok(providers) => providers, + Err(error) => return Ok(backend_tool_error("DBX_TOOL_ERROR", error)), + }; + let entry = crate::plugin_tools::build_catalog(&providers).into_iter().find(|entry| entry.exposed_name == name); + let Some(entry) = entry else { + return Ok(tool_error("TOOL_NOT_FOUND", format!("Plugin tool \"{name}\" is not available."))); + }; + 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 { + object.remove(*key); + } + } + let allowed = match self.allowed_plugin_connections().await { + Ok(allowed) => allowed.get(&entry.plugin_id).cloned().unwrap_or_default(), + Err(error) => return Ok(error), + }; + let bound = match crate::plugin_tools::select_connection(&allowed, selector.as_deref()) { + Ok(bound) => bound.cloned(), + Err(message) => return Ok(tool_error("CONNECTION_NOT_FOUND", message)), + }; + if let Some((connection_id, connection_name)) = &bound { + let _ = CALL_HISTORY.try_with(|history| { + let mut history = history.lock().unwrap(); + history.connection_id.clone_from(connection_id); + history.connection_name.clone_from(connection_name); + }); + } + if entry.injects_connection_id { + if let Some((connection_id, _)) = &bound { + if let Some(object) = arguments.as_object_mut() { + object.insert("connectionId".to_string(), serde_json::Value::String(connection_id.clone())); + } + } + } + match self + .backend + .call_plugin_mcp_tool( + &entry.plugin_id, + &entry.tool.name, + bound.as_ref().map(|(connection_id, _)| connection_id.as_str()), + &arguments, + ) + .await + { + Ok(value) => Ok(crate::plugin_tools::call_result_to_rmcp(value)), + Err(error) => Ok(backend_tool_error("DBX_TOOL_ERROR", error)), + } + } + + /// Loaded plugin-tool catalog for the meta tools: `(plugin id, name, + /// tool count, allowed-connection count)` rows plus an optional note + /// when policy filtering hid plugins. Discovery errors degrade to a + /// note instead of failing `dbx_plugin_list`. + async fn plugin_tool_catalog( + &self, + ) -> Result<(Vec<(String, String, usize, usize)>, Option), CallToolResult> { + let providers = match self.backend.list_plugin_mcp_tools().await { + Ok(providers) => providers, + Err(error) => { + return Ok((Vec::new(), Some(format!("Plugin tools are unavailable: {error}")))); + } + }; + // The catalog computes the real (possibly extended) exposed names, so + // the allowlist check below uses exactly the names a flat tools/list + // would advertise. + let entries = crate::plugin_tools::build_catalog(&providers); + // Listing degrades on policy errors the same way the flat view does; + // `dbx_plugin_tools`/`dbx_plugin_call` still fail closed. + let allowed = self.allowed_plugin_connections().await.unwrap_or_default(); + let policy = self.load_policy().await.ok(); + let mut grouped: std::collections::BTreeMap = Default::default(); + for entry in &entries { + let record = + grouped.entry(entry.plugin_id.clone()).or_insert_with(|| (entry.plugin_name.clone(), 0, false)); + record.1 += 1; + if policy.as_ref().is_none_or(|policy| policy_allows_tool(policy, &entry.exposed_name)) { + record.2 = true; + } + } + let mut rows = Vec::new(); + let mut hidden = 0usize; + for (plugin_id, (plugin_name, tool_count, any_allowed)) in grouped { + if any_allowed { + let connections = allowed.get(&plugin_id).map_or(0, Vec::len); + rows.push((plugin_id, plugin_name, tool_count, connections)); + } else { + hidden += 1; + } + } + let note = (hidden > 0).then(|| format!("{hidden} plugin(s) are hidden by the DBX MCP tool allowlist.")); + Ok((rows, note)) + } + + /// Resolves the policy-allowed connections of one plugin for the meta + /// tools. Fails closed on policy errors (same as flat calls). + async fn allowed_plugin_connections_for(&self, plugin_id: &str) -> Result, CallToolResult> { + let allowed = self.allowed_plugin_connections().await?; + Ok(allowed.get(plugin_id).cloned().unwrap_or_default()) + } + + /// Shared call core for `dbx_plugin_call`: locates the tool by + /// `(plugin_id, tool name)` over a fresh discovery pass, strips + /// selector arguments, binds the connection, and forwards to the + /// backend. Returns the raw plugin answer for the caller to render. + async fn call_plugin_by_id( + &self, + plugin_id: &str, + tool: &str, + mut arguments: serde_json::Value, + ) -> Result { + let providers = match self.backend.list_plugin_mcp_tools().await { + Ok(providers) => providers, + Err(error) => return Err(backend_tool_error("DBX_TOOL_ERROR", error)), + }; + let entry = crate::plugin_tools::build_catalog(&providers) + .into_iter() + .find(|entry| entry.plugin_id == plugin_id && entry.tool.name == tool); + let Some(entry) = entry else { + return Err(tool_error( + "TOOL_NOT_FOUND", + format!( + "Plugin \"{plugin_id}\" does not provide a tool named \"{tool}\". Use dbx_plugin_tools to list this plugin's tools." + ), + )); + }; + // Lazy calls are governed by the same per-tool allowlist as the flat + // surface: gate on the exposed name so an allowlist cannot be bypassed + // by addressing a tool through its plugin id instead. + self.ensure_tool_allowed(&entry.exposed_name).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 { + object.remove(*key); + } + } + let allowed = match self.allowed_plugin_connections().await { + Ok(allowed) => allowed.get(plugin_id).cloned().unwrap_or_default(), + Err(error) => return Err(error), + }; + let bound = match crate::plugin_tools::select_connection(&allowed, selector.as_deref()) { + Ok(bound) => bound.cloned(), + Err(message) => return Err(tool_error("CONNECTION_NOT_FOUND", message)), + }; + if let Some((connection_id, connection_name)) = &bound { + let _ = CALL_HISTORY.try_with(|history| { + let mut history = history.lock().unwrap(); + history.connection_id.clone_from(connection_id); + history.connection_name.clone_from(connection_name); + }); + } + if entry.injects_connection_id { + if let Some((connection_id, _)) = &bound { + if let Some(object) = arguments.as_object_mut() { + object.insert("connectionId".to_string(), serde_json::Value::String(connection_id.clone())); + } + } + } + self.backend + .call_plugin_mcp_tool( + plugin_id, + tool, + bound.as_ref().map(|(connection_id, _)| connection_id.as_str()), + &arguments, + ) + .await + .map_err(|error| backend_tool_error("DBX_TOOL_ERROR", error)) + } + + /// Renders a `dbx_plugin_call` answer: converts the plugin result, + /// appends a connection hint when the caller must pick one explicitly. + async fn postprocess_plugin_result( + &self, + plugin_id: &str, + tool: &str, + requested_selector: &Option, + value: serde_json::Value, + ) -> CallToolResult { + let mut result = crate::plugin_tools::call_result_to_rmcp(value); + if requested_selector.is_none() { + if let Ok(allowed) = self.allowed_plugin_connections_for(plugin_id).await { + if allowed.len() > 1 { + let choices = + allowed.iter().map(|(id, name)| format!("{id} = {name}")).collect::>().join("; "); + let hint = format!( + "\n[This plugin has several allowed connections; pass dbx_connection to choose: {choices}]" + ); + result.content.push(rmcp::model::ContentBlock::text(hint)); + } + } + } + let _ = (plugin_id, tool); + result + } } #[tool_handler(router = self.tool_router)] @@ -3099,12 +3609,21 @@ impl ServerHandler for DbxMcpServer { mcp_session_id: args.get("session_id").and_then(|v| v.as_str()).map(str::to_owned), }; let mut guard = CallHistoryGuard { backend: self.backend.clone(), fallback: Some(entry.clone()), started }; + let tool_name = request.name.to_string(); + let is_plugin_tool = crate::plugin_tools::is_plugin_tool_name(&tool_name); CALL_HISTORY.scope(std::sync::Mutex::new(entry), async { let cancellation = context.ct.clone(); - let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context); - let result = tokio::select! { - result = self.tool_router.call(tcc) => result, - _ = cancellation.cancelled() => Ok(tool_error("REQUEST_CANCELLED", "The MCP request was cancelled.")), + let result = if is_plugin_tool { + tokio::select! { + result = self.call_plugin_tool_dispatch(&tool_name, args) => result, + _ = cancellation.cancelled() => Ok(tool_error("REQUEST_CANCELLED", "The MCP request was cancelled.")), + } + } else { + let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context); + tokio::select! { + result = self.tool_router.call(tcc) => result, + _ = cancellation.cancelled() => Ok(tool_error("REQUEST_CANCELLED", "The MCP request was cancelled.")), + } }; let mut entry = CALL_HISTORY.with(|entry| entry.lock().unwrap().clone()); entry.execution_time_ms = started.elapsed().as_millis(); @@ -4639,6 +5158,8 @@ mod tests { } } + type RecordedPluginToolCalls = std::sync::Mutex, serde_json::Value)>>; + struct FakeBackend { connections: Vec, policy: McpGlobalPolicy, @@ -4657,6 +5178,8 @@ mod tests { transaction_open_error: Option, policy_override: std::sync::Mutex>, salesforce_identity: Option, + plugin_providers: Vec, + plugin_tool_calls: RecordedPluginToolCalls, } impl Default for FakeBackend { @@ -4679,6 +5202,8 @@ mod tests { transaction_open_error: None, policy_override: std::sync::Mutex::new(None), salesforce_identity: None, + plugin_providers: Vec::new(), + plugin_tool_calls: std::sync::Mutex::new(Vec::new()), } } } @@ -4733,6 +5258,29 @@ mod tests { Ok(self.connections.clone()) } + async fn list_plugin_mcp_tools(&self) -> Result, String> { + Ok(self.plugin_providers.clone()) + } + + async fn call_plugin_mcp_tool( + &self, + plugin_id: &str, + tool: &str, + connection_id: Option<&str>, + arguments: &serde_json::Value, + ) -> Result { + self.plugin_tool_calls.lock().unwrap().push(( + plugin_id.to_string(), + tool.to_string(), + connection_id.map(str::to_string), + arguments.clone(), + )); + Ok(serde_json::json!({ + "content": [{ "type": "text", "text": format!("{plugin_id}/{tool} ok") }], + "isError": false + })) + } + async fn open_transaction_owner( &self, _connection: &ConnectionConfig, @@ -4959,6 +5507,361 @@ mod tests { } } + fn plugin_connection(id: &str, name: &str, plugin_id: &str) -> ConnectionConfig { + serde_json::from_value(json!({ + "id": id, + "name": name, + "db_type": "plugin", + "plugin_id": plugin_id, + "host": "", + "port": 0, + "username": "", + "password": "" + })) + .unwrap() + } + + fn plugin_provider( + plugin_id: &str, + plugin_name: &str, + tools: serde_json::Value, + ) -> crate::plugin_tools::PluginToolProvider { + crate::plugin_tools::PluginToolProvider { + plugin_id: plugin_id.to_string(), + plugin_name: plugin_name.to_string(), + tools: dbx_core::ai::plugin_tools::parse_tool_list(&tools), + } + } + + fn kafka_plugin_listing() -> serde_json::Value { + json!({ + "tools": [ + { + "name": "kafka_topics_delete", + "description": "Delete topics", + "inputSchema": { + "type": "object", + "properties": { + "connectionId": { "type": "string" }, + "topics": { "type": "array", "items": { "type": "string" } } + }, + "required": ["connectionId", "topics"] + } + }, + { + "name": "kafka_topics_list", + "description": "List topics", + "annotations": { "readOnlyHint": true }, + "inputSchema": { + "type": "object", + "properties": { "connectionId": { "type": "string" } } + } + } + ] + }) + } + + #[tokio::test] + async fn plugin_tools_merge_into_tools_list_with_connection_selector() { + let backend = Arc::new(FakeBackend { + connections: vec![ + plugin_connection("k1", "prod", "io.dbx.kafka"), + plugin_connection("k2", "test", "io.dbx.kafka"), + plugin_connection("s1", "shell", "io.dbx.ssh"), + ], + 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 tools = server.policy_filtered_tools().await; + assert!(tools.iter().any(|tool| tool.name.as_ref() == "dbx_list_connections"), "static tools remain"); + let delete = tools + .iter() + .find(|tool| tool.name.as_ref() == "dbx_kafka__kafka_topics_delete") + .expect("plugin tool listed"); + let properties = delete.input_schema.get("properties").expect("object schema"); + let selector = properties.get("dbx_connection").expect("selector present for multiple connections"); + assert_eq!(selector["enum"], json!(["k1", "k2"])); + assert!(properties.get("connectionId").is_none(), "host-bound argument stays out of the advertised schema"); + let list = tools.iter().find(|tool| tool.name.as_ref() == "dbx_kafka__kafka_topics_list").unwrap(); + assert!(list.annotations.as_ref().and_then(|a| a.read_only_hint).expect("readOnlyHint passthrough")); + } + + #[tokio::test] + async fn plugin_meta_tools_discover_and_call_by_plugin_id() { + let backend = Arc::new(FakeBackend { + connections: vec![ + plugin_connection("k1", "prod", "io.dbx.kafka"), + plugin_connection("k2", "test", "io.dbx.kafka"), + ], + plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())], + ..Default::default() + }); + let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false); + + // dbx_plugin_list: one row, id + counts. + let list = server.plugin_list(Parameters(PluginListRequest { filter: None })).await; + assert_eq!(list.is_error, Some(false)); + let text = result_text(&list); + assert!(text.contains("io.dbx.kafka"), "{text}"); + assert!(text.contains("2 tool(s)") && text.contains("2 allowed connection(s)"), "{text}"); + + // dbx_plugin_list with a filter that matches nothing. + let none = server.plugin_list(Parameters(PluginListRequest { filter: Some("postgres".into()) })).await; + assert!(result_text(&none).contains("No DBX plugin matches"), "{}", result_text(&none)); + + // dbx_plugin_tools: per-plugin schemas with the connection selector note. + let tools = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.kafka".into() })).await; + assert_eq!(tools.is_error, Some(false)); + let text = result_text(&tools); + assert!(text.contains("kafka_topics_delete") && text.contains("kafka_topics_list"), "{text}"); + assert!(text.contains("dbx_connection"), "multi-connection hint expected: {text}"); + + // Unknown plugin id fails with a discovery pointer. + let unknown = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.nope".into() })).await; + assert_eq!(unknown.is_error, Some(true)); + assert!(result_text(&unknown).contains("does not contribute MCP tools"), "{}", result_text(&unknown)); + + // dbx_plugin_call routes by plugin id + tool name; selector stripped. + let call = server + .plugin_call(Parameters(PluginCallRequest { + plugin_id: "io.dbx.kafka".into(), + tool: "kafka_topics_delete".into(), + arguments: Some(json!({ "topics": ["t"], "dbx_connection": "k2" })), + dbx_connection: None, + })) + .await; + assert_eq!(call.is_error, Some(false), "{}", result_text(&call)); + { + let calls = backend.plugin_tool_calls.lock().unwrap(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].0, "io.dbx.kafka"); + assert_eq!(calls[0].1, "kafka_topics_delete"); + assert_eq!(calls[0].2.as_deref(), Some("k2")); + } + + // Unknown tool under a known plugin id. + let unknown_tool = server + .plugin_call(Parameters(PluginCallRequest { + plugin_id: "io.dbx.kafka".into(), + tool: "nope".into(), + arguments: None, + dbx_connection: None, + })) + .await; + assert_eq!(unknown_tool.is_error, Some(true)); + assert!(result_text(&unknown_tool).contains("does not provide a tool named"), "{}", result_text(&unknown_tool)); + } + + #[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() + }); + let server = DbxMcpServer::with_runtime_options(restricted, McpScope::default(), false); + // call/tools 被白名单拒绝。 + let call = server + .plugin_call(Parameters(PluginCallRequest { + plugin_id: "io.dbx.kafka".into(), + tool: "kafka_topics_list".into(), + arguments: None, + dbx_connection: None, + })) + .await; + assert_eq!(call.is_error, Some(true)); + assert!(result_text(&call).contains("TOOL_OUT_OF_SCOPE"), "{}", result_text(&call)); + // list 仍在白名单内,可列出。 + let list = server.plugin_list(Parameters(PluginListRequest { filter: None })).await; + assert_eq!(list.is_error, Some(false), "{}", result_text(&list)); + } + + #[tokio::test] + async fn plugin_tools_listing_is_filtered_by_the_flat_allowlist() { + // dbx_plugin_tools must disclose only what the flat surface would: + // denied tools stay hidden (with a count note) even though calls are + // gated separately. + let restricted = Arc::new(FakeBackend { + policy: McpGlobalPolicy { + allowed_tool_names: Some(vec![ + "dbx_plugin_tools".to_string(), + "dbx_kafka__kafka_topics_list".to_string(), + ]), + ..Default::default() + }, + plugin_providers: vec![ + plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing()), + plugin_provider( + "io.dbx.ssh", + "Terminal", + json!({ "tools": [{ "name": "ssh_exec", "description": "Run a command" }] }), + ), + ], + ..Default::default() + }); + let server = DbxMcpServer::with_runtime_options(restricted, McpScope::default(), false); + let listing = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.kafka".into() })).await; + assert_eq!(listing.is_error, Some(false)); + let text = result_text(&listing); + assert!(text.contains("kafka_topics_list"), "{text}"); + assert!(!text.contains("kafka_topics_delete"), "denied tool must be hidden: {text}"); + assert!(text.contains("1 further tool(s)"), "{text}"); + + let all_hidden = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.dbx.ssh".into() })).await; + assert_eq!(all_hidden.is_error, Some(true)); + assert!(result_text(&all_hidden).contains("All 1 tool(s)"), "{}", result_text(&all_hidden)); + + // A plugin whose every tool is denied resolves to the hidden reason. + // Unknown plugin ids (never installed) keep the plain not-found text. + let unknown = server.plugin_tools(Parameters(PluginToolsRequest { plugin_id: "io.nope".into() })).await; + assert_eq!(unknown.is_error, Some(true)); + assert!(result_text(&unknown).contains("does not contribute MCP tools"), "{}", result_text(&unknown)); + } + + #[tokio::test] + async fn plugin_call_is_gated_by_the_flat_tool_allowlist() { + // The meta tool itself is allowed, but the flat name of the targeted + // plugin tool is not: lazy access must not bypass the allowlist. + let restricted = Arc::new(FakeBackend { + policy: McpGlobalPolicy { + allowed_tool_names: Some(vec![ + "dbx_plugin_call".to_string(), + "dbx_kafka__kafka_topics_list".to_string(), + ]), + ..Default::default() + }, + connections: vec![plugin_connection("k1", "prod", "io.dbx.kafka")], + plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())], + ..Default::default() + }); + let server = DbxMcpServer::with_runtime_options(restricted.clone(), McpScope::default(), false); + + let denied = server + .plugin_call(Parameters(PluginCallRequest { + plugin_id: "io.dbx.kafka".into(), + tool: "kafka_topics_delete".into(), + arguments: None, + dbx_connection: None, + })) + .await; + assert_eq!(denied.is_error, Some(true)); + assert!(result_text(&denied).contains("TOOL_OUT_OF_SCOPE"), "{}", result_text(&denied)); + assert!(restricted.plugin_tool_calls.lock().unwrap().is_empty(), "the backend must not be reached"); + + let allowed = server + .plugin_call(Parameters(PluginCallRequest { + plugin_id: "io.dbx.kafka".into(), + tool: "kafka_topics_list".into(), + arguments: None, + dbx_connection: None, + })) + .await; + assert_eq!(allowed.is_error, Some(false), "{}", result_text(&allowed)); + assert_eq!(restricted.plugin_tool_calls.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn plugin_tools_mode_switches_advertised_views() { + // default(flat):router 禁用 meta 路由。 + 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_"))); + // lazy 模式:保留 meta 路由(mode 注入,避免并行测试间的环境变量竞态)。 + let lazy = DbxMcpServer::with_plugin_tools_mode( + Arc::new(FakeBackend::default()), + McpScope::default(), + false, + PluginToolsMode::Lazy, + ); + let binding = lazy.tool_router.list_all(); + let names: Vec<&str> = binding.iter().map(|tool| tool.name.as_ref()).collect(); + for expected in ["dbx_plugin_list", "dbx_plugin_tools", "dbx_plugin_call"] { + assert!(names.contains(&expected), "{expected} missing in {names:?}"); + } + } + + #[tokio::test] + async fn plugin_tool_calls_bind_connections_and_respect_policy() { + let backend = Arc::new(FakeBackend { + connections: vec![ + plugin_connection("k1", "prod", "io.dbx.kafka"), + plugin_connection("k2", "test", "io.dbx.kafka"), + plugin_connection("s1", "shell", "io.dbx.ssh"), + ], + plugin_providers: vec![plugin_provider("io.dbx.kafka", "Kafka Studio", kafka_plugin_listing())], + ..Default::default() + }); + let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false); + + // Several connections: a missing selector is an error that names the argument. + let missing = server + .call_plugin_tool_dispatch("dbx_kafka__kafka_topics_delete", json!({ "topics": ["t"] })) + .await + .unwrap(); + assert_eq!(missing.is_error, Some(true)); + assert!(result_text(&missing).contains("dbx_connection"), "{}", result_text(&missing)); + + // A selector pointing at another plugin's connection is rejected. + let cross = server + .call_plugin_tool_dispatch( + "dbx_kafka__kafka_topics_delete", + json!({ "topics": ["t"], "dbx_connection": "s1" }), + ) + .await + .unwrap(); + assert_eq!(cross.is_error, Some(true)); + assert!(result_text(&cross).contains("not an allowed connection"), "{}", result_text(&cross)); + + // An explicit selector binds host-side; selector keys are stripped and + // the plugin's declared connectionId is injected. + let ok = server + .call_plugin_tool_dispatch( + "dbx_kafka__kafka_topics_delete", + json!({ "topics": ["t"], "dbx_connection": "k2" }), + ) + .await + .unwrap(); + assert_eq!(ok.is_error, Some(false), "{}", result_text(&ok)); + { + let calls = backend.plugin_tool_calls.lock().unwrap(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].0, "io.dbx.kafka"); + assert_eq!(calls[0].1, "kafka_topics_delete"); + assert_eq!(calls[0].2.as_deref(), Some("k2")); + assert_eq!(calls[0].3["connectionId"], "k2"); + assert!(calls[0].3.get("dbx_connection").is_none()); + } + + // Unknown plugin namespace name fails cleanly. + let unknown = server.call_plugin_tool_dispatch("dbx_kafka__nope", json!({})).await.unwrap(); + assert!(result_text(&unknown).contains("not available"), "{}", result_text(&unknown)); + + // The global policy tool allowlist applies to exposed plugin names. + let restricted = Arc::new(FakeBackend { + policy: McpGlobalPolicy { + allowed_tool_names: Some(vec!["dbx_list_connections".to_string()]), + ..Default::default() + }, + connections: backend.connections.clone(), + plugin_providers: backend.plugin_providers.clone(), + ..Default::default() + }); + let server = DbxMcpServer::with_runtime_options(restricted, McpScope::default(), false); + let blocked = server + .call_plugin_tool_dispatch("dbx_kafka__kafka_topics_delete", json!({ "topics": ["t"] })) + .await + .unwrap(); + assert_eq!(blocked.is_error, Some(true)); + assert!(result_text(&blocked).contains("TOOL_OUT_OF_SCOPE"), "{}", result_text(&blocked)); + let tools = server.policy_filtered_tools().await; + assert!(!tools.iter().any(|tool| tool.name.as_ref() == "dbx_kafka__kafka_topics_delete")); + } + #[cfg(feature = "mq-admin")] #[tokio::test] async fn peek_messages_rejects_invalid_options_before_backend_call() { diff --git a/crates/dbx-mcp/tests/plugin_tools_server.rs b/crates/dbx-mcp/tests/plugin_tools_server.rs new file mode 100644 index 0000000000..132737e170 --- /dev/null +++ b/crates/dbx-mcp/tests/plugin_tools_server.rs @@ -0,0 +1,66 @@ +//! 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. +//! +//! The mechanism under test is plugin-agnostic; the ssh plugin is only the +//! concrete vehicle available here (mirroring `plugin_tools_bridge.rs`). +//! Set DBX_SSH_PACKAGE to a packaged `io.dbx.ssh` artifact; the test skips +//! itself otherwise. + +use dbx_core::plugins::{PluginInstallPolicy, PluginPackageInstaller}; +use dbx_mcp::{DbxMcpServer, LocalBackend, McpScope}; + +#[tokio::test] +async fn ssh_package_tools_are_detected_listed_and_dispatched() { + let Ok(package) = std::env::var("DBX_SSH_PACKAGE") else { + eprintln!("skipping: DBX_SSH_PACKAGE is not set"); + return; + }; + let package = std::path::PathBuf::from(package); + assert!(package.is_file(), "package missing: {}", package.display()); + + let data_dir = tempfile::tempdir().unwrap(); + let plugins_root = data_dir.path().join("plugins"); + let installer = PluginPackageInstaller::new(plugins_root.clone(), "0.7.0").expect("installer"); + let result = installer.install_file(&package, PluginInstallPolicy::LocalDevelopment).expect("install .dbxp"); + assert_eq!(result.response().plugin.manifest.id, "io.dbx.ssh"); + + let database_path = data_dir.path().join("dbx.db"); + let storage = dbx_core::storage::Storage::open(&database_path).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(); + + // 1. Opt-in-filtered discovery over the real sidecar. + let providers = backend.detect_plugin_tool_providers().await.expect("detect plugin tools"); + let ssh = providers.iter().find(|provider| provider.plugin_id == "io.dbx.ssh").expect("ssh detected"); + assert!( + ssh.tools.iter().any(|tool| tool.name == "ssh_list_known_hosts"), + "expected ssh_list_known_hosts in {:?}", + ssh.tools.iter().map(|tool| tool.name.as_str()).collect::>() + ); + + // 2. The server merges the detected tools into tools/list under the + // shared dbx___ namespace. + let backend = std::sync::Arc::new(backend); + let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false); + let tools = server.policy_filtered_tools().await; + let exposed = "dbx_ssh__ssh_list_known_hosts"; + let tool = tools.iter().find(|tool| tool.name.as_ref() == exposed).expect("plugin tool merged into tools/list"); + assert!( + tool.input_schema + .get("properties") + .map(|properties| properties.get("dbx_connection")) + .unwrap_or(None) + .is_none(), + "no saved connections, so no connection selector is advertised" + ); + + // 3. Dispatch a real call through the host-bound path. + let result = server.call_plugin_tool_dispatch(exposed, serde_json::json!({})).await.expect("dispatch ok"); + assert_ne!(result.is_error, Some(true), "tool failed: {result:?}"); + let text = result.content[0].as_text().expect("text result").text.as_str(); + let parsed: serde_json::Value = serde_json::from_str(text).expect("result JSON"); + assert!(parsed["knownHosts"].is_array(), "unexpected result: {parsed}"); +} diff --git a/crates/dbx-plugin-runtime/src/plugins/manifest.rs b/crates/dbx-plugin-runtime/src/plugins/manifest.rs index 4939f52177..ba7d672790 100644 --- a/crates/dbx-plugin-runtime/src/plugins/manifest.rs +++ b/crates/dbx-plugin-runtime/src/plugins/manifest.rs @@ -250,6 +250,7 @@ pub enum PluginContribution { ResultView(PluginResultViewContribution), Command(PluginCommandContribution), Menus(PluginMenusContribution), + Mcp(PluginMcpContribution), } impl PluginContribution { @@ -262,10 +263,46 @@ impl PluginContribution { Self::ResultView(contribution) => &contribution.id, Self::Command(contribution) => &contribution.id, Self::Menus(contribution) => &contribution.id, + Self::Mcp(contribution) => &contribution.id, } } } +/// Optional surface override for a sidecar that implements the MCP tool +/// bridge (`mcp/tools` + `mcp/call`, see `plugins/README.md` "Tools for the +/// built-in AI assistant"). +/// +/// Neither surface is exposed by install alone: the built-in AI agent only +/// sees a plugin after the user enabled it in the Plugin Center, and the +/// external `dbx` MCP server only sees plugins that declare +/// `external_tools: true` here. This contribution narrows or widens those +/// surfaces per author: `ai_tools: false` keeps the tools off the built-in AI +/// agent even when the user opts in, and `external_tools` (default `false`) +/// opts the tools into the external `dbx` MCP server. The Plugin Center +/// switch and the global MCP policy still override either surface per user. +/// Note that declaring this contribution makes the manifest unreadable to +/// hosts that predate it, so plugins that must install on older hosts should +/// not declare it. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PluginMcpContribution { + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Keep the tools on the built-in AI agent. Defaults to `true`; set to + /// `false` to keep them off that surface even when the user opts in. + #[serde(default = "default_true", skip_serializing_if = "is_true")] + pub ai_tools: bool, + /// Expose the tools on the external `dbx` MCP server. Defaults to + /// `false`; set to `true` to opt in to that surface. + #[serde(default, skip_serializing_if = "is_false")] + pub external_tools: bool, +} + +fn default_true() -> bool { + true +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PluginFormFieldDefinition { @@ -995,6 +1032,29 @@ impl PluginManifest { })) } + /// The plugin's single MCP tool declaration, if any. A manifest declaring + /// more than one is rejected during validation, so first match is exact. + pub fn mcp_contribution(&self) -> Option<&PluginMcpContribution> { + self.contributions.iter().find_map(|contribution| match contribution { + PluginContribution::Mcp(mcp) => Some(mcp), + _ => None, + }) + } + + /// 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. + pub fn ai_tools_excluded(&self) -> bool { + self.mcp_contribution().is_some_and(|mcp| !mcp.ai_tools) + } + + /// Whether the optional `mcp` declaration does not opt the sidecar tools + /// into the external `dbx` MCP server. `external_tools` defaults to + /// `false`, so only an explicit `true` exposes them there. + pub fn external_tools_excluded(&self) -> bool { + self.mcp_contribution().is_some_and(|mcp| !mcp.external_tools) + } + pub fn compatibility(&self, plugin_dir: &Path, dbx_version: &str) -> PluginCompatibility { let mut errors = Vec::new(); let mut warnings = Vec::new(); @@ -1276,6 +1336,7 @@ fn validate_contributions( let mut command_ids = HashSet::new(); let mut command_workbench_references = Vec::new(); let mut menu_command_references = Vec::new(); + let mut mcp_contributions = 0usize; for (index, contribution) in contributions.iter().enumerate() { let id = contribution.id(); @@ -1481,9 +1542,23 @@ fn validate_contributions( menu_command_references.push((id.to_string(), item.command.clone())); } } + PluginContribution::Mcp(mcp) => { + mcp_contributions += 1; + validate_optional_text( + mcp.description.as_deref(), + &format!("Mcp contribution '{id}' description"), + errors, + ); + if !has_backend { + errors.push(format!("Mcp contribution '{id}' requires a backend entrypoint")); + } + } } } + if mcp_contributions > 1 { + errors.push(format!("A manifest declares {mcp_contributions} mcp contributions; at most one is allowed")); + } for (provider, workbench) in workbench_references { if !workbench_ids.contains(&workbench) { errors.push(format!("Connection provider '{provider}' references missing workbench '{workbench}'")); @@ -1963,8 +2038,8 @@ mod tests { parse_host_network_permission, resolve_safe_plugin_path, validate_connection_actions, validate_contributions, PluginCommandAction, PluginCommandContribution, PluginCommandPresentation, PluginCommandRestore, PluginCommandReuse, PluginConnectionActionContribution, PluginConnectionProviderContribution, - PluginContribution, PluginFormFieldBinding, PluginManifest, PluginMenuItem, PluginMenuLocation, - PluginMenusContribution, PluginOpenWorkbenchAction, SUPPORTED_PLUGIN_HOST_API_VERSION, + PluginContribution, PluginFormFieldBinding, PluginManifest, PluginMcpContribution, PluginMenuItem, + PluginMenuLocation, PluginMenusContribution, PluginOpenWorkbenchAction, SUPPORTED_PLUGIN_HOST_API_VERSION, SUPPORTED_PLUGIN_PERMISSIONS, }; @@ -1992,6 +2067,85 @@ mod tests { Ok((dir, manifest)) } + #[test] + fn mcp_contribution_parses_the_frozen_contract() { + // Defaults: the built-in AI surface participates (subject to the + // Plugin Center opt-in), the external `dbx` server does not. + let mcp: PluginContribution = serde_json::from_value(serde_json::json!({ + "type": "mcp", + "id": "io.dbx.example.mcp" + })) + .unwrap(); + let PluginContribution::Mcp(mcp) = mcp else { unreachable!("parsed as mcp above") }; + assert!(mcp.ai_tools); + assert!(!mcp.external_tools); + + let widened: PluginContribution = serde_json::from_value(serde_json::json!({ + "type": "mcp", + "id": "io.dbx.example.mcp", + "external_tools": true + })) + .unwrap(); + let PluginContribution::Mcp(widened) = widened else { unreachable!() }; + assert!(widened.ai_tools); + assert!(widened.external_tools); + + // Unknown fields inside the contribution reject (frozen contract). + assert!(serde_json::from_value::(serde_json::json!({ + "type": "mcp", "id": "x", "entrypoint": "bin/example" + })) + .is_err()); + } + + #[test] + fn mcp_contribution_requires_a_backend_and_stays_single() { + let plugin_dir = std::env::temp_dir(); + let mcp = PluginContribution::Mcp(PluginMcpContribution { + id: "io.dbx.example.mcp".to_string(), + description: None, + ai_tools: true, + external_tools: true, + }); + let mut errors = Vec::new(); + validate_contributions(std::slice::from_ref(&mcp), false, false, &plugin_dir, &mut errors); + assert!(errors.iter().any(|error| error.contains("requires a backend entrypoint")), "{errors:?}"); + + let mut errors = Vec::new(); + validate_contributions(std::slice::from_ref(&mcp), 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 full_manifest_parses_the_mcp_declaration() { + let dir = tempfile::tempdir().unwrap(); + let binary_dir = dir.path().join("bin"); + std::fs::create_dir_all(&binary_dir).unwrap(); + std::fs::write(binary_dir.join("example"), b"example").unwrap(); + let manifest: PluginManifest = serde_json::from_value(serde_json::json!({ + "manifest_version": 1, + "id": "io.dbx.example", + "name": "Example", + "version": "1.0.0", + "publisher": "example", + "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" }, + "entrypoints": { "backend": { "executable": "bin/example" } }, + "contributions": [{ + "type": "mcp", + "id": "io.dbx.example.mcp" + }] + })) + .unwrap(); + 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); + } + #[test] fn command_and_menus_contributions_parse_the_frozen_contract() { let command: PluginContribution = serde_json::from_value(serde_json::json!({ @@ -2603,6 +2757,7 @@ mod tests { ("result-view", "resultViewContribution"), ("command", "commandContribution"), ("menus", "menusContribution"), + ("mcp", "mcpContribution"), ]; assert_eq!(referenced, kinds.iter().map(|(_, def)| def.to_string()).collect::>()); for (tag, def) in kinds { diff --git a/crates/dbx-web/src/routes/ai.rs b/crates/dbx-web/src/routes/ai.rs index 93fc67f777..4b70f19645 100644 --- a/crates/dbx-web/src/routes/ai.rs +++ b/crates/dbx-web/src/routes/ai.rs @@ -370,7 +370,10 @@ pub async fn ai_resolve_tool_approval(Json(body): Json>) -> Result>, AppError> { - Ok(Json(state.app.storage.load_ai_plugin_tool_plugin_ids().await.map_err(AppError::from)?)) + let mut ids = + dbx_core::ai::plugin_tools::effective_ai_tool_plugin_ids(&state.app).await.into_iter().collect::>(); + ids.sort(); + Ok(Json(ids)) } pub async fn set_ai_plugin_tool_plugin_enabled( diff --git a/docs/content/docs/ai-assistant.cn.mdx b/docs/content/docs/ai-assistant.cn.mdx index 418c972f8e..9e701ae264 100644 --- a/docs/content/docs/ai-assistant.cn.mdx +++ b/docs/content/docs/ai-assistant.cn.mdx @@ -127,13 +127,13 @@ Desktop 可以把只读的 [`SKILL.md`](https://developers.openai.com/codex/skil 使用 API 供应商的 Agent 模式下,助手还可以调用已安装插件提供的工具——例如通过 SSH 执行命令、读取容器日志、查看 Kafka 消费延迟——并与数据库工具结合起来回答同一个问题。 -1. 打开「插件中心 → 已安装」,选中插件,开启 **内置 AI 工具**。点击 **查看工具** 可以看到助手能用哪些工具,以及哪些需要确认。 +1. 插件工具按插件显式开启:打开「插件中心 → 已安装」选中插件,开启 **内置 AI 工具** 开关后助手才能调用其工具;点击 **查看工具** 可以看到助手能用哪些工具、以及哪些需要确认;关闭开关即可排除某插件(选择会持久保留)。 2. 打开助手要使用的插件连接(例如那台 SSH 服务器)。工具只会作用于已打开的连接。 3. 在 Agent 模式下提问。插件声明为只读的工具会直接执行;其他调用会暂停运行,并展示完整参数,由你选择 **允许本次** 或 **拒绝**。五分钟未响应视为拒绝,点击停止会取消等待中的请求。 绑定插件连接时,输入框显示插件图标,并隐藏数据库和 Schema 选择器。AI 不再加载数据库表结构,Agent 模式仅保留时间工具与已启用的插件工具。关闭插件的内置 AI 工具开关,也会阻止正在进行的会话继续调用该插件。 -工具输出会像查询结果一样发送给你配置的 AI 模型;不希望数据发给模型的插件,请保持该开关关闭。CLI Agent 供应商不会获得插件工具。 +工具输出会像查询结果一样发送给你配置的 AI 模型;不希望数据发给模型的插件,请关闭其 **内置 AI 工具** 开关。CLI Agent 供应商不会获得插件工具。 ## 写入和生产安全 diff --git a/docs/content/docs/ai-assistant.mdx b/docs/content/docs/ai-assistant.mdx index 626e5a5913..b14bae91d4 100644 --- a/docs/content/docs/ai-assistant.mdx +++ b/docs/content/docs/ai-assistant.mdx @@ -129,13 +129,13 @@ Skill bodies are read only when a request is sent, directly from disk, and valid In Agent mode with an API provider, the assistant can also call tools contributed by installed plugins — for example run a command over SSH, read container logs, or inspect Kafka consumer lag — and combine them with database tools in one answer. -1. Open Plugin Center → Installed, select the plugin, and turn on **Built-in AI tools**. **Show tools** lists what the assistant would get and which tools need approval. +1. Plugin tools are opt-in per plugin: open Plugin Center → Installed, select the plugin, and turn on the **Built-in AI tools** switch — until then the assistant cannot call the plugin's tools. Use **Show tools** to list what the assistant would get and which tools need approval. Switch it off to exclude a plugin (the choice persists). 2. Open the plugin connection the assistant should use (for example the SSH server). Tools only run against connections that are open. 3. Ask in Agent mode. Tools the plugin declares read-only run directly; any other call pauses the run and shows the exact arguments with **Allow once** / **Deny**. Unanswered requests are denied after five minutes, and Stop cancels a pending request. When bound to a plugin connection, the assistant shows the plugin logo and hides the database/schema selectors. It skips database metadata loading and offers only the time utility and enabled plugin tools in Agent mode. -Tool output is sent to your AI model like query results. Leave the switch off for plugins whose data should not reach the model. Turning it off also blocks subsequent calls from a run already in progress. CLI agent providers do not receive plugin tools. +Tool output is sent to your AI model like query results. Turn the **Built-in AI tools** switch off for plugins whose data should not reach the model. Turning it off also blocks subsequent calls from a run already in progress. CLI agent providers do not receive plugin tools. ## Writes and Production Safety diff --git a/docs/content/docs/mcp.cn.mdx b/docs/content/docs/mcp.cn.mdx index 805a6bf6af..7ad1f02261 100644 --- a/docs/content/docs/mcp.cn.mdx +++ b/docs/content/docs/mcp.cn.mdx @@ -152,6 +152,20 @@ DBX MCP 当前提供以下工具(具体可用工具取决于构建功能及权 启用连接作用域后,修改连接和桌面 UI 工具会被隐藏。 +## 插件工具 + +实现了 `mcp/tools` 桥接协议的 DBX 插件 sidecar,其工具可由 `dbx` MCP 服务器合并进 `tools/list`,无需在客户端逐个配置插件的 `--mcp` 进程。该机制按作者声明加入:只有 manifest 中声明了 `mcp` 贡献且 `external_tools: true` 的插件(SSH、Files、Kafka、LDAP 等均可)才会暴露工具: + +- 工具名为 `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_<前缀>__<工具名>` 逐个加入白名单(或清空白名单以全部放行); +- 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`。 + ## Resources 支持 MCP Resources 的客户端可以读取连接目录,并通过模板获取数据库元数据: diff --git a/docs/content/docs/mcp.mdx b/docs/content/docs/mcp.mdx index b6dcd1304e..d78ece051f 100644 --- a/docs/content/docs/mcp.mdx +++ b/docs/content/docs/mcp.mdx @@ -152,6 +152,20 @@ DBX MCP provides the following tools (availability depends on build features and Connection-scoped sessions hide connection-mutating and desktop UI tools. +## Plugin tools + +DBX plugins whose sidecar implements the `mcp/tools` bridge can be served by the `dbx` MCP server and merged into `tools/list` — no per-plugin `--mcp` process configuration in your client. Exposure is author opt-in: a plugin's tools appear only when its manifest declares an `mcp` contribution with `external_tools: true` (SSH, Files, Kafka, LDAP, ... any plugin can do it): + +- Tools are exposed as `dbx___`, 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___` you want exposed (or clear the allowlist to allow everything). +- 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`. + ## Resources Clients that support MCP Resources can read the connection catalog and expand templates for database metadata: diff --git a/docs/content/docs/plugin-development.cn.mdx b/docs/content/docs/plugin-development.cn.mdx index 7ea7710520..e2d9c7ed5e 100644 --- a/docs/content/docs/plugin-development.cn.mdx +++ b/docs/content/docs/plugin-development.cn.mdx @@ -107,7 +107,7 @@ Manifest 中的路径相对于包根目录,不能以 `/` 开头、不能包含 | `engines` | 是 | 运行时兼容范围,至少包含 `host_api`。 | | `permissions` | 否 | 最小权限集合,见下文。 | | `entrypoints` | 否 | UI 和原生 Sidecar 入口;贡献点存在时按需声明。 | -| `contributions` | 否 | 连接、工作台、文件系统、连接右键菜单和结果视图声明。 | +| `contributions` | 否 | 连接、工作台、文件系统、连接右键菜单、结果视图、命令/菜单和 MCP 工具面声明。 | | `localizations` | 否 | 按 locale 覆盖名称、说明、贡献点、字段和动作文案。 | ### `engines`、权限和入口 @@ -771,7 +771,7 @@ Sidecar 约束:stdout 只能输出协议消息,日志写 stderr;请求 ID 宿主在此之上负责: -- **需要用户开启。** 用户在「插件中心 → 已安装 → 内置 AI 工具」中开启前,不会暴露任何工具;同一面板会列出工具并标出哪些需要确认。 +- **显式加入、可撤销。** 插件只有在用户于「插件中心 → 已安装 → 内置 AI 工具」中开启后才会贡献工具——仅安装不会暴露任何东西。同一面板会列出工具并标出哪些需要确认,开关可把某个插件永久关闭。manifest 中的 `mcp` 贡献声明 `ai_tools: false` 可让插件即使被用户开启也不进入该面。 - **只用已打开的连接。** 只为用户当前已打开的插件连接提供工具。连接由 DBX 绑定:模型看到的 schema 中会去掉 `connectionId` / `connectionName`;如果插件 schema 声明了 `connectionId`,宿主会在转发参数中注入绑定连接的 id。打开了多个连接时,模型通过额外的 `dbx_connection` 参数选择其一。 - **默认需要确认。** 只有声明了 `"annotations": { "readOnlyHint": true }` 的工具才会直接执行。其他调用都会暂停运行,并向用户展示将要转发的完整参数,由用户选择允许一次或拒绝;五分钟未响应视为拒绝。请为真正只读的工具加上标注,同时保留插件自身的防护(只读连接标志、两阶段确认等)——宿主确认拦截的是模型的误操作,不能替代插件自己的安全规则。 - **可移植的 schema。** 工具以 `<前缀>__<工具名>` 暴露(例如 `ssh__ssh_exec`),schema 会被收敛到所有支持的模型供应商都接受的子集:`type`、`description`、`properties`、`required`、`items`、字符串 `enum` 以及数值、长度和元素数量边界。参数名请只使用字母、数字和下划线。 @@ -779,6 +779,8 @@ Sidecar 约束:stdout 只能输出协议消息,日志写 stderr;请求 ID 内置 Agent 会把工具输出当作不可信数据处理。结果里请返回事实而不是指令,也不要回显任何密钥。 +同样的工具也会出现在外部 `dbx` MCP 服务器(Claude Code、Cursor 等)上,名称为 `dbx_<前缀>__<工具名>`,并受全局 MCP 设置(工具白名单 + 连接白名单)约束、绑定到插件已保存的连接。该面按作者声明加入:manifest 中的 `mcp` 贡献声明 `external_tools: true` 才会暴露;连接选择参数为 `dbx_connection`。 + ## 创建插件 直接安装预编译 CLI,不需要 Rust,也不需要克隆 DBX 源码: diff --git a/docs/content/docs/plugin-development.mdx b/docs/content/docs/plugin-development.mdx index c16ce0ebb9..b4956c460c 100644 --- a/docs/content/docs/plugin-development.mdx +++ b/docs/content/docs/plugin-development.mdx @@ -107,7 +107,7 @@ Manifest paths are relative to the package root. They cannot start with `/`, con | `engines` | Yes | Compatibility declaration; it must contain `host_api`. | | `permissions` | No | Minimal capability set, described below. | | `entrypoints` | No | UI and native-sidecar entrypoints. | -| `contributions` | No | Connection, workbench, filesystem, connection-menu, and result-view declarations. | +| `contributions` | No | Connection, workbench, filesystem, connection-menu, result-view, command/menu, and MCP tool-surface declarations. | | `localizations` | No | Locale-specific names, descriptions, fields, and action labels. | ### Engines, Permissions, and Entrypoints @@ -771,7 +771,7 @@ A plugin with a native backend can expose tools that the built-in DBX AI assista What the host adds on top: -- **Opt-in.** Nothing is exposed until the user enables the plugin under Plugin Center → Installed → Built-in AI tools; the same panel lists the tools and marks which ones need approval. +- **Opt-in, revocable.** A plugin contributes AI tools only after the user enabled it in Plugin Center (Installed → Built-in AI tools); installing alone never exposes anything. The same panel lists the tools and marks which ones need approval, and switching a plugin off there turns it off for good. A manifest `mcp` contribution with `ai_tools: false` opts a plugin out of this surface even when opted in. - **Open connections only.** Tools are offered for the plugin connections the user currently has open. DBX binds the connection itself: it strips `connectionId` / `connectionName` from the schema the model sees and injects the bound `connectionId` into the forwarded arguments when your schema declares it. With several open connections the model picks one through an added `dbx_connection` argument. - **Approval by default.** Only tools whose entry sets `"annotations": { "readOnlyHint": true }` run without asking. Every other call pauses the run and shows the exact arguments to the user, who allows it once or denies it; an unanswered request is denied after five minutes. Mark genuinely read-only tools, and keep your own guards (read-only connection flags, two-phase confirmations) — the approval covers model mistakes, not your plugin's own safety rules. - **Portable schemas.** Tool names are exposed as `__` (for example `ssh__ssh_exec`), and schemas are reduced to the subset every supported model provider accepts: `type`, `description`, `properties`, `required`, `items`, string `enum`, and numeric/length/item bounds. Keep argument names to letters, digits, and underscores. diff --git a/plugins/README.md b/plugins/README.md index cdc0c37287..f8ec631faf 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -524,6 +524,21 @@ Every entry has `name`, canonical `uri`, `kind` (`file`, `directory`, `symlink`, Mutation methods return `{ success, message?, entry? }` and are rejected unless the provider declares the matching capability. Inline read/write payloads are capped at 4 MiB. The built-in file manager currently owns directory navigation, pagination, and bounded file preview. Large upload/download and PTY/SFTP streams use `stdio-framed` binary channels with plugin-defined transfer methods, chunk acknowledgements, cancellation, and progress events; they must not be encoded as one large JSON value. +### `mcp` + +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 +{ + "type": "mcp", + "id": "vendor.ssh.mcp", + "description": "Terminal and file tools over SSH connections.", + "external_tools": true +} +``` + +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. + ### Table Schema Metadata A plugin can read narrow, read-only schema metadata for one table without owning a driver, connection pool, credential, or SQL string. It reuses the canonical `PluginTableContext` identity used by table contributions: @@ -736,7 +751,7 @@ A backend can expose tools to the built-in DBX AI agent through the MCP-shaped s Host rules (`crates/dbx-core/src/ai/plugin_tools.rs`): -- Tools are offered only for plugins the user enabled in Plugin Center → Installed → Built-in AI tools, only in Agent mode with API model providers, and only for plugin connections that are currently open. +- Tools are opt-in: a plugin contributes AI tools only after the user enabled it in Plugin Center, and a manifest `mcp` contribution with `ai_tools: false` keeps it off the surface even when opted in. The Plugin Center switch turns a plugin off for good. Tools appear only in Agent mode with API model providers, and only for plugin connections that are currently open. - The host binds the connection: `connectionId` / `connectionName` are removed from the model-facing schema, and the bound `connectionId` is injected into the forwarded arguments when the plugin schema declares it. With several open connections the model chooses through an added `dbx_connection` argument. - A tool runs without asking only when its entry sets `annotations.readOnlyHint: true`. Every other call pauses the run behind an inline approval that shows the exact forwarded arguments; unanswered approvals are denied after five minutes (`crates/dbx-core/src/ai/tool_approval.rs`). The hint is trusted because the plugin's native backend is already trusted code; the approval protects against model mistakes and prompt injection, not against a hostile plugin. - Names are exposed as `__` (`io.dbx.ssh` → `ssh__…`). Schemas are reduced to a provider-portable subset (`type`, `description`, `properties`, `required`, `items`, string `enum`, numeric/length/item bounds); argument names must match `[A-Za-z_][A-Za-z0-9_]{0,63}`. @@ -825,7 +840,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/` 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 plugin gets no model output, no model configuration, and no SQL execution out of it. `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. -- **AI tool exposure:** plugin MCP tools reach the built-in AI agent only after the user enables the plugin for it, only on open connections, and — unless declared read-only — only after a per-call approval. +- **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. 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 11c8ad90b1..646dfb2dae 100644 --- a/plugins/manifest.schema.json +++ b/plugins/manifest.schema.json @@ -46,7 +46,7 @@ "contributions": { "type": "array", "items": { - "oneOf": [{ "$ref": "#/$defs/connectionProviderContribution" }, { "$ref": "#/$defs/workbenchContribution" }, { "$ref": "#/$defs/filesystemProviderContribution" }, { "$ref": "#/$defs/contextMenuContribution" }, { "$ref": "#/$defs/resultViewContribution" }, { "$ref": "#/$defs/commandContribution" }, { "$ref": "#/$defs/menusContribution" }] + "oneOf": [{ "$ref": "#/$defs/connectionProviderContribution" }, { "$ref": "#/$defs/workbenchContribution" }, { "$ref": "#/$defs/filesystemProviderContribution" }, { "$ref": "#/$defs/contextMenuContribution" }, { "$ref": "#/$defs/resultViewContribution" }, { "$ref": "#/$defs/commandContribution" }, { "$ref": "#/$defs/menusContribution" }, { "$ref": "#/$defs/mcpContribution" }] } }, "localizations": { @@ -429,6 +429,18 @@ "items": { "type": "array", "items": { "$ref": "#/$defs/menuItem" } } } }, + "mcpContribution": { + "type": "object", + "additionalProperties": false, + "required": ["type", "id"], + "properties": { + "type": { "const": "mcp" }, + "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." } + } + }, "menuItem": { "type": "object", "additionalProperties": false, diff --git a/src-tauri/src/commands/ai.rs b/src-tauri/src/commands/ai.rs index ae657359e5..fe7dd996be 100644 --- a/src-tauri/src/commands/ai.rs +++ b/src-tauri/src/commands/ai.rs @@ -324,9 +324,16 @@ pub async fn ai_resolve_tool_approval(session_id: String, approval_id: String, a } /// Plugin ids whose MCP tools the built-in AI agent may call. +/// Plugin ids whose MCP tools the built-in AI agent may call: every detected +/// tool-capable plugin (a manifest `mcp` contribution with `ai_tools: false` +/// opts out) minus the ids the user explicitly turned off in the Plugin +/// Center. #[tauri::command] pub async fn get_ai_plugin_tool_plugins(state: State<'_, Arc>) -> Result, String> { - state.storage.load_ai_plugin_tool_plugin_ids().await + let mut ids = + dbx_core::ai::plugin_tools::effective_ai_tool_plugin_ids(state.inner()).await.into_iter().collect::>(); + ids.sort(); + Ok(ids) } #[tauri::command]