fix lint and test failures
This commit is contained in:
@@ -176,6 +176,16 @@ func waitForMCPOAuthAuthorization(
|
||||
requestID, _ = types.RequestIDFromContext(ctx)
|
||||
}
|
||||
|
||||
// Non-interactive channels (e.g. IM bots) have no live client that can click
|
||||
// "Authorize" and call the resolve endpoint, so blocking on the OAuth wait
|
||||
// would just hang the agent until it times out (once per unauthorized
|
||||
// service). Instead, emit a one-shot notice the channel can surface to the
|
||||
// user and continue without the tool. See types.WithMCPOAuthNonInteractive.
|
||||
if types.IsMCPOAuthNonInteractive(ctx) || types.IsMCPOAuthNonInteractive(waitCtx) {
|
||||
emitMCPOAuthRequiredNotice(waitCtx, sess, service, mcpToolName, toolCallID, tenantID, requestID)
|
||||
return ctx, noop, false
|
||||
}
|
||||
|
||||
decision, waitErr := ow.RequestOAuthAndWait(waitCtx, approval.OAuthPendingRequest{
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
@@ -200,6 +210,47 @@ func waitForMCPOAuthAuthorization(
|
||||
return ctx, noop, true
|
||||
}
|
||||
|
||||
// emitMCPOAuthRequiredNotice publishes a one-shot "MCP OAuth required" event
|
||||
// WITHOUT registering a pending waiter. It is used for non-interactive channels
|
||||
// that cannot complete an in-conversation authorization: subscribers (e.g. the
|
||||
// IM reply builder) surface the notice to the user, who then authorizes the
|
||||
// service from the web console out-of-band. TimeoutSeconds is 0 to distinguish
|
||||
// this notice from a resolvable prompt.
|
||||
func emitMCPOAuthRequiredNotice(
|
||||
ctx context.Context,
|
||||
sess *MCPOAuthSession,
|
||||
service *types.MCPService,
|
||||
mcpToolName, toolCallID string,
|
||||
tenantID uint64,
|
||||
requestID string,
|
||||
) {
|
||||
if sess == nil || sess.EventBus == nil || service == nil {
|
||||
return
|
||||
}
|
||||
_ = sess.EventBus.Emit(context.WithoutCancel(ctx), event.Event{
|
||||
ID: "mcp-oauth-notice-" + service.ID,
|
||||
Type: event.EventMCPOAuthRequired,
|
||||
SessionID: sess.SessionID,
|
||||
Data: event.MCPOAuthRequiredData{
|
||||
TenantID: tenantID,
|
||||
SessionID: sess.SessionID,
|
||||
AssistantMessageID: sess.AssistantMessageID,
|
||||
ServiceID: service.ID,
|
||||
ServiceName: service.Name,
|
||||
MCPToolName: mcpToolName,
|
||||
TimeoutSeconds: 0, // 0 => notice only, not an in-conversation prompt
|
||||
RequestedAtUnix: time.Now().Unix(),
|
||||
ToolCallID: toolCallID,
|
||||
RequestID: requestID,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": sess.AssistantMessageID,
|
||||
"notice_only": true,
|
||||
},
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
// oauthAwareConnectError turns a low-level MCP connect/call error into a
|
||||
// message the agent (and ultimately the user) can act on.
|
||||
func oauthAwareConnectError(service *types.MCPService, err error) string {
|
||||
|
||||
@@ -116,6 +116,10 @@ func TestClient_Ping_403WrapsInvalidCredentials(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestClient_TokenNeverLoggedInFull(t *testing.T) {
|
||||
t.Setenv("LOG_FORMAT", "")
|
||||
logger.ConfigureFromEnv()
|
||||
defer logger.ConfigureFromEnv()
|
||||
|
||||
// Redirect the project's internal logger to an in-memory buffer so we can
|
||||
// assert the raw token never appears in log output. Using stdlib `log`
|
||||
// would be vacuous — the real logger is a private logrus instance.
|
||||
|
||||
@@ -476,9 +476,49 @@ func withIMIdentity(ctx context.Context, tenantID uint64, channelID string, msg
|
||||
ctx = types.WithPrincipal(ctx, types.Principal{Type: types.PrincipalIMUser, ID: principalID})
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
|
||||
// IM bots have no live client that can complete an in-conversation MCP OAuth
|
||||
// prompt, so mark the context non-interactive: the agent emits a one-shot
|
||||
// authorization notice (surfaced in the reply) instead of blocking until the
|
||||
// OAuth wait times out for every unauthorized service.
|
||||
ctx = types.WithMCPOAuthNonInteractive(ctx)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// formatIMMCPAuthNotice builds a user-facing hint listing OAuth-enabled MCP
|
||||
// services that still need authorization. Returns "" when there is nothing to
|
||||
// report. IM users cannot authorize inline, so they are directed to the console.
|
||||
func formatIMMCPAuthNotice(serviceNames []string) string {
|
||||
names := make([]string, 0, len(serviceNames))
|
||||
seen := make(map[string]bool, len(serviceNames))
|
||||
for _, name := range serviceNames {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" || seen[name] {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
names = append(names, name)
|
||||
}
|
||||
if len(names) == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
"⚠️ 以下 MCP 服务需要授权后才能使用:%s。请在 WeKnora 管理后台完成 OAuth 授权后重试。",
|
||||
strings.Join(names, "、"),
|
||||
)
|
||||
}
|
||||
|
||||
// appendIMAuthNotice appends an authorization notice to an existing reply body,
|
||||
// separated by a blank line. When the body is empty the notice becomes the body.
|
||||
func appendIMAuthNotice(body, notice string) string {
|
||||
if notice == "" {
|
||||
return body
|
||||
}
|
||||
if strings.TrimSpace(body) == "" {
|
||||
return notice
|
||||
}
|
||||
return body + "\n\n" + notice
|
||||
}
|
||||
|
||||
func buildIMQARequest(
|
||||
session *types.Session,
|
||||
query string,
|
||||
@@ -1900,6 +1940,11 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
|
||||
|
||||
agentCompleteFinalAnswer string
|
||||
streamedAny bool
|
||||
|
||||
// mcpAuthNotices collects OAuth service names that need out-of-band
|
||||
// authorization (IM cannot resolve the in-conversation prompt).
|
||||
mcpAuthNotices []string
|
||||
mcpAuthSeen = make(map[string]bool)
|
||||
)
|
||||
closeDone := func() { closeOnce.Do(func() { close(done) }) }
|
||||
closeComplete := func() { completeOnce.Do(func() { close(completeDone) }) }
|
||||
@@ -2104,6 +2149,23 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
|
||||
return nil
|
||||
})
|
||||
|
||||
// An OAuth-enabled MCP service the IM user has not authorized yet. IM cannot
|
||||
// resolve the in-conversation prompt, so collect the service name and append
|
||||
// an authorization notice to the final reply (deduped per service).
|
||||
eventBus.On(event.EventMCPOAuthRequired, func(_ context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.MCPOAuthRequiredData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
bufMu.Lock()
|
||||
if !mcpAuthSeen[data.ServiceID] {
|
||||
mcpAuthSeen[data.ServiceID] = true
|
||||
mcpAuthNotices = append(mcpAuthNotices, data.ServiceName)
|
||||
}
|
||||
bufMu.Unlock()
|
||||
return nil
|
||||
})
|
||||
|
||||
// Determine whether to use agent mode (already set above for event handlers).
|
||||
requestID := uuid.New().String()
|
||||
|
||||
@@ -2212,6 +2274,7 @@ loop:
|
||||
answer := resolvedAnswer
|
||||
finalErr := qaErr
|
||||
noVisibleContent := !streamedAny && strings.TrimSpace(resolvedAnswer) == ""
|
||||
authNotices := append([]string(nil), mcpAuthNotices...)
|
||||
bufMu.Unlock()
|
||||
|
||||
finalDisplay := cleanIMContent(ctx, FormatIMFinalFromParts(parts), tenant, s.defaultFileSvc)
|
||||
@@ -2225,6 +2288,10 @@ loop:
|
||||
answer = fallback
|
||||
}
|
||||
}
|
||||
if notice := formatIMMCPAuthNotice(authNotices); notice != "" {
|
||||
finalDisplay = appendIMAuthNotice(finalDisplay, notice)
|
||||
answer = appendIMAuthNotice(answer, notice)
|
||||
}
|
||||
|
||||
if err := streamer.FinalizeStream(ctx, msg, streamID, finalDisplay); err != nil {
|
||||
logger.Warnf(ctx, "[IM] FinalizeStream failed: %v", err)
|
||||
@@ -2273,6 +2340,8 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
||||
var answerMu sync.Mutex
|
||||
var answerBuilder strings.Builder
|
||||
var qaErr error
|
||||
var mcpAuthNotices []string
|
||||
mcpAuthSeen := make(map[string]bool)
|
||||
done := make(chan struct{})
|
||||
completeDone := make(chan struct{})
|
||||
var closeOnce sync.Once
|
||||
@@ -2308,6 +2377,22 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
||||
return nil
|
||||
})
|
||||
|
||||
// Collect OAuth services that need out-of-band authorization (IM cannot
|
||||
// resolve the in-conversation prompt); appended to the answer below.
|
||||
eventBus.On(event.EventMCPOAuthRequired, func(_ context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.MCPOAuthRequiredData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
answerMu.Lock()
|
||||
if !mcpAuthSeen[data.ServiceID] {
|
||||
mcpAuthSeen[data.ServiceID] = true
|
||||
mcpAuthNotices = append(mcpAuthNotices, data.ServiceName)
|
||||
}
|
||||
answerMu.Unlock()
|
||||
return nil
|
||||
})
|
||||
|
||||
// Determine whether to use agent mode
|
||||
useAgent := customAgent != nil && customAgent.IsAgentMode()
|
||||
|
||||
@@ -2408,6 +2493,7 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
||||
answerMu.Lock()
|
||||
answer := answerBuilder.String()
|
||||
qaError := qaErr
|
||||
authNotices := append([]string(nil), mcpAuthNotices...)
|
||||
answerMu.Unlock()
|
||||
|
||||
if answer == "" && qaError != nil {
|
||||
@@ -2416,6 +2502,9 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
||||
if answer == "" {
|
||||
answer = "抱歉,我暂时无法回答这个问题。"
|
||||
}
|
||||
if notice := formatIMMCPAuthNotice(authNotices); notice != "" {
|
||||
answer = appendIMAuthNotice(answer, notice)
|
||||
}
|
||||
|
||||
// Update assistant message with the full answer (including citation tags for web rendering).
|
||||
assistantMsg.Content = answer
|
||||
|
||||
@@ -37,6 +37,12 @@ const (
|
||||
LangfuseTraceContextKey ContextKey = "LangfuseTrace"
|
||||
// SystemAdminContextKey is the context key indicating whether the user is a system administrator
|
||||
SystemAdminContextKey ContextKey = "SystemAdmin"
|
||||
// MCPOAuthNonInteractiveContextKey marks a request whose channel cannot
|
||||
// resolve an in-conversation MCP OAuth prompt (e.g. an IM bot: there is no
|
||||
// live client to click "Authorize" and call the resolve endpoint). When set,
|
||||
// the agent emits a one-shot authorization notice and continues instead of
|
||||
// blocking until the OAuth wait times out. See IsMCPOAuthNonInteractive.
|
||||
MCPOAuthNonInteractiveContextKey ContextKey = "MCPOAuthNonInteractive"
|
||||
)
|
||||
|
||||
// String returns the string representation of the context key
|
||||
|
||||
@@ -113,6 +113,24 @@ func SessionTenantIDFromContext(ctx context.Context) (uint64, bool) {
|
||||
return TenantIDFromContext(ctx)
|
||||
}
|
||||
|
||||
// WithMCPOAuthNonInteractive marks ctx as originating from a channel that cannot
|
||||
// complete an in-conversation MCP OAuth prompt (e.g. an IM bot). The agent uses
|
||||
// this to emit a one-shot authorization notice instead of blocking on the OAuth
|
||||
// wait until it times out. See MCPOAuthNonInteractiveContextKey.
|
||||
func WithMCPOAuthNonInteractive(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, MCPOAuthNonInteractiveContextKey, true)
|
||||
}
|
||||
|
||||
// IsMCPOAuthNonInteractive reports whether ctx was marked non-interactive for
|
||||
// MCP OAuth (see WithMCPOAuthNonInteractive).
|
||||
func IsMCPOAuthNonInteractive(ctx context.Context) bool {
|
||||
if ctx == nil {
|
||||
return false
|
||||
}
|
||||
v, _ := ctx.Value(MCPOAuthNonInteractiveContextKey).(bool)
|
||||
return v
|
||||
}
|
||||
|
||||
// LanguageFromContext extracts the language locale string from ctx (e.g. "zh-CN", "en-US").
|
||||
// Returns ("zh-CN", false) when the key is absent.
|
||||
func LanguageFromContext(ctx context.Context) (string, bool) {
|
||||
|
||||
Reference in New Issue
Block a user