Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(mcp): show the workspace ceiling on the consent page, and consolidate the connect panel (P1b 1b-6, part 2) (#21237)
Vincent Huangde9d642e87b6
diff --git a/frontend/scripts/ui-guideline-legacy-debt.json b/frontend/scripts/ui-guideline-legacy-debt.jsonindex 74f495f988..00e485a8e7 100644--- a/frontend/scripts/ui-guideline-legacy-debt.json+++ b/frontend/scripts/ui-guideline-legacy-debt.json@@ -1842,18 +1842,6 @@"token": "bg-white","count": 1},- {- "path": "src/routes/auth/OAuth2ConsentPage.tsx",- "rule": "no-space-between",- "token": "space-y-1",- "count": 1- },- {- "path": "src/routes/auth/OAuth2ConsentPage.tsx",- "rule": "no-space-between",- "token": "space-y-6",- "count": 1- },{"path": "src/routes/auth/PasswordForgotPage.tsx","rule": "no-raw-color",diff --git a/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.test.tsx b/frontend/src/components/mcp/MCPModeContentsSheet.test.tsxsimilarity index 100%rename from frontend/src/routes/workspace/mcp/MCPModeContentsSheet.test.tsxrename to frontend/src/components/mcp/MCPModeContentsSheet.test.tsxdiff --git a/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.tsx b/frontend/src/components/mcp/MCPModeContentsSheet.tsxsimilarity index 99%rename from frontend/src/routes/workspace/mcp/MCPModeContentsSheet.tsxrename to frontend/src/components/mcp/MCPModeContentsSheet.tsxindex 2f77b14cd2..c3ebd48ed2 100644--- a/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.tsx+++ b/frontend/src/components/mcp/MCPModeContentsSheet.tsx@@ -18,7 +18,7 @@ import {MCPEngineEnforcement_Masking,MCPEngineEnforcement_ReadOnlyDepth,} from "@/types/proto-es/v1/workspace_service_pb";-import { engineNameV1 } from "@/utils";+import { engineNameV1 } from "@/utils/v1/instance";import {engineNotes,groupEnginesByMasking,diff --git a/frontend/src/routes/workspace/mcp/mcpPolicy.test.ts b/frontend/src/components/mcp/mcpPolicy.test.tssimilarity index 100%rename from frontend/src/routes/workspace/mcp/mcpPolicy.test.tsrename to frontend/src/components/mcp/mcpPolicy.test.tsdiff --git a/frontend/src/routes/workspace/mcp/mcpPolicy.ts b/frontend/src/components/mcp/mcpPolicy.tssimilarity index 100%rename from frontend/src/routes/workspace/mcp/mcpPolicy.tsrename to frontend/src/components/mcp/mcpPolicy.tsdiff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 58f67bae43..5bc18f3694 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1561,6 +1561,31 @@"error-load-failed": "Failed to load client information","error-missing-params": "Missing required OAuth2 parameters","error-switch-failed": "Failed to switch workspace",+ "mcp": {+ "disabled": {+ "ask-admin": "Think this should be on? Ask a workspace admin about the MCP access policy.",+ "description": "A workspace admin has turned off MCP access for {{workspace}}. Nothing was connected.",+ "description-no-workspace": "A workspace admin has turned off MCP access for this workspace. Nothing was connected.",+ "line": {+ "no-session": "No AI session can connect to this workspace",+ "recorded": "Any attempt to connect anyway is recorded in the audit log"+ },+ "policy-label": "Workspace policy",+ "title": "MCP access is turned off"+ },+ "line": {+ "audit": "Audited actions carry an MCP tag, and anything the policy refuses is recorded",+ "capped": "Capped by your own Bytebase permissions",+ "masking": "Your masking exemptions do not apply to this session",+ "no-write": "No data or schema changes",+ "read": "Read schemas and run read-only queries",+ "workflow": "Open issues, plans and rollouts, and export query results",+ "write": "Make the data and schema changes your permissions allow"+ },+ "see-contents": "See what this workspace's policy allows",+ "title": "This session may",+ "write-caution": "An AI session with write access makes real changes. Approve only on a machine you control."+ },"permission-access": "Access your Bytebase account with your permissions","permissions": "This application will be able to:","title": "Authorization Request",@@ -2526,6 +2551,12 @@"description": "OAuth authentication is required on first connection. Ensure you have appropriate Bytebase permissions.","title": "Authentication Required"},+ "connect": {+ "description": "Add Bytebase to your AI client, approve access in the browser, and start asking.",+ "desktop-note": "Claude Desktop reads remote servers from your Claude account, not from the config file. Add this URL as a custom connector under Customize > Connectors on claude.ai, then it appears in Claude Desktop.",+ "json-note": "This is the mcpServers shape. Client config formats differ: VS Code, for example, expects servers in its own mcp.json, so use the VS Code tab for that.",+ "title": "Connect a client"+ },"contents": {"depth": {"description": "How far the read-only ceiling is enforced on each engine.",@@ -2564,9 +2595,6 @@"example": "List all projects in my Bytebase instance","title": "Your First Prompt"},- "general-config": {- "title": "Option 1: JSON Configuration"- },"policy": {"audit": "MCP policy denials are recorded in the audit log.","description": "The most any MCP session may do in this workspace. Every session is also capped by the connecting user's own permissions.",@@ -2616,13 +2644,6 @@"title": "The stored access policy is not one this build serves"}},- "quick-start": {- "description": "Alternatively, use one of these CLI commands.",- "title": "Option 2: CLI Commands"- },- "setup": {- "add-to-config": "Add this JSON to your MCP client configuration file."- },"title": "MCP Integration"},"members": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 69eddefc61..2f5b0186e4 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1561,6 +1561,31 @@"error-load-failed": "Error al cargar la información del cliente","error-missing-params": "Faltan parámetros obligatorios de OAuth2","error-switch-failed": "Error al cambiar de workspace",+ "mcp": {+ "disabled": {+ "ask-admin": "¿Cree que debería estar activado? Pregunte a un administrador del espacio de trabajo por la política de acceso MCP.",+ "description": "Un administrador del espacio de trabajo ha desactivado el acceso MCP para {{workspace}}. No se conectó nada.",+ "description-no-workspace": "Un administrador del espacio de trabajo ha desactivado el acceso MCP para este espacio de trabajo. No se conectó nada.",+ "line": {+ "no-session": "Ninguna sesión de IA puede conectarse a este espacio de trabajo",+ "recorded": "Cualquier intento de conectarse de todos modos queda registrado en el registro de auditoría"+ },+ "policy-label": "Política del espacio de trabajo",+ "title": "El acceso MCP está desactivado"+ },+ "line": {+ "audit": "Las acciones auditadas llevan una etiqueta MCP, y lo que la política rechaza también se registra",+ "capped": "Limitada por sus propios permisos de Bytebase",+ "masking": "Sus exenciones de enmascaramiento no se aplican a esta sesión",+ "no-write": "Ningún cambio de datos ni de esquema",+ "read": "Explorar esquemas y ejecutar consultas de solo lectura",+ "workflow": "Abrir incidencias, planes y despliegues, y exportar resultados de consultas",+ "write": "Hacer los cambios de datos y esquema que permitan sus permisos"+ },+ "see-contents": "Ver lo que permite la política de este espacio de trabajo",+ "title": "Esta sesión puede",+ "write-caution": "Una sesión de IA con acceso de escritura hace cambios reales. Apruébela solo en una máquina que usted controle."+ },"permission-access": "Acceder a tu cuenta de Bytebase con tus permisos","permissions": "Esta aplicación podrá:","title": "Solicitud de autorización",@@ -2526,6 +2551,12 @@"description": "Se requiere autenticación OAuth en la primera conexión. Asegúrese de tener los permisos apropiados en Bytebase.","title": "Autenticación requerida"},+ "connect": {+ "description": "Añada Bytebase a su cliente de IA, apruebe el acceso en el navegador y empiece a preguntar.",+ "desktop-note": "Claude Desktop lee los servidores remotos de su cuenta de Claude, no del archivo de configuración. Añada esta URL como conector personalizado en Customize > Connectors de claude.ai y aparecerá en Claude Desktop.",+ "json-note": "Este es el formato mcpServers. Los formatos de configuración varían según el cliente: VS Code, por ejemplo, espera servers en su propio mcp.json, así que use la pestaña de VS Code para eso.",+ "title": "Conectar un cliente"+ },"contents": {"depth": {"description": "Hasta dónde se aplica el techo de solo lectura en cada motor.",@@ -2564,9 +2595,6 @@"example": "Listar todos los proyectos en mi instancia de Bytebase","title": "Tu primer prompt"},- "general-config": {- "title": "Opción 1: Configuración JSON"- },"policy": {"audit": "Las denegaciones de la política MCP se registran en el registro de auditoría.","description": "Lo máximo que puede hacer cualquier sesión MCP en este espacio de trabajo. Cada sesión está además limitada por los permisos del propio usuario que se conecta.",@@ -2616,13 +2644,6 @@"title": "La política de acceso almacenada no es una que esta versión ofrezca"}},- "quick-start": {- "description": "Alternativamente, use uno de estos comandos CLI.",- "title": "Opción 2: Comandos CLI"- },- "setup": {- "add-to-config": "Agregue este JSON a su archivo de configuración del cliente MCP."- },"title": "Integración MCP"},"members": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 3c97d44bd5..83d9f7d729 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1561,6 +1561,31 @@"error-load-failed": "クライアント情報の読み込みに失敗しました","error-missing-params": "必須の OAuth2 パラメータが不足しています","error-switch-failed": "ワークスペースの切り替えに失敗しました",+ "mcp": {+ "disabled": {+ "ask-admin": "オンにすべきだと思いますか?ワークスペース管理者に MCP アクセスポリシーを確認してください。",+ "description": "ワークスペース管理者が {{workspace}} の MCP アクセスをオフにしています。何も接続されていません。",+ "description-no-workspace": "ワークスペース管理者がこのワークスペースの MCP アクセスをオフにしています。何も接続されていません。",+ "line": {+ "no-session": "このワークスペースにはどの AI セッションも接続できません",+ "recorded": "それでも接続を試みた場合、その試行は監査ログに記録されます"+ },+ "policy-label": "ワークスペースポリシー",+ "title": "MCP アクセスはオフです"+ },+ "line": {+ "audit": "監査対象の操作には MCP タグが付き、ポリシーが拒否したものも記録されます",+ "capped": "上限はあなた自身の Bytebase 権限",+ "masking": "あなたのマスキング適用除外はこのセッションには適用されません",+ "no-write": "データやスキーマの変更はできない",+ "read": "スキーマを調べ、読み取り専用のクエリを実行する",+ "workflow": "イシュー・プラン・ロールアウトの作成、およびクエリ結果のエクスポート",+ "write": "あなたの権限の範囲でデータとスキーマを変更する"+ },+ "see-contents": "このワークスペースのポリシーが許可する範囲を見る",+ "title": "このセッションでできること",+ "write-caution": "書き込み権限のある AI セッションは実際に変更を加えます。自分が管理しているマシンでのみ承認してください。"+ },"permission-access": "あなたの権限で Bytebase アカウントにアクセス","permissions": "このアプリケーションは以下のことができます:","title": "認証リクエスト",@@ -2526,6 +2551,12 @@"description": "初回接続時に OAuth 認証が必要です。適切な Bytebase 権限があることを確認してください。","title": "認証が必要"},+ "connect": {+ "description": "Bytebase を AI クライアントに追加し、ブラウザーでアクセスを承認して、質問を始めてください。",+ "desktop-note": "Claude Desktop はリモートサーバーを設定ファイルではなく Claude アカウントから読み込みます。claude.ai の Customize > Connectors でこの URL をカスタムコネクタとして追加すると、Claude Desktop に表示されます。",+ "json-note": "これは mcpServers 形式です。クライアントごとに設定形式が異なります。たとえば VS Code は独自の mcp.json で servers を使うため、その場合は VS Code タブを使ってください。",+ "title": "クライアントを接続"+ },"contents": {"depth": {"description": "読み取り専用の上限が各エンジンでどこまで適用されるか。",@@ -2564,9 +2595,6 @@"example": "Bytebase インスタンス内のすべてのプロジェクトをリストする","title": "最初のプロンプト"},- "general-config": {- "title": "方法 1:JSON 設定"- },"policy": {"audit": "MCP ポリシーによる拒否は監査ログに記録されます。","description": "このワークスペースで MCP セッションが実行できる操作の上限です。各セッションは接続ユーザー自身の権限によってもさらに制限されます。",@@ -2616,13 +2644,6 @@"title": "保存されたアクセスポリシーはこのビルドが提供するものではありません"}},- "quick-start": {- "description": "または、以下の CLI コマンドを使用してください。",- "title": "方法 2:CLI コマンド"- },- "setup": {- "add-to-config": "この JSON を MCP クライアント設定ファイルに追加してください。"- },"title": "MCP 連携"},"members": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 1e0c1e6f37..51ffe5bb93 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1561,6 +1561,31 @@"error-load-failed": "Tải thông tin client thất bại","error-missing-params": "Thiếu các tham số OAuth2 bắt buộc","error-switch-failed": "Chuyển workspace thất bại",+ "mcp": {+ "disabled": {+ "ask-admin": "Bạn nghĩ nên bật? Hãy hỏi quản trị viên không gian làm việc về chính sách truy cập MCP.",+ "description": "Quản trị viên không gian làm việc đã tắt truy cập MCP cho {{workspace}}. Không có gì được kết nối.",+ "description-no-workspace": "Quản trị viên đã tắt truy cập MCP cho không gian làm việc này. Không có gì được kết nối.",+ "line": {+ "no-session": "Không phiên AI nào có thể kết nối tới không gian làm việc này",+ "recorded": "Mọi lần vẫn cố kết nối đều được ghi vào nhật ký kiểm toán"+ },+ "policy-label": "Chính sách không gian làm việc",+ "title": "Truy cập MCP đang tắt"+ },+ "line": {+ "audit": "Hành động được kiểm toán mang nhãn MCP, và những gì chính sách từ chối cũng được ghi lại",+ "capped": "Giới hạn bởi chính quyền Bytebase của bạn",+ "masking": "Các miễn trừ che dữ liệu của bạn không áp dụng cho phiên này",+ "no-write": "Không thay đổi dữ liệu hay lược đồ",+ "read": "Khám phá lược đồ và chạy truy vấn chỉ đọc",+ "workflow": "Tạo vấn đề, kế hoạch và triển khai, và xuất kết quả truy vấn",+ "write": "Thay đổi dữ liệu và lược đồ trong phạm vi quyền của bạn"+ },+ "see-contents": "Xem những gì chính sách của không gian làm việc này cho phép",+ "title": "Phiên này có thể",+ "write-caution": "Phiên AI có quyền ghi sẽ tạo ra thay đổi thật. Chỉ phê duyệt trên máy bạn kiểm soát."+ },"permission-access": "Truy cập tài khoản Bytebase của bạn với quyền hạn của bạn","permissions": "Ứng dụng này sẽ có thể:","title": "Yêu cầu ủy quyền",@@ -2526,6 +2551,12 @@"description": "Xác thực OAuth được yêu cầu khi kết nối lần đầu. Đảm bảo bạn có quyền Bytebase phù hợp.","title": "Yêu cầu xác thực"},+ "connect": {+ "description": "Thêm Bytebase vào client AI của bạn, phê duyệt truy cập trong trình duyệt, rồi bắt đầu hỏi.",+ "desktop-note": "Claude Desktop đọc máy chủ từ xa từ tài khoản Claude của bạn, không phải từ tệp cấu hình. Hãy thêm URL này làm trình kết nối tùy chỉnh tại Customize > Connectors trên claude.ai, sau đó nó sẽ xuất hiện trong Claude Desktop.",+ "json-note": "Đây là định dạng mcpServers. Mỗi client có định dạng cấu hình khác nhau: ví dụ VS Code dùng servers trong mcp.json của nó, nên hãy dùng tab VS Code cho trường hợp đó.",+ "title": "Kết nối một client"+ },"contents": {"depth": {"description": "Mức trần chỉ đọc được thực thi sâu tới đâu trên mỗi công cụ.",@@ -2564,9 +2595,6 @@"example": "Liệt kê tất cả các dự án trong phiên bản Bytebase của tôi","title": "Prompt đầu tiên của bạn"},- "general-config": {- "title": "Cách 1: Cấu hình JSON"- },"policy": {"audit": "Các lần từ chối theo chính sách MCP được ghi vào nhật ký kiểm toán.","description": "Mức tối đa mà một phiên MCP được phép làm trong không gian làm việc này. Mỗi phiên còn bị giới hạn thêm bởi quyền của chính người dùng đang kết nối.",@@ -2616,13 +2644,6 @@"title": "Chính sách truy cập đã lưu không phải loại bản dựng này phục vụ"}},- "quick-start": {- "description": "Hoặc sử dụng một trong các lệnh CLI sau.",- "title": "Cách 2: Lệnh CLI"- },- "setup": {- "add-to-config": "Thêm JSON này vào tệp cấu hình MCP client của bạn."- },"title": "Tích hợp MCP"},"members": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 6bfc1631ca..9040e466e5 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1561,6 +1561,31 @@"error-load-failed": "加载客户端信息失败","error-missing-params": "缺少必需的 OAuth2 参数","error-switch-failed": "切换工作空间失败",+ "mcp": {+ "disabled": {+ "ask-admin": "认为这里应该开启?请咨询工作空间管理员的 MCP 访问策略。",+ "description": "工作空间管理员已关闭 {{workspace}} 的 MCP 访问。未建立任何连接。",+ "description-no-workspace": "工作空间管理员已关闭本工作空间的 MCP 访问。未建立任何连接。",+ "line": {+ "no-session": "任何 AI 会话都无法连接到本工作空间",+ "recorded": "若仍尝试连接,该次尝试会记录在审计日志中"+ },+ "policy-label": "工作空间策略",+ "title": "MCP 访问已关闭"+ },+ "line": {+ "audit": "被审计的操作会带上 MCP 标记,策略拒绝的操作也会被记录",+ "capped": "以你本人的 Bytebase 权限为上限",+ "masking": "你的脱敏豁免对此会话不生效",+ "no-write": "不能修改任何数据或模式",+ "read": "浏览模式并执行只读查询",+ "workflow": "创建工单、计划和发布,以及导出查询结果",+ "write": "在你的权限范围内修改数据和模式"+ },+ "see-contents": "查看此工作区策略允许的范围",+ "title": "此会话可以",+ "write-caution": "具有写权限的 AI 会话会造成真实变更。请仅在你可控的机器上批准。"+ },"permission-access": "使用您的权限访问您的 Bytebase 账户","permissions": "此应用程序将能够:","title": "授权请求",@@ -2526,6 +2551,12 @@"description": "首次连接需要 OAuth 身份验证。请确保您拥有相应的 Bytebase 权限。","title": "需要身份验证"},+ "connect": {+ "description": "将 Bytebase 添加到你的 AI 客户端,在浏览器中批准访问,然后开始提问。",+ "desktop-note": "Claude Desktop 从你的 Claude 账户读取远程服务器,而不是配置文件。请在 claude.ai 的 Customize > Connectors 中将此 URL 添加为自定义连接器,随后它会出现在 Claude Desktop 中。",+ "json-note": "这是 mcpServers 格式。各客户端的配置格式并不相同:例如 VS Code 在自己的 mcp.json 中使用 servers,此时请改用 VS Code 标签页。",+ "title": "连接客户端"+ },"contents": {"depth": {"description": "只读上限在每个引擎上的执行强度。",@@ -2564,9 +2595,6 @@"example": "列出我的 Bytebase 实例中的所有项目","title": "您的第一个提示"},- "general-config": {- "title": "方式一:JSON 配置"- },"policy": {"audit": "MCP 策略拒绝会记录在审计日志中。","description": "本工作空间中任何 MCP 会话所能执行操作的上限。每个会话还会受到连接用户自身权限的限制。",@@ -2616,13 +2644,6 @@"title": "当前版本不提供已存储的访问策略"}},- "quick-start": {- "description": "或者使用以下 CLI 命令。",- "title": "方式二:CLI 命令"- },- "setup": {- "add-to-config": "将此 JSON 添加到您的 MCP 客户端配置文件。"- },"title": "MCP 集成"},"members": {diff --git a/frontend/src/routes/auth/MCPConsentCeiling.tsx b/frontend/src/routes/auth/MCPConsentCeiling.tsxnew file mode 100644index 0000000000..d3db149fcf--- /dev/null+++ b/frontend/src/routes/auth/MCPConsentCeiling.tsx@@ -0,0 +1,137 @@+import { Check, EyeOff, ScrollText, X } from "lucide-react";+import type { ReactNode } from "react";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { MCPModeContentsSheet } from "@/components/mcp/MCPModeContentsSheet";+import { Alert } from "@/components/ui/alert";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";+import type { MCPInfo } from "@/types/proto-es/v1/workspace_service_pb";++interface Line {+ readonly key: string;+ readonly icon: ReactNode;+ readonly text: string;+}++interface Props {+ readonly info: MCPInfo;+}++/**+ * What the workspace's ceiling lets this session do, shown before the person+ * approves rather than after.+ *+ * The same ceiling refuses the POST server-side, so this page is the richer+ * render of a decision the backend makes either way — never the decision+ * itself.+ */+export function MCPConsentCeiling({ info }: Props) {+ const { t } = useTranslation();+ const [contentsOpen, setContentsOpen] = useState(false);++ const readWrite = info.capability === MCPSetting_Capability.READ_WRITE;+ const modeKey = readWrite ? "read-write" : "read-only";+ const modeLabel = t(`settings.mcp.policy.mode.${modeKey}.title`);++ const lines: Line[] = [+ {+ key: "read",+ icon: <Check className="size-4 text-success" />,+ text: t("oauth2.consent.mcp.line.read"),+ },+ readWrite+ ? {+ key: "write",+ icon: <Check className="size-4 text-success" />,+ text: t("oauth2.consent.mcp.line.write"),+ }+ : {+ key: "no-write",+ icon: <X className="size-4 text-error" />,+ text: t("oauth2.consent.mcp.line.no-write"),+ },+ // The WRITE class is not only data and schema: CreateIssue, CreatePlan,+ // CreateRollout, BatchRunTasks, Export and the saved-query methods all+ // carry it, so approving read-write approves workflow and egress too.+ ...(readWrite+ ? [+ {+ key: "workflow",+ icon: <Check className="size-4 text-success" />,+ text: t("oauth2.consent.mcp.line.workflow"),+ },+ ]+ : []),+ {+ key: "capped",+ icon: <Check className="size-4 text-success" />,+ text: t("oauth2.consent.mcp.line.capped"),+ },+ // Both halves, because the line promises a restriction. The toggle+ // withholds unmasking exemptions from MCP sessions, which changes nothing+ // where masking does not run at all — asserting it there would tell the+ // person approving that their data is covered when it is not.+ ...(info.ignoreMaskingExemptions && info.dataMaskingAvailable+ ? [+ {+ key: "masking",+ icon: <EyeOff className="size-4 text-control-light" />,+ text: t("oauth2.consent.mcp.line.masking"),+ },+ ]+ : []),+ {+ key: "audit",+ icon: <ScrollText className="size-4 text-control-light" />,+ text: t("oauth2.consent.mcp.line.audit"),+ },+ ];++ return (+ <div className="flex flex-col gap-3">+ <div className="bg-control-bg rounded-sm p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between gap-x-2">+ <p className="text-sm text-control-light">+ {t("oauth2.consent.mcp.title")}+ </p>+ <Badge variant={readWrite ? "warning" : "success"}>{modeLabel}</Badge>+ </div>+ <ul className="text-sm text-main flex flex-col gap-2">+ {lines.map((line) => (+ <li key={line.key} className="flex items-start gap-2">+ <span className="mt-0.5 shrink-0">{line.icon}</span>+ <span>{line.text}</span>+ </li>+ ))}+ </ul>+ <Button+ appearance="link"+ size="sm"+ className="self-start px-0"+ onClick={() => setContentsOpen(true)}+ >+ {t("oauth2.consent.mcp.see-contents")}+ </Button>+ </div>++ {readWrite && (+ <Alert+ variant="warning"+ description={t("oauth2.consent.mcp.write-caution")}+ />+ )}++ <MCPModeContentsSheet+ open={contentsOpen}+ capability={info.capability}+ info={info}+ modeLabel={modeLabel}+ // No draft here: this page describes the policy in force.+ ignoreMaskingExemptions={info.ignoreMaskingExemptions}+ onClose={() => setContentsOpen(false)}+ />+ </div>+ );+}diff --git a/frontend/src/routes/auth/MCPConsentDisabled.tsx b/frontend/src/routes/auth/MCPConsentDisabled.tsxnew file mode 100644index 0000000000..d5b4729832--- /dev/null+++ b/frontend/src/routes/auth/MCPConsentDisabled.tsx@@ -0,0 +1,89 @@+import { ScrollText, X } from "lucide-react";+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";++interface Props {+ readonly workspaceTitle: string;+ /** The workspace row, so a SaaS user can switch to one that permits MCP. */+ readonly workspaceCard: ReactNode;+ readonly onDismiss: () => void;+ readonly dismissing: boolean;+}++/**+ * The consent a disabled workspace never grants.+ *+ * This stops the person before they press Approve. Dismissing posts a denial+ * rather than walking history back, so the client waiting on the callback gets+ * access_denied instead of nothing; that path returns before the ceiling check+ * (backend/api/oauth2/authorize.go), so it writes no ceiling-refusal row. The+ * audit line here is about an attempt that reaches the grant path anyway,+ * which the backend refuses and records (backend/api/oauth2/consent_audit.go).+ */+export function MCPConsentDisabled({+ workspaceTitle,+ workspaceCard,+ onDismiss,+ dismissing,+}: Props) {+ const { t } = useTranslation();++ return (+ <div className="flex flex-col gap-6">+ <div className="text-center flex flex-col gap-2">+ <h1 className="text-xl font-semibold text-main">+ {t("oauth2.consent.mcp.disabled.title")}+ </h1>+ <p className="text-control">+ {/* The workspace load is fire-and-forget and swallows its error, so+ the title can be empty. Naming a workspace with nothing in the+ blank reads worse than not naming one. */}+ {workspaceTitle+ ? t("oauth2.consent.mcp.disabled.description", {+ workspace: workspaceTitle,+ })+ : t("oauth2.consent.mcp.disabled.description-no-workspace")}+ </p>+ </div>++ {workspaceCard}++ <div className="bg-control-bg rounded-sm p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between gap-x-2">+ <p className="text-sm text-control-light">+ {t("oauth2.consent.mcp.disabled.policy-label")}+ </p>+ <Badge variant="destructive">+ {t("settings.mcp.policy.mode.disabled.title")}+ </Badge>+ </div>+ <ul className="text-sm text-main flex flex-col gap-2">+ <li className="flex items-start gap-2">+ <X className="mt-0.5 size-4 shrink-0 text-error" />+ <span>{t("oauth2.consent.mcp.disabled.line.no-session")}</span>+ </li>+ <li className="flex items-start gap-2">+ <ScrollText className="mt-0.5 size-4 shrink-0 text-control-light" />+ <span>{t("oauth2.consent.mcp.disabled.line.recorded")}</span>+ </li>+ </ul>+ </div>++ <div className="flex flex-col gap-2">+ <Button+ appearance="outline"+ size="lg"+ disabled={dismissing}+ onClick={onDismiss}+ >+ {t("common.close")}+ </Button>+ <p className="text-xs text-control-light text-center">+ {t("oauth2.consent.mcp.disabled.ask-admin")}+ </p>+ </div>+ </div>+ );+}diff --git a/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx b/frontend/src/routes/auth/OAuth2ConsentPage.test.tsxindex 4405a969f1..0a168054ac 100644--- a/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx+++ b/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx@@ -34,6 +34,7 @@ const mocks = vi.hoisted(() => ({},},fetchImpl: vi.fn(),+ getMCPInfo: vi.fn(),}));mocks.useAuthStore.mockImplementation(() => ({get isLoggedIn() {@@ -125,11 +126,18 @@ vi.mock("@/components/BytebaseLogo", () => ({BytebaseLogo: () => null,}));+vi.mock("@/api", () => ({+ workspaceServiceClientConnect: { getMCPInfo: mocks.getMCPInfo },+}));+vi.mock("react-i18next", () => ({useTranslation: () => ({t: (key: string, vars?: Record<string, string>) =>vars ? `${key}:${JSON.stringify(vars)}` : key,}),+ // The page now reaches the connect client for GetMCPInfo, and @/api's error+ // middleware imports the shared i18n instance, which registers this.+ initReactI18next: { type: "3rdParty", init: () => {} },}));let OAuth2ConsentPage: typeof import("./OAuth2ConsentPage").OAuth2ConsentPage;@@ -171,6 +179,9 @@ beforeEach(async () => {mocks.currentRoute.value.fullPath = "/oauth2/consent";globalThis.fetch = mocks.fetchImpl as typeof fetch;mocks.fetchImpl.mockReset();+ mocks.getMCPInfo.mockReset();+ // Default: the ceiling read fails, which is the pre-1b-6 shape of the card.+ mocks.getMCPInfo.mockRejectedValue(new Error("no ceiling"));({ OAuth2ConsentPage } = await import("./OAuth2ConsentPage"));});@@ -486,4 +497,191 @@ describe("OAuth2ConsentPage", () => {submitSpy.mockRestore();unmount();});++ // The ceiling states. The same ceiling refuses the POST server-side, so what+ // these pin is that the page says the same thing first — including the one+ // state where there is nothing to approve.+ const consentQuery = () => ({+ client_id: "c1",+ redirect_uri: "https://app/callback",+ state: "s",+ code_challenge: "ch",+ code_challenge_method: "S256",+ });++ const renderWithCeiling = async (info: unknown) => {+ mocks.currentRoute.value.query = consentQuery();+ mocks.fetchImpl.mockResolvedValue({+ ok: true,+ json: async () => ({ client_name: "Acme" }),+ });+ mocks.getMCPInfo.mockResolvedValue(info);+ const handle = renderIntoContainer(<OAuth2ConsentPage />);+ handle.render();+ await flushPromises();+ return handle;+ };++ // Codex, #21237: the !response.ok branch returned, its sibling catch did not.+ // The render checks loading before error, so a failed client lookup sat+ // behind the spinner until an optional policy request it no longer needed+ // finally settled.+ test("a failed client lookup shows its error without waiting on the policy", async () => {+ mocks.currentRoute.value.query = consentQuery();+ mocks.fetchImpl.mockRejectedValue(new Error("network down"));+ // Never settles: if the error waits on this, the test sees the spinner.+ mocks.getMCPInfo.mockReturnValue(new Promise(() => {}));++ const handle = renderIntoContainer(<OAuth2ConsentPage />);+ handle.render();+ await flushPromises();++ expect(handle.container.textContent).toContain(+ "oauth2.consent.error-load-failed"+ );+ expect(handle.container.querySelector(".animate-spin")).toBeNull();+ handle.unmount();+ });++ test("a read-only ceiling says what the session may not do", async () => {+ const { container, unmount } = await renderWithCeiling({+ capability: 3,+ ignoreMaskingExemptions: false,+ modes: [],+ methods: [],+ engines: [],+ });+ expect(container.textContent).toContain("oauth2.consent.mcp.line.read");+ expect(container.textContent).toContain("oauth2.consent.mcp.line.no-write");+ expect(container.textContent).not.toContain("oauth2.consent.mcp.line.write");+ // The masking line is the toggle's, not the ceiling's.+ expect(container.textContent).not.toContain(+ "oauth2.consent.mcp.line.masking"+ );+ expect(container.textContent).toContain("common.allow");+ unmount();+ });++ test("a read-write ceiling adds the write line and the caution", async () => {+ const { container, unmount } = await renderWithCeiling({+ capability: 4,+ ignoreMaskingExemptions: true,+ dataMaskingAvailable: true,+ modes: [],+ methods: [],+ engines: [],+ });+ expect(container.textContent).toContain("oauth2.consent.mcp.line.write");+ expect(container.textContent).toContain("oauth2.consent.mcp.write-caution");+ expect(container.textContent).toContain("oauth2.consent.mcp.line.masking");+ unmount();+ });++ // The masking line promises a restriction. The toggle withholds unmasking+ // exemptions from MCP sessions, which restricts nothing on a workspace where+ // masking does not run — and this card is read at the moment someone decides+ // whether to hand over access.+ test("the masking line is not promised where masking does not run", async () => {+ const { container, unmount } = await renderWithCeiling({+ capability: 4,+ ignoreMaskingExemptions: true,+ dataMaskingAvailable: false,+ modes: [],+ methods: [],+ engines: [],+ });+ // The rest of the card is unchanged, so this is the line and not the card.+ expect(container.textContent).toContain("oauth2.consent.mcp.line.write");+ expect(container.textContent).not.toContain(+ "oauth2.consent.mcp.line.masking"+ );+ unmount();+ });++ // Codex, #21237: the disabled screen's only action was router.back(), so the+ // OAuth client sat waiting on a callback that never came. A deny POST returns+ // access_denied to the registered redirect_uri, which is the answer it is+ // blocked on.+ test("dismissing a disabled ceiling denies the request instead of going back", async () => {+ const { container, unmount } = await renderWithCeiling({+ capability: 1,+ ignoreMaskingExemptions: false,+ dataMaskingAvailable: true,+ modes: [],+ methods: [],+ engines: [],+ });++ const submitted: HTMLFormElement[] = [];+ const realSubmit = HTMLFormElement.prototype.submit;+ HTMLFormElement.prototype.submit = function submit(this: HTMLFormElement) {+ submitted.push(this);+ };+ try {+ const close = [...container.querySelectorAll("button")].find((b) =>+ b.textContent?.includes("common.close")+ );+ act(() => (close as HTMLButtonElement)?.click());+ } finally {+ HTMLFormElement.prototype.submit = realSubmit;+ }++ expect(mocks.routerBack).not.toHaveBeenCalled();+ expect(submitted).toHaveLength(1);+ const action = submitted[0].querySelector('input[name="action"]');+ expect((action as HTMLInputElement)?.value).toBe("deny");+ unmount();+ });++ // Codex, #21237: a SaaS user whose current workspace has MCP off could not+ // switch to one that permits it without abandoning the OAuth flow.+ test("the disabled screen keeps the workspace switcher", async () => {+ const { container, unmount } = await renderWithCeiling({+ capability: 1,+ ignoreMaskingExemptions: false,+ dataMaskingAvailable: true,+ modes: [],+ methods: [],+ engines: [],+ });+ expect(container.textContent).toContain("oauth2.consent.workspace-label");+ unmount();+ });++ test("a disabled ceiling offers nothing to approve", async () => {+ const { container, unmount } = await renderWithCeiling({+ capability: 1,+ ignoreMaskingExemptions: false,+ modes: [],+ methods: [],+ engines: [],+ });+ expect(container.textContent).toContain("oauth2.consent.mcp.disabled.title");+ expect(container.textContent).toContain(+ "oauth2.consent.mcp.disabled.ask-admin"+ );+ // Nothing to approve and nothing to deny: the grant is not on offer.+ expect(container.textContent).not.toContain("common.allow");+ expect(container.textContent).not.toContain("common.deny");+ unmount();+ });++ test("an unreadable ceiling leaves the card as it was", async () => {+ // GetMCPInfo refuses under a ceiling this build cannot read. The backend+ // still refuses the POST with its own page, so the card falls back rather+ // than blocking a consent on a read this page does not own.+ mocks.currentRoute.value.query = consentQuery();+ mocks.fetchImpl.mockResolvedValue({+ ok: true,+ json: async () => ({ client_name: "Acme" }),+ });+ const { container, render, unmount } = renderIntoContainer(+ <OAuth2ConsentPage />+ );+ render();+ await flushPromises();+ expect(container.textContent).toContain("oauth2.consent.permission-access");+ expect(container.textContent).toContain("common.allow");+ unmount();+ });});diff --git a/frontend/src/routes/auth/OAuth2ConsentPage.tsx b/frontend/src/routes/auth/OAuth2ConsentPage.tsxindex 6817515f1d..eb657b438c 100644--- a/frontend/src/routes/auth/OAuth2ConsentPage.tsx+++ b/frontend/src/routes/auth/OAuth2ConsentPage.tsx@@ -1,6 +1,9 @@+import { createContextValues } from "@connectrpc/connect";import { Building2, Check, Loader2 } from "lucide-react";import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import { workspaceServiceClientConnect } from "@/api";+import { silentContextKey } from "@/api/context-key";import { router } from "@/app/router";import { AUTH_SIGNIN_MODULE } from "@/app/router/handles";import { BytebaseLogo } from "@/components/BytebaseLogo";@@ -14,6 +17,10 @@ import {} from "@/components/ui/select";import { useWorkspace } from "@/hooks/useAppState";import { useAppStore } from "@/stores/app";+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";+import type { MCPInfo } from "@/types/proto-es/v1/workspace_service_pb";+import { MCPConsentCeiling } from "./MCPConsentCeiling";+import { MCPConsentDisabled } from "./MCPConsentDisabled";const AUTHORIZE_URL = "/api/oauth2/authorize";@@ -23,6 +30,10 @@ export function OAuth2ConsentPage() {const [submitting, setSubmitting] = useState(false);const [error, setError] = useState("");const [clientName, setClientName] = useState("");+ // What the workspace's MCP ceiling lets this session do. Every grant this+ // server issues is an MCP grant, so the ceiling decides the POST too — this+ // is the same answer, shown before the person presses Approve.+ const [mcpInfo, setMcpInfo] = useState<MCPInfo | undefined>(undefined);const loadWorkspace = useAppStore((state) => state.loadWorkspace);const loadWorkspaceList = useAppStore((state) => state.loadWorkspaceList);@@ -95,7 +106,34 @@ export function OAuth2ConsentPage() {const data = await response.json();setClientName(data.client_name || clientId);} catch {+ // Same shape as the !response.ok branch above: with no client there is+ // nothing for the policy lookup to enrich, and the render checks+ // loading before error, so falling through would hold the spinner over+ // an error we already have.setError(t("oauth2.consent.error-load-failed"));+ setLoading(false);+ return;+ }+ // A ceiling this build cannot read refuses this call. That is the one+ // policy state the backend still has to be the first to say, so the card+ // falls back to its ceiling-free shape and the POST refuses with its own+ // page. Silent: the interceptor's toast would be the only thing on+ // screen about it, and it names a status code, not a fix.+ try {+ setMcpInfo(+ await workspaceServiceClientConnect.getMCPInfo(+ {},+ {+ contextValues: createContextValues().set(silentContextKey, true),+ // The shared transport has no deadline. This request only+ // enriches the card, so a stalled one must not leave the page on+ // its spinner with no Allow and no Deny.+ timeoutMs: 10_000,+ }+ )+ );+ } catch {+ setMcpInfo(undefined);}setLoading(false);})();@@ -136,6 +174,47 @@ export function OAuth2ConsentPage() {}};+ // Rendered in BOTH branches. A disabled workspace is exactly when a SaaS+ // user needs the switcher: another workspace may permit MCP, and without it+ // they have to abandon the OAuth flow, switch, and start over.+ const workspaceCard = currentWorkspace ? (+ <div className="bg-control-bg rounded-sm p-4 flex items-center gap-3">+ <Building2 className="size-5 text-control-light shrink-0" />+ <div className="flex-1 min-w-0">+ <p className="text-xs text-control-light">+ {t("oauth2.consent.workspace-label")}+ </p>+ {isSaaSMode && workspaceList.length > 1 ? (+ <Select+ value={currentWorkspace.name}+ onValueChange={onSwitchWorkspace}+ disabled={submitting}+ >+ <SelectTrigger size="sm" className="mt-1 w-full">+ <SelectValue>+ {(name) => {+ const ws = workspaceList.find((w) => w.name === name);+ return ws?.title || ws?.name || name || "";+ }}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {workspaceList.map((ws) => (+ <SelectItem key={ws.name} value={ws.name}>+ {ws.title || ws.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <p className="text-sm text-main truncate">+ {currentWorkspace.title || currentWorkspace.name}+ </p>+ )}+ </div>+ </div>+ ) : null;+const goBack = () => {router.back();};@@ -166,122 +245,123 @@ export function OAuth2ConsentPage() {form.submit();};- return (- <div className="h-full flex flex-col justify-center mx-auto w-full max-w-sm">- <BytebaseLogo className="mx-auto mb-8" />- <div className="rounded-sm border border-control-border bg-white p-6">- {loading ? (- <div className="flex justify-center py-8">- <Loader2 className="size-6 animate-spin" />- </div>- ) : error ? (- <div className="text-center py-4">- <p className="text-error mb-4">{error}</p>- <Button appearance="outline" onClick={goBack}>- {t("common.go-back")}- </Button>- </div>+ // Four states share this slot. Early returns rather than a ternary chain,+ // so each is named where it is decided and the consent card reads as the+ // ordinary case it is.+ const consentBody = () => {+ if (loading) {+ return (+ <div className="flex justify-center py-8">+ <Loader2 className="size-6 animate-spin" />+ </div>+ );+ }+ if (error) {+ return (+ <div className="text-center py-4">+ <p className="text-error mb-4">{error}</p>+ <Button appearance="outline" onClick={goBack}>+ {t("common.go-back")}+ </Button>+ </div>+ );+ }+ if (mcpInfo?.capability === MCPSetting_Capability.DISABLED) {+ return (+ <MCPConsentDisabled+ workspaceTitle={+ currentWorkspace?.title || currentWorkspace?.name || ""+ }+ workspaceCard={workspaceCard}+ // Not goBack: history leaves the client waiting on a callback that+ // never comes. A deny POST returns access_denied to the registered+ // redirect_uri, which is the answer the OAuth client is blocked on.+ onDismiss={deny}+ dismissing={submitting}+ />+ );+ }+ return (+ <div className="flex flex-col gap-6">+ <div className="text-center">+ <h1 className="text-xl font-semibold text-main mb-2">+ {t("oauth2.consent.title")}+ </h1>+ <p className="text-control">+ {t("oauth2.consent.description", { clientName })}+ </p>+ </div>+ {workspaceCard}+ {/* Only the two ceilings this bundle can describe. A value it+ cannot name — a newer release's, against a cached page — would+ otherwise fall through to the read-only wording and understate+ what was approved. It gets the same card as no policy data,+ which BOT-106 covers. */}+ {mcpInfo &&+ (mcpInfo.capability === MCPSetting_Capability.READ_ONLY ||+ mcpInfo.capability === MCPSetting_Capability.READ_WRITE) ? (+ <MCPConsentCeiling info={mcpInfo} />) : (- <div className="space-y-6">- <div className="text-center">- <h1 className="text-xl font-semibold text-main mb-2">- {t("oauth2.consent.title")}- </h1>- <p className="text-control">- {t("oauth2.consent.description", { clientName })}- </p>- </div>- {currentWorkspace && (- <div className="bg-control-bg rounded-sm p-4 flex items-center gap-3">- <Building2 className="size-5 text-control-light shrink-0" />- <div className="flex-1 min-w-0">- <p className="text-xs text-control-light">- {t("oauth2.consent.workspace-label")}- </p>- {isSaaSMode && workspaceList.length > 1 ? (- <Select- value={currentWorkspace.name}- onValueChange={onSwitchWorkspace}- disabled={submitting}- >- <SelectTrigger size="sm" className="mt-1 w-full">- <SelectValue>- {(name) => {- const ws = workspaceList.find(- (w) => w.name === name- );- return ws?.title || ws?.name || name || "";- }}- </SelectValue>- </SelectTrigger>- <SelectContent>- {workspaceList.map((ws) => (- <SelectItem key={ws.name} value={ws.name}>- {ws.title || ws.name}- </SelectItem>- ))}- </SelectContent>- </Select>- ) : (- <p className="text-sm text-main truncate">- {currentWorkspace.title || currentWorkspace.name}- </p>- )}- </div>- </div>- )}- <div className="bg-control-bg rounded-sm p-4">- <p className="text-sm text-control-light mb-2">- {t("oauth2.consent.permissions")}- </p>- <ul className="text-sm text-main space-y-1">- <li className="flex items-center gap-2">- <Check className="size-4 text-success" />- {t("oauth2.consent.permission-access")}- </li>- </ul>- </div>- <form method="POST" action={AUTHORIZE_URL}>- <input type="hidden" name="client_id" value={clientId} />- <input type="hidden" name="redirect_uri" value={redirectUri} />- <input type="hidden" name="state" value={oauthState} />- <input- type="hidden"- name="code_challenge"- value={codeChallenge}- />- <input- type="hidden"- name="code_challenge_method"- value={codeChallengeMethod}- />- <input type="hidden" name="resource" value={resource} />- <input type="hidden" name="scope" value={scope} />- <div className="flex gap-x-2">- <Button- type="button"- appearance="outline"- size="lg"- className="flex-1"- disabled={submitting}- onClick={deny}- >- {t("common.deny")}- </Button>- <Button- type="submit"- size="lg"- className="flex-1"- disabled={submitting}- name="action"- value="allow"- >- {t("common.allow")}- </Button>- </div>- </form>+ <div className="bg-control-bg rounded-sm p-4">+ <p className="text-sm text-control-light mb-2">+ {t("oauth2.consent.permissions")}+ </p>+ <ul className="text-sm text-main flex flex-col gap-1">+ <li className="flex items-center gap-2">+ <Check className="size-4 text-success" />+ {t("oauth2.consent.permission-access")}+ </li>+ </ul></div>)}+ <form method="POST" action={AUTHORIZE_URL}>+ <input type="hidden" name="client_id" value={clientId} />+ <input type="hidden" name="redirect_uri" value={redirectUri} />+ <input type="hidden" name="state" value={oauthState} />+ <input type="hidden" name="code_challenge" value={codeChallenge} />+ <input+ type="hidden"+ name="code_challenge_method"+ value={codeChallengeMethod}+ />+ <input type="hidden" name="resource" value={resource} />+ <input type="hidden" name="scope" value={scope} />+ <div className="flex gap-x-2">+ <Button+ type="button"+ appearance="outline"+ size="lg"+ className="flex-1"+ disabled={submitting}+ onClick={deny}+ >+ {t("common.deny")}+ </Button>+ <Button+ type="submit"+ size="lg"+ className="flex-1"+ disabled={submitting}+ name="action"+ value="allow"+ >+ {t("common.allow")}+ </Button>+ </div>+ </form>+ </div>+ );+ };++ return (+ // SplashLayout's root is overflow-hidden, so this column carries its own+ // scroll: the ceiling panel and its caution make the card taller than a+ // short viewport, and the part that clips is Allow and Deny. The auto+ // margins keep it centred while it still fits.+ <div className="h-full overflow-y-auto flex flex-col mx-auto w-full max-w-sm py-8">+ <BytebaseLogo className="mx-auto mb-8 mt-auto shrink-0" />+ <div className="rounded-sm border border-control-border bg-white p-6 mb-auto shrink-0">+ {consentBody()}</div></div>);diff --git a/frontend/src/routes/workspace/MCPPage.test.tsx b/frontend/src/routes/workspace/MCPPage.test.tsxnew file mode 100644index 0000000000..d5e7b407a1--- /dev/null+++ b/frontend/src/routes/workspace/MCPPage.test.tsx@@ -0,0 +1,107 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+ initReactI18next: { type: "3rdParty", init: () => {} },+}));++vi.mock("@/hooks/useAppState", () => ({+ useServerState: () => ({+ externalUrl: "https://bb.example.com",+ needConfigureExternalUrl: false,+ }),+}));++vi.mock("@/components/ExternalUrlAlert", () => ({ ExternalUrlAlert: () => null }));+vi.mock("./mcp/MCPAccessPolicySection", () => ({+ MCPAccessPolicySection: () => null,+}));+vi.mock("@/utils", () => ({ isDev: () => false, cn: (...a: unknown[]) => a.join(" ") }));++const { MCPPage } = await import("./MCPPage");++const render = (element: ReactElement) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ act(() => root.render(element));+ return {+ container,+ unmount: () => {+ act(() => root.unmount());+ container.remove();+ },+ };+};++// Base UI renders only the active panel, so each tab has to be visited.+const allTabValues = (container: HTMLElement) => {+ const triggers = [...container.querySelectorAll('[role="tab"]')];+ const values: string[] = [];+ for (const trigger of triggers) {+ act(() => (trigger as HTMLElement).click());+ for (const input of container.querySelectorAll("input[readonly]")) {+ values.push((input as HTMLInputElement).value);+ }+ for (const area of container.querySelectorAll("textarea[readonly]")) {+ values.push((area as HTMLTextAreaElement).value);+ }+ }+ return values;+};++describe("MCPPage connect panel", () => {+ // Codex, #21237: three of the six commands were invalid. Each was checked+ // against its own source — the codex CLI's own AddArgs (name is positional,+ // --url is the flag, there is no --transport), the Copilot CLI docs+ // (`copilot mcp add --transport http NAME URL`, and the binary is `copilot`,+ // not `gh copilot`), and the Gemini CLI docs. These assertions are the guard+ // against the wrong forms coming back; the syntax itself can only be+ // re-checked against those sources.+ test("no command uses a flag its CLI does not have", () => {+ const { container, unmount } = render(<MCPPage />);+ const values = allTabValues(container);+ expect(values.length).toBeGreaterThan(6);+ for (const value of values) {+ expect(value).not.toContain("--name ");+ expect(value).not.toMatch(/^gh /);+ // codex takes --url; the others take the URL positionally.+ if (value.startsWith("codex ")) {+ expect(value).toContain("--url ");+ } else if (value.includes(" mcp add")) {+ expect(value).not.toContain("--url ");+ }+ }+ unmount();+ });++ // Codex, #21237: claude_desktop_config.json reaches LOCAL servers only, so+ // the tab handed users a config that cannot connect to a remote Bytebase.+ // A remote server is added as a custom connector on claude.ai instead, so+ // what this tab owes the user is the URL.+ test("the Claude Desktop tab offers the endpoint URL, not a config object", () => {+ const { container, unmount } = render(<MCPPage />);+ const desktop = [...container.querySelectorAll('[role="tab"]')].find((t) =>+ t.textContent?.includes("Claude Desktop")+ );+ act(() => (desktop as HTMLElement).click());++ const shown = [+ ...container.querySelectorAll("input[readonly], textarea[readonly]"),+ ].map((n) => (n as HTMLInputElement | HTMLTextAreaElement).value);++ expect(shown).toContain("https://bb.example.com/mcp");+ // The JSON tab still offers the config object; this one must not.+ for (const value of shown) {+ expect(value).not.toContain("mcpServers");+ }+ unmount();+ });+});diff --git a/frontend/src/routes/workspace/MCPPage.tsx b/frontend/src/routes/workspace/MCPPage.tsxindex d562d5ed70..7f0184c6cf 100644--- a/frontend/src/routes/workspace/MCPPage.tsx+++ b/frontend/src/routes/workspace/MCPPage.tsx@@ -37,35 +37,52 @@ export function MCPPage() {);}, [mcpEndpointUrl]);+ // One tab per client, each carrying the whole of what that client needs:+ // a command where the client has a CLI, the config object where it does not.const tabs = useMemo(() => [{id: "claude-code",title: "Claude Code",- content: `claude mcp add bytebase --transport http ${mcpEndpointUrl}`,+ command: `claude mcp add --transport http bytebase ${mcpEndpointUrl}`,+ },+ {+ id: "claude-desktop",+ // The URL, not the config object: claude_desktop_config.json only+ // reaches LOCAL servers. A remote one is added as a custom connector+ // on claude.ai and shows up in the desktop app from there.+ title: "Claude Desktop",+ url: mcpEndpointUrl,+ note: t("settings.mcp.connect.desktop-note"),},{id: "codex",title: "Codex",- content: `codex mcp add --name bytebase --transport http --url ${mcpEndpointUrl}`,+ command: `codex mcp add bytebase --url ${mcpEndpointUrl}`,},{id: "copilot-cli",title: "Copilot CLI",- content: `gh copilot mcp add bytebase --transport http --url ${mcpEndpointUrl}`,+ command: `copilot mcp add --transport http bytebase ${mcpEndpointUrl}`,},{id: "gemini-cli",title: "Gemini CLI",- content: `gemini mcp add --name bytebase --transport http --url ${mcpEndpointUrl}`,+ command: `gemini mcp add --transport http bytebase ${mcpEndpointUrl}`,},{id: "vscode",title: "VS Code",- content: `code --add-mcp '{"name":"bytebase","type":"http","url":"${mcpEndpointUrl}"}'`,+ command: `code --add-mcp '{"name":"bytebase","type":"http","url":"${mcpEndpointUrl}"}'`,+ },+ {+ id: "json",+ title: "JSON",+ config: generalConfig,+ note: t("settings.mcp.connect.json-note"),},],- [mcpEndpointUrl]+ [mcpEndpointUrl, generalConfig, t]);const firstPromptExample = t("settings.mcp.first-prompt.example");@@ -92,62 +109,61 @@ export function MCPPage() {description={t("settings.mcp.auth.description")}/>- {/* Section 1: General Config */}- <div className="flex flex-col gap-y-3">- <div className="flex flex-col gap-y-1">- <div className="flex items-center gap-x-2">- <h3 className="text-base font-medium">- {t("settings.mcp.general-config.title")}- </h3>- <CopyButton content={generalConfig} size="sm" />- </div>- <p className="text-sm text-control-light">- {t("settings.mcp.setup.add-to-config")}- </p>- </div>- <Textarea- readOnly- value={generalConfig}- rows={7}- className="font-mono text-sm"- />- </div>-- {/* Section 2: Quick Start CLI Commands */}+ {/* Connect a client */}<div className="flex flex-col gap-y-3"><div className="flex flex-col gap-y-1"><h3 className="text-base font-medium">- {t("settings.mcp.quick-start.title")}+ {t("settings.mcp.connect.title")}</h3><p className="text-sm text-control-light">- {t("settings.mcp.quick-start.description")}+ {t("settings.mcp.connect.description")}</p></div><Tabs defaultValue="claude-code">- <TabsList>+ <TabsList className="overflow-x-auto">{tabs.map((tab) => (- <TabsTrigger key={tab.id} value={tab.id}>+ <TabsTrigger key={tab.id} value={tab.id} className="shrink-0">{tab.title}</TabsTrigger>))}</TabsList>{tabs.map((tab) => (<TabsPanel key={tab.id} value={tab.id}>- <div className="flex items-center gap-x-2">- <Input- readOnly- value={tab.content}- className="flex-1 font-mono"- onClick={(e) => (e.target as HTMLInputElement).select()}- />- <CopyButton content={tab.content} size="sm" />+ <div className="flex flex-col gap-y-2">+ {(tab.command ?? tab.url) ? (+ <div className="flex items-center gap-x-2">+ <Input+ readOnly+ value={tab.command ?? tab.url}+ className="flex-1 font-mono"+ onClick={(e) => (e.target as HTMLInputElement).select()}+ />+ <CopyButton+ content={tab.command ?? tab.url ?? ""}+ size="sm"+ />+ </div>+ ) : (+ <div className="flex items-start gap-x-2">+ <Textarea+ readOnly+ value={tab.config}+ rows={7}+ className="flex-1 font-mono text-sm"+ />+ <CopyButton content={tab.config ?? ""} size="sm" />+ </div>+ )}+ {tab.note && (+ <p className="text-sm text-control-light">{tab.note}</p>+ )}</div></TabsPanel>))}</Tabs></div>- {/* Section 3: Your First Prompt */}+ {/* Your First Prompt */}<div className="flex flex-col gap-y-3"><div className="flex flex-col gap-y-1"><h3 className="text-base font-medium">diff --git a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsxindex b55e3c6b24..77f4b47588 100644--- a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx+++ b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx@@ -45,7 +45,7 @@ vi.mock("@/components/PermissionGuard", () => ({// Stubbed to record its props: the drawer is rendered unconditionally, so this// captures what the section hands it on every render without opening it.-vi.mock("./MCPModeContentsSheet", () => ({+vi.mock("@/components/mcp/MCPModeContentsSheet", () => ({MCPModeContentsSheet: (props: Record<string, unknown>) => {mocks.sheetProps.push(props);return null;diff --git a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsxindex 94bd65f128..78b3776bfa 100644--- a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx+++ b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx@@ -9,6 +9,14 @@ import {workspaceServiceClientConnect,} from "@/api";import { silentContextKey } from "@/api/context-key";+import { MCPModeContentsSheet } from "@/components/mcp/MCPModeContentsSheet";+import type { StoredCeiling } from "@/components/mcp/mcpPolicy";+import {+ ceilingIsBroken,+ initialCapabilityPick,+ MCP_CAPABILITY_CHOICES,+ readStoredCeiling,+} from "@/components/mcp/mcpPolicy";import { PermissionGuard } from "@/components/PermissionGuard";import { Alert } from "@/components/ui/alert";import type { BadgeProps } from "@/components/ui/badge";@@ -30,14 +38,6 @@ import {} from "@/types/proto-es/v1/setting_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import type { MCPInfo } from "@/types/proto-es/v1/workspace_service_pb";-import { MCPModeContentsSheet } from "./MCPModeContentsSheet";-import type { StoredCeiling } from "./mcpPolicy";-import {- ceilingIsBroken,- initialCapabilityPick,- MCP_CAPABILITY_CHOICES,- readStoredCeiling,-} from "./mcpPolicy";// One row per ceiling an admin can pick: the locale-key stem, the glyph tone,// and the chip variant. The tone and the variant always agree, and carry from