feat(mcp): prompt and resume OAuth authorization mid-conversation
When an agent invokes an OAuth-enabled MCP service that the current user has not authorized yet, the tool call now pauses and surfaces an "Authorize" card in the chat instead of failing with an opaque error. After the user completes the per-user OAuth popup, the backend verifies a token exists and resumes the paused tool call automatically. Backend: - Add mcp_oauth_required / mcp_oauth_resolved events and response types. - Add OAuthPendingRequest + Gate.RequestOAuthAndWait, reusing the existing approval waiter, Resolve, Redis cross-instance fan-out and timeout. - MCPTool.Execute pauses on an authorization-required error for OAuth services and retries once (with a fresh ctx and recycled connection) after the user authorizes. - Forward the new events to the SSE stream. - Add ResolveMCPOAuth handler + route; it verifies authorization before unblocking so a premature resolve cannot resume into another failure. Frontend: - Add McpOAuthCard with an Authorize button reusing the popup + status-poll flow, then resolve the paused run. - Handle the new stream events (dedup multiple pending cards per service). - Add resolveMCPOAuth API client and i18n keys (zh/en/ko/ru).
This commit is contained in:
@@ -220,3 +220,13 @@ export async function resolveToolApproval(
|
||||
): Promise<void> {
|
||||
await post(`/api/v1/agent/tool-approvals/${encodeURIComponent(pendingId)}`, body)
|
||||
}
|
||||
|
||||
// Resume an agent run that paused on an in-conversation MCP OAuth prompt.
|
||||
// Call after the per-user authorization popup completes; the backend verifies
|
||||
// the token exists before unblocking the paused tool call.
|
||||
export async function resolveMCPOAuth(
|
||||
pendingId: string,
|
||||
body: { service_id: string }
|
||||
): Promise<void> {
|
||||
await post(`/api/v1/agent/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}`, body)
|
||||
}
|
||||
|
||||
@@ -595,6 +595,41 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'mcp_oauth_required': {
|
||||
if (!message.agentEventStream) message.agentEventStream = []
|
||||
const d = dataPayload || {}
|
||||
;(message.agentEventStream as ChatMessage[]).push({
|
||||
type: 'mcp_oauth_required',
|
||||
pending_id: d.pending_id,
|
||||
service_id: d.service_id,
|
||||
service_name: d.service_name,
|
||||
mcp_tool_name: d.mcp_tool_name,
|
||||
timeout_seconds: d.timeout_seconds,
|
||||
requested_at: d.requested_at,
|
||||
tool_call_id: d.tool_call_id,
|
||||
resolved: false,
|
||||
})
|
||||
break
|
||||
}
|
||||
case 'mcp_oauth_resolved': {
|
||||
const d = dataPayload || {}
|
||||
const pid = d.pending_id
|
||||
const sid = d.service_id
|
||||
const list = message.agentEventStream as ChatMessage[] | undefined
|
||||
// Resolve the matching card; also clear any other still-pending cards
|
||||
// for the same service (parallel tool calls dedup to a single auth).
|
||||
list?.forEach((e) => {
|
||||
if (e.type !== 'mcp_oauth_required' || e.resolved) return
|
||||
if (e.pending_id === pid || (sid && e.service_id === sid && d.authorized)) {
|
||||
e.resolved = true
|
||||
e.authorized = d.authorized
|
||||
e.resolve_reason = d.reason
|
||||
e.timed_out = d.timed_out
|
||||
e.canceled = d.canceled
|
||||
}
|
||||
})
|
||||
break
|
||||
}
|
||||
case 'tool_call': {
|
||||
if (dataPayload?.tool_name === 'final_answer') break
|
||||
if (message.agentEventStream) {
|
||||
|
||||
@@ -5049,6 +5049,18 @@ export default {
|
||||
submitFailed: 'Submit failed',
|
||||
userRejected: 'User rejected',
|
||||
},
|
||||
mcpOAuth: {
|
||||
banner: 'This MCP service requires OAuth authorization before it can be used',
|
||||
desc: 'Authorizing opens a new window to sign in. The tool call resumes automatically once authorization succeeds.',
|
||||
authorize: 'Authorize',
|
||||
countdown: 'About {seconds}s remaining',
|
||||
authorizedTag: 'Authorized',
|
||||
timedOutTag: 'Authorization timed out',
|
||||
canceledTag: 'Canceled',
|
||||
authorizedToast: 'Authorized, resuming',
|
||||
startFailed: 'Failed to start authorization',
|
||||
resumeFailed: 'Failed to resume execution, please retry',
|
||||
},
|
||||
tools: {
|
||||
searchKnowledge: 'Knowledge Search',
|
||||
grepChunks: 'Text Pattern Search',
|
||||
|
||||
@@ -5066,6 +5066,18 @@ export default {
|
||||
submitFailed: '제출 실패',
|
||||
userRejected: '사용자 거부',
|
||||
},
|
||||
mcpOAuth: {
|
||||
banner: '이 MCP 서비스는 OAuth 인증 후에 사용할 수 있습니다',
|
||||
desc: '인증을 누르면 새 창에서 로그인합니다. 인증이 완료되면 이 도구 호출이 자동으로 계속됩니다.',
|
||||
authorize: '인증하기',
|
||||
countdown: '약 {seconds}초 남음',
|
||||
authorizedTag: '인증됨',
|
||||
timedOutTag: '인증 시간 초과',
|
||||
canceledTag: '취소됨',
|
||||
authorizedToast: '인증 성공, 계속 진행 중',
|
||||
startFailed: '인증 시작 실패',
|
||||
resumeFailed: '실행 재개 실패, 다시 시도하세요',
|
||||
},
|
||||
tools: {
|
||||
searchKnowledge: '지식베이스 검색',
|
||||
grepChunks: '텍스트 패턴 검색',
|
||||
|
||||
@@ -4566,6 +4566,18 @@ export default {
|
||||
submitFailed: 'Ошибка отправки',
|
||||
userRejected: 'Отклонено пользователем',
|
||||
},
|
||||
mcpOAuth: {
|
||||
banner: 'Этот MCP-сервис требует авторизации OAuth перед использованием',
|
||||
desc: 'Авторизация откроет новое окно для входа. После успешной авторизации вызов инструмента продолжится автоматически.',
|
||||
authorize: 'Авторизовать',
|
||||
countdown: 'Осталось примерно {seconds}с',
|
||||
authorizedTag: 'Авторизовано',
|
||||
timedOutTag: 'Время авторизации истекло',
|
||||
canceledTag: 'Отменено',
|
||||
authorizedToast: 'Авторизация успешна, продолжаем',
|
||||
startFailed: 'Не удалось начать авторизацию',
|
||||
resumeFailed: 'Не удалось возобновить выполнение, повторите попытку',
|
||||
},
|
||||
tools: {
|
||||
searchKnowledge: 'Поиск по базе знаний',
|
||||
grepChunks: 'Поиск по текстовому шаблону',
|
||||
|
||||
@@ -5062,6 +5062,18 @@ export default {
|
||||
submitFailed: "提交失败",
|
||||
userRejected: "用户拒绝",
|
||||
},
|
||||
mcpOAuth: {
|
||||
banner: "该 MCP 服务需要 OAuth 授权后才能调用",
|
||||
desc: "点击授权将打开新窗口完成登录,授权成功后会自动继续本次工具调用。",
|
||||
authorize: "去授权",
|
||||
countdown: "剩余约 {seconds} 秒",
|
||||
authorizedTag: "已授权",
|
||||
timedOutTag: "授权超时",
|
||||
canceledTag: "已取消",
|
||||
authorizedToast: "授权成功,正在继续",
|
||||
startFailed: "发起授权失败",
|
||||
resumeFailed: "恢复执行失败,请重试",
|
||||
},
|
||||
tools: {
|
||||
searchKnowledge: "知识库检索",
|
||||
grepChunks: "搜索关键词",
|
||||
|
||||
@@ -88,6 +88,15 @@
|
||||
:resolve-reason="event.resolve_reason" />
|
||||
</div>
|
||||
|
||||
<!-- MCP OAuth in-conversation authorization prompt -->
|
||||
<div v-else-if="event.type === 'mcp_oauth_required'" class="tool-event">
|
||||
<McpOAuthCard :pending-id="event.pending_id" :service-id="event.service_id || ''"
|
||||
:service-name="event.service_name || ''" :mcp-tool-name="event.mcp_tool_name || ''"
|
||||
:timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at"
|
||||
:resolved="event.resolved" :authorized="event.authorized"
|
||||
:resolve-reason="event.resolve_reason" :timed-out="event.timed_out" :canceled="event.canceled" />
|
||||
</div>
|
||||
|
||||
<!-- Tool Call Event (non-thinking) -->
|
||||
<div v-else-if="event.type === 'tool_call'" class="tool-event">
|
||||
<div class="action-card" :class="{
|
||||
@@ -234,6 +243,15 @@
|
||||
:approved="event.approved" :resolve-reason="event.resolve_reason" />
|
||||
</div>
|
||||
|
||||
<!-- MCP OAuth in-conversation authorization prompt -->
|
||||
<div v-else-if="event.type === 'mcp_oauth_required'" class="tool-event">
|
||||
<McpOAuthCard :pending-id="event.pending_id" :service-id="event.service_id || ''"
|
||||
:service-name="event.service_name || ''" :mcp-tool-name="event.mcp_tool_name || ''"
|
||||
:timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at" :resolved="event.resolved"
|
||||
:authorized="event.authorized" :resolve-reason="event.resolve_reason" :timed-out="event.timed_out"
|
||||
:canceled="event.canceled" />
|
||||
</div>
|
||||
|
||||
<!-- Thinking Tool Call -->
|
||||
<div v-else-if="event.type === 'tool_call' && event.tool_name === 'thinking'" class="tool-event">
|
||||
<div class="action-card"
|
||||
@@ -419,6 +437,7 @@ import { marked } from 'marked';
|
||||
import 'katex/dist/katex.min.css';
|
||||
import ToolResultRenderer from './ToolResultRenderer.vue';
|
||||
import ToolApprovalCard from './ToolApprovalCard.vue';
|
||||
import McpOAuthCard from './McpOAuthCard.vue';
|
||||
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
|
||||
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
|
||||
import picturePreview from '@/components/picture-preview.vue';
|
||||
@@ -1405,6 +1424,9 @@ const getEventKey = (event: any, index: number): string => {
|
||||
if (event.type === 'tool_approval_required' && event.pending_id) {
|
||||
return `approval-${event.pending_id}`;
|
||||
}
|
||||
if (event.type === 'mcp_oauth_required' && event.pending_id) {
|
||||
return `mcp-oauth-${event.pending_id}`;
|
||||
}
|
||||
return `event-${index}-${event.type || 'unknown'}`;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
<template>
|
||||
<div class="oauth-card" :class="cardClass">
|
||||
<!-- Status strip -->
|
||||
<div class="oauth-strip">
|
||||
<span class="oauth-strip-icon">
|
||||
<t-icon v-if="!resolved" name="lock-on" />
|
||||
<t-icon v-else-if="authorized" name="check-circle-filled" />
|
||||
<t-icon v-else name="close-circle-filled" />
|
||||
</span>
|
||||
<span class="oauth-strip-text">
|
||||
<template v-if="!resolved">{{ $t('agentStream.mcpOAuth.banner') }}</template>
|
||||
<template v-else-if="authorized">{{ $t('agentStream.mcpOAuth.authorizedTag') }}</template>
|
||||
<template v-else-if="timedOut">{{ $t('agentStream.mcpOAuth.timedOutTag') }}</template>
|
||||
<template v-else>{{ $t('agentStream.mcpOAuth.canceledTag') }}</template>
|
||||
</span>
|
||||
<span v-if="!resolved && secondsLeft >= 0" class="oauth-strip-timer" :class="timerClass">
|
||||
<t-icon name="time" />
|
||||
{{ formatCountdown(secondsLeft) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Identity row -->
|
||||
<div class="oauth-identity">
|
||||
<span class="ident-service">{{ serviceName }}</span>
|
||||
<template v-if="mcpToolName">
|
||||
<t-icon name="chevron-right" class="ident-sep" />
|
||||
<span class="ident-tool">{{ mcpToolName }}</span>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div v-if="!resolved" class="oauth-desc">{{ $t('agentStream.mcpOAuth.desc') }}</div>
|
||||
|
||||
<!-- Footer (pending) -->
|
||||
<div v-if="!resolved" class="oauth-footer">
|
||||
<span class="oauth-spacer" />
|
||||
<t-button
|
||||
theme="primary"
|
||||
size="small"
|
||||
:loading="authorizing"
|
||||
:disabled="authorizing"
|
||||
@click="authorize"
|
||||
>
|
||||
{{ $t('agentStream.mcpOAuth.authorize') }}
|
||||
</t-button>
|
||||
</div>
|
||||
|
||||
<!-- Footer (resolved) -->
|
||||
<div v-else class="oauth-resolved-footer">
|
||||
<span v-if="resolveReason" class="oauth-resolved-reason">{{ resolveReason }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import {
|
||||
getMCPOAuthAuthorizeURL,
|
||||
getMCPOAuthStatus,
|
||||
resolveMCPOAuth,
|
||||
MCP_OAUTH_CALLBACK_PATH,
|
||||
} from '@/api/mcp-service'
|
||||
|
||||
const props = defineProps<{
|
||||
pendingId: string
|
||||
serviceId: string
|
||||
serviceName: string
|
||||
mcpToolName?: string
|
||||
timeoutSeconds?: number
|
||||
requestedAt?: number
|
||||
resolved?: boolean
|
||||
authorized?: boolean
|
||||
resolveReason?: string
|
||||
timedOut?: boolean
|
||||
canceled?: boolean
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const authorizing = ref(false)
|
||||
const now = ref(Date.now())
|
||||
let clock: ReturnType<typeof setInterval> | null = null
|
||||
let poll: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const deadline = computed(() => {
|
||||
const base = (props.requestedAt || 0) * 1000
|
||||
const add = (props.timeoutSeconds || 600) * 1000
|
||||
return base + add
|
||||
})
|
||||
|
||||
const secondsLeft = computed(() => {
|
||||
if (props.resolved) return -1
|
||||
return Math.max(0, Math.floor((deadline.value - now.value) / 1000))
|
||||
})
|
||||
|
||||
const timerClass = computed(() => {
|
||||
if (secondsLeft.value <= 30) return 'timer-critical'
|
||||
if (secondsLeft.value <= 120) return 'timer-warning'
|
||||
return ''
|
||||
})
|
||||
|
||||
const cardClass = computed(() => ({
|
||||
'is-resolved': !!props.resolved,
|
||||
'is-authorized': !!props.resolved && !!props.authorized,
|
||||
'is-failed': !!props.resolved && !props.authorized,
|
||||
'is-pending': !props.resolved,
|
||||
}))
|
||||
|
||||
function formatCountdown(s: number): string {
|
||||
if (s < 60) return t('agentStream.mcpOAuth.countdown', { seconds: s })
|
||||
const m = Math.floor(s / 60)
|
||||
const r = s % 60
|
||||
return `${m}:${r.toString().padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function stopPoll() {
|
||||
if (poll) {
|
||||
clearInterval(poll)
|
||||
poll = null
|
||||
}
|
||||
}
|
||||
|
||||
const authorize = async () => {
|
||||
if (props.resolved || authorizing.value) return
|
||||
authorizing.value = true
|
||||
try {
|
||||
const redirectUri = window.location.origin + MCP_OAUTH_CALLBACK_PATH
|
||||
const frontendRedirect = window.location.origin + '/'
|
||||
const authUrl = await getMCPOAuthAuthorizeURL(props.serviceId, {
|
||||
redirect_uri: redirectUri,
|
||||
frontend_redirect: frontendRedirect,
|
||||
})
|
||||
if (!authUrl) {
|
||||
MessagePlugin.error(t('agentStream.mcpOAuth.startFailed'))
|
||||
authorizing.value = false
|
||||
return
|
||||
}
|
||||
const popup = window.open(authUrl, 'mcp_oauth', 'width=600,height=720')
|
||||
// Poll until the user authorizes (status flips) or closes the popup.
|
||||
poll = window.setInterval(async () => {
|
||||
const closed = !popup || popup.closed
|
||||
let ok = false
|
||||
try {
|
||||
ok = await getMCPOAuthStatus(props.serviceId)
|
||||
} catch {
|
||||
/* transient; keep polling */
|
||||
}
|
||||
if (ok) {
|
||||
stopPoll()
|
||||
try { popup?.close() } catch { /* cross-origin close may throw */ }
|
||||
try {
|
||||
await resolveMCPOAuth(props.pendingId, { service_id: props.serviceId })
|
||||
MessagePlugin.success(t('agentStream.mcpOAuth.authorizedToast'))
|
||||
} catch (e: any) {
|
||||
const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.mcpOAuth.resumeFailed')
|
||||
MessagePlugin.error(msg)
|
||||
}
|
||||
authorizing.value = false
|
||||
} else if (closed) {
|
||||
stopPoll()
|
||||
authorizing.value = false
|
||||
}
|
||||
}, 1500)
|
||||
} catch (e: any) {
|
||||
const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.mcpOAuth.startFailed')
|
||||
MessagePlugin.error(msg)
|
||||
authorizing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
clock = setInterval(() => {
|
||||
now.value = Date.now()
|
||||
}, 1000)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (clock) clearInterval(clock)
|
||||
stopPoll()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
@warning-rgb: 237, 122, 11;
|
||||
@success-rgb: 7, 192, 95;
|
||||
@danger-rgb: 232, 80, 91;
|
||||
|
||||
.oauth-card {
|
||||
--strip-color: var(--td-brand-color);
|
||||
--strip-rgb: 0, 82, 217;
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease, opacity 0.2s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
width: 3px;
|
||||
background: var(--strip-color);
|
||||
transition: background-color 0.2s ease;
|
||||
}
|
||||
|
||||
&.is-authorized {
|
||||
--strip-color: var(--td-success-color);
|
||||
--strip-rgb: @success-rgb;
|
||||
opacity: 0.94;
|
||||
}
|
||||
|
||||
&.is-failed {
|
||||
--strip-color: var(--td-error-color);
|
||||
--strip-rgb: @danger-rgb;
|
||||
opacity: 0.94;
|
||||
}
|
||||
}
|
||||
|
||||
.oauth-strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 12px 7px 14px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--strip-color);
|
||||
background: rgba(var(--strip-rgb), 0.06);
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
.oauth-strip-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
.t-icon {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
.oauth-strip-text {
|
||||
flex: 1;
|
||||
color: var(--strip-color);
|
||||
}
|
||||
.oauth-strip-timer {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
background: rgba(0, 0, 0, 0.04);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 500;
|
||||
|
||||
.t-icon {
|
||||
font-size: 12px;
|
||||
}
|
||||
&.timer-warning {
|
||||
color: var(--td-warning-color);
|
||||
background: rgba(@warning-rgb, 0.1);
|
||||
}
|
||||
&.timer-critical {
|
||||
color: var(--td-error-color);
|
||||
background: rgba(@danger-rgb, 0.12);
|
||||
animation: timerPulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.oauth-identity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 12px 6px 14px;
|
||||
font-size: 13px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.ident-service {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-weight: 500;
|
||||
}
|
||||
.ident-sep {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: 12px;
|
||||
}
|
||||
.ident-tool {
|
||||
color: var(--td-brand-color);
|
||||
font-weight: 600;
|
||||
font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.oauth-desc {
|
||||
padding: 0 12px 4px 14px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.oauth-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px 12px 14px;
|
||||
}
|
||||
|
||||
.oauth-spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.oauth-resolved-footer {
|
||||
padding: 6px 12px 10px 14px;
|
||||
font-size: 12px;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
.oauth-resolved-reason {
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
&:empty {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes timerPulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.55; }
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user