🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: support market cloud endpoint mcp (#10484)
Shinji-Li9c7ce449f578
diff --git a/locales/ar/marketAuth.json b/locales/ar/marketAuth.jsonindex 6a2d50d20f2..a9fd0937cd1 100644--- a/locales/ar/marketAuth.json+++ b/locales/ar/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "إلغاء",+ "confirm": "تأكيد التفويض",+ "description": {+ "and": "و",+ "prefix": "بالنقر على تأكيد التفويض، فإنك توافق على",+ "privacy": "سياسة الخصوصية",+ "terms": "شروط الخدمة"+ },+ "title": "تأكيد التفويض"+ },"callback": {"buttons": {"close": "إغلاق النافذة"@@ -33,8 +44,10 @@"stateMissing": "لم يتم العثور على حالة التفويض، يرجى المحاولة مرة أخرى."},"messages": {+ "authorized": "تم تفويض خدمة LobeHub بنجاح","loading": "جارٍ بدء عملية التفويض...","success": {+ "cloudMcpInstall": "تم التفويض بنجاح! يمكنك الآن تثبيت إضافة Cloud MCP.","submit": "تم التفويض بنجاح! يمكنك الآن نشر المساعد.","upload": "تم التفويض بنجاح! يمكنك الآن نشر إصدار جديد."}diff --git a/locales/bg-BG/marketAuth.json b/locales/bg-BG/marketAuth.jsonindex 68ec1ca1300..40f23d98e2e 100644--- a/locales/bg-BG/marketAuth.json+++ b/locales/bg-BG/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Отказ",+ "confirm": "Разреши използването",+ "description": {+ "and": "и",+ "prefix": "С натискане на „Разреши използването“ се съгласявате с",+ "privacy": "Политиката за поверителност",+ "terms": "Условията за ползване"+ },+ "title": "Потвърждаване на оторизацията"+ },"callback": {"buttons": {"close": "Затвори прозореца"@@ -33,8 +44,10 @@"stateMissing": "Състоянието на упълномощаване не бе намерено, моля опитайте отново."},"messages": {+ "authorized": "Успешно упълномощаване на услугата LobeHub","loading": "Стартиране на процеса по упълномощаване...","success": {+ "cloudMcpInstall": "Успешно разрешение! Вече можете да инсталирате приставката Cloud MCP.","submit": "Упълномощаването е успешно! Вече можете да публикувате помощник.","upload": "Упълномощаването е успешно! Вече можете да публикувате нова версия."}diff --git a/locales/de-DE/marketAuth.json b/locales/de-DE/marketAuth.jsonindex 4b08ce9b391..19263ca31d9 100644--- a/locales/de-DE/marketAuth.json+++ b/locales/de-DE/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Abbrechen",+ "confirm": "Autorisieren",+ "description": {+ "and": "und",+ "prefix": "Mit dem Klick auf „Autorisieren“ stimmen Sie den",+ "privacy": "Datenschutzbestimmungen",+ "terms": "Nutzungsbedingungen"+ },+ "title": "Autorisierung bestätigen"+ },"callback": {"buttons": {"close": "Fenster schließen"@@ -33,8 +44,10 @@"stateMissing": "Autorisierungsstatus nicht gefunden, bitte erneut versuchen."},"messages": {+ "authorized": "LobeHub-Dienst erfolgreich autorisiert","loading": "Autorisierungsvorgang wird gestartet...","success": {+ "cloudMcpInstall": "Autorisierung erfolgreich! Sie können jetzt das Cloud MCP-Plugin installieren.","submit": "Autorisierung erfolgreich! Du kannst jetzt einen Assistenten veröffentlichen.","upload": "Autorisierung erfolgreich! Du kannst jetzt eine neue Version veröffentlichen."}diff --git a/locales/en-US/marketAuth.json b/locales/en-US/marketAuth.jsonindex 34f5d2560a1..1e27f5c073b 100644--- a/locales/en-US/marketAuth.json+++ b/locales/en-US/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Cancel",+ "confirm": "Authorize",+ "description": {+ "and": "and",+ "prefix": "By clicking Authorize, you agree to",+ "privacy": "Privacy Policy",+ "terms": "Terms of Service"+ },+ "title": "Confirm Authorization"+ },"callback": {"buttons": {"close": "Close Window"@@ -33,8 +44,10 @@"stateMissing": "Authorization state not found. Please try again."},"messages": {+ "authorized": "LobeHub service authorized successfully","loading": "Starting authorization process...","success": {+ "cloudMcpInstall": "Authorization successful! You can now install the Cloud MCP plugin.","submit": "Authorization successful! You can now publish your assistant.","upload": "Authorization successful! You can now publish a new version."}diff --git a/locales/es-ES/marketAuth.json b/locales/es-ES/marketAuth.jsonindex 7c5b0916e43..0773fc9e9bd 100644--- a/locales/es-ES/marketAuth.json+++ b/locales/es-ES/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Cancelar",+ "confirm": "Autorizar uso",+ "description": {+ "and": "y",+ "prefix": "Al hacer clic en autorizar uso, se considera que aceptas",+ "privacy": "la Política de Privacidad",+ "terms": "los Términos de Servicio"+ },+ "title": "Confirmar autorización"+ },"callback": {"buttons": {"close": "Cerrar ventana"@@ -33,8 +44,10 @@"stateMissing": "No se encontró el estado de autenticación, por favor inténtalo de nuevo."},"messages": {+ "authorized": "Autorización del servicio LobeHub realizada con éxito","loading": "Iniciando el proceso de autenticación...","success": {+ "cloudMcpInstall": "¡Autorización exitosa! Ahora puedes instalar el complemento Cloud MCP.","submit": "¡Autenticación exitosa! Ahora puedes publicar asistentes.","upload": "¡Autenticación exitosa! Ahora puedes publicar una nueva versión."}diff --git a/locales/fa-IR/marketAuth.json b/locales/fa-IR/marketAuth.jsonindex 963a209f87f..0a3a7a3c8f1 100644--- a/locales/fa-IR/marketAuth.json+++ b/locales/fa-IR/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "لغو",+ "confirm": "تأیید مجوز استفاده",+ "description": {+ "and": "و",+ "prefix": "با کلیک بر روی تأیید مجوز استفاده، شما با",+ "privacy": "سیاست حفظ حریم خصوصی",+ "terms": "شرایط خدمات"+ },+ "title": "تأیید مجوز"+ },"callback": {"buttons": {"close": "بستن پنجره"@@ -33,8 +44,10 @@"stateMissing": "وضعیت احراز هویت یافت نشد، لطفاً دوباره تلاش کنید."},"messages": {+ "authorized": "دسترسی به سرویس LobeHub با موفقیت تأیید شد","loading": "در حال آغاز فرآیند احراز هویت...","success": {+ "cloudMcpInstall": "مجوز با موفقیت صادر شد! اکنون میتوانید افزونه Cloud MCP را نصب کنید.","submit": "احراز هویت با موفقیت انجام شد! اکنون میتوانید دستیار را منتشر کنید.","upload": "احراز هویت با موفقیت انجام شد! اکنون میتوانید نسخه جدیدی منتشر کنید."}diff --git a/locales/fr-FR/marketAuth.json b/locales/fr-FR/marketAuth.jsonindex eea45c64aa0..28cf03b2f45 100644--- a/locales/fr-FR/marketAuth.json+++ b/locales/fr-FR/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Annuler",+ "confirm": "Autoriser l'utilisation",+ "description": {+ "and": "et",+ "prefix": "En cliquant sur « Autoriser l'utilisation », vous acceptez",+ "privacy": "la Politique de confidentialité",+ "terms": "les Conditions d'utilisation"+ },+ "title": "Confirmer l'autorisation"+ },"callback": {"buttons": {"close": "Fermer la fenêtre"@@ -33,8 +44,10 @@"stateMissing": "État d'autorisation introuvable, veuillez réessayer."},"messages": {+ "authorized": "Autorisation du service LobeHub réussie","loading": "Lancement du processus d'autorisation...","success": {+ "cloudMcpInstall": "Autorisation réussie ! Vous pouvez maintenant installer le plugin Cloud MCP.","submit": "Autorisation réussie ! Vous pouvez maintenant publier un assistant.","upload": "Autorisation réussie ! Vous pouvez maintenant publier une nouvelle version."}diff --git a/locales/it-IT/marketAuth.json b/locales/it-IT/marketAuth.jsonindex 62aa117e379..1b46a244f77 100644--- a/locales/it-IT/marketAuth.json+++ b/locales/it-IT/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Annulla",+ "confirm": "Autorizza l'utilizzo",+ "description": {+ "and": "e",+ "prefix": "Facendo clic su 'Autorizza l'utilizzo' si accetta",+ "privacy": "l'Informativa sulla privacy",+ "terms": "i Termini di servizio"+ },+ "title": "Conferma autorizzazione"+ },"callback": {"buttons": {"close": "Chiudi finestra"@@ -33,8 +44,10 @@"stateMissing": "Stato di autorizzazione non trovato, riprova."},"messages": {+ "authorized": "Autorizzazione al servizio LobeHub avvenuta con successo","loading": "Avvio del processo di autorizzazione in corso...","success": {+ "cloudMcpInstall": "Autorizzazione avvenuta con successo! Ora puoi installare il plugin Cloud MCP.","submit": "Autorizzazione riuscita! Ora puoi pubblicare l'assistente.","upload": "Autorizzazione riuscita! Ora puoi pubblicare una nuova versione."}diff --git a/locales/ja-JP/marketAuth.json b/locales/ja-JP/marketAuth.jsonindex bb75a16a7c5..cd7a39de167 100644--- a/locales/ja-JP/marketAuth.json+++ b/locales/ja-JP/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "キャンセル",+ "confirm": "使用を許可する",+ "description": {+ "and": "および",+ "prefix": "「使用を許可する」をクリックすると、以下に同意したものとみなされます:",+ "privacy": "プライバシーポリシー",+ "terms": "利用規約"+ },+ "title": "認証の確認"+ },"callback": {"buttons": {"close": "ウィンドウを閉じる"@@ -33,8 +44,10 @@"stateMissing": "認証状態が見つかりません。もう一度お試しください。"},"messages": {+ "authorized": "LobeHub サービスの認証に成功しました","loading": "認証プロセスを開始しています...","success": {+ "cloudMcpInstall": "許可が成功しました!これで Cloud MCP プラグインをインストールできます。","submit": "認証に成功しました!アシスタントを公開できます。","upload": "認証に成功しました!新しいバージョンを公開できます。"}diff --git a/locales/ko-KR/marketAuth.json b/locales/ko-KR/marketAuth.jsonindex cc6c2c8ae68..853db39389d 100644--- a/locales/ko-KR/marketAuth.json+++ b/locales/ko-KR/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "취소",+ "confirm": "사용 권한 부여",+ "description": {+ "and": "및",+ "prefix": "사용 권한 부여를 클릭하면 다음에 동의한 것으로 간주됩니다",+ "privacy": "개인정보 처리방침",+ "terms": "서비스 이용약관"+ },+ "title": "권한 확인"+ },"callback": {"buttons": {"close": "창 닫기"@@ -33,8 +44,10 @@"stateMissing": "인증 상태를 찾을 수 없습니다. 다시 시도해 주세요."},"messages": {+ "authorized": "LobeHub 서비스가 성공적으로 인증되었습니다","loading": "인증 절차를 시작하는 중입니다...","success": {+ "cloudMcpInstall": "권한 부여 완료! 이제 Cloud MCP 플러그인을 설치할 수 있습니다.","submit": "인증 성공! 이제 어시스턴트를 게시할 수 있습니다.","upload": "인증 성공! 이제 새 버전을 게시할 수 있습니다."}diff --git a/locales/nl-NL/marketAuth.json b/locales/nl-NL/marketAuth.jsonindex 7e0458d326e..f40a864cc9a 100644--- a/locales/nl-NL/marketAuth.json+++ b/locales/nl-NL/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Annuleren",+ "confirm": "Toestemming geven",+ "description": {+ "and": "en",+ "prefix": "Door op 'Toestemming geven' te klikken, ga je akkoord met onze",+ "privacy": "Privacybeleid",+ "terms": "Servicevoorwaarden"+ },+ "title": "Autorisatie bevestigen"+ },"callback": {"buttons": {"close": "Venster sluiten"@@ -33,8 +44,10 @@"stateMissing": "Autorisatiestatus niet gevonden, probeer het opnieuw."},"messages": {+ "authorized": "LobeHub-service succesvol geautoriseerd","loading": "Autorisatieproces wordt gestart...","success": {+ "cloudMcpInstall": "Toestemming succesvol! Je kunt nu de Cloud MCP-plugin installeren.","submit": "Autorisatie geslaagd! Je kunt nu een assistent publiceren.","upload": "Autorisatie geslaagd! Je kunt nu een nieuwe versie publiceren."}diff --git a/locales/pl-PL/marketAuth.json b/locales/pl-PL/marketAuth.jsonindex 5dbaded0e0a..b49fe300b05 100644--- a/locales/pl-PL/marketAuth.json+++ b/locales/pl-PL/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Anuluj",+ "confirm": "Autoryzuj użycie",+ "description": {+ "and": "oraz",+ "prefix": "Klikając „Autoryzuj użycie”, wyrażasz zgodę na",+ "privacy": "Politykę prywatności",+ "terms": "Warunki korzystania z usługi"+ },+ "title": "Potwierdź autoryzację"+ },"callback": {"buttons": {"close": "Zamknij okno"@@ -33,8 +44,10 @@"stateMissing": "Nie znaleziono stanu autoryzacji, spróbuj ponownie."},"messages": {+ "authorized": "Autoryzacja usługi LobeHub zakończona pomyślnie","loading": "Uruchamianie procesu autoryzacji...","success": {+ "cloudMcpInstall": "Autoryzacja zakończona sukcesem! Możesz teraz zainstalować wtyczkę Cloud MCP.","submit": "Autoryzacja zakończona sukcesem! Możesz teraz opublikować asystenta.","upload": "Autoryzacja zakończona sukcesem! Możesz teraz opublikować nową wersję."}diff --git a/locales/pt-BR/marketAuth.json b/locales/pt-BR/marketAuth.jsonindex ef8d9975b1e..9579bd89420 100644--- a/locales/pt-BR/marketAuth.json+++ b/locales/pt-BR/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Cancelar",+ "confirm": "Autorizar uso",+ "description": {+ "and": "e",+ "prefix": "Ao clicar em autorizar uso, você concorda com",+ "privacy": "Política de Privacidade",+ "terms": "Termos de Serviço"+ },+ "title": "Confirmar Autorização"+ },"callback": {"buttons": {"close": "Fechar janela"@@ -33,8 +44,10 @@"stateMissing": "Estado de autorização não encontrado, tente novamente."},"messages": {+ "authorized": "Autorização do serviço LobeHub realizada com sucesso","loading": "Iniciando o processo de autorização...","success": {+ "cloudMcpInstall": "Autorização bem-sucedida! Agora você pode instalar o plugin Cloud MCP.","submit": "Autorização bem-sucedida! Agora você pode publicar o assistente.","upload": "Autorização bem-sucedida! Agora você pode publicar uma nova versão."}diff --git a/locales/ru-RU/marketAuth.json b/locales/ru-RU/marketAuth.jsonindex 350c5549458..33c981bc38b 100644--- a/locales/ru-RU/marketAuth.json+++ b/locales/ru-RU/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Отмена",+ "confirm": "Подтвердить доступ",+ "description": {+ "and": "и",+ "prefix": "Нажимая «Подтвердить доступ», вы соглашаетесь с",+ "privacy": "Политикой конфиденциальности",+ "terms": "Условиями обслуживания"+ },+ "title": "Подтвердить авторизацию"+ },"callback": {"buttons": {"close": "Закрыть окно"@@ -33,8 +44,10 @@"stateMissing": "Состояние авторизации не найдено, пожалуйста, попробуйте снова."},"messages": {+ "authorized": "Авторизация сервиса LobeHub прошла успешно","loading": "Запуск процесса авторизации...","success": {+ "cloudMcpInstall": "Доступ успешно предоставлен! Теперь вы можете установить плагин Cloud MCP.","submit": "Авторизация прошла успешно! Теперь вы можете опубликовать помощника.","upload": "Авторизация прошла успешно! Теперь вы можете опубликовать новую версию."}diff --git a/locales/tr-TR/marketAuth.json b/locales/tr-TR/marketAuth.jsonindex 2cedc6918f0..83c7d89f2e5 100644--- a/locales/tr-TR/marketAuth.json+++ b/locales/tr-TR/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "İptal",+ "confirm": "Kullanıma Yetki Ver",+ "description": {+ "and": "ve",+ "prefix": "Kullanıma yetki ver'e tıklayarak şu şartları kabul etmiş olursunuz:",+ "privacy": "Gizlilik Politikası",+ "terms": "Hizmet Şartları"+ },+ "title": "Yetkilendirmeyi Onayla"+ },"callback": {"buttons": {"close": "Pencereyi Kapat"@@ -33,8 +44,10 @@"stateMissing": "Yetkilendirme durumu bulunamadı, lütfen tekrar deneyin."},"messages": {+ "authorized": "LobeHub hizmet yetkilendirmesi başarıyla tamamlandı","loading": "Yetkilendirme süreci başlatılıyor...","success": {+ "cloudMcpInstall": "Yetkilendirme başarılı! Artık Cloud MCP eklentisini yükleyebilirsiniz.","submit": "Yetkilendirme başarılı! Artık asistan yayınlayabilirsiniz.","upload": "Yetkilendirme başarılı! Artık yeni bir sürüm yayınlayabilirsiniz."}diff --git a/locales/vi-VN/marketAuth.json b/locales/vi-VN/marketAuth.jsonindex b079e58dc68..314d50afee3 100644--- a/locales/vi-VN/marketAuth.json+++ b/locales/vi-VN/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "Hủy",+ "confirm": "Ủy quyền sử dụng",+ "description": {+ "and": "và",+ "prefix": "Bằng cách nhấp vào ủy quyền sử dụng, bạn đồng ý với",+ "privacy": "Chính sách quyền riêng tư",+ "terms": "Điều khoản dịch vụ"+ },+ "title": "Xác nhận ủy quyền"+ },"callback": {"buttons": {"close": "Đóng cửa sổ"@@ -33,8 +44,10 @@"stateMissing": "Không tìm thấy trạng thái xác thực, vui lòng thử lại."},"messages": {+ "authorized": "Dịch vụ LobeHub đã được cấp quyền thành công","loading": "Đang khởi động quy trình xác thực...","success": {+ "cloudMcpInstall": "Ủy quyền thành công! Bây giờ bạn có thể cài đặt plugin Cloud MCP.","submit": "Xác thực thành công! Bây giờ bạn có thể xuất bản trợ lý.","upload": "Xác thực thành công! Bây giờ bạn có thể xuất bản phiên bản mới."}diff --git a/locales/zh-CN/marketAuth.json b/locales/zh-CN/marketAuth.jsonindex 324175a7795..129fb0a4d00 100644--- a/locales/zh-CN/marketAuth.json+++ b/locales/zh-CN/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "取消",+ "confirm": "授权使用",+ "description": {+ "and": "和",+ "prefix": "点击授权使用即视为同意",+ "privacy": "隐私协议",+ "terms": "服务条款"+ },+ "title": "确认授权"+ },"callback": {"buttons": {"close": "关闭窗口"@@ -33,8 +44,10 @@"stateMissing": "未找到授权状态,请重试。"},"messages": {+ "authorized": "LobeHub 服务授权成功","loading": "正在启动授权流程...","success": {+ "cloudMcpInstall": "授权成功!现在可以安装 Cloud MCP 插件了。","submit": "授权成功!现在可以发布助手了。","upload": "授权成功!现在可以发布新版本了。"}diff --git a/locales/zh-TW/marketAuth.json b/locales/zh-TW/marketAuth.jsonindex 731fb108660..01e708e3e21 100644--- a/locales/zh-TW/marketAuth.json+++ b/locales/zh-TW/marketAuth.json@@ -1,4 +1,15 @@{+ "authorize": {+ "cancel": "取消",+ "confirm": "授權使用",+ "description": {+ "and": "和",+ "prefix": "點擊授權使用即視為同意",+ "privacy": "隱私協議",+ "terms": "服務條款"+ },+ "title": "確認授權"+ },"callback": {"buttons": {"close": "關閉視窗"@@ -33,8 +44,10 @@"stateMissing": "找不到授權狀態,請重試。"},"messages": {+ "authorized": "LobeHub 服務授權成功","loading": "正在啟動授權流程⋯⋯","success": {+ "cloudMcpInstall": "授權成功!現在可以安裝 Cloud MCP 外掛了。","submit": "授權成功!現在可以發佈助手了。","upload": "授權成功!現在可以發佈新版本了。"}diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex ed23ac92d8c..dbe001d0569 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -80,6 +80,7 @@ export class UserModel {settingsImage: userSettings.image,settingsKeyVaults: userSettings.keyVaults,settingsLanguageModel: userSettings.languageModel,+ settingsMarket: userSettings.market,settingsSystemAgent: userSettings.systemAgent,settingsTTS: userSettings.tts,settingsTool: userSettings.tool,@@ -112,6 +113,7 @@ export class UserModel {image: state.settingsImage || {},keyVaults: decryptKeyVaults,languageModel: state.settingsLanguageModel || {},+ market: state.settingsMarket || undefined,systemAgent: state.settingsSystemAgent || {},tool: state.settingsTool || {},tts: state.settingsTTS || {},diff --git a/packages/types/src/discover/mcp.ts b/packages/types/src/discover/mcp.tsindex bee2e5d2a3c..8a89b44129d 100644--- a/packages/types/src/discover/mcp.ts+++ b/packages/types/src/discover/mcp.ts@@ -41,7 +41,7 @@ export enum McpNavKey {export enum McpConnectionType {http = 'http',- stdio = 'stdio'+ stdio = 'stdio',}export type DiscoverMcpItem = PluginItem;@@ -60,6 +60,7 @@ export interface McpQueryParams {export type McpListResponse = PluginListResponse;export interface DiscoverMcpDetail extends PluginItemDetail {+ haveCloudEndpoint?: boolean;isClaimed?: boolean;related: DiscoverMcpItem[];}diff --git a/packages/types/src/tool/plugin.ts b/packages/types/src/tool/plugin.tsindex dff086cb7d6..ea75d61c519 100644--- a/packages/types/src/tool/plugin.ts+++ b/packages/types/src/tool/plugin.ts@@ -25,8 +25,9 @@ export interface CustomPluginParams {args?: string[];env?: Record<string, string>;command?: string;- type: 'http' | 'stdio';+ type: 'http' | 'stdio' | 'cloud';url?: string;+ cloudEndPoint?: string; // Cloud gateway endpoint for cloud type// Added authentication configuration supportauth?: {type: 'none' | 'bearer' | 'oauth2';diff --git a/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishButton.tsx b/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishButton.tsxindex 22c03646b9d..30d9b7d3503 100644--- a/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishButton.tsx+++ b/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishButton.tsx@@ -87,9 +87,7 @@ const MarketPublishButton = memo<MarketPublishButtonProps>(`[MarketPublishButton][${action}] User not authenticated, starting authorization`,);try {- message.loading({ content: tMarketAuth('messages.loading'), key: 'market-auth' });const accountId = await signIn();- message.success({ content: buttonCopy.successMessage, key: 'market-auth' });let targetAction: MarketPublishAction = action;diff --git a/src/app/[variants]/(main)/discover/(detail)/mcp/features/Sidebar/ActionButton/index.tsx b/src/app/[variants]/(main)/discover/(detail)/mcp/features/Sidebar/ActionButton/index.tsxindex 62b8e08c095..02882a6735d 100644--- a/src/app/[variants]/(main)/discover/(detail)/mcp/features/Sidebar/ActionButton/index.tsx+++ b/src/app/[variants]/(main)/discover/(detail)/mcp/features/Sidebar/ActionButton/index.tsx@@ -10,6 +10,7 @@ import { Flexbox } from 'react-layout-kit';import MCPInstallProgress from '@/features/MCP/MCPInstallProgress';import { useDetailContext } from '@/features/MCPPluginDetail/DetailProvider';+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';import { useToolStore } from '@/store/tool';import { pluginSelectors } from '@/store/tool/slices/plugin/selectors';@@ -23,9 +24,11 @@ const useStyles = createStyles(({ css }) => ({const ActionButton = memo(() => {const { t } = useTranslation(['discover', 'plugin']);- const { identifier } = useDetailContext();+ const detailContext = useDetailContext();+ const { identifier, haveCloudEndpoint } = detailContext;const { styles } = useStyles();const [isLoading, setIsLoading] = useState(false);+ const { isAuthenticated, isLoading: isAuthLoading, signIn } = useMarketAuth();const [installed, installMCPPlugin, uninstallMCPPlugin] = useToolStore((s) => [pluginSelectors.isPluginInstalled(identifier!)(s),@@ -33,24 +36,47 @@ const ActionButton = memo(() => {s.uninstallMCPPlugin,]);+ // Check if this is a cloud MCP plugin+ const isCloudMcp = haveCloudEndpoint;+const installPlugin = async () => {if (!identifier) return;- setIsLoading(true);- await installMCPPlugin(identifier);+ // If this is a cloud MCP and user is not authenticated, request authorization first+ if (isCloudMcp && !isAuthenticated) {+ try {+ await signIn();+ } catch {+ return; // Don't proceed with installation if auth fails+ }+ }- setIsLoading(false);+ // Proceed with installation+ setIsLoading(true);+ try {+ await installMCPPlugin(identifier);+ } finally {+ setIsLoading(false);+ }};+ const buttonLoading = isLoading || isAuthLoading;+return installed ? (<Flexbox gap={8} horizontal>- <Button block className={styles.button} disabled={isLoading} size={'large'} type={'default'}>+ <Button+ block+ className={styles.button}+ disabled={buttonLoading}+ size={'large'}+ type={'default'}+ >{t('plugins.installed')}</Button><Buttonicon={<Icon icon={Trash2Icon} size={20} />}- loading={isLoading}+ loading={buttonLoading}onClick={async () => {setIsLoading(true);await uninstallMCPPlugin(identifier!);@@ -68,7 +94,7 @@ const ActionButton = memo(() => {<ButtonblockclassName={styles.button}- loading={isLoading}+ loading={buttonLoading}onClick={installPlugin}size={'large'}type={'primary'}diff --git a/src/features/PluginStore/McpList/List/Action.tsx b/src/features/PluginStore/McpList/List/Action.tsxindex 8edaa2d4e25..9e98206f944 100644--- a/src/features/PluginStore/McpList/List/Action.tsx+++ b/src/features/PluginStore/McpList/List/Action.tsx@@ -5,6 +5,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { Flexbox } from 'react-layout-kit';+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useToolStore } from '@/store/tool';@@ -15,13 +16,14 @@ interface ActionsProps {}const Actions = memo<ActionsProps>(({ identifier }) => {- const [installed, installing, unInstallPlugin, installMCPPlugin, cancelInstallMCPPlugin] =+ const [installed, installing, unInstallPlugin, installMCPPlugin, cancelInstallMCPPlugin, plugin] =useToolStore((s) => [pluginSelectors.isPluginInstalled(identifier)(s),mcpStoreSelectors.isMCPInstalling(identifier)(s),s.uninstallPlugin,s.installMCPPlugin,s.cancelInstallMCPPlugin,+ mcpStoreSelectors.getPluginById(identifier)(s),]);const { t } = useTranslation('plugin');@@ -30,6 +32,10 @@ const Actions = memo<ActionsProps>(({ identifier }) => {agentSelectors.currentAgentPlugins(s).includes(identifier),]);const { modal } = App.useApp();+ const { isAuthenticated, signIn } = useMarketAuth();++ // Check if this is a cloud MCP plugin+ const isCloudMcp = !!((plugin as any)?.cloudEndPoint || (plugin as any)?.haveCloudEndpoint);return (<Flexbox align={'center'} horizontal>@@ -86,6 +92,19 @@ const Actions = memo<ActionsProps>(({ identifier }) => {onClick={async (e) => {e.stopPropagation();+ // If this is a cloud MCP and user is not authenticated, request authorization first+ if (isCloudMcp && !isAuthenticated) {+ console.log(+ '[MCPListAction] Cloud MCP detected, user not authenticated, starting authorization',+ );++ try {+ await signIn();+ } catch {+ return; // Don't proceed with installation if auth fails+ }+ }+const isSuccess = await installMCPPlugin(identifier);if (isSuccess) {diff --git a/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx b/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsxnew file mode 100644index 00000000000..a3f170874c7--- /dev/null+++ b/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx@@ -0,0 +1,158 @@+'use client';++import { Modal } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { ArrowRight, ShieldCheck } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++const useStyles = createStyles(({ css, token }) => ({+ content: css`+ .ant-modal-content {+ overflow: hidden;+ padding: 0;+ }++ .ant-modal-header {+ margin-block-end: 0;+ padding: 0;+ border-block-end: none;+ }++ .ant-modal-body {+ padding: 0;+ }++ .ant-modal-footer {+ display: flex;+ align-items: center;+ justify-content: space-between;++ margin-block-start: 0;+ padding-block: 16px;+ padding-inline: 24px;+ border-block-start: 1px solid ${token.colorBorder};++ background: ${token.colorBgContainer};++ .ant-btn {+ margin: 0;+ }+ }+ `,+ description: css`+ font-size: 14px;+ line-height: 1.5;+ color: ${token.colorTextSecondary};+ text-align: center;++ a {+ color: ${token.colorPrimary};+ text-decoration: none;++ &:hover {+ text-decoration: underline;+ }+ }++ .highlight {+ font-weight: 500;+ color: ${token.colorText};+ }+ `,+ header: css`+ padding-block: 24px 16px;+ padding-inline: 24px;+ text-align: center;+ `,+ iconWrapper: css`+ display: flex;+ flex-direction: column;+ align-items: center;++ padding-block: 32px 0;+ padding-inline: 0;+ `,+ okButton: css`+ display: flex;+ gap: 8px;+ align-items: center;+ `,+ shieldIcon: css`+ display: flex;+ align-items: center;+ justify-content: center;++ width: 64px;+ height: 64px;+ border-radius: 50%;++ background: ${token.colorPrimaryBg};++ svg {+ width: 36px;+ height: 36px;+ color: ${token.colorPrimary};+ }+ `,+ title: css`+ margin-block-end: 24px;+ font-size: 18px;+ font-weight: 600;+ color: ${token.colorText};+ `,+}));++interface MarketAuthConfirmModalProps {+ onCancel: () => void;+ onConfirm: () => void;+ open: boolean;+}++const MarketAuthConfirmModal = memo<MarketAuthConfirmModalProps>(+ ({ open, onConfirm, onCancel }) => {+ const { t } = useTranslation('marketAuth');+ const { styles } = useStyles();++ return (+ <Modal+ cancelText={t('authorize.cancel')}+ className={styles.content}+ okButtonProps={{+ className: styles.okButton,+ icon: <ArrowRight size={16} />,+ }}+ okText={t('authorize.confirm')}+ onCancel={onCancel}+ onOk={onConfirm}+ open={open}+ title={null}+ width={440}+ >+ <div className={styles.iconWrapper}>+ <div className={styles.shieldIcon}>+ <ShieldCheck />+ </div>+ </div>++ <div className={styles.header}>+ <div className={styles.title}>{t('authorize.title')}</div>+ <div className={styles.description}>+ {t('authorize.description.prefix')} <span className="highlight">LobeHub</span>{' '}+ <a href="https://lobehub.com/terms" rel="noopener noreferrer" target="_blank">+ {t('authorize.description.terms')}+ </a>{' '}+ {t('authorize.description.and')}{' '}+ <a href="https://lobehub.com/privacy" rel="noopener noreferrer" target="_blank">+ {t('authorize.description.privacy')}+ </a>+ </div>+ </div>+ </Modal>+ );+ },+);++MarketAuthConfirmModal.displayName = 'MarketAuthConfirmModal';++export default MarketAuthConfirmModal;diff --git a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsxindex b36f1cd3559..21ea6944b17 100644--- a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx+++ b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx@@ -1,11 +1,14 @@'use client';+import { App } from 'antd';import { ReactNode, createContext, useContext, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';import { MARKET_OIDC_ENDPOINTS } from '@/services/_url';import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/slices/settings/selectors/settings';+import MarketAuthConfirmModal from './MarketAuthConfirmModal';import { MarketAuthError } from './errors';import { MarketOIDC } from './oidc';import { MarketAuthContextType, MarketAuthSession, MarketUserInfo, OIDCConfig } from './types';@@ -165,10 +168,20 @@ const refreshToken = async (): Promise<boolean> => {* Market 授权上下文提供者*/export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderProps) => {+ const { message } = App.useApp();+ const { t } = useTranslation('marketAuth');+const [session, setSession] = useState<MarketAuthSession | null>(null);const [status, setStatus] = useState<'loading' | 'authenticated' | 'unauthenticated'>('loading');const [oidcClient, setOidcClient] = useState<MarketOIDC | null>(null);const [shouldReauthorize, setShouldReauthorize] = useState(false);+ const [showConfirmModal, setShowConfirmModal] = useState(false);+ const [pendingSignInResolve, setPendingSignInResolve] = useState<+ ((value: number | null) => void) | null+ >(null);+ const [pendingSignInReject, setPendingSignInReject] = useState<((reason?: any) => void) | null>(+ null,+ );// 初始化 OIDC 客户端(仅在客户端)useEffect(() => {@@ -196,8 +209,56 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr*/const restoreSession = () => {console.log('[MarketAuth] Attempting to restore session');- const token = getTokenFromCookie();+ // 优先级 1: 从 DB 中获取 token(优先级最高)+ const dbTokens = getMarketTokensFromDB();+ if (dbTokens?.accessToken && dbTokens?.expiresAt) {+ // 检查 DB 中的 token 是否过期+ if (dbTokens.expiresAt > Date.now()) {+ console.log('[MarketAuth] Session restored from DB');++ // 尝试从 sessionStorage 获取用户信息(如果有的话)+ let userInfo: MarketUserInfo | undefined;+ const userInfoData = sessionStorage.getItem('market_user_info');+ if (userInfoData) {+ try {+ userInfo = JSON.parse(userInfoData);+ } catch (error) {+ console.error('[MarketAuth] Failed to parse stored user info:', error);+ }+ }++ // 创建会话对象+ const restoredSession: MarketAuthSession = {+ accessToken: dbTokens.accessToken,+ expiresAt: dbTokens.expiresAt,+ expiresIn: Math.floor((dbTokens.expiresAt - Date.now()) / 1000),+ scope: 'openid profile email',+ tokenType: 'Bearer',+ userInfo,+ };++ // 同步到 cookie 和 sessionStorage+ setTokenToCookie(dbTokens.accessToken, restoredSession.expiresIn);+ sessionStorage.setItem('market_auth_session', JSON.stringify(restoredSession));++ setSession(restoredSession);+ setStatus('authenticated');+ return;+ } else {+ console.log('[MarketAuth] DB token has expired, will trigger re-authorization');+ // 清理过期的 DB tokens+ clearMarketTokensFromDB();+ sessionStorage.removeItem('market_auth_session');+ removeTokenFromCookie();+ // 标记需要重新授权,等待 oidcClient 准备好+ setShouldReauthorize(true);+ return;+ }+ }++ // 优先级 2: 从 cookie 和 sessionStorage 中获取(DB 中没有时的备选方案)+ const token = getTokenFromCookie();if (token) {// 从 sessionStorage 中获取完整的会话信息const sessionData = sessionStorage.getItem('market_auth_session');@@ -207,14 +268,7 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr// 检查 token 是否过期if (parsedSession.expiresAt > Date.now()) {- console.log('[MarketAuth] Session restored from storage');-- console.log('parsedSession', parsedSession);- console.log('parsedSession.userInfo', parsedSession.userInfo);- console.log(- "sessionStorage.getItem('market_user_info')",- sessionStorage.getItem('market_user_info'),- );+ console.log('[MarketAuth] Session restored from cookie/sessionStorage');// 如果 session 中没有 userInfo,尝试从单独的存储中获取if (!parsedSession.userInfo) {@@ -230,6 +284,9 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr}}+ // 同步到 DB+ saveMarketTokensToDB(parsedSession.accessToken, undefined, parsedSession.expiresAt);+setSession(parsedSession);setStatus('authenticated');return;@@ -254,9 +311,9 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr};/**- * 登录方法+ * 实际执行登录的方法(内部使用)*/- const signIn = async (): Promise<number | null> => {+ const handleActualSignIn = async (): Promise<number | null> => {console.log('[MarketAuth] Starting sign in process');if (!oidcClient) {@@ -311,15 +368,65 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPrsetSession(newSession);setStatus('authenticated');- console.log('[MarketAuth] Sign in completed successfully');return userInfo?.accountId ?? null;} catch (error) {- console.error('[MarketAuth] Sign in failed:', error);setStatus('unauthenticated');++ // 根据错误类型显示不同的错误消息+ if (error instanceof MarketAuthError) {+ message.error(t(`errors.${error.code}`) || t('errors.general'));+ } else {+ message.error(t('errors.general'));+ }+throw error;}};+ /**+ * 登录方法(会先弹出确认对话框)+ */+ const signIn = async (): Promise<number | null> => {+ return new Promise<number | null>((resolve, reject) => {+ setPendingSignInResolve(() => resolve);+ setPendingSignInReject(() => reject);+ setShowConfirmModal(true);+ });+ };++ /**+ * 处理确认授权+ */+ const handleConfirmAuth = async () => {+ setShowConfirmModal(false);+ try {+ const result = await handleActualSignIn();+ if (pendingSignInResolve) {+ pendingSignInResolve(result);+ setPendingSignInResolve(null);+ setPendingSignInReject(null);+ }+ } catch (error) {+ if (pendingSignInReject) {+ pendingSignInReject(error);+ setPendingSignInResolve(null);+ setPendingSignInReject(null);+ }+ }+ };++ /**+ * 处理取消授权+ */+ const handleCancelAuth = () => {+ setShowConfirmModal(false);+ if (pendingSignInReject) {+ pendingSignInReject(new Error('User cancelled authorization'));+ setPendingSignInResolve(null);+ setPendingSignInReject(null);+ }+ };+/*** 登出方法*/@@ -468,7 +575,16 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPrstatus,};- return <MarketAuthContext.Provider value={contextValue}>{children}</MarketAuthContext.Provider>;+ return (+ <MarketAuthContext.Provider value={contextValue}>+ {children}+ <MarketAuthConfirmModal+ onCancel={handleCancelAuth}+ onConfirm={handleConfirmAuth}+ open={showConfirmModal}+ />+ </MarketAuthContext.Provider>+ );};/**diff --git a/src/libs/mcp/types.ts b/src/libs/mcp/types.tsindex 5be807d3b2b..c14670b56b2 100644--- a/src/libs/mcp/types.ts+++ b/src/libs/mcp/types.ts@@ -149,6 +149,14 @@ export interface StdioMCPParams {type: 'stdio';}+export interface CloudMCPParams {+ auth?: AuthConfig;+ headers?: Record<string, string>;+ name: string;+ type: 'cloud';+ url: string;+}+export type MCPClientParams = HttpMCPClientParams | StdioMCPParams;export type MCPErrorType =diff --git a/src/locales/default/marketAuth.ts b/src/locales/default/marketAuth.tsindex c6a54100a7d..4e0c58d18dc 100644--- a/src/locales/default/marketAuth.ts+++ b/src/locales/default/marketAuth.ts@@ -1,4 +1,15 @@export default {+ authorize: {+ cancel: '取消',+ confirm: '授权使用',+ description: {+ and: '和',+ prefix: '点击授权使用即视为同意',+ privacy: '隐私协议',+ terms: '服务条款',+ },+ title: '确认授权',+ },callback: {buttons: {close: '关闭窗口',@@ -33,8 +44,10 @@ export default {stateMissing: '未找到授权状态,请重试。',},messages: {+ authorized: 'LobeHub 服务授权成功',loading: '正在启动授权流程...',success: {+ cloudMcpInstall: '授权成功!现在可以安装 Cloud MCP 插件了。',submit: '授权成功!现在可以发布助手了。',upload: '授权成功!现在可以发布新版本了。',},diff --git a/src/server/routers/lambda/market/index.ts b/src/server/routers/lambda/market/index.tsindex e708219befa..25a6ed6806d 100644--- a/src/server/routers/lambda/market/index.ts+++ b/src/server/routers/lambda/market/index.ts@@ -4,8 +4,14 @@ import { serialize } from 'cookie';import debug from 'debug';import { z } from 'zod';-import { publicProcedure, router } from '@/libs/trpc/lambda';+import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { DiscoverService } from '@/server/services/discover';+import { FileService } from '@/server/services/file';+import {+ contentBlocksToString,+ processContentBlocks,+} from '@/server/services/mcp/contentProcessor';import {AssistantSorts,McpConnectionType,@@ -27,7 +33,85 @@ const marketProcedure = publicProcedure.use(async ({ ctx, next }) => {});});+// Procedure with user authentication for operations requiring user access token+const authedMarketProcedure = authedProcedure.use(serverDatabase).use(async ({ ctx, next }) => {+ const { UserModel } = await import('@/database/models/user');+ const userModel = new UserModel(ctx.serverDB, ctx.userId);++ return next({+ ctx: {+ discoverService: new DiscoverService({ accessToken: ctx.marketAccessToken }),+ fileService: new FileService(ctx.serverDB, ctx.userId),+ userModel,+ },+ });+});+export const marketRouter = router({+ // ============================== Cloud MCP Gateway ==============================+ callCloudMcpEndpoint: authedMarketProcedure+ .input(+ z.object({+ apiParams: z.record(z.any()),+ identifier: z.string(),+ toolName: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ log('callCloudMcpEndpoint input: %O', input);++ try {+ // Query user_settings to get market.accessToken+ const userState = await ctx.userModel.getUserState(async () => ({}));+ const userAccessToken = userState.settings?.market?.accessToken;++ log('callCloudMcpEndpoint: userAccessToken exists=%s', !!userAccessToken);++ if (!userAccessToken) {+ throw new TRPCError({+ code: 'UNAUTHORIZED',+ message: 'User access token not found. Please sign in to Market first.',+ });+ }++ const cloudResult = await ctx.discoverService.callCloudMcpEndpoint({+ apiParams: input.apiParams,+ identifier: input.identifier,+ toolName: input.toolName,+ userAccessToken,+ });++ // Format the cloud result to MCPToolCallResult format+ // Process content blocks (upload images, etc.)+ const newContent =+ cloudResult?.isError || !ctx.fileService+ ? cloudResult?.content+ : await processContentBlocks(cloudResult?.content, ctx.fileService);++ // Convert content blocks to string+ const content = contentBlocksToString(newContent);+ const state = { ...cloudResult, content: newContent };++ if (cloudResult?.isError) {+ return { content, state, success: true };+ }++ return { content, state, success: true };+ } catch (error) {+ log('Error calling cloud MCP endpoint: %O', error);++ // Re-throw TRPCError as-is+ if (error instanceof TRPCError) {+ throw error;+ }++ throw new TRPCError({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to call cloud MCP endpoint',+ });+ }+ }),+// ============================== Assistant Market ==============================getAssistantCategories: marketProcedure.input(@@ -558,7 +642,6 @@ export const marketRouter = router({}),// ============================== Analytics ==============================-reportCall: marketProcedure.input(z.object({diff --git a/src/server/services/discover/index.ts b/src/server/services/discover/index.tsindex e3aab09e161..ee84f479a97 100644--- a/src/server/services/discover/index.ts+++ b/src/server/services/discover/index.ts@@ -119,6 +119,44 @@ export class DiscoverService {};}+ // ============================== Call Cloud Mcp Endpoint Methods ==============================++ async callCloudMcpEndpoint(params: {+ apiParams: Record<string, any>;+ identifier: string;+ toolName: string;+ userAccessToken: string;+ }) {+ log('callCloudMcpEndpoint: params=%O', {+ apiParams: params.apiParams,+ hasUserAccessToken: !!params.userAccessToken,+ identifier: params.identifier,+ toolName: params.toolName,+ });++ try {+ // Call cloud gateway with user access token in Authorization header+ const result = await this.market.plugins.callCloudGateway(+ {+ apiParams: params.apiParams,+ identifier: params.identifier,+ toolName: params.toolName,+ },+ {+ headers: {+ Authorization: `Bearer ${params.userAccessToken}`,+ },+ },+ );++ log('callCloudMcpEndpoint: success, result=%O', result);+ return result;+ } catch (error) {+ log('callCloudMcpEndpoint: error=%O', error);+ throw error;+ }+ }+// ============================== Helper Methods ==============================/**@@ -539,9 +577,9 @@ export class DiscoverService {description: (data as any).description || data.summary,examples: Array.isArray((data as any).examples)? (data as any).examples.map((example: any) => ({- content: typeof example === 'string' ? example : example.content || '',- role: example.role || 'user',- }))+ content: typeof example === 'string' ? example : example.content || '',+ role: example.role || 'user',+ })): [],homepage:(data as any).homepage ||@@ -886,7 +924,10 @@ export class DiscoverService {const all = await this._getPluginList(locale);let raw = all.find((item) => item.identifier === identifier);if (!raw) {- log('getPluginDetail: plugin not found in default store for identifier=%s, trying MCP plugin', identifier);+ log(+ 'getPluginDetail: plugin not found in default store for identifier=%s, trying MCP plugin',+ identifier,+ );try {const mcpDetail = await this.getMcpDetail({ identifier, locale });const convertedMcp: Partial<DiscoverPluginDetail> = {diff --git a/src/services/discover.ts b/src/services/discover.tsindex d98f321d20c..c816305b1af 100644--- a/src/services/discover.ts+++ b/src/services/discover.ts@@ -291,7 +291,7 @@ class DiscoverService {// ============================== Helpers ==============================- private async injectMPToken() {+ async injectMPToken() {if (typeof localStorage === 'undefined') return;// Check server-set status flag cookiediff --git a/src/services/mcp.ts b/src/services/mcp.tsindex 7358bbd9735..b10e8b1f5fb 100644--- a/src/services/mcp.ts+++ b/src/services/mcp.ts@@ -5,7 +5,7 @@ import { PluginManifest } from '@lobehub/market-sdk';import { CallReportRequest } from '@lobehub/market-types';import { MCPToolCallResult } from '@/libs/mcp';-import { desktopClient, toolsClient } from '@/libs/trpc/client';+import { desktopClient, lambdaClient, toolsClient } from '@/libs/trpc/client';import { discoverService } from './discover';@@ -84,6 +84,7 @@ class MCPService {};const isStdio = plugin?.customParams?.mcp?.type === 'stdio';+ const isCloud = plugin?.customParams?.mcp?.type === 'cloud';// Record call start timeconst callStartTime = Date.now();@@ -93,10 +94,24 @@ class MCPService {let result: MCPToolCallResult | undefined;try {- // For desktop and stdio, use the desktopClient- if (isDesktop && isStdio) {+ // For cloud type, call via cloud gateway+ if (isCloud) {+ // Parse args+ const apiParams = safeParseJSON(args) || {};++ // Call cloud gateway via lambda market endpoint+ // Server will automatically get user access token from database+ // and format the result to MCPToolCallResult+ result = await lambdaClient.market.callCloudMcpEndpoint.mutate({+ apiParams,+ identifier,+ toolName: apiName,+ });+ } else if (isDesktop && isStdio) {+ // For desktop and stdio, use the desktopClientresult = await desktopClient.mcp.callTool.mutate(data, { signal });} else {+ // For other types, use the toolsClientresult = await toolsClient.mcp.callTool.mutate(data, { signal });}diff --git a/src/store/tool/slices/mcpStore/action.test.ts b/src/store/tool/slices/mcpStore/action.test.tsindex 0e9f61da128..6a022a1d799 100644--- a/src/store/tool/slices/mcpStore/action.test.ts+++ b/src/store/tool/slices/mcpStore/action.test.ts@@ -902,6 +902,147 @@ describe('mcpStore actions', () => {});});+ describe('cloudEndPoint support', () => {+ it('should create cloud type connection when cloudEndPoint is available on web', async () => {+ const { result } = renderHook(() => useToolStore());++ const mockManifestWithCloudEndpoint = {+ ...mockManifest,+ cloudEndPoint: true,+ tools: [+ {+ name: 'testTool',+ description: 'Test tool description',+ inputSchema: {+ type: 'object',+ properties: {+ param: { type: 'string' },+ },+ },+ },+ ],+ author: 'Test Author',+ createdAt: '2024-01-01T00:00:00Z',+ homepage: 'https://example.com',+ manifestUrl: 'https://example.com/manifest.json',+ icon: 'https://example.com/icon.png',+ description: 'Test description',+ tags: ['test'],+ deploymentOptions: [+ {+ connection: {+ type: 'stdio',+ configSchema: {+ type: 'object',+ properties: {+ API_KEY: { type: 'string' },+ },+ },+ },+ installationMethod: 'uv',+ },+ ],+ };++ vi.spyOn(discoverService, 'getMCPPluginManifest').mockResolvedValue(+ mockManifestWithCloudEndpoint as any,+ );++ // Mock isDesktop to false (web environment)+ const originalIsDesktop = (await import('@lobechat/const')).isDesktop;+ vi.spyOn(await import('@lobechat/const'), 'isDesktop', 'get').mockReturnValue(false);++ // Create plugin with haveCloudEndpoint field+ const mockPluginWithCloudEndpoint = {+ ...mockPlugin,+ haveCloudEndpoint: true,+ } as any;++ act(() => {+ useToolStore.setState({+ mcpPluginItems: [mockPluginWithCloudEndpoint],+ });+ });++ const installPluginSpy = vi.spyOn(pluginService, 'installPlugin');++ let installResult;+ await act(async () => {+ installResult = await result.current.installMCPPlugin('test-plugin');+ });++ expect(installResult).toBe(true);++ // Should create cloud type connection+ expect(installPluginSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ customParams: expect.objectContaining({+ mcp: expect.objectContaining({+ type: 'cloud',+ cloudEndPoint: true,+ }),+ }),+ }),+ );++ // Should NOT call stdio connection+ expect(mcpService.getStdioMcpServerManifest).not.toHaveBeenCalled();+ // Should NOT call checkInstallation (skipped for cloud)+ expect(mcpService.checkInstallation).not.toHaveBeenCalled();++ // Restore original isDesktop+ vi.spyOn(await import('@lobechat/const'), 'isDesktop', 'get').mockReturnValue(+ originalIsDesktop,+ );+ });++ it('should use stdio deployment when cloudEndPoint is not available', async () => {+ const { result } = renderHook(() => useToolStore());++ // No cloudEndPoint in manifest+ const mockManifestWithoutCloudEndpoint = {+ ...mockManifest,+ deploymentOptions: [+ {+ connection: {+ type: 'stdio',+ },+ installationMethod: 'uv',+ },+ ],+ };++ vi.spyOn(discoverService, 'getMCPPluginManifest').mockResolvedValue(+ mockManifestWithoutCloudEndpoint as any,+ );++ // Mock isDesktop to false (web environment)+ const originalIsDesktop = (await import('@lobechat/const')).isDesktop;+ vi.spyOn(await import('@lobechat/const'), 'isDesktop', 'get').mockReturnValue(false);++ act(() => {+ useToolStore.setState({+ mcpPluginItems: [mockPlugin],+ });+ });++ let installResult;+ await act(async () => {+ installResult = await result.current.installMCPPlugin('test-plugin');+ });++ expect(installResult).toBe(true);+ // Should fall back to stdio+ expect(mcpService.checkInstallation).toHaveBeenCalled();+ expect(mcpService.getStdioMcpServerManifest).toHaveBeenCalled();++ // Restore original isDesktop+ vi.spyOn(await import('@lobechat/const'), 'isDesktop', 'get').mockReturnValue(+ originalIsDesktop,+ );+ });+ });+describe('resume mode', () => {it('should resume installation with previous config info', async () => {const { result } = renderHook(() => useToolStore());diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.tsindex faebb06981c..7836a69646a 100644--- a/src/store/tool/slices/mcpStore/action.ts+++ b/src/store/tool/slices/mcpStore/action.ts@@ -1,3 +1,4 @@+import { CURRENT_VERSION, isDesktop } from '@lobechat/const';import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';import { PluginItem, PluginListResponse } from '@lobehub/market-sdk';import { TRPCClientError } from '@trpc/client';@@ -8,7 +9,6 @@ import { gt, valid } from 'semver';import useSWR, { SWRResponse } from 'swr';import { StateCreator } from 'zustand/vanilla';-import { CURRENT_VERSION, isDesktop } from '@lobechat/const';import { MCPErrorData } from '@/libs/mcp/types';import { discoverService } from '@/services/discover';import { mcpService } from '@/services/mcp';@@ -65,6 +65,71 @@ const toNonEmptyStringRecord = (input?: Record<string, any>) => {}, {});};+/**+ * Build manifest for cloud MCP connection from market data+ * 从市场数据构建 Cloud MCP 的 manifest+ */+const buildCloudMcpManifest = (params: {+ data: any;+ plugin: { description?: string, icon?: string; identifier: string; };+}): LobeChatPluginManifest => {+ const { data, plugin } = params;++ log('Using cloud connection, building manifest from market data');++ // 从 data 中获取 tools(MCP 格式)或 api(LobeChat 格式)+ const mcpTools = data.tools;+ const lobeChatApi = data.api;++ // 如果是 MCP 格式的 tools,需要转换为 LobeChat 的 api 格式+ // MCP: { name, description, inputSchema }+ // LobeChat: { name, description, parameters }+ let apiArray: any[] = [];++ if (lobeChatApi) {+ // 已经是 LobeChat 格式,直接使用+ apiArray = lobeChatApi;+ log('[Cloud MCP] Using existing LobeChat API format');+ } else if (mcpTools && Array.isArray(mcpTools)) {+ // 转换 MCP tools 格式到 LobeChat api 格式+ apiArray = mcpTools.map((tool: any) => ({+ description: tool.description || '',+ name: tool.name,+ parameters: tool.inputSchema || {},+ }));+ log('[Cloud MCP] Converted %d MCP tools to LobeChat API format', apiArray.length);+ } else {+ console.warn('[Cloud MCP] No tools or api found in manifest data');+ }++ // 构建完整的 manifest+ const manifest: LobeChatPluginManifest = {+ api: apiArray,+ author: data.author?.name || data.author || '',+ createAt: data.createdAt || new Date().toISOString(),+ homepage: data.homepage || '',+ identifier: plugin.identifier,+ manifest: data.manifestUrl || '',+ meta: {+ avatar: data.icon || plugin.icon,+ description: plugin.description || data.description,+ tags: data.tags || [],+ title: data.name || plugin.identifier,+ },+ name: data.name || plugin.identifier,+ type: 'mcp',+ version: data.version,+ } as unknown as LobeChatPluginManifest;++ log('[Cloud MCP] Final manifest built:', {+ apiCount: manifest.api?.length,+ identifier: manifest.identifier,+ version: manifest.version,+ });++ return manifest;+};+// 测试连接结果类型export interface TestMcpConnectionResult {error?: string;@@ -139,6 +204,9 @@ export const createMCPPluginStoreSlice: StateCreator<const normalizedConfig = toNonEmptyStringRecord(config);let plugin = mcpStoreSelectors.getPluginById(identifier)(get());+ // @ts-expect-error+ const { haveCloudEndpoint } = plugin || {};+if (!plugin || !plugin.manifestUrl) {const data = await discoverService.getMcpDetail({ identifier });if (!data) return;@@ -211,12 +279,18 @@ export const createMCPPluginStoreSlice: StateCreator<? data.deploymentOptions: [];- const httpOption = deploymentOptions.find(- (option) => option?.connection?.url && option?.connection?.type === 'http',- ) ||+ const httpOption =deploymentOptions.find(- (option) => option?.connection?.url && !option?.connection?.type,- );+ (option) => option?.connection?.url && option?.connection?.type === 'http',+ ) ||+ deploymentOptions.find((option) => option?.connection?.url && !option?.connection?.type);++ // 查找 stdio 类型的部署选项+ const stdioOption = deploymentOptions.find(+ (option) =>+ option?.connection?.type === 'stdio' ||+ (!option?.connection?.type && !option?.connection?.url),+ );const hasNonHttpDeployment = deploymentOptions.some((option) => {const type = option?.connection?.type;@@ -225,9 +299,46 @@ export const createMCPPluginStoreSlice: StateCreator<return type && type !== 'http';});- const shouldUseHttpDeployment = !!httpOption && (!hasNonHttpDeployment || !isDesktop);+ // 🌐 检查是否有 cloudEndPoint:网页端 + stdio 类型 + 存在 haveCloudEndpoint+ const hasCloudEndpoint = !isDesktop && stdioOption && haveCloudEndpoint;++ console.log('hasCloudEndpoint', hasCloudEndpoint);++ let shouldUseHttpDeployment = !!httpOption && (!hasNonHttpDeployment || !isDesktop);++ if (hasCloudEndpoint) {+ // 🌐 使用 cloudEndPoint,创建 cloud 类型的 connection+ log('Using cloudEndPoint for stdio plugin: %s', haveCloudEndpoint);++ connection = {+ auth: stdioOption?.connection?.auth || { type: 'none' },+ cloudEndPoint: haveCloudEndpoint,+ headers: stdioOption?.connection?.headers,+ type: 'cloud',+ } as any;++ log('Using cloud connection: %O', {+ cloudEndPoint: haveCloudEndpoint,+ type: connection.type,+ });++ const configSchema = stdioOption?.connection?.configSchema;+ const needsConfig = doesConfigSchemaRequireInput(configSchema);++ if (needsConfig && !normalizedConfig) {+ updateMCPInstallProgress(identifier, {+ configSchema,+ connection,+ manifest: data,+ needsConfig: true,+ progress: 50,+ step: MCPInstallStep.CONFIGURATION_REQUIRED,+ });- if (shouldUseHttpDeployment && httpOption) {+ updateInstallLoadingState(identifier, undefined);+ return false;+ }+ } else if (shouldUseHttpDeployment && httpOption) {// ✅ HTTP 类型:跳过系统依赖检查,直接使用 URLlog('HTTP MCP detected, skipping system dependency check');@@ -317,6 +428,7 @@ export const createMCPPluginStoreSlice: StateCreator<let mergedHttpHeaders: Record<string, string> | undefined;let mergedStdioEnv: Record<string, string> | undefined;+ let mergedCloudHeaders: Record<string, string> | undefined;if (connection?.type === 'http') {const baseHeaders = toNonEmptyStringRecord(connection.headers);@@ -340,6 +452,17 @@ export const createMCPPluginStoreSlice: StateCreator<}}+ if (connection?.type === 'cloud') {+ const baseHeaders = toNonEmptyStringRecord(connection.headers);++ if (baseHeaders || normalizedConfig) {+ mergedCloudHeaders = {+ ...baseHeaders,+ ...normalizedConfig,+ };+ }+ }+// 获取服务器清单逻辑updateInstallLoadingState(identifier, true);@@ -383,6 +506,10 @@ export const createMCPPluginStoreSlice: StateCreator<abortController.signal,);}+ if (connection?.type === 'cloud') {+ // 🌐 Cloud 类型:直接从市场数据构建 manifest+ manifest = buildCloudMcpManifest({ data, plugin });+ }// set versionif (manifest) {@@ -425,9 +552,21 @@ export const createMCPPluginStoreSlice: StateCreator<return;}+ // 更新 connection 对象,将合并后的配置写入+ const finalConnection = { ...connection };+ if (finalConnection.type === 'http' && mergedHttpHeaders) {+ finalConnection.headers = mergedHttpHeaders;+ }+ if (finalConnection.type === 'stdio' && mergedStdioEnv) {+ finalConnection.env = mergedStdioEnv;+ }+ if (finalConnection.type === 'cloud' && mergedCloudHeaders) {+ finalConnection.headers = mergedCloudHeaders;+ }+await pluginService.installPlugin({// 针对 mcp 先将 connection 信息存到 customParams 字段里- customParams: { mcp: connection },+ customParams: { mcp: finalConnection },identifier: plugin.identifier,manifest: manifest,settings: normalizedConfig,@@ -693,7 +832,9 @@ export const createMCPPluginStoreSlice: StateCreator<useFetchMCPPluginList: (params) => {const locale = globalHelpers.getCurrentLanguage();- const requestParams = isDesktop ? params : { ...params, connectionType: McpConnectionType.http };+ const requestParams = isDesktop+ ? params+ : { ...params, connectionType: McpConnectionType.http };const swrKeyParts = ['useFetchMCPPluginList',locale,@@ -702,7 +843,8 @@ export const createMCPPluginStoreSlice: StateCreator<requestParams.q,requestParams.connectionType,];- const swrKey = swrKeyParts.filter((part) => part !== undefined && part !== null && part !== '')+ const swrKey = swrKeyParts+ .filter((part) => part !== undefined && part !== null && part !== '').join('-');const page = requestParams.page ?? 1;