fix(mcp): offer OAuth prompt after tool approval and tidy tools panel (#4248)
* fix(mcp): offer OAuth prompt after tool approval and tidy tools panel * test(mcp): wrap long line for lll * style(mcp): use font-size token in tools list header * test(style): report guard hits by line, skip comments, tighten baselines * style(chat): use font-size token for rewind icon and drop touch-only !importantmain
parent
e51dee8297
commit
2511a1f932
|
|
@ -6,7 +6,9 @@ import { fileURLToPath } from 'node:url'
|
|||
|
||||
/**
|
||||
* 样式守卫(棘轮):统计 views/ components/ assets/ 里绕过设计令牌或和 TDesign 打架的写法,
|
||||
* 只允许计数下降。新增任何一处都会让测试失败;清理后请把 baseline 调低。
|
||||
* 只允许计数下降。新增任何一处都会让测试失败;清理后请把 baseline 调低(测试会提示目标值)。
|
||||
* 低于 baseline 不算失败:两个各自清理并下调 baseline 的 PR 先后合并时,main 不应因此变红。
|
||||
* 注释中的示例代码不计入。
|
||||
*
|
||||
* 令牌定义在 assets/theme/theme.css(--app-radius-* / --app-text-* / --app-space-* /
|
||||
* --app-motion-* / --z-*),TDesign 全局覆盖放在 assets/theme/tdesign-overrides.less。
|
||||
|
|
@ -28,7 +30,7 @@ const RULES = [
|
|||
name: 'legacy-blue-rgba',
|
||||
why: '旧版 TDesign 蓝 rgba(0,82,217) 已不是品牌色',
|
||||
pattern: /rgba\(\s*0\s*,\s*82\s*,\s*217\s*,/g,
|
||||
baseline: 18,
|
||||
baseline: 7,
|
||||
},
|
||||
{
|
||||
name: 'td-token-fallback',
|
||||
|
|
@ -40,43 +42,43 @@ const RULES = [
|
|||
name: 'radius-literal',
|
||||
why: '圆角请用 var(--app-radius-xs|sm|md|lg|xl|pill)(4/6/8/10/12/999px)',
|
||||
pattern: /border(?:-[a-z]+)*-radius\s*:\s*\d+(?:\.\d+)?px/g,
|
||||
baseline: 162,
|
||||
baseline: 160,
|
||||
},
|
||||
{
|
||||
name: 'font-size-literal',
|
||||
why: '字号请用 var(--app-text-2xs … 4xl)(10~24px)',
|
||||
pattern: /font-size\s*:\s*\d+(?:\.\d+)?px/g,
|
||||
baseline: 28,
|
||||
why: '字号请用 var(--app-text-2xs … 4xl)(10~24px),简写写成 font: var(--app-text-sm)/1.5 …;图标尺寸用 t-icon 的 size 属性',
|
||||
pattern: /\bfont(?:-size)?\s*:\s*\d+(?:\.\d+)?px/g,
|
||||
baseline: 33,
|
||||
},
|
||||
{
|
||||
name: 'motion-literal',
|
||||
why: '过渡时长请用 var(--app-motion-instant|fast|base|slow)(120/150/200/300ms)',
|
||||
pattern: /transition[^;{]*?(?<![\d.])(?:0?\.\d+s|\d+ms)/g,
|
||||
baseline: 65,
|
||||
baseline: 64,
|
||||
},
|
||||
{
|
||||
name: 'transition-all',
|
||||
why: 'transition: all 会让无关属性也参与动画(含 layout 属性),请列出具体属性',
|
||||
pattern: /transition\s*:\s*all\b/g,
|
||||
baseline: 78,
|
||||
baseline: 59,
|
||||
},
|
||||
{
|
||||
name: 'important',
|
||||
why: '!important 通常意味着在和 TDesign 或自己的样式打架;全局意图的覆盖放 tdesign-overrides.less',
|
||||
pattern: /!important/g,
|
||||
baseline: 510,
|
||||
baseline: 414,
|
||||
},
|
||||
{
|
||||
name: 'z-index-important',
|
||||
why: 'z-index 不应靠 !important 取胜,改用 t-popup attach="body" 或 --z-* 层级令牌',
|
||||
pattern: /z-index\s*:\s*-?\d+\s*!important/g,
|
||||
baseline: 26,
|
||||
baseline: 23,
|
||||
},
|
||||
{
|
||||
name: 'raster-icon',
|
||||
why: 'more.png / circle.png 位图图标请换成 t-icon',
|
||||
pattern: /(more|circle)\.png/g,
|
||||
baseline: 10,
|
||||
baseline: 8,
|
||||
},
|
||||
]
|
||||
|
||||
|
|
@ -92,35 +94,64 @@ function* walk(dir) {
|
|||
}
|
||||
}
|
||||
|
||||
function countMatches(rule) {
|
||||
const byFile = new Map()
|
||||
let total = 0
|
||||
// Blank out comments but keep newlines so reported line numbers stay accurate.
|
||||
// `//` only counts as a Less line comment after whitespace or at line start,
|
||||
// which leaves url(https://…) alone.
|
||||
function stripComments(text) {
|
||||
const blank = (m) => m.replace(/[^\n]/g, ' ')
|
||||
return text
|
||||
.replace(/\/\*[\s\S]*?\*\//g, blank)
|
||||
.replace(/<!--[\s\S]*?-->/g, blank)
|
||||
.replace(/(^|[ \t])\/\/[^\n]*/gm, blank)
|
||||
}
|
||||
|
||||
const sources = (() => {
|
||||
const list = []
|
||||
for (const dir of SCAN_DIRS) {
|
||||
for (const file of walk(join(SRC_ROOT, dir))) {
|
||||
const rel = relative(SRC_ROOT, file).replaceAll('\\', '/')
|
||||
if (EXEMPT_FILES.has(rel)) continue
|
||||
const text = readFileSync(file, 'utf8')
|
||||
const n = (text.match(rule.pattern) ?? []).length
|
||||
if (n > 0) {
|
||||
byFile.set(rel, n)
|
||||
total += n
|
||||
}
|
||||
if (!EXEMPT_FILES.has(rel)) list.push({ rel, text: stripComments(readFileSync(file, 'utf8')) })
|
||||
}
|
||||
}
|
||||
return { total, byFile }
|
||||
return list
|
||||
})()
|
||||
|
||||
function findMatches(rule) {
|
||||
const hits = []
|
||||
for (const { rel, text } of sources) {
|
||||
for (const m of text.matchAll(rule.pattern)) {
|
||||
const line = text.slice(0, m.index).split('\n').length
|
||||
const snippet = text.split('\n')[line - 1].trim().slice(0, 100)
|
||||
hits.push({ rel, line, snippet })
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
const MAX_LISTED_HITS = 40
|
||||
|
||||
function describeHits(hits) {
|
||||
if (hits.length <= MAX_LISTED_HITS) {
|
||||
return hits.map((h) => ` ${h.rel}:${h.line} ${h.snippet}`).join('\n')
|
||||
}
|
||||
const byFile = new Map()
|
||||
for (const h of hits) byFile.set(h.rel, (byFile.get(h.rel) ?? 0) + 1)
|
||||
return [...byFile.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 12)
|
||||
.map(([f, n]) => ` ${n}\t${f}`)
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
for (const rule of RULES) {
|
||||
test(`style guard: ${rule.name} does not exceed baseline (${rule.baseline})`, () => {
|
||||
const { total, byFile } = countMatches(rule)
|
||||
const top = [...byFile.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 8)
|
||||
.map(([f, n]) => ` ${n}\t${f}`)
|
||||
.join('\n')
|
||||
test(`style guard: ${rule.name} does not exceed baseline (${rule.baseline})`, (t) => {
|
||||
const hits = findMatches(rule)
|
||||
assert.ok(
|
||||
total <= rule.baseline,
|
||||
`${rule.name}: ${total} occurrences > baseline ${rule.baseline}.\n${rule.why}\n${top}`,
|
||||
hits.length <= rule.baseline,
|
||||
`${rule.name}: ${hits.length} occurrences > baseline ${rule.baseline}.\n${rule.why}\n${describeHits(hits)}`,
|
||||
)
|
||||
if (hits.length < rule.baseline) {
|
||||
t.diagnostic(`${rule.name}: ${hits.length} < baseline ${rule.baseline}; lower the baseline to ${hits.length}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -305,11 +305,18 @@ const confirmDangerAction = (): void => {
|
|||
|
||||
.submenu_item:not(.submenu_item_batch) {
|
||||
&:hover, &:focus-within, &.submenu_item--menu-open {
|
||||
.session-row-badge { opacity: 0; }
|
||||
.session-row-menu-wrap--badge .menu-more-wrap { opacity: 1; }
|
||||
}
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.submenu_item:not(.submenu_item_batch) {
|
||||
&:hover, &:focus-within, &.submenu_item--menu-open {
|
||||
.session-row-badge { opacity: 0; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (hover: none) {
|
||||
.session-row-menu-wrap {
|
||||
flex-basis: 24px;
|
||||
|
|
@ -332,7 +339,6 @@ const confirmDangerAction = (): void => {
|
|||
position: static;
|
||||
flex: 0 0 16px;
|
||||
height: 24px;
|
||||
opacity: 1 !important;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5646,6 +5646,9 @@ export default {
|
|||
"serverDocumentation": "Original server documentation",
|
||||
"noServerDocumentation": "This MCP server's initialize result did not include instructions or serverInfo.description (both are optional). Tool text lives in each tool's description below.",
|
||||
"policyHint": "Tool and approval switches save immediately and survive directory refreshes.",
|
||||
"columnTool": "Tool",
|
||||
"columnEnabled": "Enabled",
|
||||
"columnApproval": "Approval",
|
||||
"failed": "Could not load the tool directory",
|
||||
"setupProgress": "MCP setup steps",
|
||||
"connection": "Connection",
|
||||
|
|
|
|||
|
|
@ -5646,6 +5646,9 @@ export default {
|
|||
"serverDocumentation": "サーバーの元の説明",
|
||||
"noServerDocumentation": "この MCP サーバーの initialize に instructions / serverInfo.description はありません(どちらも任意)。ツールの説明は下の各 description にあります。",
|
||||
"policyHint": "ツールの有効化と承認設定は即時保存され、一覧の更新後も維持されます。",
|
||||
"columnTool": "ツール",
|
||||
"columnEnabled": "有効",
|
||||
"columnApproval": "承認",
|
||||
"failed": "ツール一覧を読み込めませんでした",
|
||||
"setupProgress": "MCP 設定の手順",
|
||||
"connection": "接続設定",
|
||||
|
|
|
|||
|
|
@ -2422,6 +2422,9 @@ export default {
|
|||
"serverDocumentation": "서버 원본 설명",
|
||||
"noServerDocumentation": "이 MCP 서버의 initialize 응답에 instructions / serverInfo.description이 없습니다(둘 다 선택 필드). 도구 설명은 아래 각 도구의 description에 있습니다.",
|
||||
"policyHint": "도구 활성화 및 승인 설정은 즉시 저장되며 목록을 새로 고쳐도 유지됩니다.",
|
||||
"columnTool": "도구",
|
||||
"columnEnabled": "활성화",
|
||||
"columnApproval": "승인",
|
||||
"failed": "도구 목록을 불러오지 못했습니다",
|
||||
"setupProgress": "MCP 설정 단계",
|
||||
"connection": "연결 설정",
|
||||
|
|
|
|||
|
|
@ -2422,6 +2422,9 @@ export default {
|
|||
"serverDocumentation": "Исходная документация сервера",
|
||||
"noServerDocumentation": "Ответ initialize этого MCP-сервера не содержит instructions / serverInfo.description (оба поля необязательны). Текст инструментов — в description ниже.",
|
||||
"policyHint": "Настройки включения и подтверждения сохраняются сразу и не сбрасываются при обновлении каталога.",
|
||||
"columnTool": "Инструмент",
|
||||
"columnEnabled": "Вкл.",
|
||||
"columnApproval": "Подтв.",
|
||||
"failed": "Не удалось загрузить каталог инструментов",
|
||||
"setupProgress": "Шаги настройки MCP",
|
||||
"connection": "Подключение",
|
||||
|
|
|
|||
|
|
@ -2424,6 +2424,9 @@ export default {
|
|||
"serverDocumentation": "服务端原始说明",
|
||||
"noServerDocumentation": "该 MCP Server 的 initialize 未返回 instructions / serverInfo.description(均为可选字段)。工具说明在下方各工具的 description 里。",
|
||||
"policyHint": "工具开关与审批设置即时保存;刷新目录不会覆盖这些设置。",
|
||||
"columnTool": "工具",
|
||||
"columnEnabled": "启用",
|
||||
"columnApproval": "需审批",
|
||||
"failed": "工具目录读取失败",
|
||||
"setupProgress": "MCP 配置步骤",
|
||||
"connection": "连接配置",
|
||||
|
|
|
|||
|
|
@ -2424,6 +2424,9 @@ export default {
|
|||
"serverDocumentation": "伺服器端原始說明",
|
||||
"noServerDocumentation": "該 MCP Server 的 initialize 未返回 instructions / serverInfo.description(均為可選欄位)。工具說明在下方各工具的 description 裡。",
|
||||
"policyHint": "工具開關與審批設定即時儲存;重新整理目錄不會覆蓋這些設定。",
|
||||
"columnTool": "工具",
|
||||
"columnEnabled": "啟用",
|
||||
"columnApproval": "需審批",
|
||||
"failed": "工具目錄讀取失敗",
|
||||
"setupProgress": "MCP 設定步驟",
|
||||
"connection": "連結設定",
|
||||
|
|
|
|||
|
|
@ -2178,7 +2178,7 @@ onBeforeRouteUpdate((to, from, next) => {
|
|||
flex-shrink: 0;
|
||||
margin: 0;
|
||||
padding: 3px 0 0;
|
||||
font-size: 16px;
|
||||
font-size: var(--app-text-xl);
|
||||
}
|
||||
|
||||
.t-popconfirm__inner {
|
||||
|
|
|
|||
|
|
@ -3,24 +3,25 @@
|
|||
<div class="section-title-block">
|
||||
<div class="metadata-heading">
|
||||
<h4 class="setting-drawer__section-title">{{ t('mcpMetadata.tools') }}</h4>
|
||||
<t-button
|
||||
v-if="!busy || snapshot"
|
||||
variant="text"
|
||||
size="small"
|
||||
theme="primary"
|
||||
:loading="refreshing"
|
||||
:disabled="loading || disabled || policyBusy"
|
||||
@click="refresh"
|
||||
>
|
||||
<template #icon><t-icon name="refresh" /></template>
|
||||
{{ t(snapshot ? 'mcpMetadata.refresh' : 'mcpMetadata.fetch') }}
|
||||
</t-button>
|
||||
<t-tooltip v-if="!busy || snapshot" :content="t('mcpMetadata.cacheHint')" placement="top-right"
|
||||
:overlay-inner-style="{ maxWidth: '300px', whiteSpace: 'normal' }">
|
||||
<t-button
|
||||
variant="text"
|
||||
size="small"
|
||||
theme="primary"
|
||||
:loading="refreshing"
|
||||
:disabled="loading || disabled || policyBusy"
|
||||
@click="refresh"
|
||||
>
|
||||
<template #icon><t-icon name="refresh" /></template>
|
||||
{{ t(snapshot ? 'mcpMetadata.refresh' : 'mcpMetadata.fetch') }}
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
<p class="form-desc">{{ t('mcpMetadata.cacheHint') }}</p>
|
||||
<p v-if="snapshot" class="snapshot-meta">
|
||||
<span>{{ t('mcpMetadata.toolCount', { count: snapshot.tools.length }) }}</span>
|
||||
<span v-if="snapshot.server_name">{{ snapshot.server_name }} {{ snapshot.server_version }}</span>
|
||||
<span>{{ t('mcpMetadata.syncedAt') }} {{ formatTime(snapshot.synced_at) }}</span>
|
||||
<span class="snapshot-meta__item">{{ t('mcpMetadata.toolCount', { count: snapshot.tools.length }) }}</span>
|
||||
<span v-if="snapshot.server_name" class="snapshot-meta__item">{{ snapshot.server_name }} {{ snapshot.server_version }}</span>
|
||||
<span class="snapshot-meta__item">{{ t('mcpMetadata.syncedAt') }}{{ formatTime(snapshot.synced_at) }}</span>
|
||||
<t-tooltip
|
||||
v-if="!hasServerDocumentation"
|
||||
:content="t('mcpMetadata.noServerDocumentation')"
|
||||
|
|
@ -67,7 +68,6 @@
|
|||
<p v-else-if="snapshot?.stale" class="form-desc form-desc--warn">{{ t('mcpMetadata.stale') }}</p>
|
||||
<p v-else-if="!busy && !snapshot" class="form-desc">{{ t('mcpMetadata.notSynced') }}</p>
|
||||
<template v-if="snapshot">
|
||||
<p class="form-desc">{{ t('mcpMetadata.policyHint') }}</p>
|
||||
<McpToolsList :tools="snapshot.tools" :service-id="snapshot.stale ? undefined : serviceId" @busy="onPolicyBusy" />
|
||||
</template>
|
||||
</div>
|
||||
|
|
@ -205,11 +205,20 @@ onBeforeUnmount(() => { generation++; emit('busy', false); emit('synced', false)
|
|||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 10px;
|
||||
gap: 4px 0;
|
||||
margin: 4px 0 0;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.4;
|
||||
color: var(--td-text-color-secondary);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.snapshot-meta__item + .snapshot-meta__item::before {
|
||||
content: '·';
|
||||
margin: 0 6px;
|
||||
}
|
||||
|
||||
.snapshot-meta > :not(.snapshot-meta__item) {
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.snapshot-meta__help,
|
||||
|
|
|
|||
|
|
@ -357,16 +357,18 @@
|
|||
<div class="form-item">
|
||||
<div class="usage-heading">
|
||||
<label class="form-label required">{{ t('mcpMetadata.usageInstructions') }}</label>
|
||||
<t-button variant="text" theme="primary" size="small" :loading="generatingUsage"
|
||||
:disabled="!toolsSynced || metadataBusy || submitting" @click="handleGenerateUsage">
|
||||
<template #icon><t-icon name="lightbulb" /></template>
|
||||
{{ t('mcpMetadata.generateUsage') }}
|
||||
</t-button>
|
||||
<t-tooltip :content="t('mcpMetadata.generateHint')" placement="top-right"
|
||||
:overlay-inner-style="{ maxWidth: '300px', whiteSpace: 'normal' }">
|
||||
<t-button variant="text" theme="primary" size="small" :loading="generatingUsage"
|
||||
:disabled="!toolsSynced || metadataBusy || submitting" @click="handleGenerateUsage">
|
||||
<template #icon><t-icon name="lightbulb" /></template>
|
||||
{{ t('mcpMetadata.generateUsage') }}
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
<t-textarea v-model="formData.usage_instructions" :maxlength="16000" :autosize="{ minRows: 3, maxRows: 8 }"
|
||||
<t-textarea v-model="formData.usage_instructions" class="usage-textarea" :maxlength="16000" :autosize="{ minRows: 3, maxRows: 8 }"
|
||||
:disabled="generatingUsage || submitting"
|
||||
:placeholder="t('mcpMetadata.instructionsPlaceholder')" />
|
||||
<p class="form-desc">{{ t('mcpMetadata.generateHint') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
<McpMetadataPanel v-if="currentService?.id" :key="currentService.id" :service-id="currentService.id"
|
||||
|
|
@ -1048,6 +1050,20 @@ const handleClose = () => {
|
|||
.form-label { margin-bottom: 0; }
|
||||
}
|
||||
|
||||
.usage-textarea {
|
||||
:deep(.t-textarea__inner) {
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.65;
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
:deep(.t-textarea__info_wrapper),
|
||||
:deep(.t-textarea__limit) {
|
||||
font-size: var(--app-text-xs);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
|
||||
.mcp-steps {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
|
|
|||
|
|
@ -6,76 +6,91 @@
|
|||
<t-alert v-if="policyError" theme="error" :message="policyError">
|
||||
<template #operation><t-button variant="text" size="small" @click="loadPolicies">{{ t('mcpMetadata.retry') }}</t-button></template>
|
||||
</t-alert>
|
||||
<div v-if="visibleTools.length" class="tools-list">
|
||||
<div v-if="visibleTools.length" class="tools-list" :class="{ 'has-controls': !!serviceId }">
|
||||
<div class="tools-list__header">
|
||||
<span class="tools-list__header-tool">
|
||||
{{ t('mcpMetadata.columnTool') }}
|
||||
<t-tooltip v-if="serviceId" :content="t('mcpMetadata.policyHint')" placement="top"
|
||||
:overlay-inner-style="{ maxWidth: '280px', whiteSpace: 'normal' }">
|
||||
<t-icon name="help-circle" size="14px" class="tools-list__help" />
|
||||
</t-tooltip>
|
||||
</span>
|
||||
<template v-if="serviceId">
|
||||
<span class="tools-list__header-col">{{ t('mcpMetadata.columnEnabled') }}</span>
|
||||
<span class="tools-list__header-col">{{ t('mcpMetadata.columnApproval') }}</span>
|
||||
</template>
|
||||
</div>
|
||||
<article v-for="tool in visibleTools" :key="tool.name" class="tool-row">
|
||||
<div class="tool-heading">
|
||||
<span class="tool-name">{{ tool.name }}</span>
|
||||
<t-popup
|
||||
:visible="openTool === tool.name"
|
||||
trigger="click"
|
||||
placement="bottom-right"
|
||||
attach="body"
|
||||
destroy-on-close
|
||||
overlay-class-name="mcp-tool-detail-popup"
|
||||
:overlay-inner-style="{ padding: 0 }"
|
||||
@visible-change="(visible: boolean) => setOpenTool(tool.name, visible)"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="tool-details"
|
||||
:class="{ 'is-open': openTool === tool.name }"
|
||||
:aria-expanded="openTool === tool.name"
|
||||
<div class="tool-main">
|
||||
<div class="tool-heading">
|
||||
<span class="tool-name">{{ tool.name }}</span>
|
||||
<t-popup
|
||||
:visible="openTool === tool.name"
|
||||
trigger="click"
|
||||
placement="bottom-left"
|
||||
attach="body"
|
||||
destroy-on-close
|
||||
overlay-class-name="mcp-tool-detail-popup"
|
||||
:overlay-inner-style="{ padding: 0 }"
|
||||
@visible-change="(visible: boolean) => setOpenTool(tool.name, visible)"
|
||||
>
|
||||
{{ t('mcpMetadata.details') }}
|
||||
</button>
|
||||
<template #content>
|
||||
<div class="tool-detail" @click.stop>
|
||||
<div class="tool-detail__tabs" role="tablist">
|
||||
<button
|
||||
v-for="tab in detailTabs"
|
||||
:key="tab"
|
||||
type="button"
|
||||
class="tool-detail__tab"
|
||||
:class="{ 'is-active': schemaView === tab }"
|
||||
role="tab"
|
||||
:aria-selected="schemaView === tab"
|
||||
@click="schemaView = tab"
|
||||
>{{ t(detailTabLabel[tab]) }}</button>
|
||||
</div>
|
||||
<div class="tool-detail__body">
|
||||
<p v-if="schemaView === 'description' && tool.description" class="tool-detail__desc">{{ tool.description }}</p>
|
||||
<p v-else-if="schemaView === 'description'" class="tool-detail__empty">{{ t('mcpMetadata.noDescription') }}</p>
|
||||
<template v-else-if="schemaView === 'parameters'">
|
||||
<div v-if="parametersOf(tool).length" class="tool-detail__params">
|
||||
<div v-for="parameter in parametersOf(tool)" :key="parameter.name" class="tool-detail__param">
|
||||
<div class="tool-detail__param-title">
|
||||
<code>{{ parameter.name }}</code>
|
||||
<span v-if="parameter.type">{{ parameter.type }}</span>
|
||||
<span v-if="parameter.required" class="is-required">{{ t('mcpMetadata.required') }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="tool-details"
|
||||
:class="{ 'is-open': openTool === tool.name }"
|
||||
:aria-expanded="openTool === tool.name"
|
||||
>
|
||||
{{ t('mcpMetadata.details') }}
|
||||
</button>
|
||||
<template #content>
|
||||
<div class="tool-detail" @click.stop>
|
||||
<div class="tool-detail__tabs" role="tablist">
|
||||
<button
|
||||
v-for="tab in detailTabs"
|
||||
:key="tab"
|
||||
type="button"
|
||||
class="tool-detail__tab"
|
||||
:class="{ 'is-active': schemaView === tab }"
|
||||
role="tab"
|
||||
:aria-selected="schemaView === tab"
|
||||
@click="schemaView = tab"
|
||||
>{{ t(detailTabLabel[tab]) }}</button>
|
||||
</div>
|
||||
<div class="tool-detail__body">
|
||||
<p v-if="schemaView === 'description' && tool.description" class="tool-detail__desc">{{ tool.description }}</p>
|
||||
<p v-else-if="schemaView === 'description'" class="tool-detail__empty">{{ t('mcpMetadata.noDescription') }}</p>
|
||||
<template v-else-if="schemaView === 'parameters'">
|
||||
<div v-if="parametersOf(tool).length" class="tool-detail__params">
|
||||
<div v-for="parameter in parametersOf(tool)" :key="parameter.name" class="tool-detail__param">
|
||||
<div class="tool-detail__param-title">
|
||||
<code>{{ parameter.name }}</code>
|
||||
<span v-if="parameter.type">{{ parameter.type }}</span>
|
||||
<span v-if="parameter.required" class="is-required">{{ t('mcpMetadata.required') }}</span>
|
||||
</div>
|
||||
<p v-if="parameter.description">{{ parameter.description }}</p>
|
||||
</div>
|
||||
<p v-if="parameter.description">{{ parameter.description }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="tool-detail__empty">{{ t('mcpMetadata.noParameters') }}</p>
|
||||
</template>
|
||||
<pre v-else-if="tool.inputSchema" class="tool-detail__json">{{ JSON.stringify(tool.inputSchema, null, 2) }}</pre>
|
||||
<p v-else class="tool-detail__empty">{{ t('mcpMetadata.noParameters') }}</p>
|
||||
</template>
|
||||
<pre v-else-if="tool.inputSchema" class="tool-detail__json">{{ JSON.stringify(tool.inputSchema, null, 2) }}</pre>
|
||||
<p v-else class="tool-detail__empty">{{ t('mcpMetadata.noParameters') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</template>
|
||||
</t-popup>
|
||||
</div>
|
||||
<p v-if="tool.description" class="tool-description">{{ tool.description }}</p>
|
||||
</div>
|
||||
<p v-if="tool.description" class="tool-description">{{ tool.description }}</p>
|
||||
<div v-if="serviceId" class="tool-controls">
|
||||
<label class="tool-control"><span>{{ t('mcpMetadata.enabled') }}</span>
|
||||
<template v-if="serviceId">
|
||||
<div class="tool-cell">
|
||||
<t-switch :value="policy(tool.name).enabled" size="small" :disabled="loading || !!policyError || !!busy.get(tool.name)" :loading="busy.get(tool.name) === 'enabled'"
|
||||
:aria-label="`${tool.name} ${t('mcpMetadata.enabled')}`" @change="(value: boolean) => savePolicy(tool.name, 'enabled', value)" />
|
||||
</label>
|
||||
<label class="tool-control"><span>{{ t('mcpMetadata.approval') }}</span>
|
||||
</div>
|
||||
<div class="tool-cell">
|
||||
<t-switch :value="policy(tool.name).require_approval" size="small" :disabled="loading || !!policyError || !!busy.get(tool.name)" :loading="busy.get(tool.name) === 'require_approval'"
|
||||
:aria-label="`${tool.name} ${t('mcpMetadata.approval')}`" @change="(value: boolean) => savePolicy(tool.name, 'require_approval', value)" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</article>
|
||||
</div>
|
||||
<t-empty v-else :description="t('mcpMetadata.noTools')" size="small" />
|
||||
|
|
@ -168,10 +183,36 @@ onBeforeUnmount(() => { generation++; emit('busy', false) })
|
|||
|
||||
<style scoped lang="less">
|
||||
.tools-directory { display: flex; flex-direction: column; gap: 12px; margin-top: 0; min-width: 0; }
|
||||
.tools-list { border-top: 1px solid var(--td-component-stroke); }
|
||||
.tool-row { padding: 14px 0; min-width: 0; border-bottom: 1px solid var(--td-component-stroke); }
|
||||
.tool-row:last-child { border-bottom: 0; padding-bottom: 0; }
|
||||
.tool-heading { display: flex; width: 100%; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
.tools-list {
|
||||
--tool-columns: minmax(0, 1fr);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
overflow: hidden;
|
||||
}
|
||||
.tools-list.has-controls { --tool-columns: minmax(0, 1fr) 64px 64px; }
|
||||
.tools-list__header,
|
||||
.tool-row {
|
||||
display: grid;
|
||||
grid-template-columns: var(--tool-columns);
|
||||
column-gap: 8px;
|
||||
padding: 0 14px;
|
||||
}
|
||||
.tools-list__header {
|
||||
align-items: center;
|
||||
height: 34px;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-secondary);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
.tools-list__header-tool { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.tools-list__header-col { text-align: center; white-space: nowrap; }
|
||||
.tools-list__help { color: var(--td-text-color-placeholder); cursor: help; }
|
||||
.tool-row { padding-top: 12px; padding-bottom: 12px; min-width: 0; border-bottom: 1px solid var(--td-component-stroke); }
|
||||
.tool-row:last-child { border-bottom: 0; }
|
||||
.tool-main { min-width: 0; }
|
||||
.tool-cell { display: flex; justify-content: center; align-items: flex-start; padding-top: 2px; }
|
||||
.tool-heading { display: flex; min-width: 0; align-items: baseline; gap: 8px; }
|
||||
.tool-name { min-width: 0; font-size: var(--app-text-md); font-weight: 600; line-height: 1.6; overflow-wrap: anywhere; }
|
||||
.tool-details {
|
||||
flex-shrink: 0;
|
||||
|
|
@ -188,7 +229,7 @@ onBeforeUnmount(() => { generation++; emit('busy', false) })
|
|||
.tool-details.is-open,
|
||||
.tool-details:focus-visible { color: var(--td-brand-color); }
|
||||
.tool-description {
|
||||
margin: 6px 0 0;
|
||||
margin: 2px 0 0;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.65;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
|
@ -199,8 +240,6 @@ onBeforeUnmount(() => { generation++; emit('busy', false) })
|
|||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.tool-controls { display: flex; align-items: center; gap: 24px; flex-wrap: wrap; margin-top: 10px; }
|
||||
.tool-control { display: inline-flex; align-items: center; gap: 8px; font-size: var(--app-text-sm); line-height: 20px; color: var(--td-text-color-secondary); cursor: pointer; }
|
||||
.tools-pagination { display: flex; align-items: center; justify-content: flex-end; gap: 8px; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
|
||||
</style>
|
||||
|
||||
|
|
@ -211,33 +250,45 @@ onBeforeUnmount(() => { generation++; emit('busy', false) })
|
|||
|
||||
.t-popup__content {
|
||||
padding: 0 !important;
|
||||
width: 400px;
|
||||
width: 380px;
|
||||
max-width: calc(100vw - 24px);
|
||||
border-radius: var(--app-radius-md) !important;
|
||||
border-radius: var(--app-radius-xl) !important;
|
||||
background: var(--td-bg-color-container) !important;
|
||||
border: 1px solid var(--td-component-stroke) !important;
|
||||
box-shadow: var(--td-shadow-2) !important;
|
||||
border: 0.5px solid var(--td-component-stroke) !important;
|
||||
box-shadow:
|
||||
0 0 0 0.5px rgba(0, 0, 0, 0.03),
|
||||
0 2px 4px rgba(0, 0, 0, 0.04),
|
||||
0 8px 24px rgba(0, 0, 0, 0.1) !important;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
:root[theme-mode='dark'] .mcp-tool-detail-popup .t-popup__content {
|
||||
background: rgba(36, 36, 36, 0.92) !important;
|
||||
border-color: rgba(255, 255, 255, 0.08) !important;
|
||||
}
|
||||
|
||||
.tool-detail__tabs {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
padding: 0 14px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
display: inline-flex;
|
||||
gap: 2px;
|
||||
margin: 10px 12px 0;
|
||||
padding: 2px;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
.tool-detail__tab {
|
||||
margin-bottom: -1px;
|
||||
padding: 10px 0 8px;
|
||||
height: 24px;
|
||||
padding: 0 10px;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.2;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 24px;
|
||||
color: var(--td-text-color-secondary);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
.tool-detail__tab:hover {
|
||||
|
|
@ -247,20 +298,21 @@ onBeforeUnmount(() => { generation++; emit('busy', false) })
|
|||
.tool-detail__tab.is-active {
|
||||
color: var(--td-text-color-primary);
|
||||
font-weight: 500;
|
||||
border-bottom-color: var(--td-brand-color);
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.tool-detail__body {
|
||||
padding: 12px 14px 14px;
|
||||
padding: 10px 14px 14px;
|
||||
max-height: min(50vh, 360px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.tool-detail__desc {
|
||||
margin: 0;
|
||||
font-size: var(--app-text-sm);
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.65;
|
||||
color: var(--td-text-color-secondary);
|
||||
color: var(--td-text-color-primary);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package tools
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
|
|
@ -14,6 +15,7 @@ import (
|
|||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
mcpgo "github.com/mark3labs/mcp-go/mcp"
|
||||
sdkserver "github.com/mark3labs/mcp-go/server"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
|
@ -79,6 +81,78 @@ func (g oauthRetryTestGate) RequestOAuthAndWait(
|
|||
return approval.Decision{Approved: true}, nil
|
||||
}
|
||||
|
||||
// approvedOAuthGate requires approval for every call, approves it, and then
|
||||
// completes the OAuth prompt the way oauthRetryTestGate does.
|
||||
type approvedOAuthGate struct {
|
||||
oauthRetryTestGate
|
||||
oauthPrompts *int
|
||||
}
|
||||
|
||||
func (approvedOAuthGate) NeedsApproval(context.Context, uint64, string, string) bool { return true }
|
||||
|
||||
func (approvedOAuthGate) IsEnabled(context.Context, uint64, string, string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (approvedOAuthGate) RequestAndWait(context.Context, approval.PendingRequest) (approval.Decision, error) {
|
||||
return approval.Decision{Approved: true}, nil
|
||||
}
|
||||
|
||||
func (g approvedOAuthGate) RequestOAuthAndWait(
|
||||
ctx context.Context, req approval.OAuthPendingRequest,
|
||||
) (approval.Decision, error) {
|
||||
*g.oauthPrompts++
|
||||
return g.oauthRetryTestGate.RequestOAuthAndWait(ctx, req)
|
||||
}
|
||||
|
||||
// The approval step swaps in a ctx derived from ApprovalCtx; the OAuth prompt
|
||||
// must still be offered afterwards instead of failing with "open settings".
|
||||
func TestMCPToolOffersOAuthPromptAfterApproval(t *testing.T) {
|
||||
utils.SetSSRFWhitelistFromRaw("127.0.0.1")
|
||||
t.Cleanup(utils.ResetSSRFWhitelistForTest)
|
||||
mcpServer := sdkserver.NewMCPServer("test", "1")
|
||||
mcpServer.AddTool(mcpgo.NewTool("echo"),
|
||||
func(context.Context, mcpgo.CallToolRequest) (*mcpgo.CallToolResult, error) {
|
||||
return mcpgo.NewToolResultText("pong"), nil
|
||||
})
|
||||
server := httptest.NewServer(sdkserver.NewStreamableHTTPServer(mcpServer, sdkserver.WithStateLess(true)))
|
||||
t.Cleanup(server.Close)
|
||||
service := &types.MCPService{
|
||||
ID: "svc-approval",
|
||||
Name: "km",
|
||||
Enabled: true,
|
||||
TransportType: types.MCPTransportHTTPStreamable,
|
||||
URL: &server.URL,
|
||||
AuthConfig: &types.MCPAuthConfig{AuthType: types.MCPAuthOAuth},
|
||||
}
|
||||
repo := &oauthRetryTestRepo{clients: map[string]*types.MCPOAuthClient{}, tokens: map[string]*types.MCPOAuthToken{}}
|
||||
repo.registerClient(service.ID, "client-1")
|
||||
manager := mcp.NewMCPManager(repo)
|
||||
t.Cleanup(manager.Shutdown)
|
||||
|
||||
alice := types.Principal{Type: types.PrincipalWebUser, ID: "alice"}
|
||||
prompts := 0
|
||||
gate := approvedOAuthGate{
|
||||
oauthRetryTestGate: oauthRetryTestGate{authorized: func() { repo.saveToken(alice, service.ID) }},
|
||||
oauthPrompts: &prompts,
|
||||
}
|
||||
tool := NewMCPTool(service, &types.MCPTool{Name: "echo"}, manager, gate, 0)
|
||||
|
||||
base := ctxForOAuthRetryTest(alice)
|
||||
ctx := WithToolExecContext(base, &ToolExecContext{
|
||||
EventBus: event.NewEventBus(),
|
||||
ToolCallID: "call-1",
|
||||
UserID: alice.StorageID(),
|
||||
ApprovalCtx: base,
|
||||
ExecTimeout: 5 * time.Second,
|
||||
})
|
||||
result, err := tool.Execute(ctx, json.RawMessage(`{}`))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, prompts, "the OAuth prompt must be offered after approval")
|
||||
require.True(t, result.Success, result.Error)
|
||||
require.Contains(t, result.Output, "pong")
|
||||
}
|
||||
|
||||
func ctxForOAuthRetryTest(principal types.Principal) context.Context {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, oauthRetryTestTenant)
|
||||
return types.WithPrincipal(ctx, principal)
|
||||
|
|
|
|||
|
|
@ -166,9 +166,15 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too
|
|||
}, err
|
||||
}
|
||||
|
||||
// The post-approval ctx is derived from ApprovalCtx, which does not carry
|
||||
// the exec metadata; read it once here so the OAuth prompt still works
|
||||
// for tools that require approval.
|
||||
execMeta, _ := ToolExecFromContext(ctx)
|
||||
callWindowDerived := false
|
||||
|
||||
// Human approval gate for dangerous tools (issue #1173)
|
||||
if t.gate != nil {
|
||||
if meta, ok := ToolExecFromContext(ctx); ok && meta != nil && meta.EventBus != nil {
|
||||
if meta := execMeta; meta != nil && meta.EventBus != nil {
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
if t.gate.NeedsApproval(ctx, tenantID, t.service.ID, t.mcpTool.Name) {
|
||||
// Use ApprovalCtx (round-level ctx WITHOUT defaultToolExecTimeout) so
|
||||
|
|
@ -235,13 +241,14 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too
|
|||
freshCtx, freshCancel := context.WithTimeout(meta.ApprovalCtx, t.callToolTimeout(meta.ExecTimeout))
|
||||
defer freshCancel()
|
||||
ctx = freshCtx
|
||||
callWindowDerived = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
isStdio := t.service.TransportType == types.MCPTransportStdio
|
||||
meta, _ := ToolExecFromContext(ctx)
|
||||
meta := execMeta
|
||||
oauthSess := oauthSessionFromToolExec(ctx, meta).withAuthWaitTimeout(t.authWaitTimeoutSeconds)
|
||||
toolCallID := ""
|
||||
if meta != nil {
|
||||
|
|
@ -254,9 +261,8 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too
|
|||
// with a longer timeout were silently cancelled mid-flight even though the
|
||||
// transport layers honor the value. Re-derive the window from ApprovalCtx —
|
||||
// the round-level parent without the per-tool deadline. Skipped on the
|
||||
// post-approval path, which already re-derived its window above and whose
|
||||
// swapped ctx no longer carries the exec meta.
|
||||
if meta != nil && meta.ApprovalCtx != nil {
|
||||
// post-approval path, which already re-derived its window above.
|
||||
if !callWindowDerived && meta != nil && meta.ApprovalCtx != nil {
|
||||
callCtx, callCancel := context.WithTimeout(meta.ApprovalCtx, t.callToolTimeout(meta.ExecTimeout))
|
||||
defer callCancel()
|
||||
ctx = callCtx
|
||||
|
|
|
|||
Loading…
Reference in New Issue