fix(mcp): require schema discovery before calls and render tool results (#3113)

* fix(mcp): require schema discovery before calls and render tool results

* fix(mcp): keep proxy identity until describe and localize embed results

Listing still cached the target, so skipped describe showed as an mcp_* failure instead of the proxy error. Embed chat also lacked the new MCP strings.
main
lyingbug 2026-09-08 19:15:13 +08:00 committed by GitHub
parent 277d6ee851
commit 4d95cd4581
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
21 changed files with 742 additions and 27 deletions

View File

@ -14,7 +14,7 @@ Agent 的 MCP 主路径使用 `discover_mcp_tools` 和 `call_mcp_tool`,不再
{"mode":"list_tools","server_id":"目录中的服务ID","limit":20}
```
按返回的原始名称读取完整定义:
列表仅提供名称和摘要,以及读取定义的下一步提示,不返回可调用引用。按返回的原始名称读取完整定义:
```json
{"mode":"describe","server_id":"目录中的服务ID","tool_name":"get_order"}
@ -26,6 +26,8 @@ Agent 的 MCP 主路径使用 `discover_mcp_tools` 和 `call_mcp_tool`,不再
{"tool_ref":"describe 返回的引用","arguments":{"order_id":"123"}}
```
`arguments` 必须是符合目标 schema 的 JSON 对象,不能是 JSON 编码后的字符串。调用入口会检查当前 engine 是否已成功返回该引用对应的完整定义;仅列目录、读取其他工具或沿用未读取的新 schema 引用均不能执行。格式错误返回对象示例和读取定义的提示。
`search` 是限定单个服务的名称 / 描述子串匹配,可忽略大小写;不是 BM25 或跨语言语义检索。空结果时使用 `list_tools` 完整枚举,再精确 `describe`,工具可达性不依赖搜索排名。
## 目录、连接和权限
@ -59,6 +61,8 @@ MCP 参数使用完整 JSON Schema 校验,覆盖嵌套对象、数组、组合
`ToolCall.Name / Args / ID / ProviderMetadata` 保留模型原始调用,用于当前轮及跨轮回放。新增 `ToolCall.Target` 保存实际服务、工具名和内层参数,供界面和日志展示。实时事件使用目标名称,历史恢复也读取 target;不通过改写模型调用来实现展示。
聊天时间线为目录发现和代理调用提供专用名称、图标和结果展示:目录显示服务或工具摘要、分页数量与状态;定义显示参数、必填标记和可展开的完整 schema;代理入口失败显示错误信息。历史中仅存于 `output` 的目录 JSON 也可以解析展示,实际目标工具继续沿用 MCP 结果抽屉。
MCP schema 和外部返回值保持外部身份语义,不参与 WeKnora 知识库 ID 的改写。用户显式 @MCP 时,提示语指向目录读取,不再依赖初始请求中的原生 MCP 函数名前缀。
## 间接提示注入

View File

@ -330,6 +330,29 @@ const messages = {
"resumeFailed": "恢复执行失败,请重试",
"skipFailed": "跳过失败,请重试"
},
"mcp": {
"discoverTools": "发现 MCP 工具",
"listServers": "查看 MCP 服务",
"listTools": "查看 MCP 工具",
"searchTools": "搜索 MCP 工具",
"describeTool": "读取工具定义",
"callTool": "调用 MCP 工具",
"showing": "已显示 {count} / {total} 项",
"moreAvailable": "还有更多结果",
"required": "必填",
"fullSchema": "完整参数定义",
"failed": "MCP 操作失败",
"result": "执行结果",
"status": {
"not_loaded": "未加载",
"loading": "加载中",
"ready": "可用",
"needs_auth": "需要授权",
"error": "连接失败",
"disabled": "已禁用",
"unavailable": "不可用"
}
},
"tools": {
"searchKnowledge": "知识库检索",
"grepChunks": "搜索关键词",
@ -869,6 +892,29 @@ const messages = {
"resumeFailed": "再開に失敗しました。再試行してください。",
"skipFailed": "スキップに失敗しました。再試行してください。"
},
"mcp": {
"discoverTools": "MCP ツールを検出",
"listServers": "MCP サービス一覧",
"listTools": "MCP ツール一覧",
"searchTools": "MCP ツールを検索",
"describeTool": "ツール定義を確認",
"callTool": "MCP ツールを実行",
"showing": "{total} 件中 {count} 件を表示",
"moreAvailable": "他にも結果があります",
"required": "必須",
"fullSchema": "完全なパラメータ定義",
"failed": "MCP 操作に失敗しました",
"result": "実行結果",
"status": {
"not_loaded": "未読み込み",
"loading": "読み込み中",
"ready": "利用可能",
"needs_auth": "認証が必要",
"error": "接続失敗",
"disabled": "無効",
"unavailable": "利用不可"
}
},
"tools": {
"searchKnowledge": "ナレッジベース検索",
"grepChunks": "テキストパターン検索",
@ -1408,6 +1454,29 @@ const messages = {
"resumeFailed": "Failed to resume. Please try again.",
"skipFailed": "Failed to skip. Please try again."
},
"mcp": {
"discoverTools": "Discover MCP tools",
"listServers": "List MCP services",
"listTools": "List MCP tools",
"searchTools": "Search MCP tools",
"describeTool": "Read tool definition",
"callTool": "Call MCP tool",
"showing": "Showing {count} of {total}",
"moreAvailable": "More results available",
"required": "Required",
"fullSchema": "Full parameter definition",
"failed": "MCP operation failed",
"result": "Result",
"status": {
"not_loaded": "Not loaded",
"loading": "Loading",
"ready": "Ready",
"needs_auth": "Authorization required",
"error": "Connection failed",
"disabled": "Disabled",
"unavailable": "Unavailable"
}
},
"tools": {
"searchKnowledge": "Knowledge Search",
"grepChunks": "Text Pattern Search",
@ -1731,6 +1800,29 @@ const koEmbedPublish = {
resumeFailed: '실행 재개 실패, 다시 시도하세요',
skipFailed: '건너뛰기 실패, 다시 시도하세요',
},
mcp: {
discoverTools: 'MCP 도구 탐색',
listServers: 'MCP 서비스 목록',
listTools: 'MCP 도구 목록',
searchTools: 'MCP 도구 검색',
describeTool: '도구 정의 읽기',
callTool: 'MCP 도구 호출',
showing: '{total}개 중 {count}개 표시',
moreAvailable: '결과가 더 있습니다',
required: '필수',
fullSchema: '전체 매개변수 정의',
failed: 'MCP 작업 실패',
result: '실행 결과',
status: {
not_loaded: '로드되지 않음',
loading: '로드 중',
ready: '사용 가능',
needs_auth: '인증 필요',
error: '연결 실패',
disabled: '비활성화됨',
unavailable: '사용 불가',
},
},
},
} as const
@ -1822,6 +1914,29 @@ const ruEmbedPublish = {
resumeFailed: 'Не удалось возобновить выполнение, повторите попытку',
skipFailed: 'Не удалось пропустить, повторите попытку',
},
mcp: {
discoverTools: 'Поиск инструментов MCP',
listServers: 'Сервисы MCP',
listTools: 'Инструменты MCP',
searchTools: 'Поиск инструментов MCP',
describeTool: 'Чтение определения инструмента',
callTool: 'Вызов инструмента MCP',
showing: 'Показано {count} из {total}',
moreAvailable: 'Есть другие результаты',
required: 'Обязательно',
fullSchema: 'Полное описание параметров',
failed: 'Ошибка операции MCP',
result: 'Результат',
status: {
not_loaded: 'Не загружено',
loading: 'Загрузка',
ready: 'Доступно',
needs_auth: 'Требуется авторизация',
error: 'Ошибка подключения',
disabled: 'Отключено',
unavailable: 'Недоступно',
},
},
},
} as const

View File

@ -5605,6 +5605,29 @@ export default {
searchingMixedWithQuery: 'Searching knowledge base and web: "{query}"',
searchDone: 'Search complete'
},
mcp: {
discoverTools: "Discover MCP tools",
listServers: "List MCP services",
listTools: "List MCP tools",
searchTools: "Search MCP tools",
describeTool: "Read tool definition",
callTool: "Call MCP tool",
showing: "Showing {count} of {total}",
moreAvailable: "More results available",
required: "Required",
fullSchema: "Full parameter definition",
failed: "MCP operation failed",
result: "Result",
status: {
not_loaded: "Not loaded",
loading: "Loading",
ready: "Ready",
needs_auth: "Authorization required",
error: "Connection failed",
disabled: "Disabled",
unavailable: "Unavailable",
},
},
toolStatus: {
calling: 'Calling {name}...',
searchKb: 'Searching knowledge base',

View File

@ -5605,6 +5605,29 @@ export default {
searchingMixedWithQuery: 'ナレッジベースとWebを検索中:「{query}」',
searchDone: '検索完了'
},
mcp: {
discoverTools: "MCP ツールを検出",
listServers: "MCP サービス一覧",
listTools: "MCP ツール一覧",
searchTools: "MCP ツールを検索",
describeTool: "ツール定義を確認",
callTool: "MCP ツールを実行",
showing: "{total} 件中 {count} 件を表示",
moreAvailable: "他にも結果があります",
required: "必須",
fullSchema: "完全なパラメータ定義",
failed: "MCP 操作に失敗しました",
result: "実行結果",
status: {
not_loaded: "未読み込み",
loading: "読み込み中",
ready: "利用可能",
needs_auth: "認証が必要",
error: "接続失敗",
disabled: "無効",
unavailable: "利用不可",
},
},
toolStatus: {
calling: '{name}を呼び出し中...',
searchKb: 'ナレッジベースを検索',

View File

@ -1231,6 +1231,29 @@ export default {
success: '클립보드에 복사되었습니다',
failed: '복사 실패, 수동으로 복사하세요'
},
mcp: {
discoverTools: "MCP 도구 탐색",
listServers: "MCP 서비스 목록",
listTools: "MCP 도구 목록",
searchTools: "MCP 도구 검색",
describeTool: "도구 정의 읽기",
callTool: "MCP 도구 호출",
showing: "{total}개 중 {count}개 표시",
moreAvailable: "결과가 더 있습니다",
required: "필수",
fullSchema: "전체 매개변수 정의",
failed: "MCP 작업 실패",
result: "실행 결과",
status: {
not_loaded: "로드되지 않음",
loading: "로드 중",
ready: "사용 가능",
needs_auth: "인증 필요",
error: "연결 실패",
disabled: "비활성화됨",
unavailable: "사용 불가",
},
},
toolStatus: {
calling: '{name} 호출 중...',
searchKb: '지식베이스 검색',

View File

@ -1231,6 +1231,29 @@ export default {
success: 'Скопировано в буфер обмена',
failed: 'Ошибка копирования, скопируйте вручную'
},
mcp: {
discoverTools: "Поиск инструментов MCP",
listServers: "Сервисы MCP",
listTools: "Инструменты MCP",
searchTools: "Поиск инструментов MCP",
describeTool: "Чтение определения инструмента",
callTool: "Вызов инструмента MCP",
showing: "Показано {count} из {total}",
moreAvailable: "Есть другие результаты",
required: "Обязательно",
fullSchema: "Полное описание параметров",
failed: "Ошибка операции MCP",
result: "Результат",
status: {
not_loaded: "Не загружено",
loading: "Загрузка",
ready: "Доступно",
needs_auth: "Требуется авторизация",
error: "Ошибка подключения",
disabled: "Отключено",
unavailable: "Недоступно",
},
},
toolStatus: {
calling: 'Вызов {name}...',
searchKb: 'Поиск по базе знаний',

View File

@ -1233,6 +1233,29 @@ export default {
success: '已复制到剪贴板',
failed: '复制失败,请手动复制'
},
mcp: {
discoverTools: "发现 MCP 工具",
listServers: "查看 MCP 服务",
listTools: "查看 MCP 工具",
searchTools: "搜索 MCP 工具",
describeTool: "读取工具定义",
callTool: "调用 MCP 工具",
showing: "已显示 {count} / {total} 项",
moreAvailable: "还有更多结果",
required: "必填",
fullSchema: "完整参数定义",
failed: "MCP 操作失败",
result: "执行结果",
status: {
not_loaded: "未加载",
loading: "加载中",
ready: "可用",
needs_auth: "需要授权",
error: "连接失败",
disabled: "已禁用",
unavailable: "不可用",
},
},
toolStatus: {
calling: '正在调用 {name}...',
searchKb: '检索知识库',

View File

@ -30,7 +30,9 @@ export type DisplayType =
| 'list_sandbox_files'
| 'write_sandbox_file'
| 'edit_sandbox_file'
| 'read_skill';
| 'read_skill'
| 'mcp_discovery'
| 'mcp_call';
// Search result item
export interface SearchResultItem {

View File

@ -36,7 +36,10 @@ export function getAgentToolIconName(
if (toolName === 'attachment_parsing') {
return 'attach'
}
if (toolName.startsWith('mcp_')) {
if (toolName === 'discover_mcp_tools') {
return 'search'
}
if (toolName === 'call_mcp_tool' || toolName.startsWith('mcp_')) {
return 'terminal'
}
if (toolName === 'shell_exec') {

View File

@ -0,0 +1,53 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { ComposerTranslation } from 'vue-i18n'
import { getMcpToolDisplayType, getMcpToolTitle, mcpDiscoveryRows, mcpSchemaParameters, parseMcpDiscovery, mcpToolResultOutput } from './mcpToolDisplay'
import { getAgentToolIconName } from './agent-tool-icons'
const t = ((key: string, params?: Record<string, unknown>) => `${key}${params?.name ? ` ${params.name}` : ''}`) as ComposerTranslation
test('MCP proxies have dedicated renderers and icons', () => {
assert.equal(getMcpToolDisplayType('discover_mcp_tools'), 'mcp_discovery')
assert.equal(getMcpToolDisplayType('call_mcp_tool'), 'mcp_call')
assert.equal(getMcpToolDisplayType('mcp_orders_lookup'), undefined) // Existing target reference drawer.
assert.equal(getAgentToolIconName('discover_mcp_tools'), 'search')
assert.equal(getAgentToolIconName('call_mcp_tool'), 'terminal')
})
test('old output-only discovery and schema records remain readable', () => {
const data = parseMcpDiscovery(JSON.stringify({ mode: 'list_tools', tools: [{ name: 'get_log', tool_ref: 'legacy', description: 'Logs' }], total: 2, has_more: true }))
assert.deepEqual(mcpDiscoveryRows(data), [{ name: 'get_log', description: 'Logs', status: '' }])
const output = JSON.stringify({ name: 'get_log', input_schema: { type: 'object' } })
assert.equal(getMcpToolTitle(t, { tool_name: 'discover_mcp_tools', output }), 'agentStream.mcp.describeTool:get_log')
assert.deepEqual(parseMcpDiscovery('Parameter validation failed'), {})
assert.deepEqual(mcpDiscoveryRows({ tools: [null, 'broken', { name: 'valid' }] }), [{ name: 'valid', description: '', status: '' }])
const listed = JSON.stringify({ mode: 'list_tools', tools: [{ name: 'get_log' }], total: 1 })
const liveEnvelope = { tool_name: 'discover_mcp_tools', success: true, output: listed, error: '', duration_ms: 12, tool_call_id: 'x' }
assert.deepEqual(mcpDiscoveryRows(parseMcpDiscovery(listed, liveEnvelope)), [{ name: 'get_log', description: '', status: '' }])
assert.equal(getMcpToolTitle(t, { tool_name: 'discover_mcp_tools', output: listed, tool_data: liveEnvelope }), 'agentStream.mcp.listTools')
})
test('schema preview preserves required and union types without inferring undocumented requirements', () => {
assert.deepEqual(mcpSchemaParameters({ type: 'object', required: ['start_time'], properties: {
start_time: { type: 'string', description: 'Start time' },
limit: { anyOf: [{ type: 'integer' }, { type: 'null' }] },
flag: { type: ['boolean', 'null'] },
} }), [
{ name: 'start_time', type: 'string', required: true, description: 'Start time' },
{ name: 'limit', type: 'integer | null', required: false, description: '' },
{ name: 'flag', type: 'boolean | null', required: false, description: '' },
])
assert.deepEqual(mcpSchemaParameters(false), [])
})
test('mode-aware titles handle pending and failed proxy events', () => {
for (const [mode, suffix] of Object.entries({ list_servers: 'listServers', list_tools: 'listTools', search: 'searchTools', describe: 'describeTool' })) {
const event = { tool_name: 'discover_mcp_tools', arguments: { mode } }
assert.equal(getMcpToolTitle(t, event), `agentStream.mcp.${suffix}`)
assert.match(getMcpToolTitle(t, { ...event, pending: true }), /^agentStream.toolStatus.calling /)
}
assert.equal(getMcpToolTitle(t, { tool_name: 'call_mcp_tool', success: false }), 'agentStream.toolStatus.calledFailed agentStream.mcp.callTool')
assert.equal(mcpToolResultOutput({ tool_name: 'call_mcp_tool', error: 'arguments must be an object' }), 'arguments must be an object')
assert.equal(mcpToolResultOutput({ tool_name: 'shell_exec', error: 'exited 1' }), undefined)
assert.equal(mcpToolResultOutput({ tool_name: 'shell_exec', output: 'ok', error: 'exited 1' }), 'ok')
})

View File

@ -0,0 +1,94 @@
import type { ComposerTranslation } from 'vue-i18n'
const discoveryFields = [
'mode', 'servers', 'tools', 'total', 'has_more', 'next_cursor', 'next_step',
'notice', 'status', 'name', 'description', 'input_schema', 'tool_ref', 'server_id',
] as const
function record(value: unknown): Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown> : {}
}
function discoveryOverlay(data?: unknown): Record<string, unknown> {
const extra = record(data)
const overlay: Record<string, unknown> = {}
for (const key of discoveryFields) {
if (key in extra) overlay[key] = extra[key]
}
return overlay
}
// Discovery historically stored its complete JSON in output, without tool_data.
// Live SSE copies the whole event envelope onto tool_data; only merge catalog fields.
export function parseMcpDiscovery(output?: string, data?: unknown): Record<string, unknown> {
let parsed = {}
try { parsed = record(JSON.parse(output || '')) } catch { /* Error or truncated historical output. */ }
return { ...parsed, ...discoveryOverlay(data) }
}
export function mcpDiscoveryRows(data: Record<string, unknown>) {
const source = data.mode === 'list_servers' ? data.servers : data.tools
if (!Array.isArray(source)) return []
return source.flatMap((value) => {
const row = record(value)
if (typeof row.name !== 'string') return []
return [{
name: row.name,
description: typeof row.description === 'string' ? row.description : '',
status: typeof row.status === 'string' ? row.status : '',
}]
})
}
export function mcpSchemaParameters(schema: unknown) {
const definition = record(schema)
const required = Array.isArray(definition.required) ? definition.required : []
return Object.entries(record(definition.properties)).map(([name, value]) => {
const property = record(value)
const type = property.type
const variants = property.anyOf || property.oneOf
const types = Array.isArray(variants) ? variants.flatMap((variant) => {
const type = record(variant).type
return typeof type === 'string' ? [type] : []
}) : []
return {
name,
type: typeof type === 'string' ? type : Array.isArray(type) ? type.join(' | ') : types.join(' | '),
required: required.includes(name),
description: typeof property.description === 'string' ? property.description : '',
}
})
}
export function getMcpToolDisplayType(toolName?: string): 'mcp_discovery' | 'mcp_call' | undefined {
if (toolName === 'discover_mcp_tools') return 'mcp_discovery'
if (toolName === 'call_mcp_tool') return 'mcp_call'
return undefined
}
export function mcpToolResultOutput(event: { tool_name?: string; output?: string; error?: string }): string | undefined {
if (!getMcpToolDisplayType(event.tool_name)) return event.output
return event.output || event.error
}
export function getMcpToolTitle(t: ComposerTranslation, event: {
tool_name?: string; arguments?: unknown; output?: string; tool_data?: unknown; pending?: boolean; success?: boolean
}): string {
if (!getMcpToolDisplayType(event.tool_name)) return ''
const data = parseMcpDiscovery(event.output, event.tool_data)
const args = typeof event.arguments === 'string' ? parseMcpDiscovery(event.arguments) : record(event.arguments)
const mode = data.mode || args.mode || ('input_schema' in data ? 'describe' : '')
const keys: Record<string, string> = {
list_servers: 'agentStream.mcp.listServers',
list_tools: 'agentStream.mcp.listTools',
search: 'agentStream.mcp.searchTools',
describe: 'agentStream.mcp.describeTool',
}
const label = t(event.tool_name === 'call_mcp_tool' ? 'agentStream.mcp.callTool' : keys[String(mode)] || 'agentStream.mcp.discoverTools')
const name = mode === 'describe' ? data.name || args.tool_name : ''
const title = name && typeof name === 'string' ? `${label}:${name}` : label
if (event.pending) return t('agentStream.toolStatus.calling', { name: title })
if (event.success === false) return t('agentStream.toolStatus.calledFailed', { name: title })
return title
}

View File

@ -212,7 +212,7 @@
class="action-details">
<div v-if="resolveToolDisplayType(event)" class="tool-result-wrapper">
<ToolResultRenderer :display-type="resolveToolDisplayType(event)" :tool-data="event.tool_data"
:output="event.output" :arguments="event.arguments" />
:output="mcpToolResultOutput(event)" :arguments="event.arguments" :success="event.success" />
</div>
<div v-else-if="event.output" class="tool-output-wrapper">
<div class="fallback-header">
@ -501,7 +501,7 @@
class="action-details">
<div v-if="resolveToolDisplayType(event)" class="tool-result-wrapper">
<ToolResultRenderer :display-type="resolveToolDisplayType(event)" :tool-data="event.tool_data"
:output="event.output" :arguments="event.arguments" />
:output="mcpToolResultOutput(event)" :arguments="event.arguments" :success="event.success" />
</div>
<div v-else-if="event.output" class="tool-output-wrapper">
@ -626,6 +626,7 @@ import {
import type { ProtectedFileAccessContext } from '@/utils/protectedFileAccess';
import { unwrapFinalAnswerWrappers, thinkingEqualsAnswer } from '@/utils/finalAnswer';
import { getAgentToolIconName } from '@/utils/agent-tool-icons';
import { getMcpToolDisplayType, getMcpToolTitle, mcpToolResultOutput } from '@/utils/mcpToolDisplay';
import { getQueryText, getWikiPageText } from '@/utils/agent-tool-display';
import {
formatToolTitleWithDetail,
@ -677,6 +678,8 @@ const { t } = useI18n();
ensureMermaidInitialized();
const TOOL_NAME_KEYS: Record<string, string> = {
discover_mcp_tools: 'agentStream.mcp.discoverTools',
call_mcp_tool: 'agentStream.mcp.callTool',
search_knowledge: 'agentStream.tools.searchKnowledge',
knowledge_search: 'agentStream.tools.searchKnowledge',
grep_chunks: 'agentStream.tools.grepChunks',
@ -1157,6 +1160,8 @@ const formatToolResultContent = (value: unknown): string => {
const isMcpTool = (toolName?: string | null): boolean => String(toolName || '').startsWith('mcp_');
const resolveToolDisplayType = (event: any): DisplayType | undefined => {
const mcpType = getMcpToolDisplayType(event?.tool_name)
if (mcpType) return mcpType
if (event?.display_type) return event.display_type as DisplayType
if (event?.tool_name === 'shell_exec' || event?.tool_name === 'execute_skill_script') {
return 'shell_exec'
@ -2802,6 +2807,8 @@ const getAttachmentParsingSummary = (event: any): string => {
// Get tool title - prefer summary over description, add query for search tools
const getToolTitle = (event: any): string => {
const mcpTitle = getMcpToolTitle(t, event)
if (mcpTitle) return mcpTitle
if (event.pending) {
if (event.tool_name === 'image_analysis') {
return t('agentStream.toolStatus.imageAnalyzing');

View File

@ -0,0 +1,83 @@
import assert from 'node:assert/strict'
import { after, before, test } from 'node:test'
import { fileURLToPath } from 'node:url'
import { createServer, type ViteDevServer } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSSRApp, h, type Component } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { createI18n } from 'vue-i18n'
import en from '../../../i18n/locales/en-US'
let server: ViteDevServer
let Renderer: Component
before(async () => {
server = await createServer({
configFile: false, optimizeDeps: { noDiscovery: true, entries: [] }, plugins: [
{
name: 'isolate-mcp-renderer',
enforce: 'pre',
load(id) {
// Unused result components depend on browser-only app services.
// Keep the real renderer, MCP component and shared result rows.
if (id.endsWith('.vue') && !['ToolResultRenderer.vue', 'McpToolResult.vue', 'ResultRow.vue'].some((name) => id.endsWith(`/${name}`))) {
return '<template><div /></template>'
}
},
},
vue(),
],
resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
server: { middlewareMode: true }, appType: 'custom',
})
Renderer = (await server.ssrLoadModule('/src/views/chat/components/ToolResultRenderer.vue')).default
})
after(async () => { await server?.close() })
async function render(props: Record<string, unknown>) {
const app = createSSRApp({ render: () => h(Renderer, props) })
app.use(createI18n({ legacy: false, locale: 'en-US', messages: { 'en-US': en } }))
app.component('t-icon', { render: () => h('span') })
app.component('t-popup', { render: () => h('span') })
return renderToString(app)
}
test('discovery renders tool rows instead of raw metadata, including old history', async () => {
const html = await render({ displayType: 'mcp_discovery', success: true, output: JSON.stringify({
mode: 'list_tools', tools: [{ name: 'get_log', description: '<script>alert(1)</script>', tool_ref: 'mcpt_old' }],
total: 3, has_more: true, notice: 'external',
}) })
assert.match(html, /get_log/)
assert.match(html, /Showing 1 of 3/)
assert.match(html, /More results available/)
assert.match(html, /&lt;script&gt;/)
assert.doesNotMatch(html, /fallback-output|mcpt_old|<script>/)
})
test('definition renders parameters and expandable complete schema', async () => {
const html = await render({ displayType: 'mcp_discovery', output: JSON.stringify({
name: 'get_log', input_schema: { type: 'object', required: ['start_time'], properties: { start_time: { type: 'string' } } },
}) })
assert.match(html, /start_time/)
assert.match(html, /Required/)
assert.match(html, /<details/)
assert.match(html, /Full parameter definition/)
assert.doesNotMatch(html, /fallback-output/)
})
test('proxy validation errors and empty service lists use dedicated views', async () => {
const error = await render({ displayType: 'mcp_call', success: false, output: 'arguments must be an object' })
assert.match(error, /role="alert"/)
assert.match(error, /arguments must be an object/)
assert.doesNotMatch(error, /fallback-output/)
const empty = await render({ displayType: 'mcp_discovery', output: '{"mode":"list_servers","total":0,"has_more":false}' })
assert.match(empty, /Showing 0 of 0/)
assert.doesNotMatch(empty, /fallback-output/)
const live = await render({
displayType: 'mcp_discovery',
success: true,
output: JSON.stringify({ mode: 'list_tools', tools: [{ name: 'get_log' }], total: 1 }),
toolData: { tool_name: 'discover_mcp_tools', success: true, output: '{"mode":"list_tools"}', error: '' },
})
assert.match(live, /get_log/)
assert.doesNotMatch(live, /fallback-output/)
})

View File

@ -68,6 +68,12 @@
:data="toolData as ReadSkillData"
/>
<McpToolResult
v-else-if="displayType === 'mcp_discovery' || displayType === 'mcp_call'"
:discovery="displayType === 'mcp_discovery'" :data="toolData"
:output="output" :arguments="toolArguments" :success="success"
/>
<!-- Fallback: Display raw output -->
<div v-else class="fallback-output">
<div class="fallback-header">
@ -122,15 +128,17 @@ import ShellExecResult from './tool-results/ShellExecResult.vue';
import SandboxFilesResult from './tool-results/SandboxFilesResult.vue';
import WriteSandboxFileResult from './tool-results/WriteSandboxFileResult.vue';
import ReadSkillResult from './tool-results/ReadSkillResult.vue';
import McpToolResult from './tool-results/McpToolResult.vue';
interface Props {
success?: boolean;
displayType?: DisplayType;
toolData?: Record<string, any>;
output?: string;
arguments?: Record<string, any>;
}
const props = defineProps<Props>();
const props = withDefaults(defineProps<Props>(), { success: undefined });
const displayType = computed(() => props.displayType);
const toolData = computed(() => props.toolData || {});

View File

@ -0,0 +1,88 @@
<template>
<div class="mcp-result">
<div v-if="success === false" class="mcp-error" role="alert">
<t-icon name="error-circle" />
<pre>{{ output || $t('agentStream.mcp.failed') }}</pre>
</div>
<template v-else-if="discovery && isDiscoveryResult">
<div v-if="mode !== 'describe'" class="mcp-summary">
{{ $t('agentStream.mcp.showing', { count: rows.length, total: total }) }}
<span v-if="data.has_more === true"> · {{ $t('agentStream.mcp.moreAvailable') }}</span>
</div>
<div v-for="(row, index) in rows" :key="index" class="mcp-entry">
<ResultRow :index="index + 1" :title="row.name" :meta="statusLabel(row.status)"
:popup-key="index" :show-popup="false" />
<p v-if="row.description" class="mcp-description">{{ row.description }}</p>
</div>
<template v-if="mode === 'describe'">
<p v-if="description" class="mcp-description">{{ description }}</p>
<div v-if="parameters.length" class="mcp-parameters">
<div v-for="parameter in parameters" :key="parameter.name" class="mcp-parameter">
<div class="mcp-parameter-title">
<code>{{ parameter.name }}</code>
<span>{{ parameter.type }}</span>
<span v-if="parameter.required" class="mcp-required">{{ $t('agentStream.mcp.required') }}</span>
</div>
<p v-if="parameter.description">{{ parameter.description }}</p>
</div>
</div>
<details v-if="data.input_schema !== undefined" class="mcp-definition">
<summary>{{ $t('agentStream.mcp.fullSchema') }}</summary>
<pre>{{ JSON.stringify(data.input_schema, null, 2) }}</pre>
</details>
</template>
</template>
<div v-else class="mcp-output">
<div class="mcp-summary">{{ $t('agentStream.mcp.result') }}</div>
<pre>{{ output }}</pre>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { mcpDiscoveryRows, mcpSchemaParameters, parseMcpDiscovery } from '@/utils/mcpToolDisplay'
import ResultRow from './ResultRow.vue'
const props = withDefaults(defineProps<{
discovery: boolean
output: string
data?: Record<string, unknown>
arguments?: Record<string, unknown>
success?: boolean
}>(), { success: undefined })
const { t, te } = useI18n()
const data = computed(() => parseMcpDiscovery(props.output, props.data))
const mode = computed(() => data.value.mode || props.arguments?.mode || ('input_schema' in data.value ? 'describe' : ''))
const isDiscoveryResult = computed(() => Array.isArray(data.value.servers) || Array.isArray(data.value.tools) ||
typeof data.value.total === 'number' || 'input_schema' in data.value)
const rows = computed(() => mcpDiscoveryRows({ ...data.value, mode: mode.value }))
const total = computed(() => typeof data.value.total === 'number' ? data.value.total : rows.value.length)
const parameters = computed(() => mcpSchemaParameters(data.value.input_schema))
const description = computed(() => typeof data.value.description === 'string' ? data.value.description : '')
const statusLabel = (status: string) => {
if (!status) return ''
const key = `agentStream.mcp.status.${status}`
return te(key) ? t(key) : status
}
</script>
<style lang="less" scoped>
.mcp-result { min-width: 0; font-size: 12px; color: var(--td-text-color-primary); }
.mcp-summary { margin-bottom: 8px; color: var(--td-text-color-secondary); }
.mcp-entry + .mcp-entry { margin-top: 8px; }
.mcp-description { margin: 4px 8px; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--td-text-color-secondary); line-height: 1.6; }
.mcp-parameters { margin-top: 10px; border: 1px solid var(--td-component-stroke); border-radius: 6px; overflow: hidden; }
.mcp-parameter { padding: 8px 12px; }
.mcp-parameter + .mcp-parameter { border-top: 1px solid var(--td-component-stroke); }
.mcp-parameter-title { display: flex; flex-wrap: wrap; gap: 8px; overflow-wrap: anywhere; }
.mcp-parameter-title span { color: var(--td-text-color-secondary); }
.mcp-parameter-title .mcp-required { color: var(--td-brand-color); }
.mcp-parameter p { margin: 4px 0 0; color: var(--td-text-color-secondary); white-space: pre-wrap; overflow-wrap: anywhere; }
.mcp-definition { margin-top: 10px; }
.mcp-definition summary { cursor: pointer; color: var(--td-text-color-secondary); }
pre { margin: 8px 0 0; padding: 10px 12px; background: var(--td-bg-color-secondarycontainer); border-radius: 6px; font: 12px/1.6 var(--app-font-family-mono); white-space: pre-wrap; overflow-wrap: anywhere; max-height: 320px; overflow: auto; }
.mcp-error { display: flex; align-items: flex-start; gap: 8px; color: var(--td-error-color); }
.mcp-error pre { margin: 0; flex: 1; min-width: 0; }
</style>

View File

@ -89,7 +89,11 @@ func TestAgentMCPProxyKeepsTargetEventsAndProtocolHistory(t *testing.T) {
"tool_name": "get_order"
}`)
require.True(t, definition.Result.Success, definition.Result.Error)
raw, _ := json.Marshal(map[string]any{"tool_ref": page.Tools[0].ToolRef, "arguments": map[string]any{"id": "42"}})
var described struct {
ToolRef string `json:"tool_ref"`
}
require.NoError(t, json.Unmarshal([]byte(definition.Result.Output), &described))
raw, _ := json.Marshal(map[string]any{"tool_ref": described.ToolRef, "arguments": map[string]any{"id": "42"}})
call := run("model-proxy-id", agenttools.ToolCallMCPTool, string(raw))
require.True(t, call.Result.Success, call.Result.Error)
require.Equal(t, agenttools.ToolCallMCPTool, call.Name)

View File

@ -19,7 +19,8 @@ import (
const mcpDiscoveryDescription = "" +
"Discover authorized MCP tools without loading every schema. Start with list_servers, then " +
"list_tools for a server, then describe an exact tool. Server IDs and tool names must come " +
"from this directory. Call call_mcp_tool with the returned tool_ref and arguments matching " +
"from this directory. Only describe returns a callable tool_ref. Call call_mcp_tool with that " +
"tool_ref and arguments matching " +
"input_schema. Follow next_cursor until has_more is false; an empty page does not mean a " +
"capability is unconfigured when a server is unavailable. Search is an optional case- " +
"insensitive substring filter on names and descriptions within one server; if it misses, " +
@ -70,9 +71,12 @@ const mcpCallSchema = `{
"type": "object",
"properties": {
"tool_ref": {
"description": "Reference returned by a successful describe of the exact tool in this engine.",
"type": "string"
},
"arguments": {
"description": "Original tool parameters as a JSON object matching input_schema, never a JSON-encoded string.",
"examples": [{"order_id": "123"}],
"type": "object"
}
},
@ -82,6 +86,11 @@ const mcpCallSchema = `{
],
"additionalProperties": false
}`
const mcpCallArgumentsHint = ` Read the tool with discover_mcp_tools(mode="describe", ` +
`server_id=..., tool_name=...) first. Use its tool_ref and pass arguments as a JSON object, ` +
`not a JSON-encoded string; for example ` +
`{"tool_ref":"<describe reference>","arguments":{"order_id":"123"}} (use the actual input_schema fields).`
const maxMCPDefinitionChars = 256 * 1024
// mcpExternalDataNotice keeps the trust boundary that the per-tool
@ -111,6 +120,7 @@ type MCPCatalog struct {
principal string
oauthPrincipal string
servers map[string]*mcpCatalogServer
described sync.Map // Definition references successfully returned by describe in this engine.
load mcpCatalogLoader
lookup MCPServiceLookup
gate approval.MCPApproval
@ -131,7 +141,7 @@ type mcpServerSummary struct {
Status string `json:"status"`
}
type mcpToolSummary struct {
ToolRef string `json:"tool_ref"`
ToolRef string `json:"tool_ref,omitempty"`
ServerID string `json:"server_id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
@ -147,6 +157,7 @@ type mcpDiscoveryArgs struct {
}
type mcpDiscoveryPage struct {
Mode string `json:"mode"`
NextStep string `json:"next_step,omitempty"`
Notice string `json:"notice,omitempty"`
Servers []mcpServerSummary `json:"servers,omitempty"`
Tools []mcpToolSummary `json:"tools,omitempty"`
@ -317,6 +328,11 @@ func mcpToolRef(tool *MCPTool) string {
return "mcpt_" + hex.EncodeToString(sum[:])
}
func (c *MCPCatalog) describedRef(ref string) bool {
_, ok := c.described.Load(ref)
return ok
}
func shortMCPDescription(s string) string {
runes := []rune(s)
if len(runes) > 200 {
@ -398,8 +414,9 @@ func installMCPCatalog(registry *ToolRegistry, c *MCPCatalog) {
BaseTool: NewBaseTool(
ToolCallMCPTool,
"Call an authorized MCP tool using tool_ref returned by discover_mcp_tools. Read its "+
"full input_schema with describe before calling. Pass the original tool arguments in "+
"arguments. Discovery does not bypass approval or permissions.",
"full input_schema with describe before calling; listing does not enable execution. "+
"Pass the original tool arguments in arguments as a JSON object, never a JSON-encoded string. "+
"Discovery does not bypass approval or permissions.",
json.RawMessage(mcpCallSchema),
),
catalog: c,
@ -521,6 +538,9 @@ func (t *MCPDiscoverTool) Execute(ctx context.Context, raw json.RawMessage) (*ty
"error",
)
}
if err == nil && result != nil && result.Success {
t.catalog.described.Store(mcpToolRef(tool), true)
}
return result, err
}
if args.Mode == "search" &&
@ -554,6 +574,9 @@ func paginateMCP(ctx context.Context, page mcpDiscoveryPage, args mcpDiscoveryAr
// actually present: list_servers returns locally configured service names.
if args.Mode != "list_servers" {
page.Notice = mcpExternalDataNotice
page.NextStep = `Choose a tool, then use discover_mcp_tools(mode="describe", ` +
`server_id=<its server_id>, tool_name=<its name>) to read the full input_schema and obtain ` +
`a callable tool_ref. Do not call from this summary.`
}
// Service order is by ID. Operational state and editable display metadata
// do not change membership and must not invalidate an in-progress traversal.
@ -606,7 +629,12 @@ func paginateMCP(ctx context.Context, page mcpDiscoveryPage, args mcpDiscoveryAr
if args.Mode == "list_servers" {
resultPage.Servers = page.Servers[start:end]
} else {
resultPage.Tools = page.Tools[start:end]
// Retain definition refs internally for cursor invalidation, but only
// describe exposes callable refs to the model. Copy before clearing.
resultPage.Tools = append([]mcpToolSummary(nil), page.Tools[start:end]...)
for i := range resultPage.Tools {
resultPage.Tools[i].ToolRef = ""
}
}
result, err := mcpJSONResult(resultPage)
if err != nil || !result.Success {
@ -633,7 +661,7 @@ func decodeMCPCall(raw json.RawMessage) (string, json.RawMessage, error) {
var object map[string]any
if args.ToolRef == "" || len(args.Arguments) == 0 || json.Unmarshal(args.Arguments, &object) != nil ||
object == nil {
return "", nil, fmt.Errorf("tool_ref and an arguments object are required")
return "", nil, fmt.Errorf("tool_ref and an arguments object are required.%s", mcpCallArgumentsHint)
}
return args.ToolRef, args.Arguments, nil
}
@ -681,6 +709,13 @@ func (t *MCPCallTool) resolve(ctx context.Context, raw json.RawMessage) (*MCPToo
if err := t.catalog.checkEnabled(ctx, tool); err != nil {
return nil, nil, err
}
if !t.catalog.describedRef(ref) {
return nil, nil, fmt.Errorf(
"tool schema has not been described; use discover_mcp_tools(mode=\"describe\", "+
"server_id=%q, tool_name=%q) before calling",
tool.service.ID, tool.mcpTool.Name,
)
}
return tool, args, nil
}
}
@ -717,7 +752,9 @@ func (r *ToolRegistry) MCPCallTarget(ctx context.Context, name string, raw json.
return nil
}
tool := proxy.catalog.cachedTool(ref)
if tool == nil {
if tool == nil || !proxy.catalog.describedRef(ref) {
// Listing caches the target, but presentation must stay on call_mcp_tool
// until describe has returned this exact schema reference.
return nil
}
var input map[string]any

View File

@ -90,6 +90,25 @@ func TestMCPProxyHTTPApprovalArgumentsAndImages(t *testing.T) {
require.Len(t, page.Tools, 1)
require.Positive(t, requests.Load())
require.Zero(t, calls.Load())
// Listing loads the target, but must not allow execution or approval yet.
discovery, _ := registry.GetTool(ToolDiscoverMCPTools)
snapshot, _, err := discovery.(*MCPDiscoverTool).catalog.snapshot(ctx, service.ID, false)
require.NoError(t, err)
premature, _ := json.Marshal(map[string]any{
"tool_ref": mcpToolRef(snapshot[0]), "arguments": map[string]any{"count": 2},
})
blocked, err := registry.ExecuteTool(ctx, ToolCallMCPTool, premature)
require.NoError(t, err)
require.False(t, blocked.Success)
require.Contains(t, blocked.Error, "schema has not been described")
require.Nil(t, registry.MCPCallTarget(ctx, ToolCallMCPTool, premature))
require.Zero(t, calls.Load())
require.Empty(t, gate.request.ToolCallID)
described := describeTool(ctx, t, registry, service.ID, page.Tools[0].Name)
describedRaw, _ := json.Marshal(map[string]any{
"tool_ref": described.ToolRef, "arguments": map[string]any{"count": 2},
})
require.NotNil(t, registry.MCPCallTarget(ctx, ToolCallMCPTool, describedRaw))
ctx = WithToolExecContext(
ctx,
&ToolExecContext{
@ -102,7 +121,7 @@ func TestMCPProxyHTTPApprovalArgumentsAndImages(t *testing.T) {
)
invoke := func(arguments string) *types.ToolResult {
raw, _ := json.Marshal(
map[string]any{"tool_ref": page.Tools[0].ToolRef, "arguments": json.RawMessage(arguments)},
map[string]any{"tool_ref": described.ToolRef, "arguments": json.RawMessage(arguments)},
)
result, err := registry.ExecuteTool(ctx, ToolCallMCPTool, raw)
require.NoError(t, err)

View File

@ -143,7 +143,7 @@ func TestMCPCatalogPreservesAndValidatesRawSchemaOverHTTP(t *testing.T) {
newSchema, _ := json.Marshal(changed)
server.AddTool(sdkmcp.Tool{Name: "contact", RawInputSchema: newSchema}, handler)
page = discoverPage(ctx, t, registry, map[string]any{"mode": "list_tools", "server_id": "test", "refresh": true})
require.NotEqual(t, described.ToolRef, page.Tools[0].ToolRef)
require.NotEqual(t, described.ToolRef, describeTool(ctx, t, registry, "test", page.Tools[0].Name).ToolRef)
require.False(t, invoke(described.ToolRef, `{"email":"x"}`).Success)
require.EqualValues(t, 1, calls.Load())
}
@ -179,7 +179,7 @@ func TestMCPCatalogPolicyQueriesAreBounded(t *testing.T) {
ctx, registry, catalog, _, _ := catalogFixture(t, 1000)
gate := &countingCatalogPolicy{catalogPolicy: catalogPolicy{disabled: map[string]bool{}}}
catalog.gate = gate
page := discoverPage(ctx, t, registry, map[string]any{"mode": "list_tools", "server_id": "server-1", "limit": 1})
discoverPage(ctx, t, registry, map[string]any{"mode": "list_tools", "server_id": "server-1", "limit": 1})
require.Equal(t, 1, gate.batches)
require.Zero(t, gate.checks)
result, err := registry.ExecuteTool(ctx, ToolDiscoverMCPTools, json.RawMessage(`{
@ -190,9 +190,11 @@ func TestMCPCatalogPolicyQueriesAreBounded(t *testing.T) {
require.NoError(t, err)
require.True(t, result.Success, result.Error)
require.Equal(t, 1, gate.checks)
var described mcpToolSummary
require.NoError(t, json.Unmarshal([]byte(result.Output), &described))
proxy, err := registry.GetTool(ToolCallMCPTool)
require.NoError(t, err)
raw, _ := json.Marshal(map[string]any{"tool_ref": page.Tools[0].ToolRef, "arguments": map[string]any{"count": 1}})
raw, _ := json.Marshal(map[string]any{"tool_ref": described.ToolRef, "arguments": map[string]any{"count": 1}})
_, _, err = proxy.(*MCPCallTool).resolve(ctx, raw)
require.NoError(t, err)
require.Equal(t, 2, gate.checks)

View File

@ -92,6 +92,20 @@ func discoverPage(ctx context.Context, t *testing.T, r *ToolRegistry, args map[s
return page
}
// describeTool follows the model-facing protocol and returns the executable reference.
func describeTool(ctx context.Context, t *testing.T, r *ToolRegistry, server, name string) mcpToolSummary {
t.Helper()
raw, err := json.Marshal(map[string]any{"mode": "describe", "server_id": server, "tool_name": name})
require.NoError(t, err)
result, err := r.ExecuteTool(ctx, ToolDiscoverMCPTools, raw)
require.NoError(t, err)
require.True(t, result.Success, result.Error)
var tool mcpToolSummary
require.NoError(t, json.Unmarshal([]byte(result.Output), &tool))
require.NotEmpty(t, tool.ToolRef)
return tool
}
func TestMCPCatalogRegistrationDoesNotConnect(t *testing.T) {
ctx := catalogTestContext()
r := NewToolRegistry()
@ -139,7 +153,7 @@ func TestMCPCatalogEnumeratesAllToolsWithoutSchemas(t *testing.T) {
for _, tool := range page.Tools {
require.False(t, found[tool.Name])
found[tool.Name] = true
require.NotEmpty(t, tool.ToolRef)
require.Empty(t, tool.ToolRef, "listing must not expose callable references")
}
if !page.HasMore {
require.Empty(t, page.NextCursor)
@ -182,6 +196,7 @@ func TestMCPCatalogSearchMissStillAllowsExactDiscovery(t *testing.T) {
func TestMCPCatalogPermissionsAndCursorInvalidation(t *testing.T) {
ctx, r, _, gate, _ := catalogFixture(t, 4)
first := discoverPage(ctx, t, r, map[string]any{"mode": "list_tools", "server_id": "server-1", "limit": 1})
described := describeTool(ctx, t, r, "server-1", first.Tools[0].Name)
gate.disabled["server-1/tool_002"] = true
raw, _ := json.Marshal(map[string]any{"mode": "list_tools", "server_id": "server-1", "cursor": first.NextCursor})
result, err := r.ExecuteTool(ctx, ToolDiscoverMCPTools, raw)
@ -191,7 +206,7 @@ func TestMCPCatalogPermissionsAndCursorInvalidation(t *testing.T) {
page := discoverPage(ctx, t, r, map[string]any{"mode": "list_tools", "server_id": "server-1"})
require.Equal(t, 3, page.Total)
gate.disabled["server-1/tool_000"] = true
raw, _ = json.Marshal(map[string]any{"tool_ref": first.Tools[0].ToolRef, "arguments": map[string]any{"count": 1}})
raw, _ = json.Marshal(map[string]any{"tool_ref": described.ToolRef, "arguments": map[string]any{"count": 1}})
result, err = r.ExecuteTool(ctx, ToolCallMCPTool, raw)
require.NoError(t, err)
require.False(t, result.Success)
@ -208,8 +223,8 @@ func TestMCPCatalogPermissionsAndCursorInvalidation(t *testing.T) {
func TestMCPCatalogScopeAndProxyTargetValidation(t *testing.T) {
ctx, r, _, _, _ := catalogFixture(t, 1)
page := discoverPage(ctx, t, r, map[string]any{"mode": "list_tools", "server_id": "server-1"})
raw, _ := json.Marshal(map[string]any{"tool_ref": page.Tools[0].ToolRef, "arguments": map[string]any{}})
described := describeTool(ctx, t, r, "server-1", "tool_000")
raw, _ := json.Marshal(map[string]any{"tool_ref": described.ToolRef, "arguments": map[string]any{}})
result, err := r.ExecuteTool(ctx, ToolCallMCPTool, raw)
require.NoError(t, err)
require.False(t, result.Success)
@ -249,6 +264,7 @@ func TestMCPCatalogIdentityDoesNotUseSanitizedName(t *testing.T) {
c.load = func(context.Context, *types.MCPService) ([]*MCPTool, error) { return []*MCPTool{a, b}, nil }
page := discoverPage(ctx, t, r, map[string]any{"mode": "list_tools", "server_id": "server-1"})
require.Len(t, page.Tools, 2)
describeTool(ctx, t, r, "server-1", b.mcpTool.Name)
proxy, _ := r.GetTool(ToolCallMCPTool)
raw, _ := json.Marshal(map[string]any{"tool_ref": mcpToolRef(b), "arguments": map[string]any{"count": 1}})
resolved, _, err := proxy.(*MCPCallTool).resolve(ctx, raw)
@ -261,7 +277,7 @@ func TestMCPCatalogIdentityDoesNotUseSanitizedName(t *testing.T) {
func TestMCPCatalogRefreshRetiresRemovedAndChangedDefinitions(t *testing.T) {
ctx, r, c, gate, _ := catalogFixture(t, 1)
first := discoverPage(ctx, t, r, map[string]any{"mode": "list_tools", "server_id": "server-1"})
described := describeTool(ctx, t, r, "server-1", "tool_000")
c.load = func(_ context.Context, s *types.MCPService) ([]*MCPTool, error) {
tool := catalogTestTool(s, "tool_000", "new version", gate)
tool.mcpTool.InputSchema = json.RawMessage(`{
@ -278,8 +294,8 @@ func TestMCPCatalogRefreshRetiresRemovedAndChangedDefinitions(t *testing.T) {
return []*MCPTool{tool}, nil
}
changed := discoverPage(ctx, t, r, map[string]any{"mode": "list_tools", "server_id": "server-1", "refresh": true})
require.NotEqual(t, first.Tools[0].ToolRef, changed.Tools[0].ToolRef)
raw, _ := json.Marshal(map[string]any{"tool_ref": first.Tools[0].ToolRef, "arguments": map[string]any{"count": 1}})
require.NotEqual(t, described.ToolRef, describeTool(ctx, t, r, "server-1", changed.Tools[0].Name).ToolRef)
raw, _ := json.Marshal(map[string]any{"tool_ref": described.ToolRef, "arguments": map[string]any{"count": 1}})
result, err := r.ExecuteTool(ctx, ToolCallMCPTool, raw)
require.NoError(t, err)
require.False(t, result.Success)
@ -400,12 +416,12 @@ func TestMCPCatalogWaitCanBeCanceledAndReportsLoading(t *testing.T) {
func TestMCPTargetPresentationDoesNotConnectOrReauthorize(t *testing.T) {
ctx, r, c, _, _ := catalogFixture(t, 1)
page := discoverPage(ctx, t, r, map[string]any{"mode": "list_tools", "server_id": "server-1"})
described := describeTool(ctx, t, r, "server-1", "tool_000")
c.lookup = func(context.Context, uint64, string) (*types.MCPService, error) {
t.Fatal("presentation must not perform service lookup")
return nil, nil
}
raw, _ := json.Marshal(map[string]any{"tool_ref": page.Tools[0].ToolRef, "arguments": map[string]any{"count": 1}})
raw, _ := json.Marshal(map[string]any{"tool_ref": described.ToolRef, "arguments": map[string]any{"count": 1}})
target := r.MCPCallTarget(ctx, ToolCallMCPTool, raw)
require.NotNil(t, target)
require.Equal(t, "tool_000", target.ToolName)
@ -444,3 +460,65 @@ func TestMCPCatalogMarksExternalMetadataAsUntrusted(t *testing.T) {
// The definition is still returned verbatim; only its trust level is stated.
require.Equal(t, injection, described.Description)
}
func TestMCPCatalogRequiresDescribeBeforeCalling(t *testing.T) {
ctx, r, c, _, _ := catalogFixture(t, 2)
for _, mode := range []string{"list_tools", "search"} {
args := map[string]any{"mode": mode, "server_id": "server-1"}
if mode == "search" {
args["query"] = "lookup"
}
raw, _ := json.Marshal(args)
result, err := r.ExecuteTool(ctx, ToolDiscoverMCPTools, raw)
require.NoError(t, err)
require.True(t, result.Success, result.Error)
require.NotContains(t, result.Output, `"tool_ref":`)
require.NotContains(t, result.Output, `"input_schema":`)
require.Contains(t, result.Output, `"next_step":`)
}
// Even a remembered or reconstructed reference cannot bypass describe.
snapshot, _, err := c.snapshot(ctx, "server-1", false)
require.NoError(t, err)
raw, _ := json.Marshal(map[string]any{"tool_ref": mcpToolRef(snapshot[0]), "arguments": map[string]any{"count": 1}})
proxy, _ := r.GetTool(ToolCallMCPTool)
_, _, err = proxy.(*MCPCallTool).resolve(ctx, raw)
require.ErrorContains(t, err, "schema has not been described")
require.ErrorContains(t, err, `server_id="server-1"`)
require.Nil(t, r.MCPCallTarget(ctx, ToolCallMCPTool, raw), "listing must not present a target before describe")
describeTool(ctx, t, r, "server-1", snapshot[1].mcpTool.Name)
_, _, err = proxy.(*MCPCallTool).resolve(ctx, raw)
require.ErrorContains(t, err, "schema has not been described", "describing another tool must not enable this tool")
require.Nil(t, r.MCPCallTarget(ctx, ToolCallMCPTool, raw))
described := describeTool(ctx, t, r, "server-1", snapshot[0].mcpTool.Name)
require.Equal(t, mcpToolRef(snapshot[0]), described.ToolRef)
_, _, err = proxy.(*MCPCallTool).resolve(ctx, raw)
require.NoError(t, err)
target := r.MCPCallTarget(ctx, ToolCallMCPTool, raw)
require.NotNil(t, target)
require.Equal(t, snapshot[0].mcpTool.Name, target.ToolName)
// A new schema loaded by refresh has to be described again.
c.load = func(_ context.Context, service *types.MCPService) ([]*MCPTool, error) {
tool := catalogTestTool(service, snapshot[0].mcpTool.Name, "changed", nil)
tool.mcpTool.InputSchema = json.RawMessage(`{"type":"object","properties":{"id":{"type":"string"}}}`)
return []*MCPTool{tool}, nil
}
snapshot, _, err = c.snapshot(ctx, "server-1", true)
require.NoError(t, err)
raw, _ = json.Marshal(map[string]any{"tool_ref": mcpToolRef(snapshot[0]), "arguments": map[string]any{"id": "1"}})
_, _, err = proxy.(*MCPCallTool).resolve(ctx, raw)
require.ErrorContains(t, err, "schema has not been described")
require.Nil(t, r.MCPCallTarget(ctx, ToolCallMCPTool, raw))
}
func TestMCPCallInvalidArgumentsExplainObjectEnvelope(t *testing.T) {
ctx, r, _, _, _ := catalogFixture(t, 1)
described := describeTool(ctx, t, r, "server-1", "tool_000")
for _, arguments := range []any{`{"count":1}`, []any{1}, nil} {
raw, _ := json.Marshal(map[string]any{"tool_ref": described.ToolRef, "arguments": arguments})
result, err := r.ExecuteTool(ctx, ToolCallMCPTool, raw)
require.NoError(t, err)
require.False(t, result.Success)
require.Contains(t, result.Error, "JSON object, not a JSON-encoded string")
require.Contains(t, result.Error, `"arguments":{"order_id":"123"}`)
}
}

View File

@ -192,6 +192,9 @@ func (r *ToolRegistry) execute(ctx context.Context, tool types.Tool, args json.R
}
if len(validationErrs) > 0 {
errMsg := FormatValidationErrors(validationErrs)
if name == ToolCallMCPTool {
errMsg += mcpCallArgumentsHint
}
if name == ToolWriteSandboxFile {
errMsg += writeSandboxMissingFieldHint
}