From 9fd7a7f52238d0b44bab5f242993b312b840828a Mon Sep 17 00:00:00 2001 From: wizardchen Date: Mon, 29 Jun 2026 22:37:02 +0800 Subject: [PATCH] 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). --- frontend/src/api/mcp-service.ts | 10 + .../src/composables/useChatStreamHandler.ts | 35 ++ frontend/src/i18n/locales/en-US.ts | 12 + frontend/src/i18n/locales/ko-KR.ts | 12 + frontend/src/i18n/locales/ru-RU.ts | 12 + frontend/src/i18n/locales/zh-CN.ts | 12 + .../chat/components/AgentStreamDisplay.vue | 22 ++ .../views/chat/components/McpOAuthCard.vue | 332 ++++++++++++++++++ internal/agent/approval/gate.go | 121 +++++++ internal/agent/tools/mcp_tool.go | 149 ++++++-- internal/event/event.go | 7 + internal/event/event_data.go | 28 ++ internal/handler/mcp_oauth.go | 89 ++++- .../handler/session/agent_stream_handler.go | 45 +++ internal/router/router.go | 3 + internal/types/chat.go | 7 + 16 files changed, 862 insertions(+), 34 deletions(-) create mode 100644 frontend/src/views/chat/components/McpOAuthCard.vue diff --git a/frontend/src/api/mcp-service.ts b/frontend/src/api/mcp-service.ts index 033d25f9..cce08784 100644 --- a/frontend/src/api/mcp-service.ts +++ b/frontend/src/api/mcp-service.ts @@ -220,3 +220,13 @@ export async function resolveToolApproval( ): Promise { 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 { + await post(`/api/v1/agent/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}`, body) +} diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.ts index c3d59a89..3f33095e 100644 --- a/frontend/src/composables/useChatStreamHandler.ts +++ b/frontend/src/composables/useChatStreamHandler.ts @@ -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) { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index b53517cf..f9693640 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -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', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index b2d2fc4d..669b04fb 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -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: '텍스트 패턴 검색', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index fbf71a23..40f9a4c8 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -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: 'Поиск по текстовому шаблону', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 2cba47a1..a0938cd4 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -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: "搜索关键词", diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index c79c5e4f..debe93c2 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -88,6 +88,15 @@ :resolve-reason="event.resolve_reason" /> + +
+ +
+
+ +
+ +
+
{ 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'}`; }; diff --git a/frontend/src/views/chat/components/McpOAuthCard.vue b/frontend/src/views/chat/components/McpOAuthCard.vue new file mode 100644 index 00000000..b2712fdb --- /dev/null +++ b/frontend/src/views/chat/components/McpOAuthCard.vue @@ -0,0 +1,332 @@ + + + + + diff --git a/internal/agent/approval/gate.go b/internal/agent/approval/gate.go index fe150764..70ccd8c0 100644 --- a/internal/agent/approval/gate.go +++ b/internal/agent/approval/gate.go @@ -104,6 +104,21 @@ type MCPApproval interface { RequestAndWait(ctx context.Context, req PendingRequest) (Decision, error) } +// OAuthPendingRequest carries everything needed to prompt the user to authorize +// an OAuth-enabled MCP service mid-conversation and block until they do. +type OAuthPendingRequest struct { + TenantID uint64 + UserID string // session owner; required for Resolve authorization + SessionID string + AssistantMessageID string + RequestID string + EventBus *event.EventBus + ServiceID string + ServiceName string + MCPToolName string + ToolCallID string +} + var _ MCPApproval = (*Gate)(nil) // Gate coordinates wait/resolve for MCP tool approvals. @@ -399,6 +414,112 @@ func (g *Gate) RequestAndWait(ctx context.Context, req PendingRequest) (Decision } } +// RequestOAuthAndWait emits an "MCP OAuth required" UI event, then blocks +// until the user authorizes (delivered via Resolve), the wait times out, or +// the request ctx is canceled. A returned Decision.Approved==true means the +// user completed authorization and the tool call should be retried. +// +// Unlike RequestAndWait this does NOT consult the approval checker — it is +// driven reactively by an authorization-required error from the MCP transport. +func (g *Gate) RequestOAuthAndWait(ctx context.Context, req OAuthPendingRequest) (Decision, error) { + if g == nil { + return Decision{}, fmt.Errorf("oauth gate: nil gate") + } + if req.EventBus == nil { + return Decision{}, fmt.Errorf("oauth gate: EventBus is nil") + } + + pendingID := uuid.New().String() + w := &waiter{ + ch: make(chan Decision, 1), + tenantID: req.TenantID, + userID: req.UserID, + } + + g.mu.Lock() + g.pending[pendingID] = w + g.mu.Unlock() + + defer func() { + g.mu.Lock() + delete(g.pending, pendingID) + g.mu.Unlock() + }() + + timeoutSec := int(g.timeout / time.Second) + if timeoutSec < 1 { + timeoutSec = 1 + } + + if err := req.EventBus.Emit(ctx, event.Event{ + ID: pendingID + "-mcp-oauth-required", + Type: event.EventMCPOAuthRequired, + SessionID: req.SessionID, + Data: event.MCPOAuthRequiredData{ + PendingID: pendingID, + TenantID: req.TenantID, + SessionID: req.SessionID, + AssistantMessageID: req.AssistantMessageID, + ServiceID: req.ServiceID, + ServiceName: req.ServiceName, + MCPToolName: req.MCPToolName, + TimeoutSeconds: timeoutSec, + RequestedAtUnix: time.Now().Unix(), + ToolCallID: req.ToolCallID, + RequestID: req.RequestID, + }, + Metadata: map[string]interface{}{ + "assistant_message_id": req.AssistantMessageID, + "pending_id": pendingID, + }, + RequestID: req.RequestID, + }); err != nil { + return Decision{}, fmt.Errorf("emit mcp oauth required: %w", err) + } + + emitResolved := func(d Decision) { + _ = req.EventBus.Emit(context.WithoutCancel(ctx), event.Event{ + ID: pendingID + "-mcp-oauth-resolved", + Type: event.EventMCPOAuthResolved, + SessionID: req.SessionID, + Data: event.MCPOAuthResolvedData{ + PendingID: pendingID, + ServiceID: req.ServiceID, + Authorized: d.Approved, + Reason: d.Reason, + TimedOut: d.TimedOut, + Canceled: d.ContextCanceled, + }, + Metadata: map[string]interface{}{ + "assistant_message_id": req.AssistantMessageID, + }, + RequestID: req.RequestID, + }) + } + + timer := time.NewTimer(g.timeout) + defer timer.Stop() + + var d Decision + select { + case d = <-w.ch: + emitResolved(d) + return d, nil + case <-timer.C: + d = Decision{Approved: false, Reason: "authorization timeout", TimedOut: true} + _ = w.deliver(d) + d = <-w.ch + emitResolved(d) + return d, nil + case <-ctx.Done(): + d = Decision{Approved: false, Reason: "request canceled", ContextCanceled: true} + _ = w.deliver(d) + d = <-w.ch + emitResolved(d) + return d, nil + } +} + // Resolve completes a pending approval. tenantID must match the tenant that // started the wait; userID, when non-zero, must match the session owner. // diff --git a/internal/agent/tools/mcp_tool.go b/internal/agent/tools/mcp_tool.go index 55b5c676..7cf880bd 100644 --- a/internal/agent/tools/mcp_tool.go +++ b/internal/agent/tools/mcp_tool.go @@ -174,44 +174,51 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too } } - // Get or create MCP client - client, err := t.mcpManager.GetOrCreateClient(ctx, t.service) - if err != nil { - logger.GetLogger(ctx).Errorf("Failed to get MCP client: %v", err) - return &types.ToolResult{ - Success: false, - Error: oauthAwareConnectError(t.service, err), - }, nil - } - - // For stdio transport, ensure connection is released after use isStdio := t.service.TransportType == types.MCPTransportStdio - if isStdio { - defer func() { - if err := client.Disconnect(); err != nil { - logger.GetLogger(ctx).Warnf("Failed to disconnect stdio MCP client: %v", err) - } else { - logger.GetLogger(ctx).Infof("Stdio MCP client disconnected after tool execution") - } - }() - } - // Call the tool via MCP (with one reconnection retry on failure) - result, err := client.CallTool(ctx, t.mcpTool.Name, input) - if err != nil && !isStdio { - logger.GetLogger(ctx).Warnf("MCP tool call failed, retrying with fresh connection: %v", err) - _ = client.Disconnect() - - client, err = t.mcpManager.GetOrCreateClient(ctx, t.service) + // connectAndCall performs get-client + call-tool, including the existing + // stale-session reconnection retry. Factored out so an in-conversation + // OAuth authorization prompt can replay the whole sequence once after the + // user authorizes. + connectAndCall := func(ctx context.Context) (*mcp.CallToolResult, error) { + client, err := t.mcpManager.GetOrCreateClient(ctx, t.service) if err != nil { - logger.GetLogger(ctx).Errorf("Failed to reconnect MCP client: %v", err) - return &types.ToolResult{ - Success: false, - Error: oauthAwareConnectError(t.service, err), - }, nil + return nil, err + } + // For stdio transport, ensure connection is released after use. + if isStdio { + defer func() { + if derr := client.Disconnect(); derr != nil { + logger.GetLogger(ctx).Warnf("Failed to disconnect stdio MCP client: %v", derr) + } else { + logger.GetLogger(ctx).Infof("Stdio MCP client disconnected after tool execution") + } + }() } - result, err = client.CallTool(ctx, t.mcpTool.Name, input) + // Call the tool via MCP (with one reconnection retry on failure) + result, err := client.CallTool(ctx, t.mcpTool.Name, input) + if err != nil && !isStdio { + logger.GetLogger(ctx).Warnf("MCP tool call failed, retrying with fresh connection: %v", err) + _ = client.Disconnect() + + client, err = t.mcpManager.GetOrCreateClient(ctx, t.service) + if err != nil { + return nil, err + } + result, err = client.CallTool(ctx, t.mcpTool.Name, input) + } + return result, err + } + + result, err := connectAndCall(ctx) + if err != nil { + // When an OAuth-enabled service has not been authorized by this user, + // pause and prompt them to authorize in the chat, then retry once. + if retryCtx, cancel, ok := t.waitForOAuthAndRetry(ctx, err); ok { + defer cancel() + result, err = connectAndCall(retryCtx) + } } if err != nil { logger.GetLogger(ctx).Errorf("MCP tool call failed: %v", err) @@ -376,6 +383,82 @@ func extractContentText(content []mcp.ContentItem) string { return strings.Join(textParts, "\n") } +// oauthWaiter is the subset of the approval gate used to pause the agent while +// the user completes an MCP OAuth authorization. Declared locally (and accessed +// via a type assertion) so the broader MCPApproval interface — and its test +// fakes — need not change. +type oauthWaiter interface { + RequestOAuthAndWait(ctx context.Context, req approval.OAuthPendingRequest) (approval.Decision, error) +} + +// waitForOAuthAndRetry blocks for user authorization when err indicates an +// OAuth-enabled MCP service has not been authorized by the current user. It +// emits an "authorize" prompt to the chat (via the gate) and waits until the +// user authorizes, the wait times out, or the request is canceled. +// +// It returns (retryCtx, cancel, true) only when the user authorized in time, in +// which case the caller should replay the tool call using retryCtx (a fresh +// timeout budget, since the wait may have consumed the original per-tool ctx) +// and must defer cancel. In all other cases it returns (ctx, noop, false) and +// the caller surfaces the original error. +func (t *MCPTool) waitForOAuthAndRetry( + ctx context.Context, err error, +) (context.Context, context.CancelFunc, bool) { + noop := func() {} + if !t.service.AuthConfig.IsOAuth() || !isAuthorizationRequired(err) { + return ctx, noop, false + } + ow, ok := t.gate.(oauthWaiter) + if !ok || ow == nil { + return ctx, noop, false + } + meta, ok := ToolExecFromContext(ctx) + if !ok || meta == nil || meta.EventBus == nil { + return ctx, noop, false + } + + tenantID, _ := types.TenantIDFromContext(ctx) + // Wait on the round-level ctx (no per-tool timeout) so authorization can + // legitimately take longer than the per-tool exec budget; user-stop / + // request cancel still propagates because it is a child of the request ctx. + waitCtx := ctx + if meta.ApprovalCtx != nil { + waitCtx = meta.ApprovalCtx + } + + decision, waitErr := ow.RequestOAuthAndWait(waitCtx, approval.OAuthPendingRequest{ + TenantID: tenantID, + UserID: meta.UserID, + SessionID: meta.SessionID, + AssistantMessageID: meta.AssistantMessageID, + RequestID: meta.RequestID, + EventBus: meta.EventBus, + ServiceID: t.service.ID, + ServiceName: t.service.Name, + MCPToolName: t.mcpTool.Name, + ToolCallID: meta.ToolCallID, + }) + if waitErr != nil || !decision.Approved { + return ctx, noop, false + } + + // Drop any stale (token-less) cached connection so the retry rebuilds the + // client with the freshly stored token. + _ = t.mcpManager.CloseClient(t.service.ID) + + // Re-derive a fresh tool-exec ctx; the authorization wait likely consumed + // the per-tool budget the engine applied to ctx (mirrors the approval gate). + if meta.ApprovalCtx != nil { + freshTimeout := meta.ExecTimeout + if freshTimeout <= 0 { + freshTimeout = 60 * time.Second + } + freshCtx, cancel := context.WithTimeout(meta.ApprovalCtx, freshTimeout) + return freshCtx, cancel, true + } + return ctx, noop, true +} + // oauthAwareConnectError turns a low-level MCP connect/call error into a // message the agent (and ultimately the user) can act on. For OAuth services // that have not been authorized — or whose token expired and could not be diff --git a/internal/event/event.go b/internal/event/event.go index 053c0da6..373f1272 100644 --- a/internal/event/event.go +++ b/internal/event/event.go @@ -60,6 +60,13 @@ const ( EventToolApprovalRequired EventType = "tool_approval_required" EventToolApprovalResolved EventType = "tool_approval_resolved" + // MCP OAuth in-conversation authorization prompt: emitted when an + // OAuth-enabled MCP service is invoked but the current user has not + // authorized it yet. The agent pauses until the user authorizes (or the + // wait times out / is canceled). + EventMCPOAuthRequired EventType = "mcp_oauth_required" + EventMCPOAuthResolved EventType = "mcp_oauth_resolved" + // Error events EventError EventType = "error" // 错误事件 diff --git a/internal/event/event_data.go b/internal/event/event_data.go index 84eea48c..09353da5 100644 --- a/internal/event/event_data.go +++ b/internal/event/event_data.go @@ -237,3 +237,31 @@ type ToolApprovalResolvedData struct { TimedOut bool `json:"timed_out,omitempty"` Canceled bool `json:"canceled,omitempty"` } + +// MCPOAuthRequiredData is emitted when an OAuth-enabled MCP service is invoked +// during a conversation but the current user has not authorized it yet. The +// UI surfaces an "Authorize" card; the agent pauses until the user authorizes. +type MCPOAuthRequiredData struct { + PendingID string `json:"pending_id"` + TenantID uint64 `json:"tenant_id"` + SessionID string `json:"session_id"` + AssistantMessageID string `json:"assistant_message_id"` + ServiceID string `json:"service_id"` + ServiceName string `json:"service_name"` + MCPToolName string `json:"mcp_tool_name"` + TimeoutSeconds int `json:"timeout_seconds"` + RequestedAtUnix int64 `json:"requested_at"` + ToolCallID string `json:"tool_call_id"` + RequestID string `json:"request_id,omitempty"` +} + +// MCPOAuthResolvedData confirms the outcome of an in-conversation OAuth prompt +// (authorized / timeout / cancel). +type MCPOAuthResolvedData struct { + PendingID string `json:"pending_id"` + ServiceID string `json:"service_id"` + Authorized bool `json:"authorized"` + Reason string `json:"reason,omitempty"` + TimedOut bool `json:"timed_out,omitempty"` + Canceled bool `json:"canceled,omitempty"` +} diff --git a/internal/handler/mcp_oauth.go b/internal/handler/mcp_oauth.go index dd1057d8..51a79638 100644 --- a/internal/handler/mcp_oauth.go +++ b/internal/handler/mcp_oauth.go @@ -1,9 +1,11 @@ package handler import ( + stderrors "errors" "net/http" "strings" + "github.com/Tencent/WeKnora/internal/agent/approval" "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/mcp" @@ -21,6 +23,7 @@ type MCPOAuthHandler struct { oauth *mcp.OAuthManager mcpManager *mcp.MCPManager svc interfaces.MCPServiceService + gate *approval.Gate } // NewMCPOAuthHandler constructs the handler. @@ -28,8 +31,9 @@ func NewMCPOAuthHandler( oauth *mcp.OAuthManager, mcpManager *mcp.MCPManager, svc interfaces.MCPServiceService, + gate *approval.Gate, ) *MCPOAuthHandler { - return &MCPOAuthHandler{oauth: oauth, mcpManager: mcpManager, svc: svc} + return &MCPOAuthHandler{oauth: oauth, mcpManager: mcpManager, svc: svc, gate: gate} } type mcpOAuthAuthorizeRequest struct { @@ -202,3 +206,86 @@ func (h *MCPOAuthHandler) Revoke(c *gin.Context) { _ = h.mcpManager.CloseClient(serviceID) c.Status(http.StatusNoContent) } + +type resolveMCPOAuthBody struct { + // ServiceID is the MCP service the pending prompt belongs to; used to + // verify the user actually holds a token before resuming the agent. + ServiceID string `json:"service_id" binding:"required"` +} + +// ResolveMCPOAuth resumes an agent run that paused on an in-conversation OAuth +// prompt. The frontend calls this once the per-user authorization popup has +// completed; the backend verifies a token now exists for (tenant, user, +// service) before unblocking, so a premature/failed authorization does not +// resume the tool into another failure. +// +// ResolveMCPOAuth godoc +// @Summary 完成对话内 MCP OAuth 授权 +// @Description 用户在对话中完成 OAuth 授权后调用,校验令牌存在后恢复被暂停的 Agent 工具调用 +// @Tags MCP服务 +// @Accept json +// @Produce json +// @Param pending_id path string true "待授权 ID" +// @Param request body map[string]interface{} true "{service_id: string}" +// @Success 200 {object} map[string]interface{} +// @Failure 400 {object} errors.AppError +// @Failure 409 {object} errors.AppError "用户尚未完成授权" +// @Security Bearer +// @Router /agent/mcp-oauth-resolutions/{pending_id} [post] +func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) { + ctx := c.Request.Context() + pendingID := c.Param("pending_id") + tenantID := c.GetUint64(types.TenantIDContextKey.String()) + userID, _ := types.UserIDFromContext(ctx) + if tenantID == 0 || strings.TrimSpace(userID) == "" { + c.Error(errors.NewUnauthorizedError("authentication required")) + return + } + if h.gate == nil { + c.Error(errors.NewInternalServerError("OAuth gate is not configured")) + return + } + + var body resolveMCPOAuthBody + if err := c.ShouldBindJSON(&body); err != nil { + c.Error(errors.NewBadRequestError(err.Error())) + return + } + serviceID := strings.TrimSpace(body.ServiceID) + if serviceID == "" { + c.Error(errors.NewValidationError("service_id is required")) + return + } + + // Only resume once the user genuinely holds a token; otherwise the retry + // would just fail again with another authorization-required error. + authorized, err := h.oauth.IsAuthorized(ctx, tenantID, userID, serviceID) + if err != nil { + c.Error(errors.NewInternalServerError("failed to verify authorization: " + err.Error())) + return + } + if !authorized { + c.Error(errors.NewConflictError("authorization not completed yet for this MCP service")) + return + } + + if err := h.gate.Resolve(tenantID, userID, pendingID, approval.Decision{Approved: true}); err != nil { + switch { + case stderrors.Is(err, approval.ErrPendingNotFound): + c.Error(errors.NewNotFoundError("pending authorization not found or already completed")) + case stderrors.Is(err, approval.ErrAlreadyResolved): + c.Error(errors.NewBadRequestError("pending authorization already resolved (timeout / cancel raced your action)")) + case stderrors.Is(err, approval.ErrTenantMismatch): + c.Error(errors.NewBadRequestError("tenant mismatch")) + case stderrors.Is(err, approval.ErrUserMismatch): + c.Error(errors.NewBadRequestError("user mismatch: only the session owner may resolve this prompt")) + default: + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "pending_id": secutils.SanitizeForLog(pendingID), + }) + c.Error(errors.NewInternalServerError(err.Error())) + } + return + } + c.JSON(http.StatusOK, gin.H{"success": true}) +} diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.go index 9a3fc60e..cde73e89 100644 --- a/internal/handler/session/agent_stream_handler.go +++ b/internal/handler/session/agent_stream_handler.go @@ -110,6 +110,8 @@ func (h *AgentStreamHandler) Subscribe() { h.eventBus.On(event.EventAgentComplete, h.handleComplete) h.eventBus.On(event.EventToolApprovalRequired, h.handleToolApprovalRequired) h.eventBus.On(event.EventToolApprovalResolved, h.handleToolApprovalResolved) + h.eventBus.On(event.EventMCPOAuthRequired, h.handleMCPOAuthRequired) + h.eventBus.On(event.EventMCPOAuthResolved, h.handleMCPOAuthResolved) } // handleThought handles agent thought events @@ -324,6 +326,49 @@ func (h *AgentStreamHandler) handleToolApprovalResolved(ctx context.Context, evt return nil } +// handleMCPOAuthRequired forwards an in-conversation "authorize this MCP +// service" prompt to the SSE stream so the UI can render an Authorize card. +func (h *AgentStreamHandler) handleMCPOAuthRequired(ctx context.Context, evt event.Event) error { + data, ok := evt.Data.(event.MCPOAuthRequiredData) + if !ok { + return nil + } + meta := toolApprovalDataToMap(data) + meta["pending_id"] = data.PendingID + if err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{ + ID: evt.ID, + Type: types.ResponseTypeMCPOAuthRequired, + Content: "MCP service requires OAuth authorization", + Done: true, + Timestamp: time.Now(), + Data: meta, + }); err != nil { + logger.GetLogger(h.ctx).Error("Append mcp oauth required event failed", "error", err) + } + return nil +} + +// handleMCPOAuthResolved forwards the outcome of an in-conversation OAuth prompt. +func (h *AgentStreamHandler) handleMCPOAuthResolved(ctx context.Context, evt event.Event) error { + data, ok := evt.Data.(event.MCPOAuthResolvedData) + if !ok { + return nil + } + meta := toolApprovalDataToMap(data) + meta["pending_id"] = data.PendingID + if err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{ + ID: evt.ID, + Type: types.ResponseTypeMCPOAuthResolved, + Content: "MCP OAuth authorization resolved", + Done: true, + Timestamp: time.Now(), + Data: meta, + }); err != nil { + logger.GetLogger(h.ctx).Error("Append mcp oauth resolved event failed", "error", err) + } + return nil +} + // handleReferences handles knowledge references events func (h *AgentStreamHandler) handleReferences(ctx context.Context, evt event.Event) error { data, ok := evt.Data.(event.AgentReferencesData) diff --git a/internal/router/router.go b/internal/router/router.go index 8ae92a3a..de7f8daf 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -887,6 +887,9 @@ func RegisterMCPServiceRoutes( // people who actually have context to approve, so the gate is // kept at "anyone in the tenant" instead. agentTool.POST("/tool-approvals/:pending_id", g.Viewer(), handler.ResolveToolApproval) + // Resume an agent run paused on an in-conversation MCP OAuth prompt. + // Same tenant-member (Viewer+) gating rationale as tool-approvals. + agentTool.POST("/mcp-oauth-resolutions/:pending_id", g.Viewer(), oauthHandler.ResolveMCPOAuth) } } diff --git a/internal/types/chat.go b/internal/types/chat.go index d4b0a2fa..aeddae95 100644 --- a/internal/types/chat.go +++ b/internal/types/chat.go @@ -102,6 +102,13 @@ const ( ResponseTypeToolApprovalRequired ResponseType = "tool_approval_required" // ToolApprovalResolved: user approved/rejected (or timeout); informational for UI replay ResponseTypeToolApprovalResolved ResponseType = "tool_approval_resolved" + // MCPOAuthRequired: an OAuth-enabled MCP service was invoked but the user + // has not authorized it — UI must surface an "Authorize" prompt and the + // agent pauses until authorization completes (or the wait times out). + ResponseTypeMCPOAuthRequired ResponseType = "mcp_oauth_required" + // MCPOAuthResolved: authorization completed / timed out / canceled; + // informational for UI replay. + ResponseTypeMCPOAuthResolved ResponseType = "mcp_oauth_resolved" ) // StreamResponse stream response