An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Support OAuth authorization for remote MCP services https://github.com/siyuan-note/siyuan/issues/18193
Daniel83be38d81da3
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 2174a5e49b..69f488069f 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "جارٍ التفويض",+ "mcpStatusAuthorizationRequired": "التفويض مطلوب",+ "mcpAuthorize": "تفويض",+ "mcpDisconnectAuthorization": "قطع التفويض",+ "mcpDisconnectAuthorizationConfirm": "هل تريد قطع تفويض OAuth لهذه الخدمة البعيدة؟","switchLeftDock": "تبديل تخطيط اللوحة اليسرى","switchRightDock": "تبديل تخطيط اللوحة اليمنى","switchBottomDock": "تبديل تخطيط اللوحة السفلية",@@ -199,8 +204,8 @@"aiMcpServerName": "الاسم","aiMcpServerNameTip": "يجب أن يكون فريدًا بين خوادم MCP","connectionType": "نوع الاتصال",- "aiMcpTypeStdio": "إدخال/إخراج قياسي (stdio)",- "aiMcpTypeHttp": "خدمة HTTP (http)",+ "aiMcpTypeStdio": "سطر أوامر محلي (stdio)",+ "aiMcpTypeHttp": "خدمة بعيدة (HTTP/OAuth)","command": "أمر","aiMcpCommandTip": "ملف قابل للتنفيذ، مثل npx وnode وpython وuvx","args": "وسائط",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "تم قفل دفتر التشفير [%s] تلقائياً بسبب عدم النشاط","323": "تعذر تعطيل دفاتر التشفير: ما زال سجل الدفاتر المحذوفة يعتمد على نسخة المفتاح الاحتياطية الحالية. امسح هذا السجل أولاً",- "324": "تعذر استيراد نسخة مفتاح احتياطية أثناء تفعيل دفاتر التشفير. عطلها أولاً"+ "324": "تعذر استيراد نسخة مفتاح احتياطية أثناء تفعيل دفاتر التشفير. عطلها أولاً",+ "325": "اكتمل التفويض",+ "326": "يمكنك إغلاق هذه الصفحة والعودة إلى SiYuan للتحقق من حالة الاتصال",+ "327": "لم يكتمل التفويض",+ "328": "يمكنك إغلاق هذه الصفحة والعودة إلى SiYuan للمحاولة مرة أخرى."}}diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex eb964216c0..b7a8397964 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Autorisierung läuft",+ "mcpStatusAuthorizationRequired": "Autorisierung erforderlich",+ "mcpAuthorize": "Autorisieren",+ "mcpDisconnectAuthorization": "Autorisierung trennen",+ "mcpDisconnectAuthorizationConfirm": "OAuth-Autorisierung für diesen Remotedienst trennen?","switchLeftDock": "Layout des linken Bereichs wechseln","switchRightDock": "Layout des rechten Bereichs wechseln","switchBottomDock": "Layout des unteren Bereichs wechseln",@@ -199,8 +204,8 @@"aiMcpServerName": "Name","aiMcpServerNameTip": "Muss unter MCP-Servern eindeutig sein","connectionType": "Verbindungstyp",- "aiMcpTypeStdio": "Standard-Ein-/Ausgabe (stdio)",- "aiMcpTypeHttp": "HTTP-Dienst (http)",+ "aiMcpTypeStdio": "Lokale Befehlszeile (stdio)",+ "aiMcpTypeHttp": "Remotedienst (HTTP/OAuth)","command": "Befehl","aiMcpCommandTip": "Ausführbare Datei, z. B. npx, node, python, uvx","args": "Argumente",@@ -2151,6 +2156,10 @@"321": "Der Zugriff auf verschlüsselte Notizbuchdaten wird über diese API nicht unterstützt","322": "Verschlüsseltes Notizbuch [%s] wurde wegen Inaktivität automatisch gesperrt","323": "Verschlüsselte Notizbücher können nicht deaktiviert werden: Der Verlauf gelöschter Notizbücher hängt noch vom aktuellen Schlüssel-Backup ab. Löschen Sie diesen Verlauf zuerst",- "324": "Ein Schlüssel-Backup kann nicht importiert werden, während verschlüsselte Notizbücher aktiviert sind. Deaktivieren Sie es zuerst"+ "324": "Ein Schlüssel-Backup kann nicht importiert werden, während verschlüsselte Notizbücher aktiviert sind. Deaktivieren Sie es zuerst",+ "325": "Autorisierung abgeschlossen",+ "326": "Sie können diese Seite schließen und zu SiYuan zurückkehren, um den Verbindungsstatus zu prüfen",+ "327": "Autorisierung nicht abgeschlossen",+ "328": "Sie können diese Seite schließen und zu SiYuan zurückkehren, um es erneut zu versuchen."}}diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 9599542afd..2676f23aa0 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Authorizing",+ "mcpStatusAuthorizationRequired": "Authorization required",+ "mcpAuthorize": "Authorize",+ "mcpDisconnectAuthorization": "Disconnect authorization",+ "mcpDisconnectAuthorizationConfirm": "Disconnect OAuth authorization for this remote service?","switchLeftDock": "Switch left panel layout","switchRightDock": "Switch right panel layout","switchBottomDock": "Switch bottom panel layout",@@ -199,8 +204,8 @@"aiMcpServerName": "Name","aiMcpServerNameTip": "Must be unique among MCP servers","connectionType": "Connection type",- "aiMcpTypeStdio": "Standard I/O (stdio)",- "aiMcpTypeHttp": "HTTP service (http)",+ "aiMcpTypeStdio": "Local command line (stdio)",+ "aiMcpTypeHttp": "Remote service (HTTP/OAuth)","command": "Command","aiMcpCommandTip": "Executable, e.g. npx, node, python, uvx","args": "Arguments",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "Encrypted notebook [%s] has been automatically locked due to inactivity","323": "Cannot disable encrypted notebooks: deleted-notebook history still depends on the current key backup. Clear that history first",- "324": "Cannot import a key backup while encrypted notebooks are enabled. Disable it first"+ "324": "Cannot import a key backup while encrypted notebooks are enabled. Disable it first",+ "325": "Authorization completed",+ "326": "You can close this page and return to SiYuan to check the connection status",+ "327": "Authorization was not completed",+ "328": "You can close this page and return to SiYuan to try again."}}diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex d6cf759d0b..b7c95d0ab8 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Autorizando",+ "mcpStatusAuthorizationRequired": "Se requiere autorización",+ "mcpAuthorize": "Autorizar",+ "mcpDisconnectAuthorization": "Desconectar autorización",+ "mcpDisconnectAuthorizationConfirm": "¿Desconectar la autorización OAuth de este servicio remoto?","switchLeftDock": "Cambiar el diseño del panel izquierdo","switchRightDock": "Cambiar el diseño del panel derecho","switchBottomDock": "Cambiar el diseño del panel inferior",@@ -199,8 +204,8 @@"aiMcpServerName": "Nombre","aiMcpServerNameTip": "Debe ser único entre los servidores MCP","connectionType": "Tipo de conexión",- "aiMcpTypeStdio": "Entrada/salida estándar (stdio)",- "aiMcpTypeHttp": "Servicio HTTP (http)",+ "aiMcpTypeStdio": "Línea de comandos local (stdio)",+ "aiMcpTypeHttp": "Servicio remoto (HTTP/OAuth)","command": "Comando","aiMcpCommandTip": "Ejecutable, p. ej. npx, node, python, uvx","args": "Argumentos",@@ -2151,6 +2156,10 @@"321": "El acceso a datos de cuadernos cifrados no está soportado a través de esta API","322": "El cuaderno cifrado [%s] se ha bloqueado automáticamente por inactividad","323": "No se pueden desactivar los cuadernos cifrados: el historial de cuadernos eliminados aún depende de la copia de seguridad de claves actual. Borre ese historial primero",- "324": "No se puede importar una copia de seguridad de claves mientras los cuadernos cifrados estén activados. Desactívelos primero"+ "324": "No se puede importar una copia de seguridad de claves mientras los cuadernos cifrados estén activados. Desactívelos primero",+ "325": "Autorización completada",+ "326": "Puede cerrar esta página y volver a SiYuan para comprobar el estado de la conexión",+ "327": "La autorización no se completó",+ "328": "Puede cerrar esta página y volver a SiYuan para intentarlo de nuevo."}}diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 72cdf86770..447c99687f 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Autorisation en cours",+ "mcpStatusAuthorizationRequired": "Autorisation requise",+ "mcpAuthorize": "Autoriser",+ "mcpDisconnectAuthorization": "Déconnecter l’autorisation",+ "mcpDisconnectAuthorizationConfirm": "Déconnecter l’autorisation OAuth de ce service distant ?","switchLeftDock": "Changer la disposition du panneau gauche","switchRightDock": "Changer la disposition du panneau droit","switchBottomDock": "Changer la disposition du panneau inférieur",@@ -199,8 +204,8 @@"aiMcpServerName": "Nom","aiMcpServerNameTip": "Doit être unique parmi les serveurs MCP","connectionType": "Type de connexion",- "aiMcpTypeStdio": "Entrée/sortie standard (stdio)",- "aiMcpTypeHttp": "Service HTTP (http)",+ "aiMcpTypeStdio": "Ligne de commande locale (stdio)",+ "aiMcpTypeHttp": "Service distant (HTTP/OAuth)","command": "Commande","aiMcpCommandTip": "Exécutable, ex. npx, node, python, uvx","args": "Arguments",@@ -2151,6 +2156,10 @@"321": "L'accès aux données d'un notebook chiffré n'est pas pris en charge via cette API","322": "Le notebook chiffré [%s] a été verrouillé automatiquement pour inactivité","323": "Impossible de désactiver les notebooks chiffrés : l'historique des notebooks supprimés dépend encore de la sauvegarde de clés actuelle. Effacez d'abord cet historique",- "324": "Impossible d'importer une sauvegarde de clés tant que les notebooks chiffrés sont activés. Désactivez-les d'abord"+ "324": "Impossible d'importer une sauvegarde de clés tant que les notebooks chiffrés sont activés. Désactivez-les d'abord",+ "325": "Autorisation terminée",+ "326": "Vous pouvez fermer cette page et revenir dans SiYuan pour vérifier l’état de la connexion",+ "327": "L’autorisation n’a pas abouti",+ "328": "Vous pouvez fermer cette page et revenir dans SiYuan pour réessayer."}}diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex db8457593c..3487c137be 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "מתבצע אישור",+ "mcpStatusAuthorizationRequired": "נדרש אישור",+ "mcpAuthorize": "אישור",+ "mcpDisconnectAuthorization": "ניתוק האישור",+ "mcpDisconnectAuthorizationConfirm": "לנתק את אישור OAuth עבור שירות מרוחק זה?","switchLeftDock": "החלף את פריסת החלונית השמאלית","switchRightDock": "החלף את פריסת החלונית הימנית","switchBottomDock": "החלף את פריסת החלונית התחתונה",@@ -199,8 +204,8 @@"aiMcpServerName": "שם","aiMcpServerNameTip": "חייב להיות ייחודי בין שרתי MCP","connectionType": "סוג חיבור",- "aiMcpTypeStdio": "קלט/פלט סטנדרטי (stdio)",- "aiMcpTypeHttp": "שירות HTTP (http)",+ "aiMcpTypeStdio": "שורת פקודה מקומית (stdio)",+ "aiMcpTypeHttp": "שירות מרוחק (HTTP/OAuth)","command": "פקודה","aiMcpCommandTip": "קובץ הרצה, למשל npx, node, python, uvx","args": "ארגומנטים",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "המחברת המוצפנת [%s] נעלה אוטומטית עקב חוסר פעילות","323": "לא ניתן להשבית מחברות מוצפנות: ההיסטוריה של מחברות שנמחקו עדיין תלויה בגיבוי המפתח הנוכחי. נקה היסטוריה זו תחילה",- "324": "לא ניתן לייבא גיבוי מפתח כאשר מחברות מוצפנות מופעלות. השבת אותן תחילה"+ "324": "לא ניתן לייבא גיבוי מפתח כאשר מחברות מוצפנות מופעלות. השבת אותן תחילה",+ "325": "ההרשאה הושלמה",+ "326": "ניתן לסגור דף זה ולחזור אל SiYuan כדי לבדוק את מצב החיבור",+ "327": "ההרשאה לא הושלמה",+ "328": "ניתן לסגור דף זה ולחזור אל SiYuan כדי לנסות שוב."}}diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 7b0a9561d1..80973b4802 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "प्राधिकरण जारी है",+ "mcpStatusAuthorizationRequired": "प्राधिकरण आवश्यक है",+ "mcpAuthorize": "प्राधिकृत करें",+ "mcpDisconnectAuthorization": "प्राधिकरण डिस्कनेक्ट करें",+ "mcpDisconnectAuthorizationConfirm": "क्या इस दूरस्थ सेवा का OAuth प्राधिकरण डिस्कनेक्ट करना है?","switchLeftDock": "बाएँ पैनल का लेआउट बदलें","switchRightDock": "दाएँ पैनल का लेआउट बदलें","switchBottomDock": "निचले पैनल का लेआउट बदलें",@@ -199,8 +204,8 @@"aiMcpServerName": "नाम","aiMcpServerNameTip": "MCP सर्वरों में अद्वितीय होना चाहिए","connectionType": "कनेक्शन प्रकार",- "aiMcpTypeStdio": "मानक इनपुट/आउटपुट (stdio)",- "aiMcpTypeHttp": "HTTP सेवा (http)",+ "aiMcpTypeStdio": "स्थानीय कमांड लाइन (stdio)",+ "aiMcpTypeHttp": "दूरस्थ सेवा (HTTP/OAuth)","command": "कमांड","aiMcpCommandTip": "निष्पादन योग्य फ़ाइल, जैसे npx, node, python, uvx","args": "आर्ग्युमेंट",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "एन्क्रिप्टेड नोटबुक [%s] निष्क्रियता के कारण स्वचालित रूप से लॉक हो गया है","323": "एन्क्रिप्टेड नोटबुक को अक्षम नहीं किया जा सकता: हटाई गई नोटबुक का इतिहास अभी भी वर्तमान कुंजी बैकअप पर निर्भर है। पहले उस इतिहास को साफ़ करें",- "324": "एन्क्रिप्टेड नोटबुक सक्षम होने पर कुंजी बैकअप आयात नहीं किया जा सकता। पहले इसे अक्षम करें"+ "324": "एन्क्रिप्टेड नोटबुक सक्षम होने पर कुंजी बैकअप आयात नहीं किया जा सकता। पहले इसे अक्षम करें",+ "325": "प्राधिकरण पूर्ण हुआ",+ "326": "आप इस पृष्ठ को बंद करके कनेक्शन की स्थिति देखने के लिए SiYuan पर लौट सकते हैं",+ "327": "प्राधिकरण पूर्ण नहीं हुआ",+ "328": "आप इस पृष्ठ को बंद करके फिर से प्रयास करने के लिए SiYuan पर लौट सकते हैं।"}}diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex de20a90250..2b1d1a126a 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Mengotorisasi",+ "mcpStatusAuthorizationRequired": "Otorisasi diperlukan",+ "mcpAuthorize": "Otorisasi",+ "mcpDisconnectAuthorization": "Putuskan otorisasi",+ "mcpDisconnectAuthorizationConfirm": "Putuskan otorisasi OAuth untuk layanan jarak jauh ini?","switchLeftDock": "Ganti tata letak panel kiri","switchRightDock": "Ganti tata letak panel kanan","switchBottomDock": "Ganti tata letak panel bawah",@@ -199,8 +204,8 @@"aiMcpServerName": "Nama","aiMcpServerNameTip": "Harus unik di antara server MCP","connectionType": "Jenis koneksi",- "aiMcpTypeStdio": "Input/output standar (stdio)",- "aiMcpTypeHttp": "Layanan HTTP (http)",+ "aiMcpTypeStdio": "Baris perintah lokal (stdio)",+ "aiMcpTypeHttp": "Layanan jarak jauh (HTTP/OAuth)","command": "Perintah","aiMcpCommandTip": "File yang dapat dieksekusi, mis. npx, node, python, uvx","args": "Argumen",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "Notebook terenkripsi [%s] telah dikunci otomatis karena tidak aktif","323": "Tidak dapat menonaktifkan notebook terenkripsi: riwayat notebook yang dihapus masih bergantung pada cadangan kunci saat ini. Hapus riwayat tersebut terlebih dahulu",- "324": "Tidak dapat mengimpor cadangan kunci saat notebook terenkripsi diaktifkan. Nonaktifkan terlebih dahulu"+ "324": "Tidak dapat mengimpor cadangan kunci saat notebook terenkripsi diaktifkan. Nonaktifkan terlebih dahulu",+ "325": "Otorisasi selesai",+ "326": "Anda dapat menutup halaman ini dan kembali ke SiYuan untuk memeriksa status koneksi",+ "327": "Otorisasi tidak selesai",+ "328": "Anda dapat menutup halaman ini dan kembali ke SiYuan untuk mencoba lagi."}}diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex dfff79dcc6..1eb6a15ada 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Autorizzazione in corso",+ "mcpStatusAuthorizationRequired": "Autorizzazione richiesta",+ "mcpAuthorize": "Autorizza",+ "mcpDisconnectAuthorization": "Disconnetti autorizzazione",+ "mcpDisconnectAuthorizationConfirm": "Disconnettere l’autorizzazione OAuth per questo servizio remoto?","switchLeftDock": "Cambia il layout del pannello sinistro","switchRightDock": "Cambia il layout del pannello destro","switchBottomDock": "Cambia il layout del pannello inferiore",@@ -199,8 +204,8 @@"aiMcpServerName": "Nome","aiMcpServerNameTip": "Deve essere univoco tra i server MCP","connectionType": "Tipo di connessione",- "aiMcpTypeStdio": "Input/output standard (stdio)",- "aiMcpTypeHttp": "Servizio HTTP (http)",+ "aiMcpTypeStdio": "Riga di comando locale (stdio)",+ "aiMcpTypeHttp": "Servizio remoto (HTTP/OAuth)","command": "Comando","aiMcpCommandTip": "Eseguibile, es. npx, node, python, uvx","args": "Argomenti",@@ -2151,6 +2156,10 @@"321": "L'accesso ai dati dei notebook crittografati non è supportato tramite questa API","322": "Il notebook crittografato [%s] è stato bloccato automaticamente per inattività","323": "Impossibile disabilitare i notebook crittografati: la cronologia dei notebook eliminati dipende ancora dal backup delle chiavi attuale. Cancella prima quella cronologia",- "324": "Impossibile importare un backup delle chiavi mentre i notebook crittografati sono attivi. Disattivali prima"+ "324": "Impossibile importare un backup delle chiavi mentre i notebook crittografati sono attivi. Disattivali prima",+ "325": "Autorizzazione completata",+ "326": "Puoi chiudere questa pagina e tornare a SiYuan per controllare lo stato della connessione",+ "327": "Autorizzazione non completata",+ "328": "Puoi chiudere questa pagina e tornare a SiYuan per riprovare."}}diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 6a5b611b83..70068cdcdf 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "認可中",+ "mcpStatusAuthorizationRequired": "認可が必要です",+ "mcpAuthorize": "認可",+ "mcpDisconnectAuthorization": "認可を解除",+ "mcpDisconnectAuthorizationConfirm": "このリモートサービスの OAuth 認可を解除しますか?","switchLeftDock": "左パネルのレイアウトを切り替える","switchRightDock": "右パネルのレイアウトを切り替える","switchBottomDock": "下パネルのレイアウトを切り替える",@@ -199,8 +204,8 @@"aiMcpServerName": "名前","aiMcpServerNameTip": "他の MCP サービス名と重複できません","connectionType": "接続タイプ",- "aiMcpTypeStdio": "標準入出力 (stdio)",- "aiMcpTypeHttp": "HTTP サービス (http)",+ "aiMcpTypeStdio": "ローカルコマンドライン (stdio)",+ "aiMcpTypeHttp": "リモートサービス (HTTP/OAuth)","command": "コマンド","aiMcpCommandTip": "実行ファイル(npx、node、python、uvx など)","args": "引数",@@ -2151,6 +2156,10 @@"321": "この API では暗号化ノートブックのデータ操作はサポートされていません","322": "暗号化ノートブック [%s] は操作がないため自動的にロックされました","323": "暗号化ノートブックを無効化できません:削除されたノートブックの履歴が現在のキーバックアップに依存しています。先にその履歴を削除してください",- "324": "暗号化ノートブックが有効な間はキーバックアップをインポートできません。先に無効化してください"+ "324": "暗号化ノートブックが有効な間はキーバックアップをインポートできません。先に無効化してください",+ "325": "認可が完了しました",+ "326": "このページを閉じて SiYuan に戻り、接続状態を確認できます",+ "327": "認可が完了しませんでした",+ "328": "このページを閉じて SiYuan に戻り、もう一度お試しください。"}}diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 6a320816f6..4008350081 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "인증 중",+ "mcpStatusAuthorizationRequired": "인증 필요",+ "mcpAuthorize": "인증",+ "mcpDisconnectAuthorization": "인증 연결 해제",+ "mcpDisconnectAuthorizationConfirm": "이 원격 서비스의 OAuth 인증 연결을 해제하시겠습니까?","switchLeftDock": "왼쪽 패널 레이아웃 전환","switchRightDock": "오른쪽 패널 레이아웃 전환","switchBottomDock": "아래쪽 패널 레이아웃 전환",@@ -199,8 +204,8 @@"aiMcpServerName": "이름","aiMcpServerNameTip": "다른 MCP 서비스 이름과 중복될 수 없습니다","connectionType": "연결 유형",- "aiMcpTypeStdio": "표준 입출력 (stdio)",- "aiMcpTypeHttp": "HTTP 서비스 (http)",+ "aiMcpTypeStdio": "로컬 명령줄 (stdio)",+ "aiMcpTypeHttp": "원격 서비스 (HTTP/OAuth)","command": "명령","aiMcpCommandTip": "실행 파일, 예: npx, node, python, uvx","args": "인수",@@ -2151,6 +2156,10 @@"321": "이 API를 통해 암호화된 노트북의 데이터를 조작할 수 없습니다","322": "암호화된 노트북 [%s]이(가) 장시간 미사용으로 자동 잠금되었습니다","323": "암호화 노트북을 비활성화할 수 없습니다: 삭제된 노트북의 기록이 여전히 현재 키 백업에 의존합니다. 먼저 해당 기록을 삭제하세요",- "324": "암호화 노트북이 활성화되어 있는 동안에는 키 백업을 가져올 수 없습니다. 먼저 비활성화하세요"+ "324": "암호화 노트북이 활성화되어 있는 동안에는 키 백업을 가져올 수 없습니다. 먼저 비활성화하세요",+ "325": "인증이 완료되었습니다",+ "326": "이 페이지를 닫고 SiYuan으로 돌아가 연결 상태를 확인할 수 있습니다",+ "327": "인증이 완료되지 않았습니다",+ "328": "이 페이지를 닫고 SiYuan으로 돌아가 다시 시도할 수 있습니다."}}diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 86ade1a23b..213b4d6679 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Bezig met autoriseren",+ "mcpStatusAuthorizationRequired": "Autorisatie vereist",+ "mcpAuthorize": "Autoriseren",+ "mcpDisconnectAuthorization": "Autorisatie verbreken",+ "mcpDisconnectAuthorizationConfirm": "OAuth-autorisatie voor deze externe service verbreken?","switchLeftDock": "Indeling van linkerpaneel wisselen","switchRightDock": "Indeling van rechterpaneel wisselen","switchBottomDock": "Indeling van onderpaneel wisselen",@@ -199,8 +204,8 @@"aiMcpServerName": "Naam","aiMcpServerNameTip": "Moet uniek zijn onder MCP-servers","connectionType": "Verbindingstype",- "aiMcpTypeStdio": "Standaard I/O (stdio)",- "aiMcpTypeHttp": "HTTP-service (http)",+ "aiMcpTypeStdio": "Lokale opdrachtregel (stdio)",+ "aiMcpTypeHttp": "Externe service (HTTP/OAuth)","command": "Opdracht","aiMcpCommandTip": "Uitvoerbaar bestand, bijv. npx, node, python, uvx","args": "Argumenten",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "Versleuteld notitieboek [%s] is automatisch vergrendeld wegens inactiviteit","323": "Kan versleutelde notitieboeken niet uitschakelen: de geschiedenis van verwijderde notitieboeken is nog afhankelijk van de huidige sleutelback-up. Wis die geschiedenis eerst",- "324": "Kan geen sleutelback-up importeren terwijl versleutelde notitieboeken zijn ingeschakeld. Schakel ze eerst uit"+ "324": "Kan geen sleutelback-up importeren terwijl versleutelde notitieboeken zijn ingeschakeld. Schakel ze eerst uit",+ "325": "Autorisatie voltooid",+ "326": "U kunt deze pagina sluiten en terugkeren naar SiYuan om de verbindingsstatus te controleren",+ "327": "Autorisatie niet voltooid",+ "328": "U kunt deze pagina sluiten en terugkeren naar SiYuan om het opnieuw te proberen."}}diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex b4f21f1539..cc49215f1a 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Autoryzowanie",+ "mcpStatusAuthorizationRequired": "Wymagana autoryzacja",+ "mcpAuthorize": "Autoryzuj",+ "mcpDisconnectAuthorization": "Odłącz autoryzację",+ "mcpDisconnectAuthorizationConfirm": "Odłączyć autoryzację OAuth dla tej usługi zdalnej?","switchLeftDock": "Przełącz układ lewego panelu","switchRightDock": "Przełącz układ prawego panelu","switchBottomDock": "Przełącz układ dolnego panelu",@@ -199,8 +204,8 @@"aiMcpServerName": "Nazwa","aiMcpServerNameTip": "Musi być unikalna wśród serwerów MCP","connectionType": "Typ połączenia",- "aiMcpTypeStdio": "Standardowe we/wy (stdio)",- "aiMcpTypeHttp": "Usługa HTTP (http)",+ "aiMcpTypeStdio": "Lokalny wiersz poleceń (stdio)",+ "aiMcpTypeHttp": "Usługa zdalna (HTTP/OAuth)","command": "Polecenie","aiMcpCommandTip": "Plik wykonywalny, np. npx, node, python, uvx","args": "Argumenty",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "Zaszyfrowany notatnik [%s] został automatycznie zablokowany z powodu braku aktywności","323": "Nie można wyłączyć zaszyfrowanych notatników: historia usuniętych notatników nadal zależy od bieżącej kopii zapasowej kluczy. Wyczyść tę historię najpierw",- "324": "Nie można zaimportować kopii zapasowej kluczy, gdy zaszyfrowane notatniki są włączone. Najpierw je wyłącz"+ "324": "Nie można zaimportować kopii zapasowej kluczy, gdy zaszyfrowane notatniki są włączone. Najpierw je wyłącz",+ "325": "Autoryzacja zakończona",+ "326": "Możesz zamknąć tę stronę i wrócić do SiYuan, aby sprawdzić stan połączenia",+ "327": "Autoryzacja nie została zakończona",+ "328": "Możesz zamknąć tę stronę i wrócić do SiYuan, aby spróbować ponownie."}}diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 31ed008949..56b525caf8 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Autorizando",+ "mcpStatusAuthorizationRequired": "Autorização necessária",+ "mcpAuthorize": "Autorizar",+ "mcpDisconnectAuthorization": "Desconectar autorização",+ "mcpDisconnectAuthorizationConfirm": "Desconectar a autorização OAuth deste serviço remoto?","switchLeftDock": "Alternar layout do painel esquerdo","switchRightDock": "Alternar layout do painel direito","switchBottomDock": "Alternar layout do painel inferior",@@ -199,8 +204,8 @@"aiMcpServerName": "Nome","aiMcpServerNameTip": "Deve ser único entre os servidores MCP","connectionType": "Tipo de conexão",- "aiMcpTypeStdio": "Entrada/saída padrão (stdio)",- "aiMcpTypeHttp": "Serviço HTTP (http)",+ "aiMcpTypeStdio": "Linha de comando local (stdio)",+ "aiMcpTypeHttp": "Serviço remoto (HTTP/OAuth)","command": "Comando","aiMcpCommandTip": "Executável, ex. npx, node, python, uvx","args": "Argumentos",@@ -2151,6 +2156,10 @@"321": "O acesso a dados de notebooks criptografados não é suportado via esta API","322": "O notebook criptografado [%s] foi bloqueado automaticamente por inatividade","323": "Não é possível desativar notebooks criptografados: o histórico de notebooks excluídos ainda depende do backup de chaves atual. Limpe esse histórico primeiro",- "324": "Não é possível importar um backup de chaves enquanto os notebooks criptografados estão ativados. Desative-os primeiro"+ "324": "Não é possível importar um backup de chaves enquanto os notebooks criptografados estão ativados. Desative-os primeiro",+ "325": "Autorização concluída",+ "326": "Você pode fechar esta página e voltar ao SiYuan para verificar o status da conexão",+ "327": "A autorização não foi concluída",+ "328": "Você pode fechar esta página e voltar ao SiYuan para tentar novamente."}}diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 6f934653ea..d3fa1c1c1f 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Авторизация",+ "mcpStatusAuthorizationRequired": "Требуется авторизация",+ "mcpAuthorize": "Авторизовать",+ "mcpDisconnectAuthorization": "Отключить авторизацию",+ "mcpDisconnectAuthorizationConfirm": "Отключить OAuth-авторизацию для этого удалённого сервиса?","switchLeftDock": "Переключить компоновку левой панели","switchRightDock": "Переключить компоновку правой панели","switchBottomDock": "Переключить компоновку нижней панели",@@ -199,8 +204,8 @@"aiMcpServerName": "Имя","aiMcpServerNameTip": "Должно быть уникальным среди серверов MCP","connectionType": "Тип подключения",- "aiMcpTypeStdio": "Стандартный ввод/вывод (stdio)",- "aiMcpTypeHttp": "HTTP-сервис (http)",+ "aiMcpTypeStdio": "Локальная командная строка (stdio)",+ "aiMcpTypeHttp": "Удалённый сервис (HTTP/OAuth)","command": "Команда","aiMcpCommandTip": "Исполняемый файл, напр. npx, node, python, uvx","args": "Аргументы",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "Зашифрованный блокнот [%s] автоматически заблокирован из-за бездействия","323": "Невозможно отключить зашифрованные блокноты: история удалённых блокнотов всё ещё зависит от текущей резервной копии ключей. Сначала очистите эту историю",- "324": "Невозможно импортировать резервную копию ключей, пока зашифрованные блокноты включены. Сначала отключите их"+ "324": "Невозможно импортировать резервную копию ключей, пока зашифрованные блокноты включены. Сначала отключите их",+ "325": "Авторизация завершена",+ "326": "Вы можете закрыть эту страницу и вернуться в SiYuan, чтобы проверить состояние подключения",+ "327": "Авторизация не завершена",+ "328": "Вы можете закрыть эту страницу и вернуться в SiYuan, чтобы повторить попытку."}}diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex a5927f86c0..f3b2cc7954 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Prebieha autorizácia",+ "mcpStatusAuthorizationRequired": "Vyžaduje sa autorizácia",+ "mcpAuthorize": "Autorizovať",+ "mcpDisconnectAuthorization": "Odpojiť autorizáciu",+ "mcpDisconnectAuthorizationConfirm": "Odpojiť autorizáciu OAuth pre túto vzdialenú službu?","switchLeftDock": "Prepnúť rozloženie ľavého panela","switchRightDock": "Prepnúť rozloženie pravého panela","switchBottomDock": "Prepnúť rozloženie spodného panela",@@ -199,8 +204,8 @@"aiMcpServerName": "Názov","aiMcpServerNameTip": "Musí byť jedinečný medzi servermi MCP","connectionType": "Typ pripojenia",- "aiMcpTypeStdio": "Štandardný vstup/výstup (stdio)",- "aiMcpTypeHttp": "HTTP služba (http)",+ "aiMcpTypeStdio": "Lokálny príkazový riadok (stdio)",+ "aiMcpTypeHttp": "Vzdialená služba (HTTP/OAuth)","command": "Príkaz","aiMcpCommandTip": "Spustiteľný súbor, napr. npx, node, python, uvx","args": "Argumenty",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "Šifrovaný zápisník [%s] bol automaticky uzamknutý z dôvodu nečinnosti","323": "Nie je možné zakázať šifrované zápisníky: história zmazaných zápisníkov stále závisí od aktuálnej zálohy kľúčov. Najprv túto históriu vymažte",- "324": "Nie je možné importovať zálohu kľúčov, kým sú šifrované zápisníky povolené. Najprv ich zakážte"+ "324": "Nie je možné importovať zálohu kľúčov, kým sú šifrované zápisníky povolené. Najprv ich zakážte",+ "325": "Autorizácia dokončená",+ "326": "Túto stránku môžete zavrieť a vrátiť sa do SiYuan, kde skontrolujete stav pripojenia",+ "327": "Autorizácia nebola dokončená",+ "328": "Túto stránku môžete zavrieť a vrátiť sa do SiYuan, kde to môžete skúsiť znova."}}diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 1d8ce6f9a3..e8a839c702 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "กำลังอนุญาต",+ "mcpStatusAuthorizationRequired": "ต้องได้รับอนุญาต",+ "mcpAuthorize": "อนุญาต",+ "mcpDisconnectAuthorization": "ยกเลิกการเชื่อมต่อการอนุญาต",+ "mcpDisconnectAuthorizationConfirm": "ยกเลิกการเชื่อมต่อการอนุญาต OAuth สำหรับบริการระยะไกลนี้หรือไม่?","switchLeftDock": "สลับเค้าโครงแผงด้านซ้าย","switchRightDock": "สลับเค้าโครงแผงด้านขวา","switchBottomDock": "สลับเค้าโครงแผงด้านล่าง",@@ -199,8 +204,8 @@"aiMcpServerName": "ชื่อ","aiMcpServerNameTip": "ต้องไม่ซ้ำกับเซิร์ฟเวอร์ MCP อื่น","connectionType": "ประเภทการเชื่อมต่อ",- "aiMcpTypeStdio": "อินพุต/เอาต์พุตมาตรฐาน (stdio)",- "aiMcpTypeHttp": "บริการ HTTP (http)",+ "aiMcpTypeStdio": "บรรทัดคำสั่งภายในเครื่อง (stdio)",+ "aiMcpTypeHttp": "บริการระยะไกล (HTTP/OAuth)","command": "คำสั่ง","aiMcpCommandTip": "ไฟล์ที่รันได้ เช่น npx, node, python, uvx","args": "อาร์กิวเมนต์",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "สมุดบันทึกเข้ารหัส [%s] ถูกล็อกอัตโนมัติเนื่องจากไม่มีการใช้งาน","323": "ไม่สามารถปิดใช้งานสมุดบันทึกเข้ารหัสได้: ประวัติของสมุดบันทึกที่ถูกลบยังคงขึ้นกับการสำรองคีย์ปัจจุบัน โปรดล้างประวัตินั้นก่อน",- "324": "ไม่สามารถนำเข้าการสำรองคีย์ได้ขณะที่สมุดบันทึกเข้ารหัสเปิดใช้อยู่ โปรดปิดใช้งานก่อน"+ "324": "ไม่สามารถนำเข้าการสำรองคีย์ได้ขณะที่สมุดบันทึกเข้ารหัสเปิดใช้อยู่ โปรดปิดใช้งานก่อน",+ "325": "การอนุญาตเสร็จสมบูรณ์",+ "326": "คุณสามารถปิดหน้านี้และกลับไปที่ SiYuan เพื่อตรวจสอบสถานะการเชื่อมต่อได้",+ "327": "การอนุญาตไม่เสร็จสมบูรณ์",+ "328": "คุณสามารถปิดหน้านี้และกลับไปที่ SiYuan เพื่อลองอีกครั้งได้"}}diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 555b486e39..aca9fd8700 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Yetkilendiriliyor",+ "mcpStatusAuthorizationRequired": "Yetkilendirme gerekli",+ "mcpAuthorize": "Yetkilendir",+ "mcpDisconnectAuthorization": "Yetkilendirme bağlantısını kes",+ "mcpDisconnectAuthorizationConfirm": "Bu uzak hizmet için OAuth yetkilendirmesi kesilsin mi?","switchLeftDock": "Sol panel düzenini değiştir","switchRightDock": "Sağ panel düzenini değiştir","switchBottomDock": "Alt panel düzenini değiştir",@@ -199,8 +204,8 @@"aiMcpServerName": "Ad","aiMcpServerNameTip": "MCP sunucuları arasında benzersiz olmalıdır","connectionType": "Bağlantı türü",- "aiMcpTypeStdio": "Standart g/ç (stdio)",- "aiMcpTypeHttp": "HTTP hizmeti (http)",+ "aiMcpTypeStdio": "Yerel komut satırı (stdio)",+ "aiMcpTypeHttp": "Uzak hizmet (HTTP/OAuth)","command": "Komut","aiMcpCommandTip": "Çalıştırılabilir dosya, örn. npx, node, python, uvx","args": "Bağımsız değişkenler",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "Şifreli not defteri [%s] hareketsizlik nedeniyle otomatik olarak kilitlendi","323": "Şifreli not defterleri devre dışı bırakılamıyor: silinen defterlerin geçmişi hâlâ geçerli anahtar yedeğine bağlı. Önce bu geçmişi temizleyin",- "324": "Şifreli not defterleri etkinken bir anahtar yedeği içe aktarılamaz. Önce devre dışı bırakın"+ "324": "Şifreli not defterleri etkinken bir anahtar yedeği içe aktarılamaz. Önce devre dışı bırakın",+ "325": "Yetkilendirme tamamlandı",+ "326": "Bu sayfayı kapatıp bağlantı durumunu kontrol etmek için SiYuan'a dönebilirsiniz",+ "327": "Yetkilendirme tamamlanmadı",+ "328": "Bu sayfayı kapatıp yeniden denemek için SiYuan'a dönebilirsiniz."}}diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex ffcdac9c6e..e47eb7b965 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "Авторизація",+ "mcpStatusAuthorizationRequired": "Потрібна авторизація",+ "mcpAuthorize": "Авторизувати",+ "mcpDisconnectAuthorization": "Від’єднати авторизацію",+ "mcpDisconnectAuthorizationConfirm": "Від’єднати OAuth-авторизацію для цієї віддаленої служби?","switchLeftDock": "Перемкнути компонування лівої панелі","switchRightDock": "Перемкнути компонування правої панелі","switchBottomDock": "Перемкнути компонування нижньої панелі",@@ -199,8 +204,8 @@"aiMcpServerName": "Назва","aiMcpServerNameTip": "Має бути унікальною серед серверів MCP","connectionType": "Тип підключення",- "aiMcpTypeStdio": "Стандартний ввід/вивід (stdio)",- "aiMcpTypeHttp": "HTTP-сервіс (http)",+ "aiMcpTypeStdio": "Локальний командний рядок (stdio)",+ "aiMcpTypeHttp": "Віддалена служба (HTTP/OAuth)","command": "Команда","aiMcpCommandTip": "Виконуваний файл, напр. npx, node, python, uvx","args": "Аргументи",@@ -2151,6 +2156,10 @@"321": "Access to encrypted notebook data is not supported via this API","322": "Зашифрований блокнот [%s] автоматично заблоковано через бездіяльність","323": "Неможливо вимкнути зашифровані блокноти: історія видалених блокнотів усе ще залежить від поточного резервного копіювання ключів. Спочатку очистіть цю історію",- "324": "Неможливо імпортувати резервну копію ключів, доки увімкнені зашифровані блокноти. Спочатку вимкніть їх"+ "324": "Неможливо імпортувати резервну копію ключів, доки увімкнені зашифровані блокноти. Спочатку вимкніть їх",+ "325": "Авторизацію завершено",+ "326": "Ви можете закрити цю сторінку й повернутися до SiYuan, щоб перевірити стан підключення",+ "327": "Авторизацію не завершено",+ "328": "Ви можете закрити цю сторінку й повернутися до SiYuan, щоб повторити спробу."}}diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 0aa9713e31..7f00a523b4 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "正在授权",+ "mcpStatusAuthorizationRequired": "需要授权",+ "mcpAuthorize": "授权",+ "mcpDisconnectAuthorization": "断开授权",+ "mcpDisconnectAuthorizationConfirm": "确定要断开该远程服务的 OAuth 授权吗?","switchLeftDock": "切换左侧面板布局","switchRightDock": "切换右侧面板布局","switchBottomDock": "切换底部面板布局",@@ -199,8 +204,8 @@"aiMcpServerName": "名称","aiMcpServerNameTip": "不能与其他 MCP 服务名称重复","connectionType": "连接类型",- "aiMcpTypeStdio": "标准输入输出 (stdio)",- "aiMcpTypeHttp": "HTTP 服务 (http)",+ "aiMcpTypeStdio": "本地命令行(stdio)",+ "aiMcpTypeHttp": "远程服务(HTTP/OAuth)","command": "命令","aiMcpCommandTip": "可执行文件,如 npx、node、python、uvx 等","args": "参数",@@ -2151,6 +2156,10 @@"321": "不支持通过此 API 操作加密笔记本内的数据","322": "加密笔记本 [%s] 因长时间未操作已自动锁定","323": "无法禁用加密笔记本:已删除笔记本的历史仍依赖当前密钥备份,请先清除该历史",- "324": "无法导入密钥备份:加密笔记本功能已启用,请先禁用"+ "324": "无法导入密钥备份:加密笔记本功能已启用,请先禁用",+ "325": "授权已完成",+ "326": "可以关闭此页面并返回思源查看连接状态",+ "327": "未完成授权",+ "328": "可以关闭此页面并返回思源重新授权。"}}diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 3b79857d8d..34290a4501 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,9 @@{+ "mcpStatusAuthorizing": "正在授權",+ "mcpStatusAuthorizationRequired": "需要授權",+ "mcpAuthorize": "授權",+ "mcpDisconnectAuthorization": "中斷授權",+ "mcpDisconnectAuthorizationConfirm": "確定要中斷該遠端服務的 OAuth 授權嗎?","switchLeftDock": "切換左側面板佈局","switchRightDock": "切換右側面板佈局","switchBottomDock": "切換底部面板佈局",@@ -199,8 +204,8 @@"aiMcpServerName": "名稱","aiMcpServerNameTip": "不能與其他 MCP 服務名稱重複","connectionType": "連線類型",- "aiMcpTypeStdio": "標準輸入輸出 (stdio)",- "aiMcpTypeHttp": "HTTP 服務 (http)",+ "aiMcpTypeStdio": "本機命令列(stdio)",+ "aiMcpTypeHttp": "遠端服務(HTTP/OAuth)","command": "命令","aiMcpCommandTip": "可執行檔,如 npx、node、python、uvx 等","args": "參數",@@ -2151,6 +2156,10 @@"321": "不支援透過此 API 操作加密筆記本內的資料","322": "加密筆記本 [%s] 因長時間未操作已自動鎖定","323": "無法停用加密筆記本:已刪除筆記本的歷史仍依賴目前金鑰備份,請先清除該歷史",- "324": "無法匯入金鑰備份:加密筆記本功能已啟用,請先停用"+ "324": "無法匯入金鑰備份:加密筆記本功能已啟用,請先停用",+ "325": "授權已完成",+ "326": "可以關閉此頁面並返回思源查看連線狀態",+ "327": "未完成授權",+ "328": "可以關閉此頁面並返回思源重新授權。"}}diff --git a/app/src/config/tabs/aiUi.ts b/app/src/config/tabs/aiUi.tsindex 5de05d563b..33a5c45816 100644--- a/app/src/config/tabs/aiUi.ts+++ b/app/src/config/tabs/aiUi.ts@@ -6,6 +6,10 @@ import {Constants} from "../../constants";import {isMobile} from "../../util/functions";import {fetchPost} from "../../util/fetch";import {aiConfigApi} from "./aiRuntime";+import {openByMobile} from "../../editor/openLink";+/// #if !BROWSER+import {shell} from "electron";+/// #endiftype ModelPickerGroup = "editing" | "agent" | "vision" | "imageGeneration";@@ -960,6 +964,8 @@ export const mountModelPickerBlock = (root: HTMLElement, group: ModelPickerGroupexport const getMcpServersBlockKeywords = (): string[] => [window.siyuan.languages.mcpStatusConnected,window.siyuan.languages.mcpStatusConnecting,+ window.siyuan.languages.mcpStatusAuthorizing,+ window.siyuan.languages.mcpStatusAuthorizationRequired,window.siyuan.languages.mcpStatusFailed,window.siyuan.languages.mcpStatusDisabled,window.siyuan.languages.mcpStatusTools,@@ -979,8 +985,12 @@ export const getMcpServersBlockKeywords = (): string[] => [window.siyuan.languages.aiMcpUrlTip,window.siyuan.languages.aiMcpHttpHeaders,window.siyuan.languages.apiTimeout,+ window.siyuan.languages.mcpAuthorize,+ window.siyuan.languages.mcpDisconnectAuthorization,];+const openedMcpOAuthURLs = new Map<string, string>();+export const genMcpServersBlockHtml = (): string => `<div class="b3-label config-item" id="aiMcpServersBlock"><div class="fn__flex" style="align-items:center;"><span class="b3-label__text">${window.siyuan.languages.aiMcpServersTip}</span>@@ -1008,13 +1018,23 @@ export const mountMcpServersBlock = (root: HTMLElement) => {// 轮询 MCP 连接状态,刷新每个 server 名称旁的状态圆点颜色、tooltip,以及标题右侧的汇总。const renderMcpStatus = () => {fetchPost("/api/ai/mcpStatus", {}, (response) => {- const items = response.data as Array<{name: string; status: string; tools: number}>;+ const items = response.data as Array<{+ id: string;+ name: string;+ status: string;+ tools: number;+ error?: string;+ authorizationURL?: string;+ authorized: boolean;+ }>;if (!items) {return;}const colorMap: Record<string, string> = {connected: "#65b84f",connecting: "#d97706",+ authorizing: "#d97706",+ authorization_required: "#d97706",failed: "#d23f31",disabled: "var(--b3-theme-on-surface-light)",};@@ -1025,7 +1045,20 @@ export const mountMcpServersBlock = (root: HTMLElement) => {connectedCount++;totalTools += item.tools;}- const dotWrap = block.querySelector<HTMLElement>(`[data-mcp-status-name="${CSS.escape(item.name)}"]`);+ if (item.authorizationURL && openedMcpOAuthURLs.get(item.id) !== item.authorizationURL) {+ openedMcpOAuthURLs.set(item.id, item.authorizationURL);+ /// #if !BROWSER+ void shell.openExternal(item.authorizationURL).catch((error: Error) => {+ if (openedMcpOAuthURLs.get(item.id) === item.authorizationURL) {+ openedMcpOAuthURLs.delete(item.id);+ }+ showMessage(error.message);+ });+ /// #else+ openByMobile(item.authorizationURL);+ /// #endif+ }+ const dotWrap = block.querySelector<HTMLElement>(`[data-mcp-status-id="${CSS.escape(item.id)}"]`);if (!dotWrap) {continue;}@@ -1034,7 +1067,7 @@ export const mountMcpServersBlock = (root: HTMLElement) => {dot.style.backgroundColor = colorMap[item.status] || colorMap.disabled;}// 每个 server 行上显示其工具数(仅已连接且有工具时)。- const toolsEl = block.querySelector<HTMLElement>(`[data-mcp-tools-count="${CSS.escape(item.name)}"]`);+ const toolsEl = block.querySelector<HTMLElement>(`[data-mcp-tools-count="${CSS.escape(item.id)}"]`);if (toolsEl) {toolsEl.textContent = item.status === "connected" && item.tools > 0 ? window.siyuan.languages.mcpStatusTools.replace("${x}", String(item.tools)) : "";}@@ -1046,13 +1079,27 @@ export const mountMcpServersBlock = (root: HTMLElement) => {case "connecting":label = window.siyuan.languages.mcpStatusConnecting;break;+ case "authorizing":+ label = window.siyuan.languages.mcpStatusAuthorizing;+ break;+ case "authorization_required":+ label = window.siyuan.languages.mcpStatusAuthorizationRequired;+ break;case "failed":label = window.siyuan.languages.mcpStatusFailed;break;default:label = window.siyuan.languages.mcpStatusDisabled;}- dotWrap.setAttribute("aria-label", label);+ dotWrap.setAttribute("aria-label", item.error ? `${label}: ${item.error}` : label);+ block.querySelector<HTMLElement>(`[data-mcp-authorize-id="${CSS.escape(item.id)}"]`)?.classList.toggle("fn__none", item.status !== "authorization_required");+ block.querySelector<HTMLElement>(`[data-mcp-disconnect-oauth-id="${CSS.escape(item.id)}"]`)?.classList.toggle("fn__none", !item.authorized);+ }+ const configuredServerIDs = new Set(items.map((item) => item.id));+ for (const serverID of openedMcpOAuthURLs.keys()) {+ if (!configuredServerIDs.has(serverID)) {+ openedMcpOAuthURLs.delete(serverID);+ }}// 标题右侧汇总:已连接 server 数 + 总工具数。const summaryEl = block.querySelector<HTMLElement>("#aiMcpStatusSummary");@@ -1081,6 +1128,9 @@ export const mountMcpServersBlock = (root: HTMLElement) => {const getMcpServerName = (el: HTMLElement): string | undefined => {return el.closest<HTMLElement>("[data-mcp-server-name]")?.dataset.mcpServerName;};+ const getMcpServerID = (el: HTMLElement): string | undefined => {+ return el.closest<HTMLElement>("[data-mcp-server-id]")?.dataset.mcpServerId;+ };block.addEventListener("click", (event) => {const target = event.target as HTMLElement;const actionEl = target.closest<HTMLElement>("[data-type]");@@ -1116,6 +1166,35 @@ export const mountMcpServersBlock = (root: HTMLElement) => {});return;}+ if (type === "authorizeAiMcpServer") {+ const serverID = getMcpServerID(actionEl);+ if (serverID) {+ fetchPost("/api/ai/mcpOAuthAuthorize", {id: serverID}, (response) => {+ if (response.code !== 0) {+ showMessage(response.msg);+ }+ });+ }+ event.preventDefault();+ event.stopPropagation();+ return;+ }+ if (type === "disconnectAiMcpOAuth") {+ const serverID = getMcpServerID(actionEl);+ if (serverID) {+ confirmDialog(window.siyuan.languages.mcpDisconnectAuthorization,+ window.siyuan.languages.mcpDisconnectAuthorizationConfirm, () => {+ fetchPost("/api/ai/mcpOAuthDisconnect", {id: serverID}, (response) => {+ if (response.code !== 0) {+ showMessage(response.msg);+ }+ });+ });+ }+ event.preventDefault();+ event.stopPropagation();+ return;+ }});block.addEventListener("change", (event) => {@@ -1149,10 +1228,16 @@ const renderMcpServerList = (root: HTMLElement) => {return;}const serversHtml = servers.map((server) => {- return `<div class="b3-list-item b3-list-item--narrow${hideActionClass}" data-type="aiMcpServer" data-mcp-server-name="${Lute.EscapeHTMLStr(server.name)}">- <span class="mcp-status-dot b3-tooltips b3-tooltips__n" data-mcp-status-name="${Lute.EscapeHTMLStr(server.name)}" aria-label="${server.enabled ? window.siyuan.languages.mcpStatusConnecting : window.siyuan.languages.mcpStatusDisabled}" style="display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex-shrink:0;margin-right:4px;"><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background-color:${server.enabled ? "#d97706" : "var(--b3-theme-on-surface-light)"};"></span></span>+ return `<div class="b3-list-item b3-list-item--narrow${hideActionClass}" data-type="aiMcpServer" data-mcp-server-id="${Lute.EscapeHTMLStr(server.id)}" data-mcp-server-name="${Lute.EscapeHTMLStr(server.name)}">+ <span class="mcp-status-dot b3-tooltips b3-tooltips__n" data-mcp-status-id="${Lute.EscapeHTMLStr(server.id)}" aria-label="${server.enabled ? window.siyuan.languages.mcpStatusConnecting : window.siyuan.languages.mcpStatusDisabled}" style="display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex-shrink:0;margin-right:4px;"><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background-color:${server.enabled ? "#d97706" : "var(--b3-theme-on-surface-light)"};"></span></span><span class="b3-list-item__text">${Lute.EscapeHTMLStr(server.name)}</span>- <span class="ft__on-surface fn__flex-center" data-mcp-tools-count="${Lute.EscapeHTMLStr(server.name)}" style="font-size:12px;margin-right:8px;"></span>+ <span class="ft__on-surface fn__flex-center" data-mcp-tools-count="${Lute.EscapeHTMLStr(server.id)}" style="font-size:12px;margin-right:8px;"></span>+ <span data-type="authorizeAiMcpServer" data-mcp-authorize-id="${Lute.EscapeHTMLStr(server.id)}" class="fn__none b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.mcpAuthorize}">+ <svg><use xlink:href="#iconKey"></use></svg>+ </span>+ <span data-type="disconnectAiMcpOAuth" data-mcp-disconnect-oauth-id="${Lute.EscapeHTMLStr(server.id)}" class="fn__none b3-list-item__action b3-list-item__action--warning b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.mcpDisconnectAuthorization}">+ <svg><use xlink:href="#iconLinkOff"></use></svg>+ </span><span data-type="deleteAiMcpServer" class="b3-list-item__action b3-list-item__action--warning b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.delete}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>@@ -1173,6 +1258,7 @@ const openMcpServerDialog = (root: HTMLElement, serverName: string | null) => {return;}const initialServer: Config.IMCPServer = isNew ? {+ id: "",name: "",enabled: true,type: "stdio",diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 241da37111..e9375c1242 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -238,6 +238,7 @@ declare namespace Config {}export interface IMCPServer {+ id: string;enabled: boolean;name: string;url: string;diff --git a/kernel/api/ai.go b/kernel/api/ai.goindex 998f2c2a4f..aaddd0b2c6 100644--- a/kernel/api/ai.go+++ b/kernel/api/ai.go@@ -17,6 +17,7 @@package apiimport (+ "html""net/http""github.com/88250/gulu"@@ -231,6 +232,87 @@ func mcpStatus(c *gin.Context) {ret.Data = mcpclient.MCPStatus()}+func mcpOAuthAuthorize(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ serverID, _ := arg["id"].(string)+ if model.Conf.AI == nil || model.Conf.AI.MCP == nil {+ ret.Code = -1+ ret.Msg = "MCP server not found"+ return+ }+ for _, server := range model.Conf.AI.MCP.Servers {+ if server.ID == serverID && server.Enabled && server.Type == "http" {+ mcpclient.ReconnectMCPAsync(model.Conf.AI.MCP.Servers, []string{serverID}, []string{serverID})+ return+ }+ }+ ret.Code = -1+ ret.Msg = "MCP server not found"+}++func mcpOAuthDisconnect(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ serverID, _ := arg["id"].(string)+ if err := mcpclient.DisconnectMCPOAuth(serverID); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ }+ if model.Conf.AI != nil && model.Conf.AI.MCP != nil {+ mcpclient.ReconnectMCPAsync(model.Conf.AI.MCP.Servers, []string{serverID}, nil)+ }+}++func mcpOAuthCallback(c *gin.Context) {+ if !mcpclient.IsLoopbackCallback(c.Request.RemoteAddr) {+ c.String(http.StatusForbidden, "Forbidden")+ return+ }+ c.Header("Cache-Control", "no-store")+ c.Header("Referrer-Policy", "no-referrer")+ c.Header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")+ callbackError := c.Query("error")+ if err := mcpclient.CompleteMCPOAuth(c.Param("flowID"), c.Query("code"), c.Query("state"), callbackError); err != nil {+ c.Data(http.StatusBadRequest, "text/html; charset=utf-8", renderMCPOAuthCallbackPage(+ util.LangToBCP47(model.Conf.Lang), model.Conf.Language(327), model.Conf.Language(328), false))+ return+ }+ if callbackError != "" {+ c.Data(http.StatusOK, "text/html; charset=utf-8", renderMCPOAuthCallbackPage(+ util.LangToBCP47(model.Conf.Lang), model.Conf.Language(327), model.Conf.Language(328), false))+ return+ }+ c.Data(http.StatusOK, "text/html; charset=utf-8", renderMCPOAuthCallbackPage(+ util.LangToBCP47(model.Conf.Lang), model.Conf.Language(325), model.Conf.Language(326), true))+}++func renderMCPOAuthCallbackPage(lang, title, message string, success bool) []byte {+ markClass, mark := " mark--error", "!"+ if success {+ markClass, mark = "", "✓"+ }+ return []byte(`<!doctype html><html lang="` + html.EscapeString(lang) + `"><head><meta charset="utf-8">` ++ `<meta name="viewport" content="width=device-width,initial-scale=1"><title>` + html.EscapeString(title) + `</title>` ++ `<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f5f5f5;color:#202124;font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}` ++ `main{box-sizing:border-box;width:min(480px,calc(100vw - 32px));padding:40px 32px;text-align:center;background:#fff;border:1px solid #ddd;border-radius:12px;box-shadow:0 8px 24px #00000014}` ++ `.mark{display:grid;place-items:center;width:56px;height:56px;margin:0 auto 24px;border-radius:50%;background:#2e7d32;color:#fff;font-size:32px}.mark--error{background:#c62828}` ++ `h1{margin:0 0 12px;font-size:24px;font-weight:600}p{margin:0;color:#5f6368;font-size:15px;line-height:1.7}` ++ `@media(prefers-color-scheme:dark){body{background:#171717;color:#eee}main{background:#242424;border-color:#3c3c3c;box-shadow:none}p{color:#bbb}}</style>` ++ `</head><body><main><div class="mark` + markClass + `" aria-hidden="true">` + mark + `</div><h1>` + html.EscapeString(title) ++ `</h1><p>` + html.EscapeString(message) + `</p></main></body></html>`)+}+// reindexEmbedding 清空嵌入向量表并触发后台索引器重新计算所有块,异步执行。func reindexEmbedding(c *gin.Context) {ret := gulu.Ret.NewResult()diff --git a/kernel/api/mcp_oauth_test.go b/kernel/api/mcp_oauth_test.gonew file mode 100644index 0000000000..70b1bef49a--- /dev/null+++ b/kernel/api/mcp_oauth_test.go@@ -0,0 +1,56 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+)++func TestPreserveMCPServerIDsForOlderFrontend(t *testing.T) {+ oldServers := []conf.MCPServer{+ {ID: "first-id", Name: "first"},+ {ID: "second-id", Name: "second"},+ }+ newServers := []conf.MCPServer{+ {Name: "first"},+ {Name: "second"},+ {ID: "new-id", Name: "new"},+ }+ preserveMCPServerIDs(oldServers, newServers)+ if newServers[0].ID != "first-id" || newServers[1].ID != "second-id" || newServers[2].ID != "new-id" {+ t.Fatalf("unexpected MCP server IDs: %#v", newServers)+ }+}++func TestRenderMCPOAuthCallbackPage(t *testing.T) {+ page := string(renderMCPOAuthCallbackPage("zh-CN", "已收到<script>", "返回思源 & 查看状态", true))+ for _, expected := range []string{`lang="zh-CN"`, "已收到<script>", "返回思源 & 查看状态"} {+ if !strings.Contains(page, expected) {+ t.Fatalf("OAuth callback page does not contain %q: %s", expected, page)+ }+ }+ if strings.Contains(page, "window.close") || strings.Contains(page, "已收到<script>") {+ t.Fatalf("OAuth callback page contains unsafe or auto-close content: %s", page)+ }+ failurePage := string(renderMCPOAuthCallbackPage("en", "Authorization failed", "Try again", false))+ if !strings.Contains(failurePage, `class="mark mark--error"`) {+ t.Fatalf("OAuth failure callback page does not use the error state: %s", failurePage)+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 3c7885b28f..dc69c61d03 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -39,6 +39,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/system/loginAuth", model.LoginAuth)ginServer.Handle("POST", "/api/system/logoutAuth", model.LogoutAuth)ginServer.Handle("GET", "/api/system/getCaptcha", model.GetCaptcha)+ ginServer.Handle("GET", "/api/ai/mcp/oauth/callback/:flowID", mcpOAuthCallback)// 需要鉴权ginServer.Handle("GET", "/api/icon/getDynamicIcon", model.CheckAuth, getDynamicIcon)@@ -555,6 +556,8 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/ai/listModels", model.CheckAuth, model.CheckAdminRole, listModels)ginServer.Handle("POST", "/api/ai/embeddingStat", model.CheckAuth, model.CheckAdminRole, embeddingStat)ginServer.Handle("POST", "/api/ai/mcpStatus", model.CheckAuth, model.CheckAdminRole, mcpStatus)+ ginServer.Handle("POST", "/api/ai/mcpOAuthAuthorize", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, mcpOAuthAuthorize)+ ginServer.Handle("POST", "/api/ai/mcpOAuthDisconnect", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, mcpOAuthDisconnect)ginServer.Handle("POST", "/api/ai/reindexEmbedding", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, reindexEmbedding)ginServer.Handle("POST", "/api/ai/retryFailedEmbedding", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, retryFailedEmbedding)ginServer.Handle("POST", "/api/ai/agent/chat", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChat)diff --git a/kernel/api/setting.go b/kernel/api/setting.goindex edebd0d294..db3ae034a5 100644--- a/kernel/api/setting.go+++ b/kernel/api/setting.go@@ -19,10 +19,12 @@ package apiimport ("fmt""net/http"+ "reflect""strings""github.com/88250/gulu""github.com/gin-gonic/gin"+ "github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/conf"mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client""github.com/siyuan-note/siyuan/kernel/model"@@ -199,19 +201,63 @@ func setAI(c *gin.Context) {return}- model.Conf.AI = ai-- model.Conf.AI.Normalize()- model.Conf.Save()+ var oldServers []conf.MCPServer+ if model.Conf.AI != nil && model.Conf.AI.MCP != nil {+ oldServers = append(oldServers, model.Conf.AI.MCP.Servers...)+ }+ if ai.MCP != nil {+ preserveMCPServerIDs(oldServers, ai.MCP.Servers)+ }+ ai.Normalize()+ model.Conf.SetAI(ai)// MCP 配置可能变更(开关切换、编辑、增删 server),异步重连让连接立即跟上。if model.Conf.AI.MCP != nil {- mcpclient.ReconnectMCPAsync(model.Conf.AI.MCP.Servers)+ newServers := model.Conf.AI.MCP.Servers+ oldByID := make(map[string]conf.MCPServer, len(oldServers))+ newByID := make(map[string]conf.MCPServer, len(newServers))+ for _, server := range oldServers {+ oldByID[server.ID] = server+ }+ for _, server := range newServers {+ newByID[server.ID] = server+ }++ var interactiveServerIDs []string+ for _, server := range newServers {+ old, existed := oldByID[server.ID]+ if server.Enabled && server.Type == "http" && (!existed || !reflect.DeepEqual(old, server)) {+ interactiveServerIDs = append(interactiveServerIDs, server.ID)+ }+ }+ for _, server := range oldServers {+ updated, exists := newByID[server.ID]+ if !exists || (server.Type == "http" && (updated.Type != "http" || updated.URL != server.URL)) {+ if revokeErr := mcpclient.DisconnectMCPOAuth(server.ID); revokeErr != nil {+ logging.LogWarnf("mcp oauth: disconnect server [%s] failed: %s", server.Name, revokeErr)+ }+ }+ }+ if !reflect.DeepEqual(oldServers, newServers) {+ mcpclient.ReconnectMCPAsync(newServers, nil, interactiveServerIDs)+ }}ret.Data = model.Conf.AI}+func preserveMCPServerIDs(oldServers, newServers []conf.MCPServer) {+ oldIDsByName := make(map[string]string, len(oldServers))+ for _, server := range oldServers {+ oldIDsByName[server.Name] = server.ID+ }+ for i := range newServers {+ if newServers[i].ID == "" {+ newServers[i].ID = oldIDsByName[newServers[i].Name]+ }+ }+}+func setSecrets(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex 0226671578..3ef1abe40a 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -24,6 +24,7 @@ import ("strings""github.com/88250/lute/ast"+ "github.com/google/uuid""github.com/siyuan-note/siyuan/kernel/util")@@ -126,6 +127,7 @@ type MCP struct {}type MCPServer struct {+ ID string `json:"id"`Name string `json:"name"`Enabled bool `json:"enabled"`Type string `json:"type"`@@ -368,6 +370,13 @@ func (ai *AI) Normalize() {} else if ai.MCP.Servers == nil {ai.MCP.Servers = []MCPServer{}}+ serverIDs := map[string]bool{}+ for i := range ai.MCP.Servers {+ if ai.MCP.Servers[i].ID == "" || serverIDs[ai.MCP.Servers[i].ID] {+ ai.MCP.Servers[i].ID = uuid.New().String()+ }+ serverIDs[ai.MCP.Servers[i].ID] = true+ }if ai.Agent == nil {ai.Agent = defaultAgent()} else {@@ -711,6 +720,7 @@ func migrateMCP(raw map[string]any) *MCP {continue}mcp.Servers = append(mcp.Servers, MCPServer{+ ID: getString(sm, "id"),Name: getString(sm, "name"),Enabled: getBool(sm, "enabled"),Type: getString(sm, "type"),diff --git a/kernel/conf/ai_mcp_test.go b/kernel/conf/ai_mcp_test.gonew file mode 100644index 0000000000..270d0a4edb--- /dev/null+++ b/kernel/conf/ai_mcp_test.go@@ -0,0 +1,36 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package conf++import "testing"++func TestNormalizeMCPServerIDs(t *testing.T) {+ ai := NewAI()+ ai.MCP.Servers = []MCPServer{+ {Name: "missing"},+ {ID: "duplicate", Name: "first"},+ {ID: "duplicate", Name: "second"},+ }+ ai.Normalize()+ seen := map[string]bool{}+ for _, server := range ai.MCP.Servers {+ if server.ID == "" || seen[server.ID] {+ t.Fatalf("unexpected MCP server ID: %#v", ai.MCP.Servers)+ }+ seen[server.ID] = true+ }+}diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.goindex ef4431e72d..2ee1ab09a5 100644--- a/kernel/mcp/client/mcp.go+++ b/kernel/mcp/client/mcp.go@@ -18,11 +18,13 @@ package clientimport ("context"+ "crypto/sha256""errors""fmt""io""net/http""os/exec"+ "reflect""strings""sync""time"@@ -40,50 +42,111 @@ const ()type Connection struct {- ServerName string- Session *mcp.ClientSession- Cmd *exec.Cmd- Tools int // 已注册的工具数量,供状态查询展示+ ServerID string+ ServerName string+ Session *mcp.ClientSession+ Cmd *exec.Cmd+ Tools int+ RegisteredTools map[string]*tools.Tool+ Config conf.MCPServer+}++type mcpRuntimeState struct {+ Status string+ Tools int+ Error string+ AuthorizationURL string}var (- mcpMu sync.Mutex- mcpConns []Connection- mcpServers []conf.MCPServer- mcpConnecting bool // 是否有后台连接 goroutine 正在进行,防止重复启动- mcpDisconnected bool // 连接期间是否被 DisconnectMCP 要求放弃结果+ mcpMu sync.Mutex+ mcpConns []Connection+ mcpServers []conf.MCPServer+ mcpConnecting bool // 是否有后台连接 goroutine 正在进行,防止重复启动+ mcpConnectCancel context.CancelFunc+ mcpGeneration uint64+ mcpRuntime = map[string]mcpRuntimeState{})+type mcpGenerationContextKey struct{}++func setMCPRuntimeState(serverID, status string, toolsCount int, errMsg, authorizationURL string) {+ mcpMu.Lock()+ setMCPRuntimeStateLocked(serverID, status, toolsCount, errMsg, authorizationURL)+ mcpMu.Unlock()+}++func setMCPRuntimeStateForContext(ctx context.Context, serverID, status string, toolsCount int, errMsg, authorizationURL string) {+ generation, ok := ctx.Value(mcpGenerationContextKey{}).(uint64)+ mcpMu.Lock()+ if ok && generation != mcpGeneration {+ mcpMu.Unlock()+ return+ }+ setMCPRuntimeStateLocked(serverID, status, toolsCount, errMsg, authorizationURL)+ mcpMu.Unlock()+}++func setOAuthRetryStateForError(ctx context.Context, serverID, errMsg string) bool {+ generation, ok := ctx.Value(mcpGenerationContextKey{}).(uint64)+ mcpMu.Lock()+ defer mcpMu.Unlock()+ if ok && generation != mcpGeneration {+ return false+ }+ status := mcpRuntime[serverID].Status+ if status == "oauth_retrying" && !isOAuthAuthenticationError(errMsg) {+ return false+ }+ if status != "authorizing" && status != "authorization_required" && status != "oauth_retrying" {+ return false+ }+ setMCPRuntimeStateLocked(serverID, "authorization_required", 0, errMsg, "")+ return true+}++func isOAuthAuthenticationError(errMsg string) bool {+ message := strings.ToLower(errMsg)+ return strings.Contains(message, "401") || strings.Contains(message, "403") ||+ strings.Contains(message, "unauthorized") || strings.Contains(message, "forbidden") ||+ strings.Contains(message, "invalid_token")+}++func setMCPRuntimeStateLocked(serverID, status string, toolsCount int, errMsg, authorizationURL string) {+ mcpRuntime[serverID] = mcpRuntimeState{+ Status: status,+ Tools: toolsCount,+ Error: errMsg,+ AuthorizationURL: authorizationURL,+ }+}+// EnsureMCPConnected 确保 MCP server 已连接。// 首次调用时在后台异步连接,立即返回不阻塞调用方(如 Agent 请求路径)。// 连接完成前发起的 Agent 请求本轮可能看不到 MCP 工具,下轮即可用。// 后续调用若已连接则直接返回;若后台连接仍在进行则也直接返回,等其完成。func EnsureMCPConnected(servers []conf.MCPServer) {+ servers = append([]conf.MCPServer(nil), servers...)mcpMu.Lock()- mcpServers = servers- if len(mcpConns) > 0 || mcpConnecting {+ if mcpConnecting {mcpMu.Unlock()return}- mcpConnecting = true- mcpDisconnected = false- mcpMu.Unlock()-- // 后台连接:耗时操作(握手 + 拉取工具列表)不阻塞调用方。- go func() {- conns := connectServers(servers)- mcpMu.Lock()- mcpConnecting = false- if mcpDisconnected {- // 连接期间被 DisconnectMCP 要求放弃,丢弃结果并关闭刚建好的连接避免泄漏。- mcpDisconnected = false- mcpMu.Unlock()- closeConnections(conns)- return+ connected := make(map[string]bool, len(mcpConns))+ for _, connection := range mcpConns {+ connected[connection.ServerID] = true+ }+ needsConnect := len(mcpServers) == 0+ for _, server := range servers {+ if server.Enabled && !connected[server.ID] && mcpRuntime[server.ID].Status != "authorization_required" {+ needsConnect = true+ break}- mcpConns = conns- mcpMu.Unlock()- }()+ }+ mcpMu.Unlock()+ if needsConnect {+ ReconnectMCPAsync(servers, nil, nil)+ }}// serverTimeout 归一化服务器配置的超时(秒),未配置或非法时回退到默认值。@@ -113,79 +176,192 @@ func (h *headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, errorfunc DisconnectMCP() {mcpMu.Lock()defer mcpMu.Unlock()+ if mcpConnectCancel != nil {+ mcpConnectCancel()+ mcpConnectCancel = nil+ }+ mcpGeneration+++ mcpConnecting = falsecloseConnections(mcpConns)mcpConns = nil- // 若后台仍有连接 goroutine 在进行,标记其结果应被丢弃。- mcpDisconnected = true}-func connectServers(servers []conf.MCPServer) []Connection {- var connections []Connection-+func connectServers(ctx context.Context, servers []conf.MCPServer, interactive map[string]bool, connected func(Connection) bool) {for _, server := range servers {+ if ctx.Err() != nil {+ break+ }if !server.Enabled {+ setMCPRuntimeStateForContext(ctx, server.ID, "disabled", 0, "", "")continue}+ setMCPRuntimeStateForContext(ctx, server.ID, "connecting", 0, "", "")+ connection := connectOneServer(ctx, server, interactive[server.ID])+ if connection != nil && !connected(*connection) {+ closeConnections([]Connection{*connection})+ }+ }+}- session, cmd, err := connectServer(server)- if err != nil {- logging.LogWarnf("mcp: server [%s] connect failed: %s", server.Name, err)- continue+func connectOneServer(ctx context.Context, server conf.MCPServer, interactive bool) *Connection {+ session, cmd, oauthHandler, err := connectServer(ctx, server, interactive)+ if err != nil {+ if ctx.Err() != nil {+ return nil+ }+ if errors.Is(err, errOAuthAuthorizationRequired) {+ return nil+ }+ if setOAuthRetryStateForError(ctx, server.ID, err.Error()) {+ if markErr := markOAuthCredentialRejected(server.ID, server.URL); markErr != nil {+ logging.LogWarnf("mcp oauth: mark rejected credentials failed: %s", markErr)+ }+ return nil+ }+ setMCPRuntimeStateForContext(ctx, server.ID, "failed", 0, err.Error(), "")+ logging.LogWarnf("mcp: server [%s] connect failed: %s", server.Name, err)+ return nil+ }+ if ctx.Err() != nil {+ session.Close()+ if cmd != nil && cmd.Process != nil {+ cmd.Process.Kill()+ cmd.Wait()}+ return nil+ }- listCtx, listCancel := context.WithTimeout(context.Background(), serverTimeout(server))- toolList, err := session.ListTools(listCtx, nil)- listCancel()- if err != nil {- logging.LogWarnf("mcp: server [%s] list tools failed: %s", server.Name, err)+ listCtx, listCancel := context.WithTimeout(ctx, serverTimeout(server))+ toolList, err := session.ListTools(listCtx, nil)+ listCancel()+ if err != nil {+ if ctx.Err() != nil {session.Close()if cmd != nil && cmd.Process != nil {cmd.Process.Kill()cmd.Wait()}- continue+ return nil}-- registered := 0- for _, t := range toolList.Tools {- tool := t- name := "mcp_" + sanitize(server.Name) + "_" + sanitize(tool.Name)- desc := tool.Description- if !strings.HasPrefix(desc, "[MCP]") {- desc = "[MCP:" + server.Name + "] " + desc+ if errors.Is(err, errOAuthAuthorizationRequired) || setOAuthRetryStateForError(ctx, server.ID, err.Error()) {+ if markErr := markOAuthCredentialRejected(server.ID, server.URL); markErr != nil {+ logging.LogWarnf("mcp oauth: mark rejected credentials failed: %s", markErr)}+ session.Close()+ if cmd != nil && cmd.Process != nil {+ cmd.Process.Kill()+ cmd.Wait()+ }+ return nil+ }+ setMCPRuntimeStateForContext(ctx, server.ID, "failed", 0, err.Error(), "")+ logging.LogWarnf("mcp: server [%s] list tools failed: %s", server.Name, err)+ session.Close()+ if cmd != nil && cmd.Process != nil {+ cmd.Process.Kill()+ cmd.Wait()+ }+ return nil+ }+ if oauthHandler != nil {+ oauthHandler.disableInteractive()+ }++ baseNameCounts := make(map[string]int, len(toolList.Tools))+ for _, tool := range toolList.Tools {+ baseNameCounts["mcp_"+sanitize(server.Name)+"_"+sanitize(tool.Name)]+++ }+ serverNameCollision := sanitizedServerNameCollision(server)+ registeredTools := map[string]*tools.Tool{}+ for _, t := range toolList.Tools {+ tool := t+ baseName := "mcp_" + sanitize(server.Name) + "_" + sanitize(tool.Name)+ name := mcpToolName(server, tool.Name,+ serverNameCollision || baseNameCounts[baseName] > 1 || tools.LookupTool(baseName) != nil)+ desc := tool.Description+ if !strings.HasPrefix(desc, "[MCP]") {+ desc = "[MCP:" + server.Name + "] " + desc+ }- readOnlyHint := trustedReadOnlyHint(server, tool)- handler := mcpToolContextHandler(server.Name, tool.Name, serverTimeout(server))- tools.SetTool(name, &tools.Tool{- Name: name,- Description: desc,- InputSchema: convertMCPSchema(tool.InputSchema),- Source: "mcp",- ReadOnlyHint: readOnlyHint,- EffectScope: tools.EffectScopeExternal,- Handler: func(args map[string]any) (tools.CallToolResult, error) {- return handler(context.Background(), args)- },- ContextHandler: handler,- })- registered++- }-- connections = append(connections, Connection{- ServerName: server.Name,- Session: session,- Cmd: cmd,- Tools: registered,- })- logging.LogInfof("mcp: server [%s] connected, %d tools registered", server.Name, registered)+ readOnlyHint := trustedReadOnlyHint(server, tool)+ handler := mcpToolContextHandler(server.Name, tool.Name, serverTimeout(server))+ registeredTool := &tools.Tool{+ Name: name,+ Description: desc,+ InputSchema: convertMCPSchema(tool.InputSchema),+ Source: "mcp",+ ReadOnlyHint: readOnlyHint,+ EffectScope: tools.EffectScopeExternal,+ Handler: func(args map[string]any) (tools.CallToolResult, error) {+ return handler(context.Background(), args)+ },+ ContextHandler: handler,+ }+ registeredTools[name] = registeredTool}+ if !registerMCPToolsForContext(ctx, registeredTools) {+ session.Close()+ if cmd != nil && cmd.Process != nil {+ cmd.Process.Kill()+ cmd.Wait()+ }+ return nil+ }+ registered := len(registeredTools)++ connection := &Connection{+ ServerID: server.ID,+ ServerName: server.Name,+ Session: session,+ Cmd: cmd,+ Tools: registered,+ RegisteredTools: registeredTools,+ Config: server,+ }+ setMCPRuntimeStateForContext(ctx, server.ID, "connected", registered, "", "")+ logging.LogInfof("mcp: server [%s] connected, %d tools registered", server.Name, registered)+ return connection+}- return connections+func sanitizedServerNameCollision(server conf.MCPServer) bool {+ mcpMu.Lock()+ defer mcpMu.Unlock()+ sanitizedName := sanitize(server.Name)+ for _, configured := range mcpServers {+ if configured.ID != server.ID && sanitize(configured.Name) == sanitizedName {+ return true+ }+ }+ return false+}++func mcpToolName(server conf.MCPServer, toolName string, collision bool) string {+ name := "mcp_" + sanitize(server.Name) + "_" + sanitize(toolName)+ if !collision {+ return name+ }+ hash := sha256.Sum256([]byte(server.ID + "\x00" + toolName))+ return fmt.Sprintf("%s_%x", name, hash[:6])+}++func registerMCPToolsForContext(ctx context.Context, registeredTools map[string]*tools.Tool) bool {+ generation, ok := ctx.Value(mcpGenerationContextKey{}).(uint64)+ mcpMu.Lock()+ defer mcpMu.Unlock()+ if ctx.Err() != nil || ok && generation != mcpGeneration {+ return false+ }+ for name, tool := range registeredTools {+ tools.SetTool(name, tool)+ }+ return true}func closeConnections(connections []Connection) {for _, conn := range connections {+ for toolName, registeredTool := range conn.RegisteredTools {+ tools.RemoveToolIf(toolName, registeredTool)+ }if conn.Session != nil {conn.Session.Close()}@@ -196,20 +372,21 @@ func closeConnections(connections []Connection) {}}-func connectServer(server conf.MCPServer) (*mcp.ClientSession, *exec.Cmd, error) {+func connectServer(ctx context.Context, server conf.MCPServer, interactive bool) (*mcp.ClientSession, *exec.Cmd, *mcpOAuthHandler, error) {c := mcp.NewClient(&mcp.Implementation{Name: "siyuan", Version: "3.0"}, nil)switch server.Type {case "stdio":- return connectStdio(c, server)+ session, cmd, err := connectStdio(ctx, c, server)+ return session, cmd, nil, errcase "http":- return connectHTTP(c, server)+ return connectHTTP(ctx, c, server, interactive)default:- return nil, nil, fmt.Errorf("unsupported server type: %s", server.Type)+ return nil, nil, nil, fmt.Errorf("unsupported server type: %s", server.Type)}}-func connectStdio(client *mcp.Client, server conf.MCPServer) (*mcp.ClientSession, *exec.Cmd, error) {+func connectStdio(ctx context.Context, client *mcp.Client, server conf.MCPServer) (*mcp.ClientSession, *exec.Cmd, error) {if server.Command == "" {return nil, nil, fmt.Errorf("command is required for stdio server")}@@ -229,7 +406,7 @@ func connectStdio(client *mcp.Client, server conf.MCPServer) (*mcp.ClientSessionreturn nil, nil, fmt.Errorf("start command: %w", err)}- connectCtx, connectCancel := context.WithTimeout(context.Background(), serverTimeout(server))+ connectCtx, connectCancel := context.WithTimeout(ctx, serverTimeout(server))defer connectCancel()transport := &mcp.IOTransport{Reader: stdout, Writer: stdin}session, err := client.Connect(connectCtx, transport, nil)@@ -242,14 +419,19 @@ func connectStdio(client *mcp.Client, server conf.MCPServer) (*mcp.ClientSessionreturn session, cmd, nil}-func connectHTTP(client *mcp.Client, server conf.MCPServer) (*mcp.ClientSession, *exec.Cmd, error) {+func connectHTTP(ctx context.Context, client *mcp.Client, server conf.MCPServer, interactive bool) (*mcp.ClientSession, *exec.Cmd, *mcpOAuthHandler, error) {if server.URL == "" {- return nil, nil, fmt.Errorf("url is required for http server")+ return nil, nil, nil, fmt.Errorf("url is required for http server")}transport := &mcp.StreamableClientTransport{Endpoint: server.URL,}+ var oauthHandler *mcpOAuthHandler+ if !hasAuthorizationHeader(server.Headers) {+ oauthHandler = newMCPOAuthHandler(server, interactive)+ transport.OAuthHandler = oauthHandler+ }// 所有 MCP HTTP 出站请求统一带上 SiYuan UA,便于第三方 MCP server 识别客户端身份uaBase := httpclient.NewUserAgentRoundTripper(http.DefaultTransport)if len(server.Headers) > 0 {@@ -263,28 +445,80 @@ func connectHTTP(client *mcp.Client, server conf.MCPServer) (*mcp.ClientSession,transport.HTTPClient = &http.Client{Transport: uaBase}}- connectCtx, connectCancel := context.WithTimeout(context.Background(), serverTimeout(server))+ connectTimeout := serverTimeout(server)+ if interactive {+ connectTimeout += oauthAuthorizationTimeout+ }+ connectCtx, connectCancel := context.WithTimeout(ctx, connectTimeout)defer connectCancel()session, err := client.Connect(connectCtx, transport, nil)if err != nil {- return nil, nil, fmt.Errorf("connect: %w", err)+ return nil, nil, oauthHandler, fmt.Errorf("connect: %w", err)}- return session, nil, nil+ return session, nil, oauthHandler, nil+}++func hasAuthorizationHeader(headers map[string]string) bool {+ for name := range headers {+ if strings.EqualFold(name, "Authorization") {+ return true+ }+ }+ return false}func mcpToolContextHandler(serverName, toolName string, timeout time.Duration) func(context.Context, map[string]any) (tools.CallToolResult, error) {return func(ctx context.Context, args map[string]any) (tools.CallToolResult, error) {result := callMCPToolOnce(func() (*mcp.CallToolResult, error) {- return callMCPTool(ctx, serverName, toolName, timeout, args)+ result, err := callMCPTool(ctx, serverName, toolName, timeout, args)+ updateMCPRuntimeAfterToolCall(serverName, err)+ return result, err}, func(err error) {logging.LogWarnf("mcp: server [%s] tool [%s] disconnected (%s), reconnecting", serverName, toolName, err)- go reconnectMCP()+ go reconnectMCP(serverName)})return result, nil}}+func updateMCPRuntimeAfterToolCall(serverName string, callErr error) {+ mcpMu.Lock()+ connectionIndex := -1+ for i := range mcpConns {+ if mcpConns[i].ServerName == serverName {+ connectionIndex = i+ break+ }+ }+ if connectionIndex < 0 {+ mcpMu.Unlock()+ return+ }+ connection := mcpConns[connectionIndex]+ status := mcpRuntime[connection.ServerID].Status+ if status != "oauth_retrying" && status != "authorization_required" {+ mcpMu.Unlock()+ return+ }+ if (callErr != nil && isOAuthAuthenticationError(callErr.Error())) || status == "authorization_required" {+ errMsg := ""+ if callErr != nil {+ errMsg = callErr.Error()+ }+ setMCPRuntimeStateLocked(connection.ServerID, "authorization_required", 0, errMsg, "")+ mcpConns = append(mcpConns[:connectionIndex], mcpConns[connectionIndex+1:]...)+ mcpMu.Unlock()+ if markErr := markOAuthCredentialRejected(connection.ServerID, connection.Config.URL); markErr != nil {+ logging.LogWarnf("mcp oauth: mark rejected credentials failed: %s", markErr)+ }+ closeConnections([]Connection{connection})+ return+ }+ setMCPRuntimeStateLocked(connection.ServerID, "connected", connection.Tools, "", "")+ mcpMu.Unlock()+}+// callMCPToolOnce 保证一次工具请求最多发送一次。断线时只恢复后续调用所需的连接,不重放当前请求。func callMCPToolOnce(call func() (*mcp.CallToolResult, error), reconnect func(error)) tools.CallToolResult {result, err := call()@@ -357,62 +591,108 @@ func getMCPSession(serverName string) *mcp.ClientSession {}// reconnectMCP 关闭现有连接并重新注册工具。-func reconnectMCP() bool {+func reconnectMCP(serverName string) bool {mcpMu.Lock()- // 后台首次连接仍在进行时,重连无意义(连接尚未就绪,工具调用本不会到达这里)。- if mcpConnecting || len(mcpServers) == 0 {+ if mcpConnecting {mcpMu.Unlock()return false}- closeConnections(mcpConns)- mcpConns = nil- mcpConnecting = true- mcpMu.Unlock()-- conns := connectServers(mcpServers)- mcpMu.Lock()- mcpConnecting = false- if mcpDisconnected {- mcpDisconnected = false- mcpMu.Unlock()- closeConnections(conns)- return false- }- mcpConns = conns- for _, conn := range mcpConns {- if conn.Session != nil {- logging.LogInfof("mcp: reconnected server [%s]", conn.ServerName)- mcpMu.Unlock()- return true+ servers := append([]conf.MCPServer(nil), mcpServers...)+ serverID := ""+ for _, server := range servers {+ if server.Name == serverName {+ serverID = server.ID+ break}}mcpMu.Unlock()- return false+ if serverID == "" {+ return false+ }+ ReconnectMCPAsync(servers, []string{serverID}, nil)+ return true}// ReconnectMCPAsync 用最新的 server 配置异步重连,不阻塞调用方(如 setAI 配置保存)。// 适用于配置变更(开关切换、编辑、增删 server)后让连接立即跟上,而非等下次 Agent 请求。-func ReconnectMCPAsync(servers []conf.MCPServer) {+func ReconnectMCPAsync(servers []conf.MCPServer, forceServerIDs, interactiveServerIDs []string) {+ servers = append([]conf.MCPServer(nil), servers...)+ force := make(map[string]bool, len(forceServerIDs))+ for _, serverID := range forceServerIDs {+ force[serverID] = true+ }+ interactive := make(map[string]bool, len(interactiveServerIDs))+ for _, serverID := range interactiveServerIDs {+ interactive[serverID] = true+ }mcpMu.Lock()+ if mcpConnectCancel != nil {+ mcpConnectCancel()+ }+ mcpGeneration+++ generation := mcpGeneration+ connectCtx, connectCancel := context.WithCancel(context.WithValue(context.Background(), mcpGenerationContextKey{}, generation))+ mcpConnectCancel = connectCancelmcpServers = servers- mcpConnecting = true- mcpDisconnected = false- closeConnections(mcpConns)- mcpConns = nil+ serverByID := make(map[string]conf.MCPServer, len(servers))+ for _, server := range servers {+ serverByID[server.ID] = server+ }+ var kept, closing []Connection+ connected := map[string]bool{}+ for _, connection := range mcpConns {+ server, exists := serverByID[connection.ServerID]+ if exists && server.Enabled && !force[server.ID] && reflect.DeepEqual(connection.Config, server) {+ kept = append(kept, connection)+ connected[server.ID] = true+ } else {+ closing = append(closing, connection)+ }+ }+ mcpConns = kept+ var connectingServers []conf.MCPServer+ for _, server := range servers {+ if !server.Enabled {+ setMCPRuntimeStateLocked(server.ID, "disabled", 0, "", "")+ } else if !connected[server.ID] {+ setMCPRuntimeStateLocked(server.ID, "connecting", 0, "", "")+ connectingServers = append(connectingServers, server)+ }+ }+ for serverID := range mcpRuntime {+ if _, exists := serverByID[serverID]; !exists {+ delete(mcpRuntime, serverID)+ }+ }+ mcpConnecting = len(connectingServers) > 0+ if !mcpConnecting {+ mcpConnectCancel = nil+ connectCancel()+ }mcpMu.Unlock()+ closeConnections(closing)+ if len(connectingServers) == 0 {+ return+ }go func() {- conns := connectServers(servers)+ defer connectCancel()+ connectServers(connectCtx, connectingServers, interactive, func(connection Connection) bool {+ mcpMu.Lock()+ defer mcpMu.Unlock()+ if generation != mcpGeneration {+ return false+ }+ mcpConns = append(mcpConns, connection)+ return true+ })mcpMu.Lock()- mcpConnecting = false- if mcpDisconnected {- // 连接期间被 DisconnectMCP 要求放弃,丢弃结果并关闭刚建好的连接避免泄漏。- mcpDisconnected = false+ if generation != mcpGeneration {mcpMu.Unlock()- closeConnections(conns)return}- mcpConns = conns+ mcpConnecting = false+ mcpConnectCancel = nilmcpMu.Unlock()}()}@@ -464,39 +744,43 @@ func sanitize(s string) string {// MCPStatusItem 描述单个 MCP server 的连接状态,供前端展示。type MCPStatusItem struct {- Name string `json:"name"`- Status string `json:"status"` // connected | connecting | failed | disabled- Tools int `json:"tools"` // 已注册工具数(仅 connected 时有意义)+ ID string `json:"id"`+ Name string `json:"name"`+ Status string `json:"status"` // connected | connecting | authorizing | authorization_required | failed | disabled+ Tools int `json:"tools"` // 已注册工具数(仅 connected 时有意义)+ Error string `json:"error,omitempty"`+ AuthorizationURL string `json:"authorizationURL,omitempty"`+ Authorized bool `json:"authorized"`}// MCPStatus 返回所有已配置 MCP server 的当前连接状态。func MCPStatus() []MCPStatusItem {mcpMu.Lock()- servers := mcpServers- conns := mcpConns- connecting := mcpConnecting- mcpMu.Unlock()-- // 建立已连接 server 名 → 连接信息的索引。- connMap := make(map[string]*Connection, len(conns))- for i := range conns {- connMap[conns[i].ServerName] = &conns[i]+ servers := append([]conf.MCPServer(nil), mcpServers...)+ runtimeStates := make(map[string]mcpRuntimeState, len(mcpRuntime))+ for serverID, state := range mcpRuntime {+ runtimeStates[serverID] = state}+ mcpMu.Unlock()items := make([]MCPStatusItem, 0, len(servers))for _, srv := range servers {- item := MCPStatusItem{Name: srv.Name}- switch {- case !srv.Enabled:- item.Status = "disabled"- case connecting && connMap[srv.Name] == nil:- // 后台连接仍在进行,且该 server 尚未出现在已连接列表中。+ state := runtimeStates[srv.ID]+ item := MCPStatusItem{+ ID: srv.ID,+ Name: srv.Name,+ Status: state.Status,+ Tools: state.Tools,+ Error: state.Error,+ AuthorizationURL: state.AuthorizationURL,+ Authorized: srv.Type == "http" && hasOAuthCredential(srv.ID, srv.URL),+ }+ if item.Status == "oauth_retrying" {item.Status = "connecting"- case connMap[srv.Name] != nil:- item.Status = "connected"- item.Tools = connMap[srv.Name].Tools- default:- // 已启用但既未连上、也不在连接中(连接失败或尚未触发首次连接)。+ }+ if !srv.Enabled {+ item.Status = "disabled"+ } else if item.Status == "" {item.Status = "failed"}items = append(items, item)diff --git a/kernel/mcp/client/mcp_test.go b/kernel/mcp/client/mcp_test.goindex 8fb70d4ee3..2559b568ad 100644--- a/kernel/mcp/client/mcp_test.go+++ b/kernel/mcp/client/mcp_test.go@@ -20,6 +20,7 @@ import ("context""errors""testing"+ "time""github.com/modelcontextprotocol/go-sdk/mcp""github.com/siyuan-note/siyuan/kernel/conf"@@ -80,3 +81,144 @@ func TestTrustedReadOnlyHint(t *testing.T) {t.Fatal("trusted read-only annotation was ignored")}}++func TestMCPToolNameDisambiguatesSanitizedCollisions(t *testing.T) {+ serverA := conf.MCPServer{ID: "server-a", Name: "name with space"}+ serverB := conf.MCPServer{ID: "server-b", Name: "name_with_space"}+ nameA := mcpToolName(serverA, "read item", true)+ nameB := mcpToolName(serverB, "read item", true)+ if nameA == nameB {+ t.Fatalf("colliding MCP tool names: %q", nameA)+ }+ if name := mcpToolName(serverA, "read_item", false); name != "mcp_name_with_space_read_item" {+ t.Fatalf("unexpected ordinary MCP tool name: %q", name)+ }+}++func TestOAuthRetryFailureRequiresAuthenticationError(t *testing.T) {+ serverID := "oauth-retry-server"+ mcpMu.Lock()+ oldState, existed := mcpRuntime[serverID]+ mcpRuntime[serverID] = mcpRuntimeState{Status: "oauth_retrying"}+ mcpMu.Unlock()+ t.Cleanup(func() {+ mcpMu.Lock()+ if existed {+ mcpRuntime[serverID] = oldState+ } else {+ delete(mcpRuntime, serverID)+ }+ mcpMu.Unlock()+ })++ if setOAuthRetryStateForError(context.Background(), serverID, "500 Internal Server Error") {+ t.Fatal("non-authentication failure was treated as an authorization failure")+ }+ if !setOAuthRetryStateForError(context.Background(), serverID, "401 Unauthorized") {+ t.Fatal("rejected refreshed token did not return to the authorization-required state")+ }+}++func TestOAuthToolFailureRemovesUnauthorizedConnection(t *testing.T) {+ serverID := "oauth-tool-server"+ mcpMu.Lock()+ oldConns := mcpConns+ oldRuntime := mcpRuntime+ mcpConns = []Connection{{ServerID: serverID, ServerName: "oauth-tool", Tools: 1}}+ mcpRuntime = map[string]mcpRuntimeState{serverID: {Status: "oauth_retrying", Tools: 1}}+ mcpMu.Unlock()+ t.Cleanup(func() {+ mcpMu.Lock()+ mcpConns = oldConns+ mcpRuntime = oldRuntime+ mcpMu.Unlock()+ })++ updateMCPRuntimeAfterToolCall("oauth-tool", errors.New("401 Unauthorized"))+ mcpMu.Lock()+ connections := len(mcpConns)+ state := mcpRuntime[serverID]+ mcpMu.Unlock()+ if connections != 0 || state.Status != "authorization_required" {+ t.Fatalf("unexpected unauthorized connection state: connections=%d state=%#v", connections, state)+ }+}++func TestReconnectMCPDoesNotInterruptPendingConnection(t *testing.T) {+ mcpMu.Lock()+ oldConnecting := mcpConnecting+ oldServers := mcpServers+ oldGeneration := mcpGeneration+ mcpConnecting = true+ mcpServers = []conf.MCPServer{{ID: "server-id", Name: "server"}}+ mcpGeneration = 42+ mcpMu.Unlock()+ t.Cleanup(func() {+ mcpMu.Lock()+ mcpConnecting = oldConnecting+ mcpServers = oldServers+ mcpGeneration = oldGeneration+ mcpMu.Unlock()+ })++ if reconnectMCP("server") {+ t.Fatal("pending connection was interrupted")+ }+ mcpMu.Lock()+ generation := mcpGeneration+ mcpMu.Unlock()+ if generation != 42 {+ t.Fatalf("unexpected MCP generation: %d", generation)+ }+}++func TestReconnectMCPAsyncKeepsOtherConnections(t *testing.T) {+ serverA := conf.MCPServer{ID: "server-a", Name: "server-a", Enabled: true, Type: "stdio"}+ serverB := conf.MCPServer{ID: "server-b", Name: "server-b", Enabled: true, Type: "stdio"}+ mcpMu.Lock()+ oldConns := mcpConns+ oldServers := mcpServers+ oldRuntime := mcpRuntime+ oldConnecting := mcpConnecting+ oldCancel := mcpConnectCancel+ oldGeneration := mcpGeneration+ mcpConns = []Connection{+ {ServerID: serverA.ID, ServerName: serverA.Name, Config: serverA},+ {ServerID: serverB.ID, ServerName: serverB.Name, Config: serverB},+ }+ mcpServers = []conf.MCPServer{serverA, serverB}+ mcpRuntime = map[string]mcpRuntimeState{}+ mcpConnecting = false+ mcpConnectCancel = nil+ mcpMu.Unlock()+ t.Cleanup(func() {+ mcpMu.Lock()+ if mcpConnectCancel != nil {+ mcpConnectCancel()+ }+ mcpConns = oldConns+ mcpServers = oldServers+ mcpRuntime = oldRuntime+ mcpConnecting = oldConnecting+ mcpConnectCancel = oldCancel+ mcpGeneration = oldGeneration+ mcpMu.Unlock()+ })++ ReconnectMCPAsync([]conf.MCPServer{serverA, serverB}, []string{serverA.ID}, nil)+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ mcpMu.Lock()+ connecting := mcpConnecting+ connections := append([]Connection(nil), mcpConns...)+ mcpMu.Unlock()+ if !connecting {+ if len(connections) != 1 || connections[0].ServerID != serverB.ID {+ t.Fatalf("unrelated connection was changed: %#v", connections)+ }+ return+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Fatal("target MCP reconnect did not finish")+}diff --git a/kernel/mcp/client/oauth.go b/kernel/mcp/client/oauth.gonew file mode 100644index 0000000000..ef50f3787c--- /dev/null+++ b/kernel/mcp/client/oauth.go@@ -0,0 +1,787 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package client++import (+ "context"+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/url"+ "slices"+ "strings"+ "sync"+ "sync/atomic"+ "time"++ "github.com/modelcontextprotocol/go-sdk/auth"+ "github.com/modelcontextprotocol/go-sdk/oauthex"+ "github.com/siyuan-note/httpclient"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+ "golang.org/x/oauth2"+)++const oauthAuthorizationTimeout = 5 * time.Minute++var errOAuthAuthorizationRequired = errors.New("mcp oauth authorization required")++type oauthCallbackResult struct {+ Code string+ State string+ Error string+}++type oauthFlow struct {+ State string+ Result chan oauthCallbackResult+ Expires time.Time+}++var oauthFlows = struct {+ sync.Mutex+ items map[string]*oauthFlow+}{items: map[string]*oauthFlow{}}++type mcpOAuthHandler struct {+ server conf.MCPServer+ client *http.Client++ interactive atomic.Bool++ sourceMu sync.Mutex+ source *storedOAuthTokenSource+}++type storedOAuthTokenSource struct {+ sync.Mutex+ credential oauthCredential+ client *http.Client+ invalid bool+}++type oauthTokenError struct {+ Code string `json:"error"`+ Description string `json:"error_description"`+}++func (e *oauthTokenError) Error() string {+ if e.Description == "" {+ return e.Code+ }+ return e.Code + ": " + e.Description+}++func newMCPOAuthHandler(server conf.MCPServer, interactive bool) *mcpOAuthHandler {+ handler := &mcpOAuthHandler{+ server: server,+ client: &http.Client{+ Transport: httpclient.NewUserAgentRoundTripper(http.DefaultTransport),+ Timeout: 30 * time.Second,+ },+ }+ handler.interactive.Store(interactive)+ return handler+}++func (h *mcpOAuthHandler) disableInteractive() {+ h.interactive.Store(false)+}++func (h *mcpOAuthHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {+ h.sourceMu.Lock()+ defer h.sourceMu.Unlock()+ if h.source != nil {+ return h.source, nil+ }+ credential, ok := getOAuthCredential(h.server.ID, h.server.URL)+ if !ok || credential.Rejected {+ return nil, nil+ }+ valid, err := h.validateCredentialIssuer(ctx, credential)+ if err != nil {+ return nil, err+ }+ if !valid {+ return nil, nil+ }+ h.source = &storedOAuthTokenSource{credential: credential, client: h.client}+ return h.source, nil+}++func (s *storedOAuthTokenSource) Token() (*oauth2.Token, error) {+ s.Lock()+ defer s.Unlock()+ if s.invalid {+ return nil, nil+ }+ credential := s.credential+ if credential.AccessToken != "" && (credential.Expiry.IsZero() || time.Now().Add(30*time.Second).Before(credential.Expiry)) {+ return credentialToken(credential), nil+ }+ if oauthClientRegistrationExpired(credential) {+ s.invalid = true+ credential.AccessToken = ""+ credential.RefreshToken = ""+ credential.Expiry = time.Time{}+ _ = putOAuthCredential(credential)+ return nil, nil+ }+ if credential.RefreshToken == "" {+ return nil, nil+ }++ refreshed, permanent, err := refreshOAuthCredential(context.Background(), s.client, credential)+ if err != nil {+ if permanent {+ s.invalid = true+ credential.AccessToken = ""+ credential.RefreshToken = ""+ credential.Expiry = time.Time{}+ _ = putOAuthCredential(credential)+ return nil, nil+ }+ return nil, err+ }+ s.credential = refreshed+ if err = putOAuthCredential(refreshed); err != nil {+ return nil, err+ }+ return credentialToken(refreshed), nil+}++func credentialToken(credential oauthCredential) *oauth2.Token {+ return &oauth2.Token{+ AccessToken: credential.AccessToken,+ TokenType: credential.TokenType,+ RefreshToken: credential.RefreshToken,+ Expiry: credential.Expiry,+ }+}++func (h *mcpOAuthHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) (retErr error) {+ defer resp.Body.Close()+ defer io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))++ challenges, err := oauthex.ParseWWWAuthenticate(resp.Header.Values("WWW-Authenticate"))+ if err != nil {+ return fmt.Errorf("parse OAuth challenge: %w", err)+ }+ if !hasBearerChallenge(challenges) {+ return fmt.Errorf("server returned %s without an OAuth Bearer challenge", resp.Status)+ }+ challengeError := bearerChallengeParam(challenges, "error")+ if resp.StatusCode == http.StatusForbidden && challengeError != "insufficient_scope" {+ return fmt.Errorf("server returned %s", resp.Status)+ }+ interactive := h.interactive.Load()+ if interactive {+ defer func() {+ if retErr != nil && !errors.Is(retErr, context.Canceled) {+ setMCPRuntimeStateForContext(ctx, h.server.ID, "authorization_required", 0, retErr.Error(), "")+ }+ }()+ }++ prm, err := discoverProtectedResource(ctx, challenges, req.URL.String(), h.client)+ if err != nil {+ return err+ }++ asm, err := auth.GetAuthServerMetadata(ctx, prm.AuthorizationServers[0], h.client)+ if err != nil {+ return fmt.Errorf("discover OAuth authorization server: %w", err)+ }+ if asm == nil {+ return fmt.Errorf("OAuth authorization server metadata not found")+ }+ credential, hasCredential := getOAuthCredential(h.server.ID, h.server.URL)+ if hasCredential && credential.Issuer == asm.Issuer {+ credential.TokenEndpoint = asm.TokenEndpoint+ credential.RevocationEndpoint = asm.RevocationEndpoint+ }+ if hasCredential && credential.Issuer == asm.Issuer && credential.RefreshToken != "" &&+ challengeError != "insufficient_scope" && !credential.Rejected && !oauthClientRegistrationExpired(credential) {+ refreshed, permanent, refreshErr := refreshOAuthCredential(ctx, h.client, credential)+ if refreshErr == nil {+ if saveErr := putOAuthCredential(refreshed); saveErr != nil {+ logging.LogWarnf("mcp oauth: save refreshed credentials failed: %s", saveErr)+ }+ h.sourceMu.Lock()+ h.source = &storedOAuthTokenSource{credential: refreshed, client: h.client}+ h.sourceMu.Unlock()+ setMCPRuntimeStateForContext(ctx, h.server.ID, "oauth_retrying", 0, "", "")+ return nil+ }+ if !permanent {+ return fmt.Errorf("refresh OAuth credentials: %w", refreshErr)+ }+ credential.AccessToken = ""+ credential.RefreshToken = ""+ credential.Expiry = time.Time{}+ if saveErr := putOAuthCredential(credential); saveErr != nil {+ logging.LogWarnf("mcp oauth: clear invalid credentials failed: %s", saveErr)+ }+ }+ if !interactive {+ setMCPRuntimeStateForContext(ctx, h.server.ID, "authorization_required", 0, "", "")+ return errOAuthAuthorizationRequired+ }+ if !slices.Contains(asm.CodeChallengeMethodsSupported, "S256") {+ return fmt.Errorf("OAuth authorization server does not support PKCE S256")+ }+ if len(asm.ResponseTypesSupported) > 0 && !slices.Contains(asm.ResponseTypesSupported, "code") {+ return fmt.Errorf("OAuth authorization server does not support the authorization code response type")+ }+ if len(asm.GrantTypesSupported) > 0 && !slices.Contains(asm.GrantTypesSupported, "authorization_code") {+ return fmt.Errorf("OAuth authorization server does not support the authorization code grant")+ }++ flowID := reusableOAuthFlowID(credential)+ if flowID == "" {+ flowID, err = secureRandomString(24)+ if err != nil {+ return err+ }+ }+ state, err := secureRandomString(24)+ if err != nil {+ return err+ }+ callbackURL := fmt.Sprintf("http://127.0.0.1:%s/api/ai/mcp/oauth/callback/%s", util.ServerPort, flowID)+ scopes := append([]string(nil), prm.ScopesSupported...)+ if len(scopes) == 0 {+ scopes = append(scopes, asm.ScopesSupported...)+ }+ for _, scope := range strings.Fields(bearerChallengeParam(challenges, "scope")) {+ if !slices.Contains(scopes, scope) {+ scopes = append(scopes, scope)+ }+ }+ registrationCredential := credential+ canReuseRegistration := hasCredential && credential.Issuer == asm.Issuer && credential.RedirectURL == callbackURL &&+ credential.ClientID != "" && !oauthClientRegistrationExpired(credential) && oauthScopesContain(credential.Scopes, scopes)+ if !canReuseRegistration {+ if asm.RegistrationEndpoint == "" {+ return fmt.Errorf("OAuth authorization server does not support dynamic client registration")+ }+ tokenAuthMethod := preferredTokenAuthMethod(asm.TokenEndpointAuthMethodsSupported)+ if len(asm.TokenEndpointAuthMethodsSupported) > 0 && tokenAuthMethod == "" {+ return fmt.Errorf("OAuth authorization server does not support a compatible token endpoint authentication method")+ }+ grantTypes := []string{"authorization_code"}+ if len(asm.GrantTypesSupported) == 0 || slices.Contains(asm.GrantTypesSupported, "refresh_token") {+ grantTypes = append(grantTypes, "refresh_token")+ }+ registration, registerErr := oauthex.RegisterClient(ctx, asm.RegistrationEndpoint, &oauthex.ClientRegistrationMetadata{+ RedirectURIs: []string{callbackURL},+ TokenEndpointAuthMethod: tokenAuthMethod,+ GrantTypes: grantTypes,+ ResponseTypes: []string{"code"},+ ClientName: "SiYuan",+ Scope: strings.Join(scopes, " "),+ ApplicationType: "native",+ }, h.client)+ if registerErr != nil {+ return fmt.Errorf("register OAuth client: %w", registerErr)+ }+ registrationCredential = oauthCredential{+ ServerID: h.server.ID,+ Endpoint: h.server.URL,+ Resource: prm.Resource,+ Issuer: asm.Issuer,+ ResourceMetadataURL: prm.MetadataURL,+ RedirectURL: callbackURL,+ ClientID: registration.ClientID,+ ClientSecret: registration.ClientSecret,+ ClientSecretExpiry: registration.ClientSecretExpiresAt,+ TokenEndpoint: asm.TokenEndpoint,+ RevocationEndpoint: asm.RevocationEndpoint,+ TokenAuthMethod: registration.TokenEndpointAuthMethod,+ Scopes: scopes,+ }+ if registrationCredential.TokenAuthMethod == "" {+ if registration.ClientSecret == "" {+ registrationCredential.TokenAuthMethod = "none"+ } else {+ registrationCredential.TokenAuthMethod = "client_secret_basic"+ }+ }+ if !isSupportedTokenAuthMethod(registrationCredential.TokenAuthMethod) {+ return fmt.Errorf("OAuth client registration returned an unsupported token endpoint authentication method")+ }+ if err = putOAuthCredential(registrationCredential); err != nil {+ return fmt.Errorf("save OAuth client registration: %w", err)+ }+ }++ authMethod := registrationCredential.TokenAuthMethod+ if authMethod == "" {+ if registrationCredential.ClientSecret == "" {+ authMethod = "none"+ } else {+ authMethod = "client_secret_basic"+ }+ }+ config := &oauth2.Config{+ ClientID: registrationCredential.ClientID,+ ClientSecret: registrationCredential.ClientSecret,+ RedirectURL: callbackURL,+ Scopes: scopes,+ Endpoint: oauth2.Endpoint{+ AuthURL: asm.AuthorizationEndpoint,+ TokenURL: asm.TokenEndpoint,+ AuthStyle: oauthAuthStyle(authMethod),+ },+ }+ verifier := oauth2.GenerateVerifier()+ authorizationURL := config.AuthCodeURL(state,+ oauth2.S256ChallengeOption(verifier),+ oauth2.SetAuthURLParam("resource", prm.Resource))++ flow := &oauthFlow{+ State: state,+ Result: make(chan oauthCallbackResult, 1),+ Expires: time.Now().Add(oauthAuthorizationTimeout),+ }+ oauthFlows.Lock()+ oauthFlows.items[flowID] = flow+ oauthFlows.Unlock()+ defer removeOAuthFlow(flowID, flow)+ setMCPRuntimeStateForContext(ctx, h.server.ID, "authorizing", 0, "", authorizationURL)++ var callback oauthCallbackResult+ timer := time.NewTimer(oauthAuthorizationTimeout)+ defer timer.Stop()+ select {+ case callback = <-flow.Result:+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ return fmt.Errorf("OAuth authorization timed out")+ }+ if callback.Error != "" {+ return fmt.Errorf("OAuth authorization failed: %s", callback.Error)+ }+ if callback.State != state {+ return fmt.Errorf("OAuth state mismatch")+ }+ if callback.Code == "" {+ return fmt.Errorf("OAuth callback did not include an authorization code")+ }++ exchangeCtx := context.WithValue(ctx, oauth2.HTTPClient, h.client)+ token, err := config.Exchange(exchangeCtx, callback.Code,+ oauth2.VerifierOption(verifier),+ oauth2.SetAuthURLParam("resource", prm.Resource))+ if err != nil {+ return fmt.Errorf("exchange OAuth authorization code: %w", err)+ }+ if token.TokenType != "" && !strings.EqualFold(token.TokenType, "Bearer") {+ return fmt.Errorf("OAuth token endpoint returned unsupported token type %q", token.TokenType)+ }+ credential = registrationCredential+ credential.TokenAuthMethod = authMethod+ credential.AccessToken = token.AccessToken+ credential.RefreshToken = token.RefreshToken+ credential.TokenType = token.TokenType+ credential.Expiry = token.Expiry+ credential.Scopes = scopes+ credential.Rejected = false+ if err = putOAuthCredential(credential); err != nil {+ return fmt.Errorf("save OAuth credentials: %w", err)+ }+ h.sourceMu.Lock()+ h.source = &storedOAuthTokenSource{credential: credential, client: h.client}+ h.sourceMu.Unlock()+ setMCPRuntimeStateForContext(ctx, h.server.ID, "oauth_retrying", 0, "", "")+ return nil+}++func hasBearerChallenge(challenges []oauthex.Challenge) bool {+ for _, challenge := range challenges {+ if strings.EqualFold(challenge.Scheme, "bearer") {+ return true+ }+ }+ return false+}++func bearerChallengeParam(challenges []oauthex.Challenge, name string) string {+ for _, challenge := range challenges {+ if strings.EqualFold(challenge.Scheme, "bearer") {+ return challenge.Params[name]+ }+ }+ return ""+}++func preferredTokenAuthMethod(supported []string) string {+ for _, method := range []string{"none", "client_secret_post", "client_secret_basic"} {+ if slices.Contains(supported, method) {+ return method+ }+ }+ return ""+}++func isSupportedTokenAuthMethod(method string) bool {+ return method == "none" || method == "client_secret_post" || method == "client_secret_basic"+}++func oauthClientRegistrationExpired(credential oauthCredential) bool {+ return !credential.ClientSecretExpiry.IsZero() && !time.Now().Before(credential.ClientSecretExpiry)+}++func oauthScopesContain(available, required []string) bool {+ for _, scope := range required {+ if !slices.Contains(available, scope) {+ return false+ }+ }+ return true+}++func reusableOAuthFlowID(credential oauthCredential) string {+ callback, err := url.Parse(credential.RedirectURL)+ if err != nil || callback.Scheme != "http" || callback.Hostname() != "127.0.0.1" || callback.Port() != util.ServerPort {+ return ""+ }+ prefix := "/api/ai/mcp/oauth/callback/"+ if !strings.HasPrefix(callback.Path, prefix) || callback.RawQuery != "" || callback.Fragment != "" {+ return ""+ }+ flowID := strings.TrimPrefix(callback.Path, prefix)+ if flowID == "" || strings.Contains(flowID, "/") {+ return ""+ }+ return flowID+}++type protectedResourceURL struct {+ URL string+ Resource string+}++type discoveredProtectedResource struct {+ *oauthex.ProtectedResourceMetadata+ MetadataURL string+}++func discoverProtectedResource(ctx context.Context, challenges []oauthex.Challenge, resource string, client *http.Client) (*discoveredProtectedResource, error) {+ metadataURL := ""+ for _, challenge := range challenges {+ if strings.EqualFold(challenge.Scheme, "bearer") && challenge.Params["resource_metadata"] != "" {+ metadataURL = challenge.Params["resource_metadata"]+ break+ }+ }+ for _, candidate := range protectedResourceURLs(metadataURL, resource) {+ prm, err := oauthex.GetProtectedResourceMetadata(ctx, candidate.URL, candidate.Resource, client)+ if err != nil {+ continue+ }+ if len(prm.AuthorizationServers) == 0 {+ return nil, fmt.Errorf("OAuth protected resource metadata has no authorization server")+ }+ return &discoveredProtectedResource{ProtectedResourceMetadata: prm, MetadataURL: candidate.URL}, nil+ }+ return nil, fmt.Errorf("OAuth protected resource metadata not found")+}++func (h *mcpOAuthHandler) validateCredentialIssuer(ctx context.Context, credential oauthCredential) (bool, error) {+ var challenges []oauthex.Challenge+ resource := h.server.URL+ if credential.ResourceMetadataURL != "" {+ challenges = []oauthex.Challenge{{Scheme: "bearer", Params: map[string]string{"resource_metadata": credential.ResourceMetadataURL}}}+ resource = credential.Resource+ }+ prm, err := discoverProtectedResource(ctx, challenges, resource, h.client)+ if err != nil {+ return false, fmt.Errorf("validate OAuth protected resource: %w", err)+ }+ if prm.Resource != credential.Resource || len(prm.AuthorizationServers) == 0 {+ return false, nil+ }+ asm, err := auth.GetAuthServerMetadata(ctx, prm.AuthorizationServers[0], h.client)+ if err != nil {+ return false, fmt.Errorf("validate OAuth issuer: %w", err)+ }+ return asm != nil && asm.Issuer == credential.Issuer && asm.TokenEndpoint == credential.TokenEndpoint, nil+}++func protectedResourceURLs(metadataURL, resource string) []protectedResourceURL {+ var result []protectedResourceURL+ if metadataURL != "" {+ result = append(result, protectedResourceURL{URL: metadataURL, Resource: resource})+ }+ resourceURL, err := url.Parse(resource)+ if err != nil {+ return result+ }+ metadata := *resourceURL+ metadata.RawPath = ""+ metadata.RawQuery = ""+ metadata.Fragment = ""+ metadata.Path = "/.well-known/oauth-protected-resource/" + strings.TrimLeft(resourceURL.Path, "/")+ result = append(result, protectedResourceURL{URL: metadata.String(), Resource: resource})+ metadata.Path = "/.well-known/oauth-protected-resource"+ resourceURL.Path = ""+ resourceURL.RawPath = ""+ resourceURL.RawQuery = ""+ resourceURL.Fragment = ""+ result = append(result, protectedResourceURL{URL: metadata.String(), Resource: resourceURL.String()})+ return result+}++func oauthAuthStyle(method string) oauth2.AuthStyle {+ switch method {+ case "none", "client_secret_post":+ return oauth2.AuthStyleInParams+ case "client_secret_basic":+ return oauth2.AuthStyleInHeader+ default:+ return oauth2.AuthStyleAutoDetect+ }+}++func secureRandomString(size int) (string, error) {+ data := make([]byte, size)+ if _, err := rand.Read(data); err != nil {+ return "", err+ }+ return base64.RawURLEncoding.EncodeToString(data), nil+}++func removeOAuthFlow(flowID string, flow *oauthFlow) {+ oauthFlows.Lock()+ if oauthFlows.items[flowID] == flow {+ delete(oauthFlows.items, flowID)+ }+ oauthFlows.Unlock()+}++func CompleteMCPOAuth(flowID, code, state, callbackError string) error {+ oauthFlows.Lock()+ flow := oauthFlows.items[flowID]+ if flow == nil || time.Now().After(flow.Expires) {+ delete(oauthFlows.items, flowID)+ oauthFlows.Unlock()+ return fmt.Errorf("OAuth flow is missing or expired")+ }+ if state != flow.State {+ oauthFlows.Unlock()+ return fmt.Errorf("OAuth state mismatch")+ }+ delete(oauthFlows.items, flowID)+ oauthFlows.Unlock()+ select {+ case flow.Result <- oauthCallbackResult{Code: code, State: state, Error: callbackError}:+ return nil+ default:+ return fmt.Errorf("OAuth callback was already handled")+ }+}++func IsLoopbackCallback(remoteAddr string) bool {+ host, _, err := net.SplitHostPort(remoteAddr)+ if err != nil {+ return false+ }+ ip := net.ParseIP(host)+ return ip != nil && ip.IsLoopback()+}++func refreshOAuthCredential(ctx context.Context, client *http.Client, credential oauthCredential) (oauthCredential, bool, error) {+ values := url.Values{+ "grant_type": {"refresh_token"},+ "refresh_token": {credential.RefreshToken},+ "resource": {credential.Resource},+ }+ response, tokenErr, err := oauthTokenRequest(ctx, client, credential, values)+ if err != nil {+ permanent := tokenErr != nil && (tokenErr.Code == "invalid_grant" || tokenErr.Code == "invalid_client")+ return credential, permanent, err+ }+ credential.AccessToken = response.AccessToken+ credential.TokenType = response.TokenType+ credential.Rejected = false+ if response.RefreshToken != "" {+ credential.RefreshToken = response.RefreshToken+ }+ if response.ExpiresIn > 0 {+ credential.Expiry = time.Now().Add(time.Duration(response.ExpiresIn) * time.Second)+ } else {+ credential.Expiry = time.Time{}+ }+ if response.Scope != "" {+ credential.Scopes = strings.Fields(response.Scope)+ }+ return credential, false, nil+}++type oauthTokenResponse struct {+ AccessToken string `json:"access_token"`+ TokenType string `json:"token_type"`+ RefreshToken string `json:"refresh_token"`+ ExpiresIn int64 `json:"expires_in"`+ Scope string `json:"scope"`+}++func oauthTokenRequest(ctx context.Context, client *http.Client, credential oauthCredential, values url.Values) (*oauthTokenResponse, *oauthTokenError, error) {+ applyOAuthClientAuthentication(values, nil, credential)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, credential.TokenEndpoint, strings.NewReader(values.Encode()))+ if err != nil {+ return nil, nil, err+ }+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ req.Header.Set("Accept", "application/json")+ applyOAuthClientAuthentication(nil, req, credential)+ resp, err := client.Do(req)+ if err != nil {+ return nil, nil, err+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))+ if err != nil {+ return nil, nil, err+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ tokenErr := &oauthTokenError{}+ if json.Unmarshal(body, tokenErr) != nil || tokenErr.Code == "" {+ return nil, nil, fmt.Errorf("OAuth token endpoint returned %s", resp.Status)+ }+ return nil, tokenErr, tokenErr+ }+ result := &oauthTokenResponse{}+ if err = json.Unmarshal(body, result); err != nil {+ return nil, nil, err+ }+ if result.AccessToken == "" {+ return nil, nil, fmt.Errorf("OAuth token endpoint returned no access token")+ }+ if result.TokenType != "" && !strings.EqualFold(result.TokenType, "Bearer") {+ return nil, nil, fmt.Errorf("OAuth token endpoint returned unsupported token type %q", result.TokenType)+ }+ return result, nil, nil+}++func applyOAuthClientAuthentication(values url.Values, req *http.Request, credential oauthCredential) {+ switch credential.TokenAuthMethod {+ case "client_secret_basic":+ if req != nil {+ req.SetBasicAuth(url.QueryEscape(credential.ClientID), url.QueryEscape(credential.ClientSecret))+ }+ default:+ if values != nil {+ values.Set("client_id", credential.ClientID)+ if credential.TokenAuthMethod == "client_secret_post" && credential.ClientSecret != "" {+ values.Set("client_secret", credential.ClientSecret)+ }+ }+ }+}++func DisconnectMCPOAuth(serverID string) error {+ credentials := listOAuthCredentials(serverID)+ if err := removeOAuthCredential(serverID, "", ""); err != nil {+ return err+ }+ setMCPRuntimeState(serverID, "authorization_required", 0, "", "")+ if len(credentials) > 0 {+ go func() {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ client := &http.Client{Transport: httpclient.NewUserAgentRoundTripper(http.DefaultTransport), Timeout: 15 * time.Second}+ var revokeErr error+ for _, credential := range credentials {+ if err := revokeOAuthCredential(ctx, client, credential); err != nil {+ revokeErr = errors.Join(revokeErr, err)+ }+ }+ if revokeErr != nil {+ logging.LogWarnf("mcp oauth: revoke credentials for server [%s] failed: %s", serverID, revokeErr)+ }+ }()+ }+ return nil+}++func revokeOAuthCredential(ctx context.Context, client *http.Client, credential oauthCredential) error {+ if credential.RevocationEndpoint == "" {+ return nil+ }+ if !isSecureOAuthEndpoint(credential.RevocationEndpoint) {+ return fmt.Errorf("OAuth revocation endpoint must use HTTPS or loopback HTTP")+ }+ var result error+ for _, token := range []struct {+ value string+ hint string+ }{{credential.RefreshToken, "refresh_token"}, {credential.AccessToken, "access_token"}} {+ if token.value == "" {+ continue+ }+ values := url.Values{"token": {token.value}, "token_type_hint": {token.hint}}+ applyOAuthClientAuthentication(values, nil, credential)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, credential.RevocationEndpoint, strings.NewReader(values.Encode()))+ if err != nil {+ result = errors.Join(result, err)+ continue+ }+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ applyOAuthClientAuthentication(nil, req, credential)+ resp, err := client.Do(req)+ if err != nil {+ result = errors.Join(result, err)+ continue+ }+ io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))+ resp.Body.Close()+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ result = errors.Join(result, fmt.Errorf("OAuth revocation endpoint returned %s", resp.Status))+ }+ }+ if result != nil {+ logging.LogWarnf("mcp oauth: revoke credentials failed: %s", result)+ }+ return result+}++func isSecureOAuthEndpoint(endpoint string) bool {+ parsed, err := url.Parse(endpoint)+ if err != nil {+ return false+ }+ if parsed.Scheme == "https" {+ return true+ }+ if parsed.Scheme != "http" {+ return false+ }+ if strings.EqualFold(parsed.Hostname(), "localhost") {+ return true+ }+ ip := net.ParseIP(parsed.Hostname())+ return ip != nil && ip.IsLoopback()+}diff --git a/kernel/mcp/client/oauth_store.go b/kernel/mcp/client/oauth_store.gonew file mode 100644index 0000000000..c9bf8be520--- /dev/null+++ b/kernel/mcp/client/oauth_store.go@@ -0,0 +1,207 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package client++import (+ "encoding/hex"+ "encoding/json"+ "fmt"+ "strings"+ "sync"+ "time"++ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type oauthCredential struct {+ ServerID string `json:"serverId"`+ Endpoint string `json:"endpoint"`+ Resource string `json:"resource"`+ Issuer string `json:"issuer"`+ ResourceMetadataURL string `json:"resourceMetadataUrl,omitempty"`+ RedirectURL string `json:"redirectUrl,omitempty"`+ ClientID string `json:"clientId"`+ ClientSecret string `json:"clientSecret,omitempty"`+ ClientSecretExpiry time.Time `json:"clientSecretExpiry,omitempty"`+ TokenEndpoint string `json:"tokenEndpoint"`+ RevocationEndpoint string `json:"revocationEndpoint,omitempty"`+ TokenAuthMethod string `json:"tokenAuthMethod,omitempty"`+ AccessToken string `json:"accessToken"`+ RefreshToken string `json:"refreshToken,omitempty"`+ TokenType string `json:"tokenType,omitempty"`+ Expiry time.Time `json:"expiry,omitempty"`+ Scopes []string `json:"scopes,omitempty"`+ Rejected bool `json:"rejected,omitempty"`+}++type oauthCredentialData struct {+ Credentials []oauthCredential `json:"credentials"`+}++var oauthCredentialStore = struct {+ sync.Mutex+ loaded bool+ credentials []oauthCredential+}{}++func loadOAuthCredentialsLocked() {+ if oauthCredentialStore.loaded {+ return+ }+ oauthCredentialStore.loaded = true+ oauthCredentialStore.credentials = []oauthCredential{}+ if model.Conf == nil || model.Conf.GetMCPOAuth() == "" {+ return+ }++ ciphertext := model.Conf.GetMCPOAuth()+ if len(ciphertext)%32 != 0 {+ logging.LogWarnf("mcp oauth: ignored malformed encrypted credentials")+ return+ }+ decrypted := decryptOAuthCredentials(ciphertext)+ if len(decrypted) == 0 {+ return+ }+ plain, err := hex.DecodeString(string(decrypted))+ if err != nil {+ logging.LogWarnf("mcp oauth: decode credentials failed: %s", err)+ return+ }+ data := &oauthCredentialData{}+ if err = json.Unmarshal(plain, data); err != nil {+ logging.LogWarnf("mcp oauth: parse credentials failed: %s", err)+ return+ }+ oauthCredentialStore.credentials = data.Credentials+}++func decryptOAuthCredentials(ciphertext string) (decrypted []byte) {+ defer func() {+ if recovered := recover(); recovered != nil {+ logging.LogWarnf("mcp oauth: decrypt credentials failed: %v", recovered)+ decrypted = nil+ }+ }()+ return util.AESDecrypt(ciphertext)+}++func persistOAuthCredentialsLocked() error {+ if model.Conf == nil {+ return fmt.Errorf("configuration is not initialized")+ }+ data, err := json.Marshal(&oauthCredentialData{Credentials: oauthCredentialStore.credentials})+ if err != nil {+ return err+ }+ model.Conf.SetMCPOAuth(util.AESEncrypt(string(data)))+ return nil+}++func getOAuthCredential(serverID, endpoint string) (oauthCredential, bool) {+ oauthCredentialStore.Lock()+ defer oauthCredentialStore.Unlock()+ loadOAuthCredentialsLocked()+ for i := len(oauthCredentialStore.credentials) - 1; i >= 0; i-- {+ credential := oauthCredentialStore.credentials[i]+ credentialEndpoint := credential.Endpoint+ if credentialEndpoint == "" {+ credentialEndpoint = credential.Resource+ }+ if credential.ServerID == serverID && credentialEndpoint == endpoint {+ return credential, true+ }+ }+ return oauthCredential{}, false+}++func putOAuthCredential(credential oauthCredential) error {+ oauthCredentialStore.Lock()+ defer oauthCredentialStore.Unlock()+ loadOAuthCredentialsLocked()+ filtered := oauthCredentialStore.credentials[:0]+ for _, item := range oauthCredentialStore.credentials {+ itemEndpoint := item.Endpoint+ if itemEndpoint == "" {+ itemEndpoint = item.Resource+ }+ credentialEndpoint := credential.Endpoint+ if credentialEndpoint == "" {+ credentialEndpoint = credential.Resource+ }+ if item.ServerID == credential.ServerID && itemEndpoint == credentialEndpoint && item.Issuer == credential.Issuer {+ continue+ }+ filtered = append(filtered, item)+ }+ oauthCredentialStore.credentials = append(filtered, credential)+ return persistOAuthCredentialsLocked()+}++func removeOAuthCredential(serverID, resource, issuer string) error {+ oauthCredentialStore.Lock()+ defer oauthCredentialStore.Unlock()+ loadOAuthCredentialsLocked()+ filtered := oauthCredentialStore.credentials[:0]+ for _, credential := range oauthCredentialStore.credentials {+ if credential.ServerID == serverID && (resource == "" || credential.Resource == resource) && (issuer == "" || credential.Issuer == issuer) {+ continue+ }+ filtered = append(filtered, credential)+ }+ oauthCredentialStore.credentials = filtered+ return persistOAuthCredentialsLocked()+}++func markOAuthCredentialRejected(serverID, endpoint string) error {+ oauthCredentialStore.Lock()+ defer oauthCredentialStore.Unlock()+ loadOAuthCredentialsLocked()+ for i := len(oauthCredentialStore.credentials) - 1; i >= 0; i-- {+ credential := &oauthCredentialStore.credentials[i]+ credentialEndpoint := credential.Endpoint+ if credentialEndpoint == "" {+ credentialEndpoint = credential.Resource+ }+ if credential.ServerID != serverID || credentialEndpoint != endpoint {+ continue+ }+ credential.Rejected = true+ return persistOAuthCredentialsLocked()+ }+ return nil+}++func listOAuthCredentials(serverID string) []oauthCredential {+ oauthCredentialStore.Lock()+ defer oauthCredentialStore.Unlock()+ loadOAuthCredentialsLocked()+ var result []oauthCredential+ for _, credential := range oauthCredentialStore.credentials {+ if credential.ServerID == serverID {+ result = append(result, credential)+ }+ }+ return result+}++func hasOAuthCredential(serverID, endpoint string) bool {+ credential, ok := getOAuthCredential(serverID, endpoint)+ return ok && (strings.TrimSpace(credential.AccessToken) != "" || strings.TrimSpace(credential.RefreshToken) != "")+}diff --git a/kernel/mcp/client/oauth_test.go b/kernel/mcp/client/oauth_test.gonew file mode 100644index 0000000000..70ebdcbf80--- /dev/null+++ b/kernel/mcp/client/oauth_test.go@@ -0,0 +1,556 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package client++import (+ "context"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "slices"+ "strings"+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestProtectedResourceURLs(t *testing.T) {+ candidates := protectedResourceURLs("https://example.com/custom-metadata", "https://example.com/mcp?tenant=one#fragment")+ if len(candidates) != 3 {+ t.Fatalf("unexpected candidate count: %d", len(candidates))+ }+ if candidates[0].URL != "https://example.com/custom-metadata" ||+ candidates[1].URL != "https://example.com/.well-known/oauth-protected-resource/mcp" ||+ candidates[2].URL != "https://example.com/.well-known/oauth-protected-resource" {+ t.Fatalf("unexpected metadata candidates: %#v", candidates)+ }+}++func TestCompleteMCPOAuth(t *testing.T) {+ flowID := "test-flow"+ flow := &oauthFlow{State: "test-state", Result: make(chan oauthCallbackResult, 1), Expires: time.Now().Add(time.Minute)}+ oauthFlows.Lock()+ oauthFlows.items[flowID] = flow+ oauthFlows.Unlock()+ t.Cleanup(func() { removeOAuthFlow(flowID, flow) })++ if err := CompleteMCPOAuth(flowID, "code", "wrong-state", ""); err == nil {+ t.Fatal("expected state mismatch")+ }+ if err := CompleteMCPOAuth(flowID, "code", "test-state", ""); err != nil {+ t.Fatal(err)+ }+ result := <-flow.Result+ if result.Code != "code" || result.State != "test-state" {+ t.Fatalf("unexpected callback result: %#v", result)+ }+}++func TestRefreshOAuthCredential(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if err := r.ParseForm(); err != nil {+ t.Error(err)+ }+ if r.Form.Get("grant_type") != "refresh_token" || r.Form.Get("refresh_token") != "old-refresh" ||+ r.Form.Get("resource") != "https://example.com/mcp" || r.Form.Get("client_id") != "client-id" {+ t.Errorf("unexpected refresh request: %#v", r.Form)+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"access_token":"new-access","token_type":"Bearer","expires_in":3600,"scope":"todo.read offline_access"}`))+ }))+ defer server.Close()++ credential := oauthCredential{+ Resource: "https://example.com/mcp",+ ClientID: "client-id",+ TokenEndpoint: server.URL,+ TokenAuthMethod: "none",+ RefreshToken: "old-refresh",+ }+ refreshed, permanent, err := refreshOAuthCredential(context.Background(), server.Client(), credential)+ if err != nil || permanent {+ t.Fatalf("refresh failed: permanent=%v err=%v", permanent, err)+ }+ if refreshed.AccessToken != "new-access" || refreshed.RefreshToken != "old-refresh" ||+ !slices.Equal(refreshed.Scopes, []string{"todo.read", "offline_access"}) || refreshed.Expiry.Before(time.Now()) {+ t.Fatalf("unexpected refreshed credential: %#v", refreshed)+ }+}++func TestIsLoopbackCallback(t *testing.T) {+ if !IsLoopbackCallback("127.0.0.1:1234") || !IsLoopbackCallback("[::1]:1234") || IsLoopbackCallback("192.0.2.1:1234") {+ t.Fatal("unexpected loopback callback result")+ }+}++func TestReusableOAuthFlowIDFollowsKernelPort(t *testing.T) {+ oldServerPort := util.ServerPort+ t.Cleanup(func() { util.ServerPort = oldServerPort })+ credential := oauthCredential{RedirectURL: "http://127.0.0.1:6806/api/ai/mcp/oauth/callback/flow-id"}+ util.ServerPort = "6806"+ if flowID := reusableOAuthFlowID(credential); flowID != "flow-id" {+ t.Fatalf("unexpected reusable flow ID: %q", flowID)+ }+ util.ServerPort = "6807"+ if flowID := reusableOAuthFlowID(credential); flowID != "" {+ t.Fatalf("callback from an old kernel port was reused: %q", flowID)+ }+}++func TestOAuthClientRegistrationExpiry(t *testing.T) {+ if oauthClientRegistrationExpired(oauthCredential{}) {+ t.Fatal("registration without an expiry was treated as expired")+ }+ if !oauthClientRegistrationExpired(oauthCredential{ClientSecretExpiry: time.Now().Add(-time.Minute)}) {+ t.Fatal("expired client registration was reused")+ }+ if oauthClientRegistrationExpired(oauthCredential{ClientSecretExpiry: time.Now().Add(time.Minute)}) {+ t.Fatal("valid client registration was treated as expired")+ }+}++func TestMCPOAuthInteractiveModeIsDisabledAfterBootstrap(t *testing.T) {+ handler := newMCPOAuthHandler(conf.MCPServer{}, true)+ if !handler.interactive.Load() {+ t.Fatal("interactive OAuth was not enabled for bootstrap")+ }+ handler.disableInteractive()+ if handler.interactive.Load() {+ t.Fatal("interactive OAuth remained enabled after bootstrap")+ }+}++func TestOAuthCredentialEncryptedPersistence(t *testing.T) {+ useOAuthTestConf(t)++ credential := oauthCredential{+ ServerID: "server-id",+ Endpoint: "https://example.com/mcp",+ Resource: "https://example.com/mcp",+ Issuer: "https://example.com",+ ClientID: "client-id",+ TokenEndpoint: "https://example.com/token",+ AccessToken: "secret-access-token",+ RefreshToken: "secret-refresh-token",+ }+ if err := putOAuthCredential(credential); err != nil {+ t.Fatal(err)+ }+ ciphertext := model.Conf.GetMCPOAuth()+ if ciphertext == "" || strings.Contains(ciphertext, credential.AccessToken) {+ t.Fatal("OAuth credentials were not encrypted")+ }+ decrypted := util.AESDecrypt(ciphertext)+ plain, err := hex.DecodeString(string(decrypted))+ if err != nil {+ t.Fatal(err)+ }+ data := &oauthCredentialData{}+ if err = json.Unmarshal(plain, data); err != nil || len(data.Credentials) != 1 || data.Credentials[0].RefreshToken != credential.RefreshToken {+ t.Fatalf("unexpected persisted credentials: %#v, %v", data, err)+ }++ resetOAuthCredentialStore()+ loaded, ok := getOAuthCredential(credential.ServerID, credential.Endpoint)+ if !ok || loaded.AccessToken != credential.AccessToken {+ t.Fatalf("unexpected loaded credential: %#v", loaded)+ }+}++func TestOAuthCredentialLookupUsesMCPEndpoint(t *testing.T) {+ useOAuthTestConf(t)+ credential := oauthCredential{+ ServerID: "server-id",+ Endpoint: "https://example.com/mcp",+ Resource: "https://example.com",+ Issuer: "https://auth.example.com",+ ClientID: "client-id",+ TokenEndpoint: "https://auth.example.com/token",+ AccessToken: "access-token",+ }+ if err := putOAuthCredential(credential); err != nil {+ t.Fatal(err)+ }+ loaded, ok := getOAuthCredential(credential.ServerID, credential.Endpoint)+ if !ok || loaded.Resource != credential.Resource {+ t.Fatalf("unexpected credential lookup result: %#v", loaded)+ }+}++func TestMarkOAuthCredentialRejectedKeepsTokensForRevocation(t *testing.T) {+ useOAuthTestConf(t)+ credential := oauthCredential{+ ServerID: "server-id",+ Endpoint: "https://example.com/mcp",+ Resource: "https://example.com/mcp",+ Issuer: "https://example.com",+ ClientID: "client-id",+ TokenEndpoint: "https://example.com/token",+ AccessToken: "access-token",+ RefreshToken: "refresh-token",+ }+ if err := putOAuthCredential(credential); err != nil {+ t.Fatal(err)+ }+ if err := markOAuthCredentialRejected(credential.ServerID, credential.Endpoint); err != nil {+ t.Fatal(err)+ }+ cleared, ok := getOAuthCredential(credential.ServerID, credential.Endpoint)+ if !ok || cleared.ClientID != credential.ClientID || cleared.AccessToken != credential.AccessToken ||+ cleared.RefreshToken != credential.RefreshToken || !cleared.Rejected {+ t.Fatalf("unexpected rejected credential: %#v", cleared)+ }+}++func TestMalformedOAuthCredentialCiphertextIsIgnored(t *testing.T) {+ useOAuthTestConf(t)+ model.Conf.MCPOAuth = strings.Repeat("0", 32)+ resetOAuthCredentialStore()+ if credentials := listOAuthCredentials("server-id"); len(credentials) != 0 {+ t.Fatalf("unexpected credentials: %#v", credentials)+ }+}++func TestMCPOAuthAuthorizationCodeFlow(t *testing.T) {+ useOAuthTestConf(t)+ oldServerPort := util.ServerPort+ util.ServerPort = "6806"+ t.Cleanup(func() { util.ServerPort = oldServerPort })++ registrationRedirect := make(chan string, 1)+ var server *httptest.Server+ server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/resource-metadata":+ writeOAuthTestJSON(w, http.StatusOK, map[string]any{+ "resource": server.URL + "/mcp",+ "authorization_servers": []string{server.URL},+ "scopes_supported": []string{"todo.read", "offline_access"},+ })+ case "/.well-known/oauth-authorization-server":+ writeOAuthTestJSON(w, http.StatusOK, oauthTestAuthorizationServerMetadata(server.URL))+ case "/register":+ metadata := struct {+ RedirectURIs []string `json:"redirect_uris"`+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`+ Scope string `json:"scope"`+ }{}+ if err := json.NewDecoder(r.Body).Decode(&metadata); err != nil {+ t.Errorf("decode registration: %v", err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ if len(metadata.RedirectURIs) != 1 || metadata.TokenEndpointAuthMethod != "none" ||+ metadata.Scope != "todo.read offline_access" {+ t.Errorf("unexpected registration metadata: %#v", metadata)+ }+ registrationRedirect <- metadata.RedirectURIs[0]+ writeOAuthTestJSON(w, http.StatusCreated, map[string]any{+ "client_id": "client-id",+ "token_endpoint_auth_method": "none",+ })+ case "/token":+ if err := r.ParseForm(); err != nil {+ t.Errorf("parse token request: %v", err)+ }+ if r.Form.Get("grant_type") != "authorization_code" || r.Form.Get("code") != "authorization-code" ||+ r.Form.Get("client_id") != "client-id" || r.Form.Get("code_verifier") == "" ||+ r.Form.Get("resource") != server.URL+"/mcp" {+ t.Errorf("unexpected token request: %#v", r.Form)+ }+ writeOAuthTestJSON(w, http.StatusOK, map[string]any{+ "access_token": "access-token",+ "refresh_token": "refresh-token",+ "token_type": "Bearer",+ "expires_in": 3600,+ })+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ serverID := "authorization-code-server"+ handler := newMCPOAuthHandler(conf.MCPServer{ID: serverID, URL: server.URL + "/mcp"}, true)+ authorizeResult := make(chan error, 1)+ go func() {+ authorizeResult <- handler.Authorize(context.Background(), httptest.NewRequest(http.MethodPost, server.URL+"/mcp", nil),+ newOAuthChallengeResponse(server.URL+"/resource-metadata"))+ }()++ var redirectURL string+ select {+ case redirectURL = <-registrationRedirect:+ case <-time.After(5 * time.Second):+ t.Fatal("OAuth client registration did not complete")+ }+ callback, err := url.Parse(redirectURL)+ if err != nil {+ t.Fatal(err)+ }+ if callback.Host != "127.0.0.1:6806" {+ t.Fatalf("unexpected callback host: %s", callback.Host)+ }+ flowID := strings.TrimPrefix(callback.Path, "/api/ai/mcp/oauth/callback/")+ if flowID == "" || flowID == callback.Path {+ t.Fatalf("unexpected callback path: %s", callback.Path)+ }++ authorizationURL := waitForOAuthAuthorizationURL(t, serverID)+ authorizationRequest, err := url.Parse(authorizationURL)+ if err != nil {+ t.Fatal(err)+ }+ query := authorizationRequest.Query()+ if authorizationRequest.Path != "/authorize" || query.Get("client_id") != "client-id" ||+ query.Get("redirect_uri") != redirectURL || query.Get("code_challenge_method") != "S256" ||+ query.Get("resource") != server.URL+"/mcp" || query.Get("scope") != "todo.read offline_access" {+ t.Fatalf("unexpected authorization URL: %s", authorizationURL)+ }+ if err = CompleteMCPOAuth(flowID, "authorization-code", query.Get("state"), ""); err != nil {+ t.Fatal(err)+ }+ select {+ case err = <-authorizeResult:+ if err != nil {+ t.Fatal(err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("OAuth authorization did not complete")+ }++ credential, ok := getOAuthCredential(serverID, server.URL+"/mcp")+ if !ok || credential.AccessToken != "access-token" || credential.RefreshToken != "refresh-token" ||+ credential.Endpoint != server.URL+"/mcp" || credential.ResourceMetadataURL != server.URL+"/resource-metadata" {+ t.Fatalf("unexpected stored credential: %#v", credential)+ }+}++func TestAuthorizeRefreshesRejectedAccessToken(t *testing.T) {+ useOAuthTestConf(t)+ refreshRequests := make(chan url.Values, 1)+ var server *httptest.Server+ server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/resource-metadata":+ writeOAuthTestJSON(w, http.StatusOK, map[string]any{+ "resource": server.URL + "/mcp",+ "authorization_servers": []string{server.URL},+ })+ case "/.well-known/oauth-authorization-server":+ writeOAuthTestJSON(w, http.StatusOK, oauthTestAuthorizationServerMetadata(server.URL))+ case "/token":+ if err := r.ParseForm(); err != nil {+ t.Errorf("parse refresh request: %v", err)+ }+ refreshRequests <- r.Form+ writeOAuthTestJSON(w, http.StatusOK, map[string]any{+ "access_token": "new-access-token",+ "refresh_token": "new-refresh-token",+ "token_type": "Bearer",+ "expires_in": 3600,+ })+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ credential := oauthCredential{+ ServerID: "refresh-server",+ Endpoint: server.URL + "/mcp",+ Resource: server.URL + "/mcp",+ Issuer: server.URL,+ ResourceMetadataURL: server.URL + "/resource-metadata",+ ClientID: "client-id",+ TokenEndpoint: server.URL + "/old-token",+ TokenAuthMethod: "none",+ AccessToken: "rejected-access-token",+ RefreshToken: "refresh-token",+ TokenType: "Bearer",+ Expiry: time.Now().Add(time.Hour),+ }+ if err := putOAuthCredential(credential); err != nil {+ t.Fatal(err)+ }+ handler := newMCPOAuthHandler(conf.MCPServer{ID: credential.ServerID, URL: credential.Endpoint}, false)+ if err := handler.Authorize(context.Background(), httptest.NewRequest(http.MethodPost, credential.Endpoint, nil),+ newOAuthChallengeResponse(credential.ResourceMetadataURL)); err != nil {+ t.Fatal(err)+ }+ select {+ case form := <-refreshRequests:+ if form.Get("grant_type") != "refresh_token" || form.Get("refresh_token") != credential.RefreshToken {+ t.Fatalf("unexpected refresh request: %#v", form)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("refresh request was not sent")+ }+ refreshed, ok := getOAuthCredential(credential.ServerID, credential.Endpoint)+ if !ok || refreshed.AccessToken != "new-access-token" || refreshed.RefreshToken != "new-refresh-token" {+ t.Fatalf("unexpected refreshed credential: %#v", refreshed)+ }+}++func TestInteractiveOAuthFailureCanBeRetried(t *testing.T) {+ server := httptest.NewServer(http.NotFoundHandler())+ defer server.Close()+ serverID := "retry-server"+ t.Cleanup(func() {+ mcpMu.Lock()+ delete(mcpRuntime, serverID)+ mcpMu.Unlock()+ })+ handler := newMCPOAuthHandler(conf.MCPServer{ID: serverID, URL: server.URL + "/mcp"}, true)+ err := handler.Authorize(context.Background(), httptest.NewRequest(http.MethodPost, server.URL+"/mcp", nil),+ newOAuthChallengeResponse(server.URL+"/missing-resource-metadata"))+ if err == nil {+ t.Fatal("expected OAuth discovery failure")+ }+ mcpMu.Lock()+ state := mcpRuntime[serverID]+ mcpMu.Unlock()+ if state.Status != "authorization_required" || state.Error == "" {+ t.Fatalf("unexpected retry state: %#v", state)+ }+}++func TestDisconnectMCPOAuthClearsBeforeRemoteRevocation(t *testing.T) {+ useOAuthTestConf(t)+ revoked := make(chan string, 2)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if err := r.ParseForm(); err != nil {+ t.Errorf("parse revocation request: %v", err)+ }+ revoked <- r.Form.Get("token")+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()+ credential := oauthCredential{+ ServerID: "disconnect-server",+ Endpoint: server.URL + "/mcp",+ Resource: server.URL + "/mcp",+ Issuer: server.URL,+ ClientID: "client-id",+ TokenEndpoint: server.URL + "/token",+ RevocationEndpoint: server.URL,+ TokenAuthMethod: "none",+ AccessToken: "access-token",+ RefreshToken: "refresh-token",+ }+ if err := putOAuthCredential(credential); err != nil {+ t.Fatal(err)+ }+ started := time.Now()+ if err := DisconnectMCPOAuth(credential.ServerID); err != nil {+ t.Fatal(err)+ }+ if time.Since(started) > time.Second {+ t.Fatal("disconnect waited for remote revocation")+ }+ if _, ok := getOAuthCredential(credential.ServerID, credential.Endpoint); ok {+ t.Fatal("credential was not cleared locally")+ }+ var tokens []string+ for len(tokens) < 2 {+ select {+ case token := <-revoked:+ tokens = append(tokens, token)+ case <-time.After(5 * time.Second):+ t.Fatalf("remote revocation did not complete: %#v", tokens)+ }+ }+ if !slices.Contains(tokens, "access-token") || !slices.Contains(tokens, "refresh-token") {+ t.Fatalf("unexpected revoked tokens: %#v", tokens)+ }+}++func oauthTestAuthorizationServerMetadata(issuer string) map[string]any {+ return map[string]any{+ "issuer": issuer,+ "authorization_endpoint": issuer + "/authorize",+ "token_endpoint": issuer + "/token",+ "registration_endpoint": issuer + "/register",+ "revocation_endpoint": issuer + "/revoke",+ "code_challenge_methods_supported": []string{"S256"},+ "token_endpoint_auth_methods_supported": []string{"none"},+ "grant_types_supported": []string{"authorization_code", "refresh_token"},+ "response_types_supported": []string{"code"},+ "scopes_supported": []string{"todo.read", "offline_access"},+ }+}++func newOAuthChallengeResponse(metadataURL string) *http.Response {+ response := &http.Response{+ StatusCode: http.StatusUnauthorized,+ Status: "401 Unauthorized",+ Header: http.Header{},+ Body: io.NopCloser(strings.NewReader("")),+ }+ response.Header.Set("WWW-Authenticate", fmt.Sprintf(`Bearer resource_metadata="%s"`, metadataURL))+ return response+}++func waitForOAuthAuthorizationURL(t *testing.T, serverID string) string {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ mcpMu.Lock()+ state := mcpRuntime[serverID]+ mcpMu.Unlock()+ if state.AuthorizationURL != "" {+ return state.AuthorizationURL+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Fatal("authorization URL was not published")+ return ""+}++func writeOAuthTestJSON(w http.ResponseWriter, status int, value any) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(value)+}++func useOAuthTestConf(t *testing.T) {+ t.Helper()+ oldConf, oldConfDir, oldReadOnly := model.Conf, util.ConfDir, util.ReadOnly+ model.Conf = model.NewAppConf()+ model.Conf.System = &conf.System{}+ util.ConfDir = t.TempDir()+ util.ReadOnly = false+ resetOAuthCredentialStore()+ t.Cleanup(func() {+ model.Conf, util.ConfDir, util.ReadOnly = oldConf, oldConfDir, oldReadOnly+ resetOAuthCredentialStore()+ })+}++func resetOAuthCredentialStore() {+ oauthCredentialStore.Lock()+ oauthCredentialStore.loaded = false+ oauthCredentialStore.credentials = nil+ oauthCredentialStore.Unlock()+}diff --git a/kernel/mcp/handler.go b/kernel/mcp/handler.goindex 8085c0f099..8da7d2aac7 100644--- a/kernel/mcp/handler.go+++ b/kernel/mcp/handler.go@@ -229,10 +229,7 @@ func handleDiscover(req *JsonRpcRequest) *JsonRpcResponse {}func handleToolsList2026(id any) *JsonRpcResponse {- toolList := make([]*tools.Tool, 0, len(tools.Registry))- for _, t := range tools.Registry {- toolList = append(toolList, t)- }+ toolList := tools.GetAllTools()return &JsonRpcResponse{JsonRpc: "2.0",Result: map[string]any{diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.goindex 56f41fdb45..24da2aee96 100644--- a/kernel/mcp/tools/register.go+++ b/kernel/mcp/tools/register.go@@ -79,6 +79,14 @@ func RemoveTool(name string) {delete(Registry, name)}+func RemoveToolIf(name string, tool *Tool) {+ registryMu.Lock()+ defer registryMu.Unlock()+ if Registry[name] == tool {+ delete(Registry, name)+ }+}+func register(t *Tool) {if t.Source == "" {t.Source = "native"diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 6d0fbbc85d..0c5e7d7416 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -86,6 +86,8 @@ type AppConf struct {DataIndexState int `json:"dataIndexState"` // 数据索引状态,0:已索引,1:未索引CookieKey string `json:"cookieKey"` // 用于加密 Cookie 的密钥+ MCPOAuth string `json:"mcpOAuth"` // MCP OAuth 凭据密文+m *sync.RWMutex // 配置数据锁userLock *sync.RWMutex // 用户数据独立锁,避免与配置保存操作竞争}@@ -98,6 +100,26 @@ func NewAppConf() *AppConf {}}+func (conf *AppConf) GetMCPOAuth() string {+ conf.m.RLock()+ defer conf.m.RUnlock()+ return conf.MCPOAuth+}++func (conf *AppConf) SetMCPOAuth(value string) {+ conf.m.Lock()+ conf.MCPOAuth = value+ conf.m.Unlock()+ conf.Save()+}++func (conf *AppConf) SetAI(ai *conf.AI) {+ conf.m.Lock()+ conf.AI = ai+ conf.m.Unlock()+ conf.Save()+}+func (conf *AppConf) GetUILayout() *conf.UILayout {conf.m.Lock()defer conf.m.Unlock()@@ -998,26 +1020,35 @@ func (conf *AppConf) Save() {return}- Conf.m.Lock()- defer Conf.m.Unlock()+ conf.m.Lock()+ defer conf.m.Unlock()- if nil != Conf.AI {- Conf.AI.EncryptAPIKeys()- defer Conf.AI.DecryptAPIKeys()+ plainData, err := gulu.JSON.MarshalJSON(conf)+ if err != nil {+ logging.LogErrorf("marshal conf failed: %s", err)+ return}-- if nil != Conf.Secrets {- Conf.Secrets.Encrypt()- defer Conf.Secrets.Decrypt()+ snapshot := NewAppConf()+ if err = gulu.JSON.UnmarshalJSON(plainData, snapshot); err != nil {+ logging.LogErrorf("copy conf failed: %s", err)+ return+ }+ if snapshot.AI != nil {+ snapshot.AI.EncryptAPIKeys()+ }+ if snapshot.Secrets != nil {+ snapshot.Secrets.Encrypt()}-// safeMode 是纯运行时状态(由 --safe-mode 注入),不随 conf.json 持久化,避免跨启动残留。- // 序列化写盘时临时清零,写完恢复内存值(供 getConf 等运行时读取)。- safeMode := Conf.System.SafeMode- Conf.System.SafeMode = false- defer func() { Conf.System.SafeMode = safeMode }()+ if snapshot.System != nil {+ snapshot.System.SafeMode = false+ }- newData, _ := gulu.JSON.MarshalIndentJSON(Conf, "", " ")+ newData, err := gulu.JSON.MarshalIndentJSON(snapshot, "", " ")+ if err != nil {+ logging.LogErrorf("marshal conf snapshot failed: %s", err)+ return+ }confPath := filepath.Join(util.ConfDir, "conf.json")oldData, err := filelock.ReadFile(confPath)if err != nil {@@ -1194,6 +1225,7 @@ func GetMaskedConf() (ret *AppConf, err error) {}ret.UserData = MaskedUserData+ ret.MCPOAuth = ""if "" != ret.AccessAuthCode {ret.AccessAuthCode = MaskedAccessAuthCode}@@ -1204,6 +1236,7 @@ func GetMaskedConf() (ret *AppConf, err error) {// REF: https://github.com/siyuan-note/siyuan/issues/11364func HideConfSecret(c *AppConf) {c.AI = &conf.AI{}+ c.MCPOAuth = ""c.Api = &conf.API{}c.Flashcard = &conf.Flashcard{}c.ServerAddrs = []string{}diff --git a/kernel/model/conf_save_test.go b/kernel/model/conf_save_test.gonew file mode 100644index 0000000000..f3974b38b4--- /dev/null+++ b/kernel/model/conf_save_test.go@@ -0,0 +1,62 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/gulu"+ appconf "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestSaveUsesEncryptedSnapshot(t *testing.T) {+ oldConfDir, oldReadOnly := util.ConfDir, util.ReadOnly+ util.ConfDir = t.TempDir()+ util.ReadOnly = false+ t.Cleanup(func() {+ util.ConfDir, util.ReadOnly = oldConfDir, oldReadOnly+ })++ app := NewAppConf()+ app.System = &appconf.System{SafeMode: true}+ app.AI = appconf.NewAI()+ app.AI.Providers = []*appconf.Provider{{APIKey: "plain-api-key"}}+ app.Secrets = &appconf.Secrets{Items: []*appconf.Secret{{Name: "token", Value: "plain-secret"}}}+ app.MCPOAuth = "encrypted-oauth-data"+ app.Save()++ if app.AI.Providers[0].APIKey != "plain-api-key" || app.Secrets.Items[0].Value != "plain-secret" || !app.System.SafeMode {+ t.Fatalf("live configuration was mutated: %#v", app)+ }+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil {+ t.Fatal(err)+ }+ stored := NewAppConf()+ if err = gulu.JSON.UnmarshalJSON(data, stored); err != nil {+ t.Fatal(err)+ }+ if stored.AI.Providers[0].APIKey == "plain-api-key" || stored.Secrets.Items[0].Value == "plain-secret" || stored.System.SafeMode {+ t.Fatalf("stored configuration was not sanitized: %#v", stored)+ }+ if stored.MCPOAuth != app.MCPOAuth {+ t.Fatalf("unexpected stored MCP OAuth data: %q", stored.MCPOAuth)+ }+}