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:
wizardchen
2026-06-29 22:37:02 +08:00
committed by lyingbug
parent f2686e9e39
commit 9fd7a7f522
16 changed files with 862 additions and 34 deletions
+121
View File
@@ -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.
//
+116 -33
View File
@@ -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
+7
View File
@@ -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" // 错误事件
+28
View File
@@ -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"`
}
+88 -1
View File
@@ -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})
}
@@ -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)
+3
View File
@@ -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)
}
}
+7
View File
@@ -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