feat(im): include per-service MCP OAuth URLs in IM auth notices
IM channels cannot complete in-conversation OAuth prompts, so when an MCP service needs authorization the reply now includes clickable authorization URLs (when APP_EXTERNAL_URL and OAuth manager are available) instead of only directing users to the admin console.
This commit is contained in:
@@ -1,14 +1,20 @@
|
|||||||
package im
|
package im
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestFormatIMMCPAuthNotice(t *testing.T) {
|
// buildIMMCPAuthNotice with a nil OAuth manager falls back to a per-service
|
||||||
|
// console hint (no authorization URL). These cases exercise the dedup and
|
||||||
|
// empty-input handling without needing a live OAuth manager.
|
||||||
|
func TestBuildIMMCPAuthNotice(t *testing.T) {
|
||||||
|
svc := &Service{} // nil oauthManager => console-hint fallback
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
input []string
|
input []imMCPAuthService
|
||||||
want string
|
want string
|
||||||
contains []string
|
contains []string
|
||||||
}{
|
}{
|
||||||
@@ -18,33 +24,37 @@ func TestFormatIMMCPAuthNotice(t *testing.T) {
|
|||||||
want: "",
|
want: "",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "all blank names",
|
name: "all blank ids",
|
||||||
input: []string{"", " ", "\t"},
|
input: []imMCPAuthService{{ID: "", Name: "x"}, {ID: "", Name: "y"}},
|
||||||
want: "",
|
want: "",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "single service",
|
name: "single service",
|
||||||
input: []string{"GitHub MCP"},
|
input: []imMCPAuthService{{ID: "svc-1", Name: "GitHub MCP"}},
|
||||||
contains: []string{"GitHub MCP", "OAuth 授权"},
|
contains: []string{"GitHub MCP", "OAuth 授权"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "dedupe and trim",
|
name: "dedupe by id",
|
||||||
input: []string{" A ", "A", " B", " ", "B"},
|
input: []imMCPAuthService{
|
||||||
contains: []string{"A、B"},
|
{ID: "a", Name: "A"},
|
||||||
|
{ID: "a", Name: "A"},
|
||||||
|
{ID: "b", Name: "B"},
|
||||||
|
},
|
||||||
|
contains: []string{"A", "B"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
got := formatIMMCPAuthNotice(tt.input)
|
got := svc.buildIMMCPAuthNotice(context.Background(), tt.input)
|
||||||
if tt.contains == nil {
|
if tt.contains == nil {
|
||||||
if got != tt.want {
|
if got != tt.want {
|
||||||
t.Fatalf("formatIMMCPAuthNotice() = %q, want %q", got, tt.want)
|
t.Fatalf("buildIMMCPAuthNotice() = %q, want %q", got, tt.want)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
for _, sub := range tt.contains {
|
for _, sub := range tt.contains {
|
||||||
if !strings.Contains(got, sub) {
|
if !strings.Contains(got, sub) {
|
||||||
t.Fatalf("formatIMMCPAuthNotice() = %q, want substring %q", got, sub)
|
t.Fatalf("buildIMMCPAuthNotice() = %q, want substring %q", got, sub)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
+89
-29
@@ -20,6 +20,7 @@ import (
|
|||||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||||
"github.com/Tencent/WeKnora/internal/event"
|
"github.com/Tencent/WeKnora/internal/event"
|
||||||
"github.com/Tencent/WeKnora/internal/logger"
|
"github.com/Tencent/WeKnora/internal/logger"
|
||||||
|
mcppkg "github.com/Tencent/WeKnora/internal/mcp"
|
||||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||||
"github.com/Tencent/WeKnora/internal/ratelimit"
|
"github.com/Tencent/WeKnora/internal/ratelimit"
|
||||||
"github.com/Tencent/WeKnora/internal/types"
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
@@ -361,6 +362,11 @@ type Service struct {
|
|||||||
// modelService is used to obtain the chat model for generating smart notification replies.
|
// modelService is used to obtain the chat model for generating smart notification replies.
|
||||||
modelService interfaces.ModelService
|
modelService interfaces.ModelService
|
||||||
|
|
||||||
|
// oauthManager builds MCP OAuth authorization URLs so IM users can authorize
|
||||||
|
// OAuth-enabled MCP services out-of-band (IM cannot resolve the in-conversation
|
||||||
|
// prompt). May be nil, in which case a generic console hint is shown instead.
|
||||||
|
oauthManager *mcppkg.OAuthManager
|
||||||
|
|
||||||
// streamManager writes/reads QA events for distributed stop detection,
|
// streamManager writes/reads QA events for distributed stop detection,
|
||||||
// consistent with the web StopSession mechanism. May be nil in Lite mode
|
// consistent with the web StopSession mechanism. May be nil in Lite mode
|
||||||
// (but NewStreamManager always returns at least a memory implementation).
|
// (but NewStreamManager always returns at least a memory implementation).
|
||||||
@@ -484,27 +490,79 @@ func withIMIdentity(ctx context.Context, tenantID uint64, channelID string, msg
|
|||||||
return ctx
|
return ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatIMMCPAuthNotice builds a user-facing hint listing OAuth-enabled MCP
|
// imMCPAuthService identifies an OAuth-enabled MCP service that the IM user has
|
||||||
// services that still need authorization. Returns "" when there is nothing to
|
// not authorized yet, collected during a turn so an authorization notice can be
|
||||||
// report. IM users cannot authorize inline, so they are directed to the console.
|
// appended to the reply.
|
||||||
func formatIMMCPAuthNotice(serviceNames []string) string {
|
type imMCPAuthService struct {
|
||||||
names := make([]string, 0, len(serviceNames))
|
ID string
|
||||||
seen := make(map[string]bool, len(serviceNames))
|
Name string
|
||||||
for _, name := range serviceNames {
|
}
|
||||||
name = strings.TrimSpace(name)
|
|
||||||
if name == "" || seen[name] {
|
// mcpOAuthCallbackURL returns the absolute backend callback URL registered with
|
||||||
continue
|
// the authorization server, derived from APP_EXTERNAL_URL. Empty when unset.
|
||||||
}
|
func mcpOAuthCallbackURL() string {
|
||||||
seen[name] = true
|
base := strings.TrimRight(strings.TrimSpace(os.Getenv("APP_EXTERNAL_URL")), "/")
|
||||||
names = append(names, name)
|
if base == "" {
|
||||||
}
|
|
||||||
if len(names) == 0 {
|
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
return fmt.Sprintf(
|
return base + "/api/v1/mcp-oauth/callback"
|
||||||
"⚠️ 以下 MCP 服务需要授权后才能使用:%s。请在 WeKnora 管理后台完成 OAuth 授权后重试。",
|
}
|
||||||
strings.Join(names, "、"),
|
|
||||||
)
|
// buildIMMCPAuthNotice builds a user-facing authorization notice for the given
|
||||||
|
// OAuth-enabled MCP services. When the OAuth manager and APP_EXTERNAL_URL are
|
||||||
|
// available it generates a per-service authorization URL (StartAuthorization)
|
||||||
|
// the user can open; otherwise it falls back to a console hint. Returns "" when
|
||||||
|
// there is nothing to report. The user authorizes out-of-band, then re-sends
|
||||||
|
// their message to use the service (IM cannot resolve the prompt inline).
|
||||||
|
func (s *Service) buildIMMCPAuthNotice(ctx context.Context, services []imMCPAuthService) string {
|
||||||
|
// Deduplicate by service ID, preserving order.
|
||||||
|
seen := make(map[string]bool, len(services))
|
||||||
|
uniq := make([]imMCPAuthService, 0, len(services))
|
||||||
|
for _, svc := range services {
|
||||||
|
if svc.ID == "" || seen[svc.ID] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[svc.ID] = true
|
||||||
|
uniq = append(uniq, svc)
|
||||||
|
}
|
||||||
|
if len(uniq) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||||
|
principal := types.MCPOAuthPrincipalFromContext(ctx)
|
||||||
|
redirectURI := mcpOAuthCallbackURL()
|
||||||
|
frontendRedirect := strings.TrimSpace(os.Getenv("APP_EXTERNAL_URL"))
|
||||||
|
if frontendRedirect == "" {
|
||||||
|
frontendRedirect = "/"
|
||||||
|
}
|
||||||
|
|
||||||
|
var lines []string
|
||||||
|
for _, svc := range uniq {
|
||||||
|
name := strings.TrimSpace(svc.Name)
|
||||||
|
if name == "" {
|
||||||
|
name = svc.ID
|
||||||
|
}
|
||||||
|
var authURL string
|
||||||
|
if s.oauthManager != nil && redirectURI != "" && tenantID != 0 && principal.Valid() {
|
||||||
|
url, err := s.oauthManager.StartAuthorizationForService(
|
||||||
|
ctx, tenantID, principal, svc.ID, redirectURI, frontendRedirect,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf(ctx, "[IM] Failed to build MCP OAuth URL for service %s: %v", svc.ID, err)
|
||||||
|
} else {
|
||||||
|
authURL = url
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if authURL != "" {
|
||||||
|
lines = append(lines, fmt.Sprintf("• %s:%s", name, authURL))
|
||||||
|
} else {
|
||||||
|
lines = append(lines, fmt.Sprintf("• %s(请在 WeKnora 管理后台完成 OAuth 授权)", name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "⚠️ 以下 MCP 服务需要授权后才能使用,请点击链接完成授权,然后重新发送你的消息:\n" +
|
||||||
|
strings.Join(lines, "\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
// appendIMAuthNotice appends an authorization notice to an existing reply body,
|
// appendIMAuthNotice appends an authorization notice to an existing reply body,
|
||||||
@@ -726,6 +784,7 @@ func NewService(
|
|||||||
modelService interfaces.ModelService,
|
modelService interfaces.ModelService,
|
||||||
streamManager interfaces.StreamManager,
|
streamManager interfaces.StreamManager,
|
||||||
defaultFileSvc interfaces.FileService,
|
defaultFileSvc interfaces.FileService,
|
||||||
|
oauthManager *mcppkg.OAuthManager,
|
||||||
redisClient *redis.Client,
|
redisClient *redis.Client,
|
||||||
appCfg *config.Config,
|
appCfg *config.Config,
|
||||||
) *Service {
|
) *Service {
|
||||||
@@ -752,6 +811,7 @@ func NewService(
|
|||||||
modelService: modelService,
|
modelService: modelService,
|
||||||
streamManager: streamManager,
|
streamManager: streamManager,
|
||||||
defaultFileSvc: defaultFileSvc,
|
defaultFileSvc: defaultFileSvc,
|
||||||
|
oauthManager: oauthManager,
|
||||||
cmdRegistry: registry,
|
cmdRegistry: registry,
|
||||||
channels: make(map[string]*channelState),
|
channels: make(map[string]*channelState),
|
||||||
adapterFactories: make(map[string]AdapterFactory),
|
adapterFactories: make(map[string]AdapterFactory),
|
||||||
@@ -1941,10 +2001,10 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
|
|||||||
agentCompleteFinalAnswer string
|
agentCompleteFinalAnswer string
|
||||||
streamedAny bool
|
streamedAny bool
|
||||||
|
|
||||||
// mcpAuthNotices collects OAuth service names that need out-of-band
|
// mcpAuthServices collects OAuth services that need out-of-band
|
||||||
// authorization (IM cannot resolve the in-conversation prompt).
|
// authorization (IM cannot resolve the in-conversation prompt).
|
||||||
mcpAuthNotices []string
|
mcpAuthServices []imMCPAuthService
|
||||||
mcpAuthSeen = make(map[string]bool)
|
mcpAuthSeen = make(map[string]bool)
|
||||||
)
|
)
|
||||||
closeDone := func() { closeOnce.Do(func() { close(done) }) }
|
closeDone := func() { closeOnce.Do(func() { close(done) }) }
|
||||||
closeComplete := func() { completeOnce.Do(func() { close(completeDone) }) }
|
closeComplete := func() { completeOnce.Do(func() { close(completeDone) }) }
|
||||||
@@ -2160,7 +2220,7 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
|
|||||||
bufMu.Lock()
|
bufMu.Lock()
|
||||||
if !mcpAuthSeen[data.ServiceID] {
|
if !mcpAuthSeen[data.ServiceID] {
|
||||||
mcpAuthSeen[data.ServiceID] = true
|
mcpAuthSeen[data.ServiceID] = true
|
||||||
mcpAuthNotices = append(mcpAuthNotices, data.ServiceName)
|
mcpAuthServices = append(mcpAuthServices, imMCPAuthService{ID: data.ServiceID, Name: data.ServiceName})
|
||||||
}
|
}
|
||||||
bufMu.Unlock()
|
bufMu.Unlock()
|
||||||
return nil
|
return nil
|
||||||
@@ -2274,7 +2334,7 @@ loop:
|
|||||||
answer := resolvedAnswer
|
answer := resolvedAnswer
|
||||||
finalErr := qaErr
|
finalErr := qaErr
|
||||||
noVisibleContent := !streamedAny && strings.TrimSpace(resolvedAnswer) == ""
|
noVisibleContent := !streamedAny && strings.TrimSpace(resolvedAnswer) == ""
|
||||||
authNotices := append([]string(nil), mcpAuthNotices...)
|
authServices := append([]imMCPAuthService(nil), mcpAuthServices...)
|
||||||
bufMu.Unlock()
|
bufMu.Unlock()
|
||||||
|
|
||||||
finalDisplay := cleanIMContent(ctx, FormatIMFinalFromParts(parts), tenant, s.defaultFileSvc)
|
finalDisplay := cleanIMContent(ctx, FormatIMFinalFromParts(parts), tenant, s.defaultFileSvc)
|
||||||
@@ -2288,7 +2348,7 @@ loop:
|
|||||||
answer = fallback
|
answer = fallback
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if notice := formatIMMCPAuthNotice(authNotices); notice != "" {
|
if notice := s.buildIMMCPAuthNotice(ctx, authServices); notice != "" {
|
||||||
finalDisplay = appendIMAuthNotice(finalDisplay, notice)
|
finalDisplay = appendIMAuthNotice(finalDisplay, notice)
|
||||||
answer = appendIMAuthNotice(answer, notice)
|
answer = appendIMAuthNotice(answer, notice)
|
||||||
}
|
}
|
||||||
@@ -2340,7 +2400,7 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
|||||||
var answerMu sync.Mutex
|
var answerMu sync.Mutex
|
||||||
var answerBuilder strings.Builder
|
var answerBuilder strings.Builder
|
||||||
var qaErr error
|
var qaErr error
|
||||||
var mcpAuthNotices []string
|
var mcpAuthServices []imMCPAuthService
|
||||||
mcpAuthSeen := make(map[string]bool)
|
mcpAuthSeen := make(map[string]bool)
|
||||||
done := make(chan struct{})
|
done := make(chan struct{})
|
||||||
completeDone := make(chan struct{})
|
completeDone := make(chan struct{})
|
||||||
@@ -2387,7 +2447,7 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
|||||||
answerMu.Lock()
|
answerMu.Lock()
|
||||||
if !mcpAuthSeen[data.ServiceID] {
|
if !mcpAuthSeen[data.ServiceID] {
|
||||||
mcpAuthSeen[data.ServiceID] = true
|
mcpAuthSeen[data.ServiceID] = true
|
||||||
mcpAuthNotices = append(mcpAuthNotices, data.ServiceName)
|
mcpAuthServices = append(mcpAuthServices, imMCPAuthService{ID: data.ServiceID, Name: data.ServiceName})
|
||||||
}
|
}
|
||||||
answerMu.Unlock()
|
answerMu.Unlock()
|
||||||
return nil
|
return nil
|
||||||
@@ -2493,7 +2553,7 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
|||||||
answerMu.Lock()
|
answerMu.Lock()
|
||||||
answer := answerBuilder.String()
|
answer := answerBuilder.String()
|
||||||
qaError := qaErr
|
qaError := qaErr
|
||||||
authNotices := append([]string(nil), mcpAuthNotices...)
|
authServices := append([]imMCPAuthService(nil), mcpAuthServices...)
|
||||||
answerMu.Unlock()
|
answerMu.Unlock()
|
||||||
|
|
||||||
if answer == "" && qaError != nil {
|
if answer == "" && qaError != nil {
|
||||||
@@ -2502,7 +2562,7 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
|||||||
if answer == "" {
|
if answer == "" {
|
||||||
answer = "抱歉,我暂时无法回答这个问题。"
|
answer = "抱歉,我暂时无法回答这个问题。"
|
||||||
}
|
}
|
||||||
if notice := formatIMMCPAuthNotice(authNotices); notice != "" {
|
if notice := s.buildIMMCPAuthNotice(ctx, authServices); notice != "" {
|
||||||
answer = appendIMAuthNotice(answer, notice)
|
answer = appendIMAuthNotice(answer, notice)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -143,6 +143,26 @@ func (m *OAuthManager) StartAuthorization(
|
|||||||
return authURL, nil
|
return authURL, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StartAuthorizationForService loads the MCP service by ID and starts the
|
||||||
|
// authorization-code flow, returning the URL the user must open. It is a
|
||||||
|
// convenience for callers (e.g. IM channels) that only hold a service ID and
|
||||||
|
// cannot reach the MCP service lookup directly.
|
||||||
|
func (m *OAuthManager) StartAuthorizationForService(
|
||||||
|
ctx context.Context,
|
||||||
|
tenantID uint64,
|
||||||
|
principal types.Principal,
|
||||||
|
serviceID, redirectURI, frontendRedirect string,
|
||||||
|
) (string, error) {
|
||||||
|
service, err := m.serviceRepo.GetByID(ctx, tenantID, serviceID)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to load MCP service: %w", err)
|
||||||
|
}
|
||||||
|
if service == nil {
|
||||||
|
return "", fmt.Errorf("MCP service not found")
|
||||||
|
}
|
||||||
|
return m.StartAuthorization(ctx, service, tenantID, principal, redirectURI, frontendRedirect)
|
||||||
|
}
|
||||||
|
|
||||||
// CompleteAuthorization handles the provider callback: it validates state,
|
// CompleteAuthorization handles the provider callback: it validates state,
|
||||||
// exchanges the code for tokens (PKCE), and persists the per-user token.
|
// exchanges the code for tokens (PKCE), and persists the per-user token.
|
||||||
// Returns the frontend redirect URL recorded at StartAuthorization time.
|
// Returns the frontend redirect URL recorded at StartAuthorization time.
|
||||||
|
|||||||
Reference in New Issue
Block a user