feat(mcp): add OAuth2 authorization for MCP services

Support connecting to MCP servers that require OAuth2, with a Cursor-like
zero-config flow: the user provides only a URL and the system performs
metadata discovery, dynamic client registration (DCR), and the
authorization code flow with PKCE on first connect.

- Persist per-user access/refresh tokens and per-service DCR client
  credentials, encrypted at rest (AES-256-GCM)
- Store the PKCE verifier/state during the flow via Redis with an
  in-memory fallback for Lite mode
- Cache MCP clients per (service, user) so tokens stay user-isolated
- Add endpoints for authorize-url, callback, status, and token revoke;
  the callback is allowlisted for unauthenticated access
- Surface a structured "authorization required" hint when a tool call
  hits an unauthorized MCP service
- Frontend: add an auth-type selector with OAuth config, inline
  authorization status/actions, and render the connection test result
  inline in the editor drawer instead of a stacked centered dialog
This commit is contained in:
wizardchen
2026-06-22 20:15:52 +08:00
committed by lyingbug
parent c25d762ed1
commit 7f3f219f58
27 changed files with 1920 additions and 686 deletions
+40
View File
@@ -10,6 +10,10 @@ export interface MCPService {
url?: string // Optional: required for SSE/HTTP Streamable
headers?: Record<string, string>
auth_config?: {
// Authentication strategy. Empty/absent means none. "oauth" enables the
// per-user OAuth2 authorization-code flow (zero-config: discovery +
// dynamic client registration).
auth_type?: '' | 'api_key' | 'bearer' | 'oauth'
// Secret fields (api_key, token) are NEVER returned by the server in
// this shape — they live behind the /credentials subresource. The
// optional-property typing remains so create-mode payloads can still
@@ -17,6 +21,9 @@ export interface MCPService {
api_key?: string
token?: string
custom_headers?: Record<string, string>
// OAuth-only, non-secret configuration.
scopes?: string[]
auth_server_metadata_url?: string
}
advanced_config?: {
timeout?: number
@@ -166,6 +173,39 @@ export async function deleteMCPCredentialField(
await del(`/api/v1/mcp-services/${serviceId}/credentials/${field}`)
}
// ----------------------------------------------------------------------------
// Per-user OAuth2 authorization-code flow.
//
// The user authorizes a service once; the backend stores their access/refresh
// token (per tenant + user + service) and refreshes it transparently. The
// callback is a public backend route that the third-party authorization
// server redirects to.
// ----------------------------------------------------------------------------
// Path of the public backend OAuth callback (registered outside /mcp-services
// to avoid a route conflict, and allow-listed for no-auth in the backend).
export const MCP_OAUTH_CALLBACK_PATH = '/api/v1/mcp-oauth/callback'
// Begin authorization for the current user. Returns the URL to open in a popup.
export async function getMCPOAuthAuthorizeURL(
serviceId: string,
body: { redirect_uri: string; frontend_redirect?: string }
): Promise<string> {
const response: any = await post(`/api/v1/mcp-services/${serviceId}/oauth/authorize-url`, body)
return (response.data ?? response)?.authorization_url ?? ''
}
// Whether the current user has authorized this service.
export async function getMCPOAuthStatus(serviceId: string): Promise<boolean> {
const response: any = await get(`/api/v1/mcp-services/${serviceId}/oauth/status`)
return Boolean((response.data ?? response)?.authorized)
}
// Revoke the current user's token (forces re-authorization).
export async function revokeMCPOAuthToken(serviceId: string): Promise<void> {
await del(`/api/v1/mcp-services/${serviceId}/oauth/token`)
}
export async function resolveToolApproval(
pendingId: string,
body: { decision: 'approve' | 'reject'; modified_args?: Record<string, unknown>; reason?: string }
+18
View File
@@ -4343,6 +4343,7 @@ export default {
connectionSection: "连接配置",
enableServiceDesc: "关闭后该服务不会被调用",
testAfterSaveHint: "保存后可测试连接",
testResultTitle: "测试结果",
unitSecond: "秒",
unitTimes: "次",
name: "服务名称",
@@ -4367,6 +4368,19 @@ export default {
addEnvVar: "添加环境变量",
enableService: "启用服务",
authConfig: "认证配置",
authType: "认证方式",
authTypeNone: "无 / 自定义 Header",
authTypeApiKey: "API Key",
authTypeBearer: "Bearer Token",
authTypeOAuth: "OAuth 2.0(首次连接授权)",
oauthScopes: "Scopes(可选,空格分隔)",
oauthAuthorization: "授权状态",
oauthAuthorized: "已授权",
oauthUnauthorized: "未授权",
oauthAuthorize: "去授权",
oauthReauthorize: "重新授权",
oauthRevoke: "撤销授权",
oauthSaveFirstHint: "保存服务后,可在编辑页发起首次授权(每个用户独立授权)。",
apiKey: "API Key",
bearerToken: "Bearer Token",
optional: "可选",
@@ -4387,6 +4401,10 @@ export default {
updated: "MCP 服务已更新",
createFailed: "创建 MCP 服务失败",
updateFailed: "更新 MCP 服务失败",
authorized: "授权成功",
authorizeFailed: "发起授权失败",
revoked: "已撤销授权",
revokeFailed: "撤销失败",
},
},
promptTemplate: {
+1 -25
View File
@@ -112,15 +112,6 @@
:service="currentService"
:mode="dialogMode"
@success="handleDialogSuccess"
@test="handleDrawerTest"
/>
<!-- Test Result Dialog -->
<McpTestResult
v-model:visible="testDialogVisible"
:result="testResult"
:service-name="testingServiceName"
:service-id="testingServiceId"
/>
</div>
</template>
@@ -134,11 +125,9 @@ import {
listMCPServices,
updateMCPService,
deleteMCPService,
type MCPService,
type MCPTestResult
type MCPService
} from '@/api/mcp-service'
import McpServiceDialog from './components/McpServiceDialog.vue'
import McpTestResult from './components/McpTestResult.vue'
import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
import { useAuthStore } from '@/stores/auth'
@@ -151,10 +140,6 @@ const loading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const currentService = ref<MCPService | null>(null)
const testDialogVisible = ref(false)
const testResult = ref<MCPTestResult | null>(null)
const testingServiceName = ref('')
const testingServiceId = ref('')
// Load MCP services
const loadServices = async () => {
@@ -266,15 +251,6 @@ const getBuiltinServiceOptions = () => {
]
}
// Drawer 内点击"测试连接"后,复用现有的 testResult dialog 展示结果。
// 抽屉只负责调 API + 拿结果,弹窗位置/状态由父组件统一管。
const handleDrawerTest = ({ service, result }: { service: MCPService; result: MCPTestResult }) => {
testingServiceName.value = service.name
testingServiceId.value = service.id
testResult.value = result
testDialogVisible.value = true
}
// Handle menu action. 'test' has been removed from the menu — testing now
// lives only in the editor drawer. We keep the switch's case list narrow
// so a stray 'test' from somewhere else falls through harmlessly.
@@ -123,43 +123,88 @@
</div>
</section>
<!-- Section 3 — 认证配置(API Key / Bearer Token) -->
<!-- Section 3 — 认证配置(无 / API Key / Bearer Token / OAuth) -->
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('mcpServiceDialog.authConfig') }}</h4>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.authType', '认证方式') }}</label>
<t-select v-model="formData.auth_config.auth_type" :options="authTypeOptions" />
</div>
<!-- OAuth 2.0:零配置(自动发现 + 动态客户端注册),按用户授权 -->
<template v-if="isOAuth">
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.oauthScopes', 'Scopes(可选,空格分隔)') }}</label>
<t-input v-model="oauthScopesText" :placeholder="t('mcpServiceDialog.optional')" />
</div>
<div v-if="mode === 'edit' && props.service?.id" class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.oauthAuthorization', '授权状态') }}</label>
<div class="oauth-status">
<t-tag v-if="oauthAuthorized" theme="success" variant="light">
{{ t('mcpServiceDialog.oauthAuthorized', '已授权') }}
</t-tag>
<t-tag v-else theme="warning" variant="light">
{{ t('mcpServiceDialog.oauthUnauthorized', '未授权') }}
</t-tag>
<t-button
size="small"
theme="primary"
:loading="oauthAuthorizing || oauthChecking"
@click="handleAuthorize"
>
{{ oauthAuthorized ? t('mcpServiceDialog.oauthReauthorize', '重新授权') : t('mcpServiceDialog.oauthAuthorize', '去授权') }}
</t-button>
<t-button
v-if="oauthAuthorized"
size="small"
theme="danger"
variant="outline"
@click="handleRevokeOAuth"
>
{{ t('mcpServiceDialog.oauthRevoke', '撤销授权') }}
</t-button>
</div>
</div>
<p v-else class="oauth-hint">
{{ t('mcpServiceDialog.oauthSaveFirstHint', '保存服务后,可在编辑页发起首次授权(每个用户独立授权)。') }}
</p>
</template>
<!--
Edit 模式下凭证由 CredentialResource 管理(独立的 /credentials
子资源调用),不与本表单 submit 耦合;Create 模式下用 plain
password input + lock prefix-icon。两个字段都是 optional —
MCP 服务可能完全不需要鉴权(依赖 IP 白名单等)。
非 OAuth:Edit 模式下凭证由 CredentialResource 管理(独立的
/credentials 子资源调用);Create 模式下用 plain password input。
两个字段都是 optional — MCP 服务可能完全不需要鉴权。
-->
<CredentialResource
v-if="mode === 'edit' && props.service?.id"
:api="credentialApi"
:fields="credentialFields"
:meta="credentialMeta"
/>
<template v-else>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.apiKey') }}</label>
<t-input
v-model="formData.auth_config.api_key"
type="password"
:placeholder="t('mcpServiceDialog.optional')"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.bearerToken') }}</label>
<t-input
v-model="formData.auth_config.token"
type="password"
:placeholder="t('mcpServiceDialog.optional')"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
<CredentialResource
v-if="mode === 'edit' && props.service?.id"
:api="credentialApi"
:fields="credentialFields"
:meta="credentialMeta"
/>
<template v-else>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.apiKey') }}</label>
<t-input
v-model="formData.auth_config.api_key"
type="password"
:placeholder="t('mcpServiceDialog.optional')"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.bearerToken') }}</label>
<t-input
v-model="formData.auth_config.token"
type="password"
:placeholder="t('mcpServiceDialog.optional')"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
</template>
</template>
</section>
@@ -217,12 +262,30 @@
</t-input>
</div>
</section>
<!-- Section 5 — 测试结果(内联,避免在抽屉上再叠一个居中弹窗) -->
<section v-if="testResult" ref="testResultSection" class="setting-drawer__section">
<div class="test-result-header">
<h4 class="setting-drawer__section-title">{{ t('mcpServiceDialog.testResultTitle', '测试结果') }}</h4>
<t-button
variant="text"
theme="default"
shape="square"
size="small"
class="test-result-close"
@click="testResult = null"
>
<template #icon><t-icon name="close" /></template>
</t-button>
</div>
<McpTestResultBody :result="testResult" :service-id="props.service?.id" />
</section>
</t-form>
</SettingDrawer>
</template>
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ref, watch, computed, nextTick } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
@@ -232,11 +295,16 @@ import {
putMCPCredentials,
deleteMCPCredentialField,
testMCPService,
getMCPOAuthAuthorizeURL,
getMCPOAuthStatus,
revokeMCPOAuthToken,
MCP_OAUTH_CALLBACK_PATH,
type MCPService,
type McpCredentialField,
type MCPTestResult,
} from '@/api/mcp-service'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import McpTestResultBody from './McpTestResultBody.vue'
import CredentialResource, {
type CredentialFieldDef,
type CredentialResourceApi,
@@ -251,11 +319,6 @@ interface Props {
interface Emits {
(e: 'update:visible', value: boolean): void
(e: 'success'): void
// Fired after a /test call inside the drawer so the parent can reuse its
// existing McpTestResult dialog. We deliberately don't render that dialog
// here — the parent owns the test-result dialog state across multiple
// entry points (drawer test button, list 行操作菜单 used to call it too).
(e: 'test', payload: { service: MCPService; result: MCPTestResult }): void
}
const props = defineProps<Props>()
@@ -272,9 +335,14 @@ const formData = ref({
transport_type: 'sse' as 'sse' | 'http-streamable',
url: '',
auth_config: {
// Authentication strategy: '' (none) | 'api_key' | 'bearer' | 'oauth'.
auth_type: '' as '' | 'api_key' | 'bearer' | 'oauth',
// Only used in add-mode; in edit-mode the CredentialResource owns these.
api_key: '',
token: '',
// OAuth-only, non-secret config.
scopes: [] as string[],
auth_server_metadata_url: '',
},
advanced_config: {
timeout: 30,
@@ -283,6 +351,93 @@ const formData = ref({
},
})
// Comma/space separated text binding for OAuth scopes.
const oauthScopesText = computed({
get: () => (formData.value.auth_config.scopes || []).join(' '),
set: (val: string) => {
formData.value.auth_config.scopes = val
.split(/[\s,]+/)
.map((s) => s.trim())
.filter(Boolean)
},
})
const isOAuth = computed(() => formData.value.auth_config.auth_type === 'oauth')
const authTypeOptions = computed(() => [
{ value: '', label: t('mcpServiceDialog.authTypeNone', '无 / 自定义 Header') },
{ value: 'api_key', label: t('mcpServiceDialog.authTypeApiKey', 'API Key') },
{ value: 'bearer', label: t('mcpServiceDialog.authTypeBearer', 'Bearer Token') },
{ value: 'oauth', label: t('mcpServiceDialog.authTypeOAuth', 'OAuth 2.0(首次连接授权)') },
])
// ---- OAuth authorization state (edit mode only) ----
const oauthAuthorized = ref(false)
const oauthChecking = ref(false)
const oauthAuthorizing = ref(false)
async function refreshOAuthStatus() {
if (props.mode !== 'edit' || !props.service?.id || !isOAuth.value) return
oauthChecking.value = true
try {
oauthAuthorized.value = await getMCPOAuthStatus(props.service.id)
} catch (e) {
console.error('Failed to query MCP OAuth status:', e)
} finally {
oauthChecking.value = false
}
}
async function handleAuthorize() {
if (!props.service?.id) return
oauthAuthorizing.value = true
try {
const redirectUri = window.location.origin + MCP_OAUTH_CALLBACK_PATH
// After the backend completes the exchange it bounces the popup here. The
// app root is harmless; the popup is closed by the opener below once the
// authorization status flips, so this page is only shown briefly.
const frontendRedirect = window.location.origin + '/'
const authUrl = await getMCPOAuthAuthorizeURL(props.service.id, {
redirect_uri: redirectUri,
frontend_redirect: frontendRedirect,
})
if (!authUrl) {
MessagePlugin.error(t('mcpServiceDialog.toasts.authorizeFailed', '发起授权失败') as string)
return
}
const popup = window.open(authUrl, 'mcp_oauth', 'width=600,height=720')
// Poll for completion: either the popup closes or the status flips.
const timer = window.setInterval(async () => {
const closed = !popup || popup.closed
await refreshOAuthStatus()
if (oauthAuthorized.value || closed) {
window.clearInterval(timer)
oauthAuthorizing.value = false
if (oauthAuthorized.value) {
try { popup?.close() } catch { /* cross-origin close may throw */ }
MessagePlugin.success(t('mcpServiceDialog.toasts.authorized', '授权成功') as string)
}
}
}, 1500)
} catch (e) {
console.error('Failed to start MCP OAuth authorization:', e)
MessagePlugin.error(t('mcpServiceDialog.toasts.authorizeFailed', '发起授权失败') as string)
oauthAuthorizing.value = false
}
}
async function handleRevokeOAuth() {
if (!props.service?.id) return
try {
await revokeMCPOAuthToken(props.service.id)
oauthAuthorized.value = false
MessagePlugin.success(t('mcpServiceDialog.toasts.revoked', '已撤销授权') as string)
} catch (e) {
console.error('Failed to revoke MCP OAuth token:', e)
MessagePlugin.error(t('mcpServiceDialog.toasts.revokeFailed', '撤销失败') as string)
}
}
// Header icon name + transport label, mirrored from McpSettings list cards
// so the list-card → drawer hand-off stays visually continuous.
const transportIcon = computed(() => {
@@ -356,11 +511,24 @@ const testing = ref(false)
// false=just failed. Cleared when transport/url change so a stale ✓/✗
// doesn't sit next to a config the user is now editing.
const lastTestOk = ref<boolean | null>(null)
// In-drawer test result, rendered inline (no centered dialog stacked on the
// drawer). Cleared when the target config changes so a stale result doesn't
// sit next to edited config.
const testResult = ref<MCPTestResult | null>(null)
const testResultSection = ref<HTMLElement | null>(null)
// 结果区在抽屉最底部,测试完成后主动滚动到可见,免得用户以为没反应。
function scrollToTestResult() {
void nextTick(() => {
testResultSection.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
})
}
watch(
() => [formData.value.transport_type, formData.value.url],
() => {
lastTestOk.value = null
testResult.value = null
},
)
@@ -380,7 +548,8 @@ async function handleTestConnection() {
message: t('mcpSettings.toasts.noResponse') as string,
}
lastTestOk.value = safe.success === true
emit('test', { service: props.service, result: safe })
testResult.value = safe
scrollToTestResult()
} catch (error: any) {
MessagePlugin.closeAll()
const errorMessage =
@@ -389,10 +558,8 @@ async function handleTestConnection() {
(t('mcpSettings.toasts.testFailed') as string)
console.error('Failed to test MCP service:', error)
lastTestOk.value = false
emit('test', {
service: props.service,
result: { success: false, message: errorMessage },
})
testResult.value = { success: false, message: errorMessage }
scrollToTestResult()
} finally {
testing.value = false
}
@@ -451,7 +618,7 @@ const resetForm = () => {
enabled: true,
transport_type: 'sse',
url: '',
auth_config: { api_key: '', token: '' },
auth_config: { auth_type: '', api_key: '', token: '', scopes: [], auth_server_metadata_url: '' },
advanced_config: { timeout: 30, retry_count: 3, retry_delay: 1 },
}
formRef.value?.clearValidate()
@@ -462,6 +629,7 @@ watch(
(service) => {
// 切到不同服务(或新增)时清空上次测试反馈,避免旧的 ✓/✗ 漂在新表单上
lastTestOk.value = null
testResult.value = null
if (service) {
const transportType = service.transport_type === 'stdio' ? 'sse' : (service.transport_type || 'sse')
formData.value = {
@@ -472,13 +640,21 @@ watch(
url: service.url || '',
// Credentials are owned by CredentialResource in edit mode, but reset
// the local state too so a switch to add-mode starts clean.
auth_config: { api_key: '', token: '' },
auth_config: {
auth_type: (service.auth_config?.auth_type as '' | 'api_key' | 'bearer' | 'oauth') || '',
api_key: '',
token: '',
scopes: service.auth_config?.scopes ? [...service.auth_config.scopes] : [],
auth_server_metadata_url: service.auth_config?.auth_server_metadata_url || '',
},
advanced_config: {
timeout: service.advanced_config?.timeout || 30,
retry_count: service.advanced_config?.retry_count || 3,
retry_delay: service.advanced_config?.retry_delay || 1,
},
}
oauthAuthorized.value = false
refreshOAuthStatus()
} else {
resetForm()
}
@@ -501,18 +677,34 @@ const handleSubmit = async () => {
url: formData.value.url || undefined,
}
// Non-secret auth config (strategy + OAuth params) flows through the main
// body on both create and update. Secret fields are handled separately:
// on create they ride along in the POST; on edit they go through the
// /credentials subresource.
const auth: NonNullable<MCPService['auth_config']> = {
auth_type: formData.value.auth_config.auth_type,
}
if (isOAuth.value) {
auth.scopes = formData.value.auth_config.scopes
if (formData.value.auth_config.auth_server_metadata_url) {
auth.auth_server_metadata_url = formData.value.auth_config.auth_server_metadata_url
}
}
if (props.mode === 'add') {
// Initial credentials go along with the first POST. Subsequent edits
// route through the /credentials subresource.
const initialAuth: NonNullable<MCPService['auth_config']> = {}
if (formData.value.auth_config.api_key) initialAuth.api_key = formData.value.auth_config.api_key
if (formData.value.auth_config.token) initialAuth.token = formData.value.auth_config.token
if (Object.keys(initialAuth).length > 0) data.auth_config = initialAuth
if (!isOAuth.value) {
if (formData.value.auth_config.api_key) auth.api_key = formData.value.auth_config.api_key
if (formData.value.auth_config.token) auth.token = formData.value.auth_config.token
}
data.auth_config = auth
await createMCPService(data)
MessagePlugin.success(t('mcpServiceDialog.toasts.created'))
} else {
// Edit-mode: never send credential fields here. CredentialResource
// already committed any changes through the dedicated endpoint.
data.auth_config = auth
await updateMCPService(props.service!.id, data)
MessagePlugin.success(t('mcpServiceDialog.toasts.updated'))
}
@@ -541,6 +733,35 @@ const handleClose = () => {
margin-bottom: 0;
}
.oauth-status {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.test-result-header {
display: flex;
align-items: center;
justify-content: space-between;
.setting-drawer__section-title {
margin-bottom: 0;
}
.test-result-close {
flex-shrink: 0;
color: var(--td-text-color-placeholder);
}
}
.oauth-hint {
margin: 0;
font-size: 12px;
color: var(--td-text-color-secondary);
line-height: 1.5;
}
.form-label {
display: block;
margin-bottom: 6px;
@@ -1,563 +0,0 @@
<template>
<t-dialog
v-model:visible="dialogVisible"
:header="$t('mcp.testResult.title', { name: serviceName })"
width="600px"
:footer="false"
>
<div v-if="result" class="test-result">
<!-- Success/Error Status -->
<div class="status-section">
<div v-if="result.success" class="status-success">
<t-icon name="check-circle-filled" size="20px" />
<span class="status-text">{{ $t('mcp.testResult.connectionSuccess') }}</span>
</div>
<div v-else class="status-error">
<t-icon name="close-circle-filled" size="20px" />
<span class="status-text">{{ $t('mcp.testResult.connectionFailed') }}</span>
</div>
<p v-if="result.message" class="status-message">{{ result.message }}</p>
</div>
<!-- Details Section -->
<div v-if="result.success" class="details-section">
<!-- Tools List -->
<div v-if="result.tools && result.tools.length > 0" class="section">
<div class="section-header">
<h3>{{ $t('mcp.testResult.toolsTitle') }}</h3>
<t-tag theme="primary" variant="light" size="small">{{ result.tools.length }}</t-tag>
</div>
<div class="tools-grid">
<div
v-for="(tool, index) in displayTools"
:key="index"
class="tool-card"
:class="{ 'tool-card-expanded': expandedToolIndex === index }"
>
<div class="tool-card-header" @click="toggleTool(index)">
<div class="tool-header-left">
<t-icon name="tools" class="tool-icon" />
<div class="tool-info">
<div class="tool-name">{{ tool.name }}</div>
<div v-if="tool.description" class="tool-desc-preview">
{{ tool.description }}
</div>
</div>
</div>
<div class="tool-header-right" @click.stop>
<t-tooltip v-if="serviceId" :content="$t('mcp.testResult.requireApprovalTip')" placement="top">
<div class="approval-switch">
<t-icon name="error-circle-filled" class="danger-icon" />
<span class="approval-label">{{ $t('mcp.testResult.requireApproval') }}</span>
<t-switch
:value="tool.require_approval"
:loading="approvalLoading[tool.name]"
size="small"
@change="(v: boolean) => onRequireApprovalChange(tool.name, v)"
/>
</div>
</t-tooltip>
<t-icon
:name="expandedToolIndex === index ? 'chevron-up' : 'chevron-down'"
class="expand-icon"
/>
</div>
</div>
<div v-if="expandedToolIndex === index" class="tool-card-content">
<div v-if="tool.description" class="tool-description">
<div class="label">{{ $t('mcp.testResult.descriptionLabel') }}</div>
<div class="value">{{ tool.description }}</div>
</div>
<div v-if="tool.inputSchema" class="tool-schema">
<div class="label">{{ $t('mcp.testResult.schemaLabel') }}</div>
<div class="schema-content">
<pre>{{ formatSchema(tool.inputSchema) }}</pre>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Resources List -->
<div v-if="result.resources && result.resources.length > 0" class="section">
<div class="section-header">
<h3>{{ $t('mcp.testResult.resourcesTitle') }}</h3>
<t-tag theme="primary" variant="light" size="small">{{ result.resources.length }}</t-tag>
</div>
<div class="resources-grid">
<div
v-for="(resource, index) in result.resources"
:key="index"
class="resource-card"
>
<div class="resource-header">
<t-icon name="file" class="resource-icon" />
<div class="resource-info">
<div class="resource-name">{{ resource.name || resource.uri }}</div>
<div v-if="resource.description" class="resource-desc">
{{ resource.description }}
</div>
</div>
</div>
<div class="resource-meta">
<div v-if="resource.uri" class="resource-uri">
<t-icon name="link" size="14px" />
<span>{{ resource.uri }}</span>
</div>
<t-tag v-if="resource.mimeType" theme="default" variant="light-outline" size="small">
{{ resource.mimeType }}
</t-tag>
</div>
</div>
</div>
</div>
<!-- Empty State -->
<div
v-if="
(!result.tools || result.tools.length === 0) &&
(!result.resources || result.resources.length === 0)
"
class="empty-state"
>
<t-empty :description="$t('mcp.testResult.emptyDescription')" />
</div>
</div>
</div>
<template #footer>
<t-button @click="handleClose">{{ $t('common.close') }}</t-button>
</template>
</t-dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { MCPTestResult, MCPTool } from '@/api/mcp-service'
import { getMCPToolApprovals, setMCPToolApproval } from '@/api/mcp-service'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
interface Props {
visible: boolean
result: MCPTestResult | null
serviceName: string
/** When set, loads/saves per-tool approval flags */
serviceId?: string
}
interface Emits {
(e: 'update:visible', value: boolean): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const expandedToolIndex = ref<number | null>(null)
const { t } = useI18n()
const displayTools = ref<MCPTool[]>([])
const approvalLoading = ref<Record<string, boolean>>({})
const mergeApprovals = async () => {
const tools = props.result?.tools
if (!tools?.length) {
displayTools.value = []
return
}
if (!props.serviceId) {
displayTools.value = tools.map((x) => ({ ...x }))
return
}
try {
const rows = await getMCPToolApprovals(props.serviceId)
const map = new Map(rows.map((r) => [r.tool_name, r.require_approval]))
displayTools.value = tools.map((tool) => ({
...tool,
require_approval: map.get(tool.name) || false,
}))
} catch {
displayTools.value = tools.map((x) => ({ ...x }))
}
}
watch(
() => [props.visible, props.serviceId, props.result?.tools],
() => {
if (props.visible) {
void mergeApprovals()
}
},
{ deep: true }
)
const onRequireApprovalChange = async (toolName: string, value: boolean) => {
if (!props.serviceId) return
approvalLoading.value = { ...approvalLoading.value, [toolName]: true }
try {
await setMCPToolApproval(props.serviceId, toolName, value)
displayTools.value = displayTools.value.map((x) =>
x.name === toolName ? { ...x, require_approval: value } : x
)
} catch (e) {
console.error(e)
MessagePlugin.error(t('mcp.testResult.approvalSaveFailed'))
} finally {
approvalLoading.value = { ...approvalLoading.value, [toolName]: false }
}
}
const dialogVisible = computed({
get: () => props.visible,
set: (value) => emit('update:visible', value)
})
const toggleTool = (index: number) => {
if (expandedToolIndex.value === index) {
expandedToolIndex.value = null
} else {
expandedToolIndex.value = index
}
}
const formatSchema = (schema: any): string => {
if (!schema) return ''
return JSON.stringify(schema, null, 2)
}
const handleClose = () => {
dialogVisible.value = false
expandedToolIndex.value = null
}
</script>
<style scoped lang="less">
.test-result {
padding: 20px 0;
.status-section {
margin-bottom: 24px;
.status-success,
.status-error {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
padding: 12px 16px;
border-radius: 6px;
background: var(--td-bg-color-secondarycontainer);
:deep(.t-icon) {
font-size: 20px;
}
.status-text {
font-size: 15px;
font-weight: 500;
}
}
.status-success {
:deep(.t-icon) {
color: var(--td-success-color);
}
.status-text {
color: var(--td-success-color);
}
}
.status-error {
:deep(.t-icon) {
color: var(--td-error-color);
}
.status-text {
color: var(--td-error-color);
}
}
.status-message {
margin: 0;
padding: 12px 16px;
background: var(--td-bg-color-secondarycontainer);
border-radius: 6px;
font-size: 13px;
color: var(--td-text-color-secondary);
line-height: 1.6;
word-break: break-word;
}
}
.details-section {
.section {
margin-bottom: 30px;
.section-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 16px;
h3 {
font-size: 16px;
font-weight: 600;
margin: 0;
color: var(--td-text-color-primary);
}
}
.tools-grid {
display: flex;
flex-direction: column;
gap: 12px;
}
.tool-card {
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
background: var(--td-bg-color-container);
transition: all 0.2s ease;
overflow: hidden;
&:hover {
border-color: var(--td-brand-color);
box-shadow: 0 2px 8px var(--td-brand-color-light);
}
&.tool-card-expanded {
border-color: var(--td-brand-color);
box-shadow: 0 2px 12px var(--td-brand-color-light);
}
.tool-card-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 16px;
cursor: pointer;
user-select: none;
.tool-header-left {
display: flex;
align-items: flex-start;
gap: 12px;
flex: 1;
min-width: 0;
.tool-icon {
color: var(--td-brand-color);
font-size: 18px;
margin-top: 2px;
flex-shrink: 0;
}
.tool-info {
flex: 1;
min-width: 0;
.tool-name {
font-size: 15px;
font-weight: 600;
color: var(--td-text-color-primary);
margin-bottom: 4px;
word-break: break-word;
}
.tool-desc-preview {
font-size: 13px;
color: var(--td-text-color-placeholder);
line-height: 1.5;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.tool-header-right {
display: flex;
align-items: center;
gap: 10px;
flex-shrink: 0;
}
.approval-switch {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--td-text-color-secondary);
.danger-icon {
color: var(--td-warning-color);
font-size: 16px;
}
.approval-label {
max-width: 88px;
line-height: 1.2;
}
}
.expand-icon {
color: var(--td-text-color-placeholder);
font-size: 16px;
flex-shrink: 0;
transition: transform 0.2s ease;
}
}
.tool-card-content {
padding: 0 16px 16px 16px;
border-top: 1px solid var(--td-bg-color-secondarycontainer);
margin-top: 12px;
padding-top: 16px;
animation: slideDown 0.2s ease;
.tool-description,
.tool-schema {
margin-bottom: 16px;
&:last-child {
margin-bottom: 0;
}
.label {
font-size: 12px;
font-weight: 600;
color: var(--td-text-color-placeholder);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 8px;
}
.value {
font-size: 14px;
color: var(--td-text-color-secondary);
line-height: 1.6;
}
.schema-content {
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
overflow: hidden;
pre {
margin: 0;
padding: 12px;
overflow-x: auto;
font-size: 12px;
font-family: var(--app-font-family-mono);
color: var(--td-text-color-primary);
line-height: 1.6;
background: transparent;
border: none;
}
}
}
}
}
.resources-grid {
display: flex;
flex-direction: column;
gap: 12px;
}
.resource-card {
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
background: var(--td-bg-color-container);
padding: 14px 16px;
transition: all 0.2s ease;
&:hover {
border-color: var(--td-brand-color);
box-shadow: 0 2px 8px var(--td-brand-color-light);
}
.resource-header {
display: flex;
align-items: flex-start;
gap: 12px;
margin-bottom: 12px;
.resource-icon {
color: var(--td-brand-color);
font-size: 18px;
margin-top: 2px;
flex-shrink: 0;
}
.resource-info {
flex: 1;
min-width: 0;
.resource-name {
font-size: 15px;
font-weight: 600;
color: var(--td-text-color-primary);
margin-bottom: 4px;
word-break: break-word;
}
.resource-desc {
font-size: 13px;
color: var(--td-text-color-placeholder);
line-height: 1.5;
}
}
}
.resource-meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding-top: 12px;
border-top: 1px solid var(--td-bg-color-secondarycontainer);
.resource-uri {
display: flex;
align-items: center;
gap: 6px;
flex: 1;
min-width: 0;
font-size: 12px;
color: var(--td-text-color-placeholder);
:deep(.t-icon) {
color: var(--td-text-color-placeholder);
}
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
}
}
}
.empty-state {
padding: 40px 0;
}
}
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
@@ -0,0 +1,373 @@
<template>
<div v-if="result" class="mtr">
<!-- 状态条 -->
<div class="mtr-status" :class="result.success ? 'is-success' : 'is-error'">
<t-icon :name="result.success ? 'check-circle-filled' : 'close-circle-filled'" />
<span>{{ result.success ? $t('mcp.testResult.connectionSuccess') : $t('mcp.testResult.connectionFailed') }}</span>
</div>
<p v-if="result.message" class="mtr-message">{{ result.message }}</p>
<template v-if="result.success">
<!-- 工具列表 -->
<div v-if="result.tools && result.tools.length > 0" class="mtr-group">
<div class="mtr-group-title">
<span>{{ $t('mcp.testResult.toolsTitle') }}</span>
<t-tag theme="primary" variant="light" size="small">{{ result.tools.length }}</t-tag>
</div>
<div class="mtr-list">
<div
v-for="(tool, index) in displayTools"
:key="index"
class="mtr-item"
:class="{ 'is-open': expandedToolIndex === index }"
>
<div class="mtr-item-head" @click="toggleTool(index)">
<t-icon name="tools" class="mtr-item-icon" />
<span class="mtr-item-name">{{ tool.name }}</span>
<div class="mtr-item-actions" @click.stop>
<t-tooltip v-if="serviceId" :content="$t('mcp.testResult.requireApprovalTip')" placement="top">
<span class="mtr-approval">
<t-icon name="error-circle-filled" class="mtr-approval-icon" />
<span class="mtr-approval-label">{{ $t('mcp.testResult.requireApproval') }}</span>
<t-switch
:value="tool.require_approval"
:loading="approvalLoading[tool.name]"
size="small"
@change="(v: boolean) => onRequireApprovalChange(tool.name, v)"
/>
</span>
</t-tooltip>
<t-icon
:name="expandedToolIndex === index ? 'chevron-up' : 'chevron-down'"
class="mtr-chevron"
/>
</div>
</div>
<div
v-if="tool.description"
class="mtr-item-desc"
:class="{ 'is-clamped': expandedToolIndex !== index }"
>
{{ tool.description }}
</div>
<div v-if="expandedToolIndex === index && tool.inputSchema" class="mtr-item-schema">
<div class="mtr-schema-label">{{ $t('mcp.testResult.schemaLabel') }}</div>
<pre>{{ formatSchema(tool.inputSchema) }}</pre>
</div>
</div>
</div>
</div>
<!-- 资源列表 -->
<div v-if="result.resources && result.resources.length > 0" class="mtr-group">
<div class="mtr-group-title">
<span>{{ $t('mcp.testResult.resourcesTitle') }}</span>
<t-tag theme="primary" variant="light" size="small">{{ result.resources.length }}</t-tag>
</div>
<div class="mtr-list">
<div v-for="(resource, index) in result.resources" :key="index" class="mtr-item">
<div class="mtr-item-head is-static">
<t-icon name="file" class="mtr-item-icon" />
<span class="mtr-item-name">{{ resource.name || resource.uri }}</span>
<t-tag v-if="resource.mimeType" theme="default" variant="light-outline" size="small">
{{ resource.mimeType }}
</t-tag>
</div>
<div v-if="resource.description" class="mtr-item-desc">{{ resource.description }}</div>
<div v-if="resource.uri" class="mtr-item-uri">
<t-icon name="link" />
<span>{{ resource.uri }}</span>
</div>
</div>
</div>
</div>
<!-- 空状态 -->
<t-empty
v-if="(!result.tools || result.tools.length === 0) && (!result.resources || result.resources.length === 0)"
:description="$t('mcp.testResult.emptyDescription')"
class="mtr-empty"
/>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import type { MCPTestResult, MCPTool } from '@/api/mcp-service'
import { getMCPToolApprovals, setMCPToolApproval } from '@/api/mcp-service'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
interface Props {
result: MCPTestResult | null
/** When set, loads/saves per-tool approval flags */
serviceId?: string
/** When true, (re)loads approval flags. Lets the dialog gate the fetch on
* visibility; defaults to true for always-rendered inline usage. */
active?: boolean
}
const props = withDefaults(defineProps<Props>(), { active: true })
const expandedToolIndex = ref<number | null>(null)
const { t } = useI18n()
const displayTools = ref<MCPTool[]>([])
const approvalLoading = ref<Record<string, boolean>>({})
const mergeApprovals = async () => {
const tools = props.result?.tools
if (!tools?.length) {
displayTools.value = []
return
}
if (!props.serviceId) {
displayTools.value = tools.map((x) => ({ ...x }))
return
}
try {
const rows = await getMCPToolApprovals(props.serviceId)
const map = new Map(rows.map((r) => [r.tool_name, r.require_approval]))
displayTools.value = tools.map((tool) => ({
...tool,
require_approval: map.get(tool.name) || false,
}))
} catch {
displayTools.value = tools.map((x) => ({ ...x }))
}
}
watch(
() => [props.active, props.serviceId, props.result?.tools],
() => {
if (props.active) {
void mergeApprovals()
}
},
{ deep: true, immediate: true }
)
const onRequireApprovalChange = async (toolName: string, value: boolean) => {
if (!props.serviceId) return
approvalLoading.value = { ...approvalLoading.value, [toolName]: true }
try {
await setMCPToolApproval(props.serviceId, toolName, value)
displayTools.value = displayTools.value.map((x) =>
x.name === toolName ? { ...x, require_approval: value } : x
)
} catch (e) {
console.error(e)
MessagePlugin.error(t('mcp.testResult.approvalSaveFailed'))
} finally {
approvalLoading.value = { ...approvalLoading.value, [toolName]: false }
}
}
const toggleTool = (index: number) => {
expandedToolIndex.value = expandedToolIndex.value === index ? null : index
}
const formatSchema = (schema: any): string => {
if (!schema) return ''
return JSON.stringify(schema, null, 2)
}
</script>
<style scoped lang="less">
.mtr {
display: flex;
flex-direction: column;
gap: 16px;
}
/* 状态条 */
.mtr-status {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
&.is-success {
color: var(--td-success-color);
background: var(--td-success-color-1, var(--td-bg-color-secondarycontainer));
}
&.is-error {
color: var(--td-error-color);
background: var(--td-error-color-1, var(--td-bg-color-secondarycontainer));
}
:deep(.t-icon) {
font-size: 18px;
}
}
.mtr-message {
margin: 0;
font-size: 13px;
color: var(--td-text-color-secondary);
line-height: 1.6;
word-break: break-word;
}
/* 分组 */
.mtr-group {
display: flex;
flex-direction: column;
gap: 10px;
}
.mtr-group-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 600;
color: var(--td-text-color-secondary);
}
/* 列表:扁平卡片,靠分隔与圆角,无重阴影,贴合抽屉 */
.mtr-list {
display: flex;
flex-direction: column;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
overflow: hidden;
}
.mtr-item {
padding: 12px 14px;
background: var(--td-bg-color-container);
& + .mtr-item {
border-top: 1px solid var(--td-component-stroke);
}
&.is-open {
background: var(--td-bg-color-secondarycontainer);
}
}
.mtr-item-head {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
user-select: none;
&.is-static {
cursor: default;
}
}
.mtr-item-icon {
flex-shrink: 0;
font-size: 16px;
color: var(--td-brand-color);
}
.mtr-item-name {
flex: 1;
min-width: 0;
font-size: 14px;
font-weight: 600;
color: var(--td-text-color-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mtr-item-actions {
display: flex;
align-items: center;
gap: 10px;
flex-shrink: 0;
}
.mtr-approval {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--td-text-color-secondary);
.mtr-approval-icon {
font-size: 15px;
color: var(--td-warning-color);
}
.mtr-approval-label {
white-space: nowrap;
}
}
.mtr-chevron {
font-size: 16px;
color: var(--td-text-color-placeholder);
flex-shrink: 0;
}
/* 描述:独占整行,绝不与右侧开关挤在一起 */
.mtr-item-desc {
margin-top: 6px;
font-size: 13px;
color: var(--td-text-color-placeholder);
line-height: 1.6;
word-break: break-word;
&.is-clamped {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
}
.mtr-item-schema {
margin-top: 10px;
.mtr-schema-label {
font-size: 12px;
font-weight: 600;
color: var(--td-text-color-placeholder);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 6px;
}
pre {
margin: 0;
padding: 10px 12px;
border-radius: 6px;
background: var(--td-bg-color-page);
border: 1px solid var(--td-component-stroke);
overflow-x: auto;
font-size: 12px;
font-family: var(--app-font-family-mono);
color: var(--td-text-color-primary);
line-height: 1.6;
}
}
.mtr-item-uri {
display: flex;
align-items: center;
gap: 6px;
margin-top: 8px;
font-size: 12px;
color: var(--td-text-color-placeholder);
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.mtr-empty {
padding: 24px 0;
}
</style>