RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
refa: derive connector, MCP, and memory identity from context (#21952)
buua436455a0d52c7d6
diff --git a/internal/agent/retrievalbridge/memory.go b/internal/agent/retrievalbridge/memory.goindex f7f5fb7e6a..27c939b2fc 100644--- a/internal/agent/retrievalbridge/memory.go+++ b/internal/agent/retrievalbridge/memory.go@@ -35,7 +35,6 @@ import (type memoryMessageSearcher interface {SearchMessage(ctx context.Context,- userID string,filterDict, params map[string]any,) ([]map[string]any, common.ErrorCode, error)}@@ -80,14 +79,23 @@ func (a *MemoryAdapter) Search(if len(memoryIDs) == 0 {return nil, fmt.Errorf("memory retrieval: memory_ids is required")}- actorID := strings.TrimSpace(req.TenantID)- if state, stateErr := runtime.GetStateFromContext(ctx); stateErr == nil && state != nil {- if userID, _ := state.GetSysString("user_id"); strings.TrimSpace(userID) != "" {+ actorID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ if actorID == "" {+ if state, stateErr := runtime.GetStateFromContext(ctx); stateErr == nil && state != nil {+ userID, _ := state.GetSysString("user_id")actorID = strings.TrimSpace(userID)+ if tenantID == "" {+ stateTenantID, _ := state.GetSysString("tenant_id")+ tenantID = strings.TrimSpace(stateTenantID)+ }}}if actorID == "" {- return nil, fmt.Errorf("memory retrieval: user id is required")+ return nil, permission.ErrUnauthenticated+ }+ if permission.UserIDFromContext(ctx) == "" {+ ctx = permission.WithIdentity(ctx, actorID, tenantID)}if err := agenttool.CheckCanvasDependencies(ctx, db, permission.ResourceKindMemory, memoryIDs); err != nil {return nil, err@@ -120,12 +128,7 @@ func (a *MemoryAdapter) Search(if req.SimilarityThreshold != nil {params["similarity_threshold"] = *req.SimilarityThreshold}- messages, _, err := a.svc.SearchMessage(- ctx,- actorID,- filter,- params,- )+ messages, _, err := a.svc.SearchMessage(ctx, filter, params)if err != nil {return nil, err}diff --git a/internal/agent/retrievalbridge/memory_test.go b/internal/agent/retrievalbridge/memory_test.goindex 045eec4292..41a6951ac2 100644--- a/internal/agent/retrievalbridge/memory_test.go+++ b/internal/agent/retrievalbridge/memory_test.go@@ -24,24 +24,27 @@ import (agenttool "ragflow/internal/agent/tool""ragflow/internal/common"+ "ragflow/internal/permission")type captureMessageSearcher struct {- userID stringparams map[string]any}func (s *captureMessageSearcher) SearchMessage(_ context.Context,- userID string,_ map[string]any,params map[string]any,) ([]map[string]any, common.ErrorCode, error) {- s.userID = userIDs.params = paramsreturn nil, common.CodeSuccess, nil}+func memoryRequestContext(t *testing.T) context.Context {+ t.Helper()+ return permission.WithIdentity(t.Context(), "user-1", "tenant-1")+}+type fakeQueryTranslator struct {calls inttenantID string@@ -77,7 +80,7 @@ func TestMemoryAdapterTranslatesQueryWithCrossLanguages(t *testing.T) {translator := &fakeQueryTranslator{result: "what happened yesterday?"}adapter := &MemoryAdapter{svc: searcher, translator: translator}- if _, err := adapter.Search(t.Context(), nil, memoryRequest("English")); err != nil {+ if _, err := adapter.Search(memoryRequestContext(t), nil, memoryRequest("English")); err != nil {t.Fatal(err)}if translator.calls != 1 {@@ -97,7 +100,7 @@ func TestMemoryAdapterSkipsTranslationWithoutCrossLanguages(t *testing.T) {translator := &fakeQueryTranslator{result: "unused"}adapter := &MemoryAdapter{svc: searcher, translator: translator}- if _, err := adapter.Search(t.Context(), nil, memoryRequest()); err != nil {+ if _, err := adapter.Search(memoryRequestContext(t), nil, memoryRequest()); err != nil {t.Fatal(err)}if translator.calls != 0 {@@ -120,7 +123,7 @@ func TestMemoryAdapterKeepsOriginalQueryWhenTranslationFails(t *testing.T) {searcher := &captureMessageSearcher{}adapter := &MemoryAdapter{svc: searcher, translator: tc.translator}- if _, err := adapter.Search(t.Context(), nil, memoryRequest("English")); err != nil {+ if _, err := adapter.Search(memoryRequestContext(t), nil, memoryRequest("English")); err != nil {t.Fatal(err)}if got := searcher.params["query"]; got != "¿qué pasó ayer?" {@@ -143,7 +146,7 @@ func TestMemoryAdapterRejectsCrossLanguagesWithoutTranslator(t *testing.T) {searcher := &captureMessageSearcher{}adapter := &MemoryAdapter{svc: searcher}- if _, err := adapter.Search(t.Context(), nil, memoryRequest("English")); err == nil {+ if _, err := adapter.Search(memoryRequestContext(t), nil, memoryRequest("English")); err == nil {t.Fatal("expected an error when cross_languages is set and no translator is configured")}if searcher.params != nil {diff --git a/internal/handler/connector.go b/internal/handler/connector.goindex a8ba66f68b..29e275d240 100644--- a/internal/handler/connector.go+++ b/internal/handler/connector.go@@ -35,22 +35,22 @@ import ()type connectorServiceIface interface {- ListConnectors(ctx context.Context, userID, tenantID string) (*service.ListConnectorsResponse, error)- CreateConnector(ctx context.Context, userID string, req *service.CreateConnectorRequest) (*entity.Connector, error)- GetConnector(ctx context.Context, connectorID, userID string) (*entity.Connector, error)- ListLog(ctx context.Context, connectorID, userID string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error)- ListLogs(ctx context.Context, userID, datasetID string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error)- DeleteConnector(ctx context.Context, connectorID, userID string) (bool, common.ErrorCode, error)- RebuildConnector(ctx context.Context, connectorID, userID, kbID string) (bool, common.ErrorCode, error)- ResumeFailedSync(ctx context.Context, connectorID, userID string, req *service.ResumeFailedSyncRequest) (bool, common.ErrorCode, error)- TestConnector(ctx context.Context, connectorID, userID string, config entity.JSONMap) error- UpdateConnector(ctx context.Context, connectorID, userID string, req *service.UpdateConnectorRequest) (*entity.Connector, common.ErrorCode, error)- StartGoogleWebOAuth(ctx context.Context, userID, source string, req *service.StartGoogleWebOAuthRequest) (*service.StartGoogleWebOAuthResponse, common.ErrorCode, error)+ ListConnectors(ctx context.Context, tenantID string) (*service.ListConnectorsResponse, error)+ CreateConnector(ctx context.Context, req *service.CreateConnectorRequest) (*entity.Connector, error)+ GetConnector(ctx context.Context, connectorID string) (*entity.Connector, error)+ ListLog(ctx context.Context, connectorID string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error)+ ListLogs(ctx context.Context, datasetID string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error)+ DeleteConnector(ctx context.Context, connectorID string) (bool, common.ErrorCode, error)+ RebuildConnector(ctx context.Context, connectorID, kbID string) (bool, common.ErrorCode, error)+ ResumeFailedSync(ctx context.Context, connectorID string, req *service.ResumeFailedSyncRequest) (bool, common.ErrorCode, error)+ TestConnector(ctx context.Context, connectorID string, config entity.JSONMap) error+ UpdateConnector(ctx context.Context, connectorID string, req *service.UpdateConnectorRequest) (*entity.Connector, common.ErrorCode, error)+ StartGoogleWebOAuth(ctx context.Context, source string, req *service.StartGoogleWebOAuthRequest) (*service.StartGoogleWebOAuthResponse, common.ErrorCode, error)GoogleWebOAuthCallback(ctx context.Context, source, stateID, oauthError, errorDescription, code string) string- PollGoogleWebOAuthResult(ctx context.Context, userID, source string, req *service.PollGoogleWebOAuthResultRequest) (*service.PollGoogleWebOAuthResultResponse, common.ErrorCode, error)- StartBoxWebOAuth(ctx context.Context, userID string, req *service.StartBoxWebOAuthRequest) (*service.StartBoxWebOAuthResponse, common.ErrorCode, error)+ PollGoogleWebOAuthResult(ctx context.Context, source string, req *service.PollGoogleWebOAuthResultRequest) (*service.PollGoogleWebOAuthResultResponse, common.ErrorCode, error)+ StartBoxWebOAuth(ctx context.Context, req *service.StartBoxWebOAuthRequest) (*service.StartBoxWebOAuthResponse, common.ErrorCode, error)BoxWebOAuthCallback(ctx context.Context, flowID string, oauthError string, errorDescription string, code string) string- PollBoxWebOAuthResult(ctx context.Context, userID string, req *service.PollBoxWebOAuthResultRequest) (*service.PollBoxWebOAuthResultResponse, common.ErrorCode, error)+ PollBoxWebOAuthResult(ctx context.Context, req *service.PollBoxWebOAuthResultRequest) (*service.PollBoxWebOAuthResultResponse, common.ErrorCode, error)}// ConnectorHandler connector handler@@ -77,16 +77,10 @@ func NewConnectorHandler(connectorService *service.ConnectorService, userService// @Success 200 {object} service.ListConnectorsResponse// @Router /connector/list [get]func (h *ConnectorHandler) ListConnectors(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }- userID := user.IDctx := c.Request.Context()// List connectors- result, err := h.connectorService.ListConnectors(ctx, userID, c.Query("tenant_id"))+ result, err := h.connectorService.ListConnectors(ctx, c.Query("tenant_id"))if err != nil {if connectorErrorResponse(c, err) {return@@ -131,14 +125,9 @@ func connectorErrorResponse(c *gin.Context, err error) bool {// @Success 200 {object} map[string]interface{}// @Router /api/v1/connectors/{connector_id} [get]func (h *ConnectorHandler) GetConnector(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()- connector, err := h.connectorService.GetConnector(ctx, c.Param("connector_id"), user.ID)+ connector, err := h.connectorService.GetConnector(ctx, c.Param("connector_id"))if connectorErrorResponse(c, err) {return}@@ -148,11 +137,6 @@ func (h *ConnectorHandler) GetConnector(c *gin.Context) {// UpdateConnector Update an accessible connector's polling configuration.func (h *ConnectorHandler) UpdateConnector(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }req, err := decodeUpdateConnectorRequest(c)if err != nil {@@ -162,7 +146,7 @@ func (h *ConnectorHandler) UpdateConnector(c *gin.Context) {ctx := c.Request.Context()- connector, code, err := h.connectorService.UpdateConnector(ctx, c.Param("connector_id"), user.ID, req)+ connector, code, err := h.connectorService.UpdateConnector(ctx, c.Param("connector_id"), req)if err != nil {common.RespondError(c, code, err.Error())return@@ -207,11 +191,6 @@ func decodeUpdateConnectorRequest(c *gin.Context) (*service.UpdateConnectorReque// @Success 200 {object} map[string]interface{}// @Router /api/v1/connectors/{connector_id}/logs [get]func (h *ConnectorHandler) ListLogs(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }page := 1if rawPage := strings.TrimSpace(c.DefaultQuery("page", "1")); rawPage != "" {@@ -235,7 +214,7 @@ func (h *ConnectorHandler) ListLogs(c *gin.Context) {ctx := c.Request.Context()- logs, total, code, err := h.connectorService.ListLog(ctx, c.Param("connector_id"), user.ID, page, pageSize)+ logs, total, code, err := h.connectorService.ListLog(ctx, c.Param("connector_id"), page, pageSize)if err != nil {common.RespondError(c, code, err.Error())return@@ -258,11 +237,6 @@ func (h *ConnectorHandler) ListLogs(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/connectors/sync-logs [get]func (h *ConnectorHandler) ListSyncLogs(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }page := 1pageSize := 15@@ -287,7 +261,7 @@ func (h *ConnectorHandler) ListSyncLogs(c *gin.Context) {ctx := c.Request.Context()- logs, total, code, err := h.connectorService.ListLogs(ctx, user.ID, datasetID, page, pageSize)+ logs, total, code, err := h.connectorService.ListLogs(ctx, datasetID, page, pageSize)if err != nil {common.RespondError(c, code, err.Error())return@@ -308,11 +282,6 @@ func (h *ConnectorHandler) ListSyncLogs(c *gin.Context) {// @Success 200 {object} service.ListConnectorsResponse// @Router /connector/ [post]func (h *ConnectorHandler) CreateConnector(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }var req service.CreateConnectorRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -335,7 +304,7 @@ func (h *ConnectorHandler) CreateConnector(c *gin.Context) {ctx := c.Request.Context()- connector, err := h.connectorService.CreateConnector(ctx, user.ID, &req)+ connector, err := h.connectorService.CreateConnector(ctx, &req)if err != nil {if errors.Is(err, service.ErrConnectorInvalidFreq) {common.RespondError(c, common.CodeDataError, err.Error())@@ -362,11 +331,6 @@ type testConnectorRequest struct {// @Router /api/v1/connectors/{connector_id}/test [post]func (h *ConnectorHandler) TestConnector(c *gin.Context) {// check user and connector- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }connectorID := c.Param("connector_id")if connectorID == "" {@@ -393,7 +357,7 @@ func (h *ConnectorHandler) TestConnector(c *gin.Context) {}}- err := h.connectorService.TestConnector(ctx, connectorID, user.ID, request)+ err := h.connectorService.TestConnector(ctx, connectorID, request)if permissionresponse.IsPermissionError(err) {connectorErrorResponse(c, err)return@@ -430,15 +394,10 @@ func (h *ConnectorHandler) TestConnector(c *gin.Context) {// @Accept json// @Produce jsonfunc (h *ConnectorHandler) DeleteConnector(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()- _, code, err := h.connectorService.DeleteConnector(ctx, c.Param("connector_id"), user.ID)+ _, code, err := h.connectorService.DeleteConnector(ctx, c.Param("connector_id"))if err != nil {common.RespondError(c, code, err.Error())return@@ -456,11 +415,6 @@ func (h *ConnectorHandler) DeleteConnector(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /connector/:connector_id/rebuild [post]func (h *ConnectorHandler) RebuildConnector(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }// Parse request body to get kb_idvar req struct {@@ -477,7 +431,7 @@ func (h *ConnectorHandler) RebuildConnector(c *gin.Context) {}ctx := c.Request.Context()- _, code, err := h.connectorService.RebuildConnector(ctx, c.Param("connector_id"), user.ID, req.KbID)+ _, code, err := h.connectorService.RebuildConnector(ctx, c.Param("connector_id"), req.KbID)if err != nil {common.RespondError(c, code, err.Error())return@@ -495,11 +449,6 @@ func (h *ConnectorHandler) RebuildConnector(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /connector/:connector_id/resume-failed-sync [post]func (h *ConnectorHandler) ResumeFailedSync(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }var req service.ResumeFailedSyncRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -508,7 +457,7 @@ func (h *ConnectorHandler) ResumeFailedSync(c *gin.Context) {}ctx := c.Request.Context()- _, code, err := h.connectorService.ResumeFailedSync(ctx, c.Param("connector_id"), user.ID, &req)+ _, code, err := h.connectorService.ResumeFailedSync(ctx, c.Param("connector_id"), &req)if err != nil {common.RespondError(c, code, err.Error())return@@ -517,11 +466,6 @@ func (h *ConnectorHandler) ResumeFailedSync(c *gin.Context) {}func (h *ConnectorHandler) StartGoogleWebOAuth(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }var req service.StartGoogleWebOAuthRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -531,7 +475,7 @@ func (h *ConnectorHandler) StartGoogleWebOAuth(c *gin.Context) {ctx := c.Request.Context()- data, code, err := h.connectorService.StartGoogleWebOAuth(ctx, user.ID, c.DefaultQuery("type", "google-drive"), &req)+ data, code, err := h.connectorService.StartGoogleWebOAuth(ctx, c.DefaultQuery("type", "google-drive"), &req)if err != nil {common.RespondError(c, code, err.Error())return@@ -541,11 +485,6 @@ func (h *ConnectorHandler) StartGoogleWebOAuth(c *gin.Context) {}func (h *ConnectorHandler) PollGoogleWebOAuthResult(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }var req service.PollGoogleWebOAuthResultRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -555,7 +494,7 @@ func (h *ConnectorHandler) PollGoogleWebOAuthResult(c *gin.Context) {ctx := c.Request.Context()- data, code, err := h.connectorService.PollGoogleWebOAuthResult(ctx, user.ID, c.Query("type"), &req)+ data, code, err := h.connectorService.PollGoogleWebOAuthResult(ctx, c.Query("type"), &req)if err != nil {common.RespondError(c, code, err.Error())return@@ -590,11 +529,6 @@ func (h *ConnectorHandler) googleWebOAuthCallback(c *gin.Context, source string)}func (h *ConnectorHandler) StartBoxWebOAuth(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }var req service.StartBoxWebOAuthRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeBadRequest, err.Error())@@ -602,7 +536,7 @@ func (h *ConnectorHandler) StartBoxWebOAuth(c *gin.Context) {}ctx := c.Request.Context()- resp, code, err := h.connectorService.StartBoxWebOAuth(ctx, user.ID, &req)+ resp, code, err := h.connectorService.StartBoxWebOAuth(ctx, &req)if err != nil {common.RespondError(c, code, err.Error())return@@ -624,11 +558,6 @@ func (h *ConnectorHandler) BoxWebOAuthCallback(c *gin.Context) {}func (h *ConnectorHandler) PollBoxWebOAuthResult(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }var req service.PollBoxWebOAuthResultRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeBadRequest, err.Error())@@ -636,7 +565,7 @@ func (h *ConnectorHandler) PollBoxWebOAuthResult(c *gin.Context) {}ctx := c.Request.Context()- resp, code, err := h.connectorService.PollBoxWebOAuthResult(ctx, user.ID, &req)+ resp, code, err := h.connectorService.PollBoxWebOAuthResult(ctx, &req)if err != nil {common.RespondError(c, code, err.Error())returndiff --git a/internal/handler/connector_test.go b/internal/handler/connector_test.goindex b47cefbccb..94f0204391 100644--- a/internal/handler/connector_test.go+++ b/internal/handler/connector_test.go@@ -34,36 +34,36 @@ type logListCapture struct {pageSize int}-func (s fakeConnectorService) ListConnectors(context.Context, string, string) (*service.ListConnectorsResponse, error) {+func (s fakeConnectorService) ListConnectors(context.Context, string) (*service.ListConnectorsResponse, error) {return &service.ListConnectorsResponse{}, nil}-func (s fakeConnectorService) TestConnector(context.Context, string, string, entity.JSONMap) error {+func (s fakeConnectorService) TestConnector(context.Context, string, entity.JSONMap) error {return s.err}-func (s fakeConnectorService) CreateConnector(context.Context, string, *service.CreateConnectorRequest) (*entity.Connector, error) {+func (s fakeConnectorService) CreateConnector(context.Context, *service.CreateConnectorRequest) (*entity.Connector, error) {if s.err != nil {return nil, s.err}return s.connector, nil}-func (s fakeConnectorService) GetConnector(context.Context, string, string) (*entity.Connector, error) {+func (s fakeConnectorService) GetConnector(context.Context, string) (*entity.Connector, error) {if s.err != nil {return nil, s.err}return s.connector, nil}-func (s fakeConnectorService) UpdateConnector(context.Context, string, string, *service.UpdateConnectorRequest) (*entity.Connector, common.ErrorCode, error) {+func (s fakeConnectorService) UpdateConnector(context.Context, string, *service.UpdateConnectorRequest) (*entity.Connector, common.ErrorCode, error) {if s.err != nil {return nil, s.code, s.err}return s.connector, common.CodeSuccess, nil}-func (s fakeConnectorService) StartGoogleWebOAuth(context.Context, string, string, *service.StartGoogleWebOAuthRequest) (*service.StartGoogleWebOAuthResponse, common.ErrorCode, error) {+func (s fakeConnectorService) StartGoogleWebOAuth(context.Context, string, *service.StartGoogleWebOAuthRequest) (*service.StartGoogleWebOAuthResponse, common.ErrorCode, error) {if s.err != nil {return nil, s.code, s.err}@@ -74,14 +74,14 @@ func (s fakeConnectorService) GoogleWebOAuthCallback(context.Context, string, streturn ""}-func (s fakeConnectorService) PollGoogleWebOAuthResult(context.Context, string, string, *service.PollGoogleWebOAuthResultRequest) (*service.PollGoogleWebOAuthResultResponse, common.ErrorCode, error) {+func (s fakeConnectorService) PollGoogleWebOAuthResult(context.Context, string, *service.PollGoogleWebOAuthResultRequest) (*service.PollGoogleWebOAuthResultResponse, common.ErrorCode, error) {if s.err != nil {return nil, s.code, s.err}return &service.PollGoogleWebOAuthResultResponse{}, common.CodeSuccess, nil}-func (s fakeConnectorService) StartBoxWebOAuth(context.Context, string, *service.StartBoxWebOAuthRequest) (*service.StartBoxWebOAuthResponse, common.ErrorCode, error) {+func (s fakeConnectorService) StartBoxWebOAuth(context.Context, *service.StartBoxWebOAuthRequest) (*service.StartBoxWebOAuthResponse, common.ErrorCode, error) {if s.err != nil {return nil, s.code, s.err}@@ -99,21 +99,21 @@ func (s fakeConnectorService) BoxWebOAuthCallback(context.Context, string, strinreturn "<html>box</html>"}-func (s fakeConnectorService) PollBoxWebOAuthResult(context.Context, string, *service.PollBoxWebOAuthResultRequest) (*service.PollBoxWebOAuthResultResponse, common.ErrorCode, error) {+func (s fakeConnectorService) PollBoxWebOAuthResult(context.Context, *service.PollBoxWebOAuthResultRequest) (*service.PollBoxWebOAuthResultResponse, common.ErrorCode, error) {if s.err != nil {return nil, s.code, s.err}return &service.PollBoxWebOAuthResultResponse{}, common.CodeSuccess, nil}-func (s fakeConnectorService) ListLog(context.Context, string, string, int, int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error) {+func (s fakeConnectorService) ListLog(context.Context, string, int, int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error) {if s.err != nil {return nil, 0, s.code, s.err}return s.logs, s.total, common.CodeSuccess, nil}-func (s fakeConnectorService) ListLogs(_ context.Context, _, _ string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error) {+func (s fakeConnectorService) ListLogs(_ context.Context, _ string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error) {if s.err != nil {return nil, 0, s.code, s.err}@@ -124,21 +124,21 @@ func (s fakeConnectorService) ListLogs(_ context.Context, _, _ string, page, pagreturn s.logs, s.total, common.CodeSuccess, nil}-func (s fakeConnectorService) DeleteConnector(context.Context, string, string) (bool, common.ErrorCode, error) {+func (s fakeConnectorService) DeleteConnector(context.Context, string) (bool, common.ErrorCode, error) {if s.err != nil {return false, s.code, s.err}return true, common.CodeSuccess, nil}-func (s fakeConnectorService) RebuildConnector(context.Context, string, string, string) (bool, common.ErrorCode, error) {+func (s fakeConnectorService) RebuildConnector(context.Context, string, string) (bool, common.ErrorCode, error) {if s.err != nil {return false, s.code, s.err}return true, common.CodeSuccess, nil}-func (s fakeConnectorService) ResumeFailedSync(context.Context, string, string, *service.ResumeFailedSyncRequest) (bool, common.ErrorCode, error) {+func (s fakeConnectorService) ResumeFailedSync(context.Context, string, *service.ResumeFailedSyncRequest) (bool, common.ErrorCode, error) {if s.err != nil {return false, s.code, s.err}diff --git a/internal/handler/mcp.go b/internal/handler/mcp.goindex ce68a56d85..a391abbdef 100644--- a/internal/handler/mcp.go+++ b/internal/handler/mcp.go@@ -70,11 +70,6 @@ func NewMCPHandler(mcpService *service.MCPService) *MCPHandler {// CreateMCPServer creates an MCP server for the current user.func (h *MCPHandler) CreateMCPServer(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }var req service.CreateMCPServerRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -83,7 +78,7 @@ func (h *MCPHandler) CreateMCPServer(c *gin.Context) {}ctx := c.Request.Context()- result, code, err := h.mcpService.CreateMCPServer(ctx, user.ID, req)+ result, code, err := h.mcpService.CreateMCPServer(ctx, req)if err != nil {common.RespondError(c, code, err.Error())return@@ -94,11 +89,6 @@ func (h *MCPHandler) CreateMCPServer(c *gin.Context) {// ListMCPServers lists MCP servers for an owned tenant or a requested tenant the caller belongs to.func (h *MCPHandler) ListMCPServers(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }page, err := parseMCPServerPage(c.Query("page"))if err != nil {@@ -117,7 +107,7 @@ func (h *MCPHandler) ListMCPServers(c *gin.Context) {mcpIDs := getMCPIDsFromQuery(c)tenantID := c.Query("tenant_id")- result, code, err := h.mcpService.ListMCPServers(ctx, user.ID, tenantID, mcpIDs, keywords, page, pageSize, orderby, desc)+ result, code, err := h.mcpService.ListMCPServers(ctx, tenantID, mcpIDs, keywords, page, pageSize, orderby, desc)if err != nil {if code == common.CodeServerError {common.Respond(c, http.StatusInternalServerError, code, nil, err.Error())@@ -131,15 +121,10 @@ func (h *MCPHandler) ListMCPServers(c *gin.Context) {}func (h *MCPHandler) GetMCPServer(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()mcpID := c.Param("mcp_id")if c.Query("mode") == "download" {- result, code, err := h.mcpService.ExportMCPServer(ctx, user.ID, mcpID)+ result, code, err := h.mcpService.ExportMCPServer(ctx, mcpID)if err != nil {mcpDetailError(c, code, err)return@@ -148,7 +133,7 @@ func (h *MCPHandler) GetMCPServer(c *gin.Context) {return}- result, code, err := h.mcpService.GetMCPServer(ctx, user.ID, mcpID)+ result, code, err := h.mcpService.GetMCPServer(ctx, mcpID)if err != nil {mcpDetailError(c, code, err)return@@ -166,11 +151,6 @@ func mcpDetailError(c *gin.Context, code common.ErrorCode, err error) {// UpdateMCPServer updates an MCP server for the current user.func (h *MCPHandler) UpdateMCPServer(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }mcpID := c.Param("mcp_id")var req service.UpdateMCPServerRequest@@ -179,7 +159,7 @@ func (h *MCPHandler) UpdateMCPServer(c *gin.Context) {return}ctx := c.Request.Context()- result, code, err := h.mcpService.UpdateMCPServer(ctx, user.ID, mcpID, req)+ result, code, err := h.mcpService.UpdateMCPServer(ctx, mcpID, req)if err != nil {common.RespondError(c, code, err.Error())return@@ -190,13 +170,8 @@ func (h *MCPHandler) UpdateMCPServer(c *gin.Context) {// DeleteMCPServer deletes an MCP server for the current user.func (h *MCPHandler) DeleteMCPServer(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()- _, code, err := h.mcpService.DeleteMCPServer(ctx, user.ID, c.Param("mcp_id"))+ _, code, err := h.mcpService.DeleteMCPServer(ctx, c.Param("mcp_id"))if err != nil {common.RespondError(c, code, err.Error())return@@ -284,11 +259,6 @@ type ImportMCPRequest struct {// @Param request body handler.ImportMCPRequest true "import config"// @Router /api/v1/mcp/servers/import [post]func (h *MCPHandler) ImportMCPServers(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }body, err := io.ReadAll(c.Request.Body)if err != nil {@@ -329,7 +299,7 @@ func (h *MCPHandler) ImportMCPServers(c *gin.Context) {_ = json.Unmarshal(rawTimeout, &timeout)}ctx := c.Request.Context()- results, err := h.mcpService.ImportServers(ctx, user.ID, servers, timeout)+ results, err := h.mcpService.ImportServers(ctx, servers, timeout)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalized := permissionresponse.Normalize(err)@@ -352,11 +322,6 @@ func (h *MCPHandler) ImportMCPServers(c *gin.Context) {// @Param request body service.TestServerRequest true "test parameters"// @Router /api/v1/mcp/servers/{mcp_id}/test [post]func (h *MCPHandler) TestMCPServer(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }mcpID := c.Param("mcp_id")if mcpID == "" {@@ -383,7 +348,7 @@ func (h *MCPHandler) TestMCPServer(c *gin.Context) {}ctx := c.Request.Context()- tools, err := h.mcpService.TestServer(ctx, user.ID, mcpID, &req)+ tools, err := h.mcpService.TestServer(ctx, mcpID, &req)if mcpErrorResponse(c, err) {return}diff --git a/internal/handler/memory.go b/internal/handler/memory.goindex 1d080809ac..4a891d041b 100644--- a/internal/handler/memory.go+++ b/internal/handler/memory.go@@ -76,8 +76,8 @@ func NewMemoryHandler(memoryService *service.MemoryService) *MemoryHandler {// - message: "success" on success, error message on failure// - data: Memory object on success//-// Business Logic (matching Python create_memory):-// 1. Validate user login status+// Business Logic:+// 1. Apply billing and application quotas// 2. Parse and validate request parameters// 3. Call service layer to create memory// 4. Return creation result@@ -91,15 +91,6 @@ func (h *MemoryHandler) CreateMemory(c *gin.Context) {return}- // Get current logged-in user information- // GetUser is a context value set by the authentication middleware- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }- userID := user.ID-// Parse JSON request bodyvar req service.CreateMemoryRequestif err = c.ShouldBindJSON(&req); err != nil {@@ -135,7 +126,7 @@ func (h *MemoryHandler) CreateMemory(c *gin.Context) {ctx := c.Request.Context()// Call service layer to create memory- result, err := h.memoryService.CreateMemory(ctx, userID, &req)+ result, err := h.memoryService.CreateMemory(ctx, &req)if err != nil {errMsg := err.Error()// Determine if it's an argument error and return appropriate error code@@ -188,14 +179,6 @@ func (h *MemoryHandler) UpdateMemory(c *gin.Context) {return}- // Get current logged-in user information- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }- userID := user.ID-// Parse JSON request bodyvar req service.UpdateMemoryRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -206,7 +189,7 @@ func (h *MemoryHandler) UpdateMemory(c *gin.Context) {ctx := c.Request.Context()// Call service layer to update memory- result, err := h.memoryService.UpdateMemory(ctx, userID, memoryID, &req)+ result, err := h.memoryService.UpdateMemory(ctx, memoryID, &req)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -252,16 +235,10 @@ func (h *MemoryHandler) DeleteMemory(c *gin.Context) {return}- // Get current logged-in user for access control- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()// Call service layer to delete memory (with access control)- err := h.memoryService.DeleteMemory(ctx, user.ID, memoryID)+ err := h.memoryService.DeleteMemory(ctx, memoryID)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -319,14 +296,8 @@ func splitQueryValues(c *gin.Context, key string) []string {// - data.memory_list: Array of Memory objects// - data.total_count: Total record countfunc (h *MemoryHandler) ListMemories(c *gin.Context) {- // Get current logged-in user information- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }if c.Query("type") == "filter" {- result, err := h.memoryService.ListMemoryFilters(c.Request.Context(), user.ID)+ result, err := h.memoryService.ListMemoryFilters(c.Request.Context())if err != nil {common.RespondError(c, common.CodeServerError, err.Error())return@@ -363,7 +334,7 @@ func (h *MemoryHandler) ListMemories(c *gin.Context) {ctx := c.Request.Context()// Call service layer to get memory list- result, err := h.memoryService.ListMemories(ctx, user.ID, tenantIDs, memoryTypes, storageType, keywords, page, pageSize, c.Query("canvas_id"))+ result, err := h.memoryService.ListMemories(ctx, tenantIDs, memoryTypes, storageType, keywords, page, pageSize, c.Query("canvas_id"))if err != nil {code := common.CodeServerErrorif errors.Is(err, permission.ErrUnauthenticated) || errors.Is(err, permission.ErrPermissionDenied) ||@@ -397,16 +368,10 @@ func (h *MemoryHandler) GetMemoryConfig(c *gin.Context) {return}- // Get current logged-in user for access control- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()// Call service layer to get memory configuration (with access control)- result, err := h.memoryService.GetMemoryConfig(ctx, user.ID, memoryID)+ result, err := h.memoryService.GetMemoryConfig(ctx, memoryID)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -447,17 +412,6 @@ func (h *MemoryHandler) GetMemoryConfig(c *gin.Context) {// - data.messages: Array of message objects// - data.storage_type: Storage typefunc (h *MemoryHandler) GetMemoryMessages(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-- userID := strings.TrimSpace(user.ID)- if userID == "" {- common.RespondError(c, common.CodeAuthenticationError, "user id is required")- return- }memoryID := strings.TrimSpace(c.Param("memory_id"))if memoryID == "" {@@ -483,7 +437,7 @@ func (h *MemoryHandler) GetMemoryMessages(c *gin.Context) {return}- data, err := h.memoryService.GetMemoryMessages(c.Request.Context(), userID, memoryID, agentIDs, keywords, page, pageSize)+ data, err := h.memoryService.GetMemoryMessages(c.Request.Context(), memoryID, agentIDs, keywords, page, pageSize)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -543,17 +497,7 @@ type AddMessageRequest struct {// - agent_response (required): Agent response// - user_id (optional): User IDfunc (h *MemoryHandler) AddMessage(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-- currentUserID := strings.TrimSpace(user.ID)- if currentUserID == "" {- common.RespondError(c, common.CodeArgumentError, "user_id is required")- return- }+ currentUserID := strings.TrimSpace(permission.UserIDFromContext(c.Request.Context()))var reqBody AddMessageRequestif err := c.ShouldBindJSON(&reqBody); err != nil {@@ -584,7 +528,7 @@ func (h *MemoryHandler) AddMessage(c *gin.Context) {AgentResponse: reqBody.AgentResponse,}- ok, message, err := h.memoryService.AddMessage(c.Request.Context(), currentUserID, []string(reqBody.MemoryIDs), msg)+ ok, message, err := h.memoryService.AddMessage(c.Request.Context(), []string(reqBody.MemoryIDs), msg)if err != nil || !ok {common.RespondError(c, common.CodeServerError, "Some messages failed to add. Detail:"+message)return@@ -604,11 +548,6 @@ func (h *MemoryHandler) AddMessage(c *gin.Context) {// - memory_id: Memory ID// - message_id: Message ID (integer)func (h *MemoryHandler) ForgetMessage(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }memoryID, messageID, err := parseMemoryMessagePath(c.Param("memory_message"))if err != nil {@@ -616,7 +555,7 @@ func (h *MemoryHandler) ForgetMessage(c *gin.Context) {return}- if err = h.memoryService.ForgetMessage(c.Request.Context(), user.ID, memoryID, messageID); err != nil {+ if err = h.memoryService.ForgetMessage(c.Request.Context(), memoryID, messageID); err != nil {if respondPermissionErrorIf(c, err, true) {return}@@ -676,17 +615,6 @@ func parseMemoryMessagePath(memoryMessage string) (string, int64, error) {// Request Parameters (JSON Body):// - status (required): Message status, booleanfunc (h *MemoryHandler) UpdateMessage(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-- userID := strings.TrimSpace(user.ID)- if userID == "" {- common.RespondError(c, common.CodeAuthenticationError, "user id is required")- return- }memoryID, messageID, err := parseMemoryMessagePath(c.Param("memory_message"))if err != nil {@@ -706,7 +634,7 @@ func (h *MemoryHandler) UpdateMessage(c *gin.Context) {return}- ok, err = h.memoryService.UpdateMessageStatus(c.Request.Context(), userID, memoryID, messageID, status)+ ok, err = h.memoryService.UpdateMessageStatus(c.Request.Context(), memoryID, messageID, status)if err != nil || !ok {if respondPermissionErrorIf(c, err, true) {return@@ -735,17 +663,6 @@ func (h *MemoryHandler) UpdateMessage(c *gin.Context) {//func (h *MemoryHandler) GetMessageContent(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-- userID := strings.TrimSpace(user.ID)- if userID == "" {- common.RespondError(c, common.CodeAuthenticationError, "user id is required")- return- }memoryID, messageID, err := parseMemoryMessagePath(c.Param("memory_message"))if err != nil {@@ -753,7 +670,7 @@ func (h *MemoryHandler) GetMessageContent(c *gin.Context) {return}- data, err := h.memoryService.GetMessageContent(c.Request.Context(), userID, memoryID, messageID)+ data, err := h.memoryService.GetMessageContent(c.Request.Context(), memoryID, messageID)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -787,17 +704,6 @@ func (h *MemoryHandler) GetMessageContent(c *gin.Context) {// - session_id (optional): Session ID filter// - user_id (optional): User ID filterfunc (h *MemoryHandler) SearchMessage(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-- userID := strings.TrimSpace(user.ID)- if userID == "" {- common.RespondError(c, common.CodeAuthenticationError, "user id is required")- return- }memoryIDs := splitQueryValues(c, "memory_id")@@ -836,7 +742,7 @@ func (h *MemoryHandler) SearchMessage(c *gin.Context) {"top_n": topN,}- res, code, err := h.memoryService.SearchMessage(c.Request.Context(), userID, filterDict, params)+ res, code, err := h.memoryService.SearchMessage(c.Request.Context(), filterDict, params)if err != nil {common.RespondError(c, code, err.Error())return@@ -858,17 +764,6 @@ func (h *MemoryHandler) SearchMessage(c *gin.Context) {// - session_id (optional): Session ID filter// - limit (optional): Number of results to return, default 10func (h *MemoryHandler) GetMessages(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-- userID := strings.TrimSpace(user.ID)- if userID == "" {- common.RespondError(c, common.CodeAuthenticationError, "user id is required")- return- }memoryIDs := splitQueryValues(c, "memory_id")@@ -884,7 +779,7 @@ func (h *MemoryHandler) GetMessages(c *gin.Context) {return}- data, code, err := h.memoryService.GetMessages(c.Request.Context(), memoryIDs, userID, agentID, sessionID, limit)+ data, code, err := h.memoryService.GetMessages(c.Request.Context(), memoryIDs, agentID, sessionID, limit)if err != nil {common.RespondError(c, code, err.Error())returndiff --git a/internal/service/connector.go b/internal/service/connector.goindex c1c703ddad..1799b454dd 100644--- a/internal/service/connector.go+++ b/internal/service/connector.go@@ -277,7 +277,11 @@ func (s *ConnectorService) cancelConnectorTasks(ctx context.Context, connectorID}// CreateConnector creates a connector owned by the current user.-func (s *ConnectorService) CreateConnector(ctx context.Context, userID string, req *CreateConnectorRequest) (*entity.Connector, error) {+func (s *ConnectorService) CreateConnector(ctx context.Context, req *CreateConnectorRequest) (*entity.Connector, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }tenantID, err := requireCurrentTenantID(ctx, userID)if err != nil {return nil, err@@ -333,7 +337,7 @@ func (s *ConnectorService) CreateConnector(ctx context.Context, userID string, r}// GetConnector returns one connector when the user has read permission.-func (s *ConnectorService) GetConnector(ctx context.Context, connectorID, userID string) (*entity.Connector, error) {+func (s *ConnectorService) GetConnector(ctx context.Context, connectorID string) (*entity.Connector, error) {if strings.TrimSpace(connectorID) == "" {return nil, ErrConnectorIDRequired}@@ -354,10 +358,10 @@ func (s *ConnectorService) GetConnector(ctx context.Context, connectorID, userID}// ListConnectors returns connectors belonging to a tenant the caller can use.-func (s *ConnectorService) ListConnectors(ctx context.Context, userID, requestedTenantID string) (*ListConnectorsResponse, error) {- userID = strings.TrimSpace(userID)+func (s *ConnectorService) ListConnectors(ctx context.Context, requestedTenantID string) (*ListConnectorsResponse, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))if userID == "" {- return nil, fmt.Errorf("user_id is required")+ return nil, permission.ErrUnauthenticated}tenantID := strings.TrimSpace(requestedTenantID)@@ -384,7 +388,7 @@ func (s *ConnectorService) ListConnectors(ctx context.Context, userID, requested}// TestConnector validates connector settings without persisting or syncing.-func (s *ConnectorService) TestConnector(ctx context.Context, connectorID, userID string, config entity.JSONMap) error {+func (s *ConnectorService) TestConnector(ctx context.Context, connectorID string, config entity.JSONMap) error {var storedConnector *entity.Connectorif connectorID != "" {permissionErr := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindConnector, ID: connectorID}, permission.OperationUse)@@ -497,7 +501,11 @@ func stringConfigValue(value any) string {}}-func (s *ConnectorService) StartGoogleWebOAuth(ctx context.Context, userID, source string, req *StartGoogleWebOAuthRequest) (*StartGoogleWebOAuthResponse, common.ErrorCode, error) {+func (s *ConnectorService) StartGoogleWebOAuth(ctx context.Context, source string, req *StartGoogleWebOAuthRequest) (*StartGoogleWebOAuthResponse, common.ErrorCode, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated+ }source = strings.TrimSpace(source)if source == "" {source = "google-drive"@@ -638,7 +646,11 @@ func (s *ConnectorService) GoogleWebOAuthCallback(ctx context.Context, source, sreturn renderWebOAuthPopup(stateID, true, "Authorization completed successfully.", source)}-func (s *ConnectorService) PollGoogleWebOAuthResult(ctx context.Context, userID, source string, req *PollGoogleWebOAuthResultRequest) (*PollGoogleWebOAuthResultResponse, common.ErrorCode, error) {+func (s *ConnectorService) PollGoogleWebOAuthResult(ctx context.Context, source string, req *PollGoogleWebOAuthResultRequest) (*PollGoogleWebOAuthResultResponse, common.ErrorCode, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated+ }source = strings.TrimSpace(source)if source != "google-drive" && source != "gmail" {return nil, common.CodeArgumentError, fmt.Errorf("invalid Google OAuth type")@@ -942,7 +954,7 @@ func webOAuthSourceDisplayName(source string) string {return "OAuth"}-func (s *ConnectorService) DeleteConnector(ctx context.Context, connectorID, userID string) (bool, common.ErrorCode, error) {+func (s *ConnectorService) DeleteConnector(ctx context.Context, connectorID string) (bool, common.ErrorCode, error) {if connectorID == "" {return false, common.CodeDataError, fmt.Errorf("connector_id is required")}@@ -978,7 +990,7 @@ type UpdateConnectorRequest struct {Status string `json:"status,omitempty"`}-func (s *ConnectorService) UpdateConnector(ctx context.Context, connectorID, userID string, req *UpdateConnectorRequest) (*entity.Connector, common.ErrorCode, error) {+func (s *ConnectorService) UpdateConnector(ctx context.Context, connectorID string, req *UpdateConnectorRequest) (*entity.Connector, common.ErrorCode, error) {if connectorID == "" {return nil, common.CodeDataError, fmt.Errorf("connector_id is required")}@@ -1074,7 +1086,7 @@ func isConnectorScheduleStatus(status string) bool {}// RebuildConnector schedules a rebuild for an accessible connector and knowledge base.-func (s *ConnectorService) RebuildConnector(ctx context.Context, connectorID, userID, kbID string) (bool, common.ErrorCode, error) {+func (s *ConnectorService) RebuildConnector(ctx context.Context, connectorID, kbID string) (bool, common.ErrorCode, error) {if connectorID == "" {return false, common.CodeDataError, fmt.Errorf("connector_id is required")}@@ -1098,7 +1110,7 @@ func (s *ConnectorService) RebuildConnector(ctx context.Context, connectorID, us// be accessible to the caller and the connector must be bound to it.if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindDataset, ID: kbID}, permission.OperationRun); err != nil {common.Warn("rebuild denied: kb not accessible",- zap.String("connector_id", connectorID), zap.String("kb_id", kbID), zap.String("user_id", userID))+ zap.String("connector_id", connectorID), zap.String("kb_id", kbID), zap.String("user_id", permission.UserIDFromContext(ctx)))code, permissionErr := permissionresponse.Normalize(err)return false, code, permissionErr}@@ -1108,7 +1120,7 @@ func (s *ConnectorService) RebuildConnector(ctx context.Context, connectorID, us}if !bound {common.Warn("rebuild denied: connector not bound to kb",- zap.String("connector_id", connectorID), zap.String("kb_id", kbID), zap.String("user_id", userID))+ zap.String("connector_id", connectorID), zap.String("kb_id", kbID), zap.String("user_id", permission.UserIDFromContext(ctx)))return false, common.CodeAuthenticationError, ErrConnectorNotBoundToKB}@@ -1135,7 +1147,7 @@ func (s *ConnectorService) RebuildConnector(ctx context.Context, connectorID, us}// ResumeFailedSync schedules a failed sync task to continue from its saved checkpoint.-func (s *ConnectorService) ResumeFailedSync(ctx context.Context, connectorID, userID string, req *ResumeFailedSyncRequest) (bool, common.ErrorCode, error) {+func (s *ConnectorService) ResumeFailedSync(ctx context.Context, connectorID string, req *ResumeFailedSyncRequest) (bool, common.ErrorCode, error) {if connectorID == "" {return false, common.CodeDataError, fmt.Errorf("connector_id is required")}@@ -1273,7 +1285,7 @@ func (s *ConnectorService) deleteConnectorDocumentChunks(ctx context.Context, te}}-func (s *ConnectorService) ListLog(ctx context.Context, connectorID, userID string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error) {+func (s *ConnectorService) ListLog(ctx context.Context, connectorID string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error) {if connectorID == "" {return nil, 0, common.CodeDataError, fmt.Errorf("connector_id is required")}@@ -1320,10 +1332,9 @@ func (s *ConnectorService) ListLog(ctx context.Context, connectorID, userID stri// ListLogs lists sync logs for the current user with pagination.// When datasetID is non-empty, only logs of that dataset are returned.-func (s *ConnectorService) ListLogs(ctx context.Context, userID, datasetID string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error) {- userID = strings.TrimSpace(userID)- if userID == "" {- return nil, 0, common.CodeDataError, fmt.Errorf("user_id is required")+func (s *ConnectorService) ListLogs(ctx context.Context, datasetID string, page, pageSize int) ([]*entity.ConnectorSyncLog, int64, common.ErrorCode, error) {+ if strings.TrimSpace(permission.UserIDFromContext(ctx)) == "" {+ return nil, 0, common.CodeUnauthorized, permission.ErrUnauthenticated}if datasetID != "" {@@ -1387,7 +1398,11 @@ func (s *ConnectorService) ListLogs(ctx context.Context, userID, datasetID strinreturn logs, total, common.CodeSuccess, nil}-func (s *ConnectorService) StartBoxWebOAuth(ctx context.Context, userID string, req *StartBoxWebOAuthRequest) (*StartBoxWebOAuthResponse, common.ErrorCode, error) {+func (s *ConnectorService) StartBoxWebOAuth(ctx context.Context, req *StartBoxWebOAuthRequest) (*StartBoxWebOAuthResponse, common.ErrorCode, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated+ }var clientID, clientSecret, redirectURI stringif req != nil {clientID = strings.TrimSpace(req.ClientID)@@ -1487,7 +1502,11 @@ func (s *ConnectorService) BoxWebOAuthCallback(ctx context.Context, flowID strinreturn renderWebOAuthPopup(flowID, true, "Authorization completed successfully.", "box")}-func (s *ConnectorService) PollBoxWebOAuthResult(ctx context.Context, userID string, req *PollBoxWebOAuthResultRequest) (*PollBoxWebOAuthResultResponse, common.ErrorCode, error) {+func (s *ConnectorService) PollBoxWebOAuthResult(ctx context.Context, req *PollBoxWebOAuthResultRequest) (*PollBoxWebOAuthResultResponse, common.ErrorCode, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated+ }if req == nil || strings.TrimSpace(req.FlowID) == "" {return nil, common.CodeArgumentError, fmt.Errorf("required argument is missing: flow_id")}diff --git a/internal/service/connector_box_oauth_test.go b/internal/service/connector_box_oauth_test.goindex e4f6fec10e..ba1f919231 100644--- a/internal/service/connector_box_oauth_test.go+++ b/internal/service/connector_box_oauth_test.go@@ -140,9 +140,9 @@ func TestExchangeBoxAuthorizationCodeRequestBody(t *testing.T) {func TestStartBoxWebOAuthRequiresClientCredentials(t *testing.T) {svc := NewConnectorService()- ctx := t.Context()+ ctx := serviceTestContext(t, "user-1", "user-1")- _, code, err := svc.StartBoxWebOAuth(ctx, "user-1", &StartBoxWebOAuthRequest{ClientID: "client-1"})+ _, code, err := svc.StartBoxWebOAuth(ctx, &StartBoxWebOAuthRequest{ClientID: "client-1"})if err == nil {t.Fatal("expected error")}@@ -158,9 +158,9 @@ func TestPollBoxWebOAuthResultPendingWithoutRedis(t *testing.T) {forceNilConnectorRedis(t)svc := NewConnectorService()- ctx := t.Context()+ ctx := serviceTestContext(t, "user-1", "user-1")- _, code, err := svc.PollBoxWebOAuthResult(ctx, "user-1", &PollBoxWebOAuthResultRequest{FlowID: "flow-1"})+ _, code, err := svc.PollBoxWebOAuthResult(ctx, &PollBoxWebOAuthResultRequest{FlowID: "flow-1"})if err == nil {t.Fatal("expected pending error")}diff --git a/internal/service/connector_freq_test.go b/internal/service/connector_freq_test.goindex 6e2bbbe7d3..e7108e32b1 100644--- a/internal/service/connector_freq_test.go+++ b/internal/service/connector_freq_test.go@@ -41,7 +41,7 @@ func TestCreateConnectorRejectsNonPositiveFreq(t *testing.T) {"prune zero": {Name: "c", Source: "rss", Config: entity.JSONMap{}, PruneFreq: int64Ptr(0)},"prune negative": {Name: "c", Source: "rss", Config: entity.JSONMap{}, PruneFreq: int64Ptr(-1)},} {- if _, err := svc.CreateConnector(serviceTestContext(t, "user-1", "user-1"), "user-1", req); err == nil {+ if _, err := svc.CreateConnector(serviceTestContext(t, "user-1", "user-1"), req); err == nil {t.Fatalf("%s: CreateConnector succeeded, want frequency error", name)} else if !errors.Is(err, ErrConnectorInvalidFreq) {t.Fatalf("%s: error = %v, want ErrConnectorInvalidFreq", name, err)@@ -59,7 +59,7 @@ func TestUpdateConnectorRejectsNonPositiveFreq(t *testing.T) {"prune zero": {PruneFreq: int64Ptr(0)},"prune negative": {PruneFreq: int64Ptr(-1)},} {- _, code, err := svc.UpdateConnector(serviceTestContext(t, "user-1", "user-1"), "conn-freq", "user-1", req)+ _, code, err := svc.UpdateConnector(serviceTestContext(t, "user-1", "user-1"), "conn-freq", req)if err == nil {t.Fatalf("%s: UpdateConnector succeeded, want frequency error", name)}diff --git a/internal/service/connector_logs_test.go b/internal/service/connector_logs_test.goindex ef200f935c..47b9e47282 100644--- a/internal/service/connector_logs_test.go+++ b/internal/service/connector_logs_test.go@@ -80,7 +80,7 @@ func TestListLogsPaginationModes(t *testing.T) {svc := NewConnectorService()ctx := serviceTestContext(t, "user-1", "user-1")- all, total, code, err := svc.ListLogs(ctx, "user-1", "", 1, 0)+ all, total, code, err := svc.ListLogs(ctx, "", 1, 0)if err != nil || code != common.CodeSuccess {t.Fatalf("ListLogs(all): code=%v err=%v", code, err)}@@ -88,7 +88,7 @@ func TestListLogsPaginationModes(t *testing.T) {t.Fatalf("ListLogs(all) = total %d len %d, want 5/5", total, len(all))}- first, total, code, err := svc.ListLogs(ctx, "user-1", "", 1, 2)+ first, total, code, err := svc.ListLogs(ctx, "", 1, 2)if err != nil || code != common.CodeSuccess {t.Fatalf("ListLogs(page): code=%v err=%v", code, err)}@@ -96,7 +96,7 @@ func TestListLogsPaginationModes(t *testing.T) {t.Fatalf("ListLogs(page) = total %d len %d, want 5/2", total, len(first))}- second, total, code, err := svc.ListLogs(ctx, "user-1", "", 2, 2)+ second, total, code, err := svc.ListLogs(ctx, "", 2, 2)if err != nil || code != common.CodeSuccess {t.Fatalf("ListLogs(page2): code=%v err=%v", code, err)}@@ -104,7 +104,7 @@ func TestListLogsPaginationModes(t *testing.T) {t.Fatalf("ListLogs(page2) = total %d len %d, want 5/2", total, len(second))}- normalized, total, code, err := svc.ListLogs(ctx, "user-1", "", 0, 101)+ normalized, total, code, err := svc.ListLogs(ctx, "", 0, 101)if err != nil || code != common.CodeSuccess {t.Fatalf("ListLogs(normalize): code=%v err=%v", code, err)}@@ -183,7 +183,7 @@ func TestListLogsStatusPriority(t *testing.T) {svc := NewConnectorService()ctx := serviceTestContext(t, "user-1", "user-1")- byConnector, total, code, err := svc.ListLog(ctx, "conn-1", "user-1", 1, 100)+ byConnector, total, code, err := svc.ListLog(ctx, "conn-1", 1, 100)if err != nil || code != common.CodeSuccess {t.Fatalf("ListLog: code=%v err=%v", code, err)}@@ -192,7 +192,7 @@ func TestListLogsStatusPriority(t *testing.T) {}assertLogOrder(t, "ListLog", byConnector, want)- tenantWide, total, code, err := svc.ListLogs(ctx, "user-1", "", 1, 100)+ tenantWide, total, code, err := svc.ListLogs(ctx, "", 1, 100)if err != nil || code != common.CodeSuccess {t.Fatalf("ListLogs: code=%v err=%v", code, err)}diff --git a/internal/service/connector_syncer_test.go b/internal/service/connector_syncer_test.goindex dd0b158592..25e41e7a37 100644--- a/internal/service/connector_syncer_test.go+++ b/internal/service/connector_syncer_test.go@@ -91,7 +91,7 @@ func TestUpdateConnectorSchedulePublishesSyncerTask(t *testing.T) {}t.Cleanup(func() { getSyncerTaskPublisher = previousPublisher })- _, code, err := NewConnectorService().UpdateConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", "user-1", &UpdateConnectorRequest{+ _, code, err := NewConnectorService().UpdateConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", &UpdateConnectorRequest{Status: string(entity.TaskStatusSchedule),})if err != nil {@@ -180,7 +180,7 @@ func TestResumeFailedSyncSchedulesOriginalTaskFromCheckpoint(t *testing.T) {getSyncCheckpointLoader = previousLoader})- ok, code, err := NewConnectorService().ResumeFailedSync(serviceTestContext(t, "user-1", "user-1"), "conn-1", "user-1", &ResumeFailedSyncRequest{KbID: "kb-1", TaskID: "task-1"})+ ok, code, err := NewConnectorService().ResumeFailedSync(serviceTestContext(t, "user-1", "user-1"), "conn-1", &ResumeFailedSyncRequest{KbID: "kb-1", TaskID: "task-1"})if err != nil {t.Fatalf("ResumeFailedSync error: %v", err)}@@ -272,7 +272,7 @@ func TestRebuildConnectorDeletesOldSyncCheckpointsBeforePublishing(t *testing.T)getSyncCheckpointDeleter = previousDeleter})- ok, code, err := NewConnectorService().RebuildConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", "user-1", "kb-1")+ ok, code, err := NewConnectorService().RebuildConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", "kb-1")if err != nil {t.Fatalf("RebuildConnector error: %v", err)}@@ -326,7 +326,7 @@ func TestRebuildConnectorRejectsCrossTenantAndUnboundKB(t *testing.T) {// The caller can access kb-1, but conn-1 is not bound to it: denied before// any documents are listed or deleted.- ok, code, err := svc.RebuildConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", "user-1", "kb-1")+ ok, code, err := svc.RebuildConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", "kb-1")if err == nil || !errors.Is(err, ErrConnectorNotBoundToKB) {t.Fatalf("err = %v, want ErrConnectorNotBoundToKB", err)}@@ -335,7 +335,7 @@ func TestRebuildConnectorRejectsCrossTenantAndUnboundKB(t *testing.T) {}// The caller cannot access a cross-tenant kb at all: denied up front.- ok, code, err = svc.RebuildConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", "user-1", "kb-foreign")+ ok, code, err = svc.RebuildConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", "kb-foreign")if err == nil || (!errors.Is(err, permission.ErrResourceNotFound) && !errors.Is(err, permission.ErrPermissionDenied)) {t.Fatalf("err = %v, want hidden cross-tenant resource", err)}@@ -400,7 +400,7 @@ func TestUpdateConnectorScheduleDoesNotDuplicateRunningTask(t *testing.T) {}t.Cleanup(func() { getSyncerTaskPublisher = previousPublisher })- _, code, err := NewConnectorService().UpdateConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", "user-1", &UpdateConnectorRequest{+ _, code, err := NewConnectorService().UpdateConnector(serviceTestContext(t, "user-1", "user-1"), "conn-1", &UpdateConnectorRequest{Status: string(entity.TaskStatusSchedule),})if err != nil {diff --git a/internal/service/connector_test_connection_test.go b/internal/service/connector_test_connection_test.goindex 6a094cec47..66cc9d4693 100644--- a/internal/service/connector_test_connection_test.go+++ b/internal/service/connector_test_connection_test.go@@ -43,7 +43,7 @@ func TestConnectorServiceTestConnectorUsesRequestConfig(t *testing.T) {"source": "mock","config": entity.JSONMap{"from": "request"},}- if err := svc.TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "conn-1", "tenant-1", request); err != nil {+ if err := svc.TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "conn-1", request); err != nil {t.Fatalf("TestConnector failed: %v", err)}if capturedConfig["from"] != "request" {@@ -65,7 +65,7 @@ func TestConnectorServiceTestConnectorAllowsUnsavedConnectorWithSource(t *testinsvc := NewConnectorService()svc.connectorRegistry = registry- err := svc.TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", "tenant-1", entity.JSONMap{+ err := svc.TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", entity.JSONMap{"source": "mock","config": entity.JSONMap{"ok": true},})@@ -88,7 +88,7 @@ func TestConnectorServiceTestConnectorSurfacesRawValidationError(t *testing.T) {svc := NewConnectorService()svc.connectorRegistry = registry- err := svc.TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", "tenant-1", entity.JSONMap{+ err := svc.TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", entity.JSONMap{"source": "mock","config": entity.JSONMap{"ok": true},})@@ -105,7 +105,7 @@ func TestConnectorServiceTestConnectorRejectsMissingConfigForMissingConnector(tt.Fatalf("migrate connector tables: %v", err)}- err := NewConnectorService().TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", "tenant-1", nil)+ err := NewConnectorService().TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", nil)if !errors.Is(err, ErrConnectorNotFound) {t.Fatalf("error = %v, want ErrConnectorNotFound", err)}@@ -129,7 +129,7 @@ func TestConnectorServiceTestConnectorRejectsUnauthorizedConnector(t *testing.T)t.Fatalf("insert connector: %v", err)}- err := NewConnectorService().TestConnector(serviceTestContext(t, "user-2", "user-2"), "conn-1", "user-2", entity.JSONMap{+ err := NewConnectorService().TestConnector(serviceTestContext(t, "user-2", "user-2"), "conn-1", entity.JSONMap{"source": "mock","config": entity.JSONMap{"ok": true},})@@ -145,7 +145,7 @@ func TestConnectorServiceTestConnectorRejectsUnsupportedSource(t *testing.T) {t.Fatalf("migrate connector tables: %v", err)}- err := NewConnectorService().TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", "tenant-1", entity.JSONMap{+ err := NewConnectorService().TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", entity.JSONMap{"source": "unknown","config": entity.JSONMap{"ok": true},})@@ -168,7 +168,7 @@ func TestConnectorServiceTestConnectorRejectsConnectorWithoutValidator(t *testinsvc := NewConnectorService()svc.connectorRegistry = registry- err := svc.TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", "tenant-1", entity.JSONMap{+ err := svc.TestConnector(serviceTestContext(t, "tenant-1", "tenant-1"), "missing", entity.JSONMap{"source": "plain","config": entity.JSONMap{"ok": true},})diff --git a/internal/service/mcp.go b/internal/service/mcp.goindex 44f65b21f4..64e487f34b 100644--- a/internal/service/mcp.go+++ b/internal/service/mcp.go@@ -108,7 +108,12 @@ type ListMCPServersResponse struct {const maxMCPFetchTimeoutSec = 60// CreateMCPServer creates an MCP server in the caller's owned tenant.-func (s *MCPService) CreateMCPServer(ctx context.Context, userID string, req CreateMCPServerRequest) (*CreateMCPServerResponse, common.ErrorCode, error) {+func (s *MCPService) CreateMCPServer(ctx context.Context, req CreateMCPServerRequest) (*CreateMCPServerResponse, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ code, normalized := permissionresponse.Normalize(permission.ErrUnauthenticated)+ return nil, code, normalized+ }if req.Timeout < 0 || req.Timeout > maxMCPFetchTimeoutSec {return nil, common.CodeDataError, errors.New("invalid timeout")}@@ -369,7 +374,7 @@ func importedMCPHeaders(raw interface{}) (map[string]string, map[string]interfacreturn headers, values, true}-func (s *MCPService) GetMCPServer(ctx context.Context, userID, mcpID string) (*entity.MCPServer, common.ErrorCode, error) {+func (s *MCPService) GetMCPServer(ctx context.Context, mcpID string) (*entity.MCPServer, common.ErrorCode, error) {if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindMCPServer, ID: mcpID}, permission.OperationRead); err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized@@ -385,8 +390,8 @@ func (s *MCPService) GetMCPServer(ctx context.Context, userID, mcpID string) (*ereturn server, common.CodeSuccess, nil}-func (s *MCPService) ExportMCPServer(ctx context.Context, userID, mcpID string) (*ExportMCPServerResponse, common.ErrorCode, error) {- server, code, err := s.GetMCPServer(ctx, userID, mcpID)+func (s *MCPService) ExportMCPServer(ctx context.Context, mcpID string) (*ExportMCPServerResponse, common.ErrorCode, error) {+ server, code, err := s.GetMCPServer(ctx, mcpID)if err != nil {return nil, code, err}@@ -394,7 +399,7 @@ func (s *MCPService) ExportMCPServer(ctx context.Context, userID, mcpID string)}// UpdateMCPServer updates an MCP server the caller can manage.-func (s *MCPService) UpdateMCPServer(ctx context.Context, userID, mcpID string, req UpdateMCPServerRequest) (*entity.MCPServer, common.ErrorCode, error) {+func (s *MCPService) UpdateMCPServer(ctx context.Context, mcpID string, req UpdateMCPServerRequest) (*entity.MCPServer, common.ErrorCode, error) {if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindMCPServer, ID: mcpID}, permission.OperationUpdate); err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized@@ -542,7 +547,8 @@ func headerOrVariablesChanged(req UpdateMCPServerRequest) bool {}// ListMCPServers lists MCP servers belonging to a tenant the caller can use.-func (s *MCPService) ListMCPServers(ctx context.Context, userID, requestedTenantID string, ids []string, keywords string, page, pageSize int, orderby string, desc bool) (*ListMCPServersResponse, common.ErrorCode, error) {+func (s *MCPService) ListMCPServers(ctx context.Context, requestedTenantID string, ids []string, keywords string, page, pageSize int, orderby string, desc bool) (*ListMCPServersResponse, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)tenantID := strings.TrimSpace(requestedTenantID)if tenantID == "" {var err error@@ -628,7 +634,7 @@ func (s *MCPService) ListMCPServers(ctx context.Context, userID, requestedTenant}// DeleteMCPServer deletes an MCP server the caller can manage.-func (s *MCPService) DeleteMCPServer(ctx context.Context, userID, mcpID string) (bool, common.ErrorCode, error) {+func (s *MCPService) DeleteMCPServer(ctx context.Context, mcpID string) (bool, common.ErrorCode, error) {if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindMCPServer, ID: mcpID}, permission.OperationDelete); err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return false, code, normalized@@ -727,7 +733,11 @@ type ImportResult struct {}// ImportServers bulk-imports MCP servers from a {"mcpServers": {name: config}} map.-func (s *MCPService) ImportServers(ctx context.Context, userID string, servers map[string]map[string]interface{}, timeoutSeconds float64) ([]ImportResult, error) {+func (s *MCPService) ImportServers(ctx context.Context, servers map[string]map[string]interface{}, timeoutSeconds float64) ([]ImportResult, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }tenantID, err := requireCurrentTenantID(ctx, userID)if err != nil {_, normalized := permissionresponse.Normalize(err)@@ -871,7 +881,7 @@ type TestServerRequest struct {}// TestServer opens a live MCP session and returns the tools the server advertises.-func (s *MCPService) TestServer(ctx context.Context, userID, mcpID string, req *TestServerRequest) ([]map[string]interface{}, error) {+func (s *MCPService) TestServer(ctx context.Context, mcpID string, req *TestServerRequest) ([]map[string]interface{}, error) {if req == nil || req.URL == "" {return nil, fmt.Errorf("%w: Invalid MCP url", ErrMCPInvalidURL)}diff --git a/internal/service/mcp_test.go b/internal/service/mcp_test.goindex b5810df081..c59a07935e 100644--- a/internal/service/mcp_test.go+++ b/internal/service/mcp_test.go@@ -77,17 +77,17 @@ func TestUpdateMCPServerRejectsDuplicatedName(t *testing.T) {}// Renaming to an existing server name of the same tenant is rejected.- if _, code, err := s.UpdateMCPServer(ctx, tenantID, "mcp-1", nameReq("beta")); err == nil || code != common.CodeDataError {+ if _, code, err := s.UpdateMCPServer(ctx, "mcp-1", nameReq("beta")); err == nil || code != common.CodeDataError {t.Errorf("expected duplicated name data error, got code=%v err=%v", code, err)}// Keeping the current name is allowed.- if _, code, err := s.UpdateMCPServer(ctx, tenantID, "mcp-1", nameReq("alpha")); err != nil || code != common.CodeSuccess {+ if _, code, err := s.UpdateMCPServer(ctx, "mcp-1", nameReq("alpha")); err != nil || code != common.CodeSuccess {t.Errorf("expected success keeping current name, got code=%v err=%v", code, err)}// Renaming to a fresh name is allowed.- updated, code, err := s.UpdateMCPServer(ctx, tenantID, "mcp-1", nameReq("gamma"))+ updated, code, err := s.UpdateMCPServer(ctx, "mcp-1", nameReq("gamma"))if err != nil || code != common.CodeSuccess {t.Fatalf("expected success renaming to fresh name, got code=%v err=%v", code, err)}@@ -101,17 +101,17 @@ func TestServerInputValidation(t *testing.T) {ctx := t.Context()// Empty URL is rejected before any connection attempt.- if _, err := s.TestServer(ctx, "tenant-1", "id-1", &TestServerRequest{ServerType: mcpServerTypeSSE}); !errors.Is(err, ErrMCPInvalidURL) {+ if _, err := s.TestServer(ctx, "id-1", &TestServerRequest{ServerType: mcpServerTypeSSE}); !errors.Is(err, ErrMCPInvalidURL) {t.Errorf("expected ErrMCPInvalidURL for empty url, got %v", err)}// nil body is treated as empty URL.- if _, err := s.TestServer(ctx, "tenant-1", "id-1", nil); !errors.Is(err, ErrMCPInvalidURL) {+ if _, err := s.TestServer(ctx, "id-1", nil); !errors.Is(err, ErrMCPInvalidURL) {t.Errorf("expected ErrMCPInvalidURL for nil body, got %v", err)}// Invalid server type is rejected before connecting.- if _, err := s.TestServer(ctx, "tenant-1", "id-1", &TestServerRequest{URL: "http://example.com/sse", ServerType: "stdio"}); !errors.Is(err, ErrMCPInvalidType) {+ if _, err := s.TestServer(ctx, "id-1", &TestServerRequest{URL: "http://example.com/sse", ServerType: "stdio"}); !errors.Is(err, ErrMCPInvalidType) {t.Errorf("expected ErrMCPInvalidType for bad type, got %v", err)}}@@ -132,7 +132,7 @@ func TestImportServersValidationErrors(t *testing.T) {"bad-type": {"url": "http://example.com", "type": "stdio"},}ctx := serviceTestContext(t, "tenant-1", "tenant-1")- results, err := s.ImportServers(ctx, "tenant-1", configs, 1)+ results, err := s.ImportServers(ctx, configs, 1)if err != nil {t.Fatalf("unexpected error: %v", err)}@@ -221,7 +221,7 @@ func TestMCPManagedTokenLifecycle(t *testing.T) {withMCPDiscoveryOverrides(t, server)s := NewMCPService()ctx := serviceTestContext(t, "tenant-1", "tenant-1")- created, code, err := s.CreateMCPServer(ctx, "tenant-1", CreateMCPServerRequest{+ created, code, err := s.CreateMCPServer(ctx, CreateMCPServerRequest{Name: "managed-auth", URL: server.URL, ServerType: mcpServerTypeStreamableHTTP,Headers: json.RawMessage(`{"Authorization":"Bearer ${authorization_token}"}`),Variables: json.RawMessage(`{"authorization_token":"ragflow-secret"}`),@@ -235,18 +235,18 @@ func TestMCPManagedTokenLifecycle(t *testing.T) {if created.Headers["Authorization"] != maskedMCPSecret {t.Fatal("create response exposed headers")}- listed, _, err := s.ListMCPServers(ctx, "tenant-1", "", nil, "", 0, 0, "create_time", false)+ listed, _, err := s.ListMCPServers(ctx, "", nil, "", 0, 0, "create_time", false)if err != nil || len(listed.MCPServers) != 1 || listed.MCPServers[0].Variables["authorization_token"] != maskedMCPSecret {t.Fatalf("list: result=%#v err=%v", listed, err)}testReq := &TestServerRequest{URL: server.URL, ServerType: mcpServerTypeStreamableHTTP, Headers: map[string]any(created.Headers), Variables: map[string]any{"authorization_token": maskedMCPSecret}}beforeRejected := len(captured())testReq.URL = server.URL + "/other"- if _, err := s.TestServer(ctx, "tenant-1", created.ID, testReq); err == nil {+ if _, err := s.TestServer(ctx, created.ID, testReq); err == nil {t.Fatal("preview reused credentials for a different URL")}testReq.Variables["authorization_token"] = "replacement"- if _, err := s.TestServer(ctx, "tenant-1", created.ID, testReq); err == nil {+ if _, err := s.TestServer(ctx, created.ID, testReq); err == nil {t.Fatal("preview reused masked headers for a different URL")}testReq.Variables["authorization_token"] = maskedMCPSecret@@ -257,23 +257,23 @@ func TestMCPManagedTokenLifecycle(t *testing.T) {{"variables": json.RawMessage(`{"authorization_token":"replacement"}`), "headers": json.RawMessage(`{"Authorization":"********"}`)},} {extra["url"] = json.RawMessage(fmt.Sprintf("%q", server.URL+"/other"))- if _, _, err := s.UpdateMCPServer(ctx, "tenant-1", created.ID, extra); err == nil {+ if _, _, err := s.UpdateMCPServer(ctx, created.ID, extra); err == nil {t.Fatal("update reused credentials for a different URL")}}if len(captured()) != beforeRejected {t.Fatal("rejected endpoint changes made outbound requests")}- if _, err := s.TestServer(serviceTestContext(t, "other-tenant", "other-tenant"), "other-tenant", created.ID, testReq); err == nil {+ if _, err := s.TestServer(serviceTestContext(t, "other-tenant", "other-tenant"), created.ID, testReq); err == nil {t.Fatal("masked preview resolved another tenant's credential")}- if _, err := s.TestServer(ctx, "tenant-1", created.ID, testReq); err != nil {+ if _, err := s.TestServer(ctx, created.ID, testReq); err != nil {t.Fatalf("masked preview: %v", err)}if testReq.Variables["authorization_token"] != maskedMCPSecret || testReq.Headers["Authorization"] != maskedMCPSecret {t.Fatal("preview mutated the client payload")}- updated, code, err := s.UpdateMCPServer(ctx, "tenant-1", created.ID, UpdateMCPServerRequest{+ updated, code, err := s.UpdateMCPServer(ctx, created.ID, UpdateMCPServerRequest{"url": json.RawMessage(fmt.Sprintf("%q", server.URL)),"variables": json.RawMessage(`{"authorization_token":"********"}`),"headers": json.RawMessage(`{"Authorization":"********"}`),@@ -281,7 +281,7 @@ func TestMCPManagedTokenLifecycle(t *testing.T) {if err != nil || code != common.CodeSuccess || updated.URL != server.URL || updated.Variables["authorization_token"] != "ragflow-secret" {t.Fatalf("masked update: result=%#v code=%d err=%v", updated, code, err)}- stored, _, err := s.GetMCPServer(ctx, "tenant-1", created.ID)+ stored, _, err := s.GetMCPServer(ctx, created.ID)if err != nil || stored.URL != server.URL || stored.Variables["authorization_token"] != "ragflow-secret" {t.Fatalf("reload: result=%#v err=%v", stored, err)}@@ -293,7 +293,7 @@ func TestMCPManagedTokenLifecycle(t *testing.T) {t.Fatalf("authentication not preserved: %#v", headers)}}- exported, _, err := s.ExportMCPServer(ctx, "tenant-1", created.ID)+ exported, _, err := s.ExportMCPServer(ctx, created.ID)if err != nil {t.Fatal(err)}@@ -301,7 +301,7 @@ func TestMCPManagedTokenLifecycle(t *testing.T) {if err != nil || !strings.Contains(string(payload), "ragflow-secret") {t.Fatalf("explicit credential export: payload=%s err=%v", payload, err)}- updated, code, err = s.UpdateMCPServer(ctx, "tenant-1", created.ID, UpdateMCPServerRequest{+ updated, code, err = s.UpdateMCPServer(ctx, created.ID, UpdateMCPServerRequest{"url": json.RawMessage(fmt.Sprintf("%q", server.URL+"/other")),"variables": json.RawMessage(`{"authorization_token":"replacement"}`),"headers": json.RawMessage(`{"Authorization":"Bearer ${authorization_token}"}`),@@ -348,7 +348,7 @@ func TestImportServersPreservesExplicitHeadersAndVariables(t *testing.T) {defer srv.Close()withMCPDiscoveryOverrides(t, srv)- results, err := NewMCPService().ImportServers(serviceTestContext(t, "tenant-1", "tenant-1"), "tenant-1", map[string]map[string]interface{}{+ results, err := NewMCPService().ImportServers(serviceTestContext(t, "tenant-1", "tenant-1"), map[string]map[string]interface{}{"parallel": {"type": mcpServerTypeStreamableHTTP,"url": srv.URL,@@ -412,7 +412,7 @@ func TestImportServersPreservesExplicitHeadersAndVariables(t *testing.T) {t.Fatalf("export did not contain parallel config: %s", exported)}capturedBefore := len(captured())- reimported, err := NewMCPService().ImportServers(serviceTestContext(t, "tenant-1", "tenant-1"), "tenant-1", map[string]map[string]interface{}{+ reimported, err := NewMCPService().ImportServers(serviceTestContext(t, "tenant-1", "tenant-1"), map[string]map[string]interface{}{"parallel": reimportConfig,}, 2)if err != nil {@@ -527,7 +527,7 @@ func TestListMCPServersAppliesAuthorizationBeforeSQLPagination(t *testing.T) {}ctx := serviceTestContext(t, "owner", "tenant-1")- listed, code, err := NewMCPService().ListMCPServers(ctx, "owner", "tenant-1", nil, "", 2, 1, "name", false)+ listed, code, err := NewMCPService().ListMCPServers(ctx, "tenant-1", nil, "", 2, 1, "name", false)if err != nil || code != common.CodeSuccess {t.Fatalf("ListMCPServers() = (code %d, %v), want success", code, err)}diff --git a/internal/service/memory.go b/internal/service/memory.goindex b190a4cd0d..96cd971fe5 100644--- a/internal/service/memory.go+++ b/internal/service/memory.go@@ -411,7 +411,7 @@ type MemoryFiltersResponse struct {Total int64 `json:"total"`}-func (s *MemoryService) ListMemoryFilters(ctx context.Context, userID string) (*MemoryFiltersResponse, error) {+func (s *MemoryService) ListMemoryFilters(ctx context.Context) (*MemoryFiltersResponse, error) {memoryScope, err := permission.NewDatabaseChecker(s.db).Scope(ctx, permission.ScopeQuery{Kind: permission.ResourceKindMemory,Operation: permission.OperationRead,@@ -486,7 +486,7 @@ func filterOptionsInOrder(counts map[string]int64, canonicalOrder []string) []Me// It validates the request, generates a unique name if needed, and creates the memory record//// Parameters:-// - tenantID: The tenant ID for which to create the memory+// - ctx: The authenticated caller and active tenant context// - req: The memory creation request containing name, memory_type, embd_id, llm_id, etc.//// Returns:@@ -496,8 +496,12 @@ func filterOptionsInOrder(counts map[string]int64, canonicalOrder []string) []Me// Example://// req := &CreateMemoryRequest{Name: "MyMemory", MemoryType: []string{"semantic"}, EmbdID: "embd1", LLMID: "llm1"}-// resp, err := service.CreateMemory("tenant123", req)-func (s *MemoryService) CreateMemory(ctx context.Context, userID string, req *CreateMemoryRequest) (*CreateMemoryResponse, error) {+// resp, err := service.CreateMemory(ctx, req)+func (s *MemoryService) CreateMemory(ctx context.Context, req *CreateMemoryRequest) (*CreateMemoryResponse, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }tenantID, err := requireCurrentTenantID(ctx, userID)if err != nil {return nil, err@@ -613,7 +617,6 @@ func (s *MemoryService) CreateMemory(ctx context.Context, userID string, req *Cr// Only the fields specified in the request will be updated (partial update)//// Parameters:-// - tenantID: The tenant ID for ownership verification// - memoryID: The ID of the memory to update// - req: The update request with optional fields to update//@@ -624,8 +627,8 @@ func (s *MemoryService) CreateMemory(ctx context.Context, userID string, req *Cr// Example://// req := &UpdateMemoryRequest{Name: ptr("NewName"), MemorySize: ptr(int64(1000000))}-// resp, err := service.UpdateMemory("tenant123", "memory456", req)-func (s *MemoryService) UpdateMemory(ctx context.Context, userID string, memoryID string, req *UpdateMemoryRequest) (*CreateMemoryResponse, error) {+// resp, err := service.UpdateMemory(ctx, "memory456", req)+func (s *MemoryService) UpdateMemory(ctx context.Context, memoryID string, req *UpdateMemoryRequest) (*CreateMemoryResponse, error) {updateDict := make(map[string]interface{})if err := permission.NewDatabaseChecker(s.db).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindMemory, ID: memoryID}, permission.OperationUpdate); err != nil {return nil, err@@ -964,7 +967,6 @@ func sameStringSet(a, b []string) bool {// It also deletes associated message indexes before removing the memory record.//// Parameters:-// - userID: The ID of the user requesting the deletion (access control)// - memoryID: The ID of the memory to delete//// Returns:@@ -972,10 +974,10 @@ func sameStringSet(a, b []string) bool {//// Example://-// err := service.DeleteMemory(ctx, "user123", "memory456")-func (s *MemoryService) DeleteMemory(ctx context.Context, userID, memoryID string) error {+// err := service.DeleteMemory(ctx, "memory456")+func (s *MemoryService) DeleteMemory(ctx context.Context, memoryID string) error {// Verify the caller can delete this memory before removing its stored data.- memory, err := s.memoryWithAccess(ctx, userID, memoryID, permission.OperationDelete)+ memory, err := s.memoryWithAccess(ctx, memoryID, permission.OperationDelete)if err != nil {return err}@@ -998,8 +1000,8 @@ func (s *MemoryService) DeleteMemory(ctx context.Context, userID, memoryID strin// ForgetMessage marks a memory message as forgotten by setting forget_at.// This mirrors Python memory_api_service.forget_message and keeps the message// record for retention/cleanup policies instead of deleting it immediately.-func (s *MemoryService) ForgetMessage(ctx context.Context, userID string, memoryID string, messageID int64) error {- memory, err := s.memoryWithAccess(ctx, userID, memoryID, permission.OperationUpdate)+func (s *MemoryService) ForgetMessage(ctx context.Context, memoryID string, messageID int64) error {+ memory, err := s.memoryWithAccess(ctx, memoryID, permission.OperationUpdate)if err != nil {return err}@@ -1039,11 +1041,11 @@ func (s *MemoryService) ForgetMessage(ctx context.Context, userID string, memory}// AddMessage filters inaccessible memories and queues the raw message for-// memory extraction. The currentUserID is used only for access control; msg.UserID-// is the attribution stored on the message and may differ for API-token callers.-func (s *MemoryService) AddMessage(ctx context.Context, currentUserID string, memoryIDs []string, msg MemoryMessage) (bool, string, error) {+// memory extraction. msg.UserID is the attribution stored on the message and+// may differ for API-token callers.+func (s *MemoryService) AddMessage(ctx context.Context, memoryIDs []string, msg MemoryMessage) (bool, string, error) {requestedMemoryIDs := splitFilterValues(memoryIDs)- memories, err := s.filterAccessibleMemories(ctx, currentUserID, memoryIDs)+ memories, err := s.filterAccessibleMemories(ctx, memoryIDs)if err != nil {return false, err.Error(), err}@@ -1077,8 +1079,8 @@ func (s *MemoryService) AddMessage(ctx context.Context, currentUserID string, mereturn true, "All add to task.", nil}-func (s *MemoryService) saveAgentMessage(ctx context.Context, userID string, memoryIDs []string, msg MemoryMessage) (bool, string, error) {- memories, err := s.filterAccessibleMemories(ctx, userID, memoryIDs)+func (s *MemoryService) saveAgentMessage(ctx context.Context, memoryIDs []string, msg MemoryMessage) (bool, string, error) {+ memories, err := s.filterAccessibleMemories(ctx, memoryIDs)if err != nil {return false, err.Error(), err}@@ -1149,8 +1151,8 @@ func memorySaveErrorMessage(res *QueueSaveResult) string {return b.String()}-func (s *MemoryService) UpdateMessageStatus(ctx context.Context, userID, memoryID string, messageID int64, status bool) (bool, error) {- memory, err := s.memoryWithAccess(ctx, userID, memoryID, permission.OperationUpdate)+func (s *MemoryService) UpdateMessageStatus(ctx context.Context, memoryID string, messageID int64, status bool) (bool, error) {+ memory, err := s.memoryWithAccess(ctx, memoryID, permission.OperationUpdate)if err != nil {return false, err}@@ -1191,12 +1193,8 @@ func (s *MemoryService) UpdateMessageStatus(ctx context.Context, userID, memoryIreturn true, nil}-func (s *MemoryService) UpdateMessage(ctx context.Context, userID, memoryID string, messageID int64, status bool) (bool, error) {- return s.UpdateMessageStatus(ctx, userID, memoryID, messageID, status)-}--func (s *MemoryService) GetMessageContent(ctx context.Context, userID, memoryID string, messageID int64) (map[string]interface{}, error) {- memory, err := s.memoryWithAccess(ctx, userID, memoryID, permission.OperationRead)+func (s *MemoryService) GetMessageContent(ctx context.Context, memoryID string, messageID int64) (map[string]interface{}, error) {+ memory, err := s.memoryWithAccess(ctx, memoryID, permission.OperationRead)if err != nil {return nil, err}@@ -1224,7 +1222,7 @@ func (s *MemoryService) GetMessageContent(ctx context.Context, userID, memoryIDreturn common.ConvertFloatsToPyFormat(message).(map[string]interface{}), nil}-func (s *MemoryService) SearchMessage(ctx context.Context, userID string, filterDict, params map[string]interface{}) ([]map[string]interface{}, common.ErrorCode, error) {+func (s *MemoryService) SearchMessage(ctx context.Context, filterDict, params map[string]interface{}) ([]map[string]interface{}, common.ErrorCode, error) {for _, field := range []string{"similarity_threshold", "keywords_similarity_weight"} {if value, exists := params[field]; exists {number := memoryFloatParam(value, math.NaN())@@ -1234,7 +1232,7 @@ func (s *MemoryService) SearchMessage(ctx context.Context, userID string, filter}}memoryIDs := splitFilterValues(filterDict["memory_id"])- memories, err := s.filterAccessibleMemories(ctx, userID, memoryIDs)+ memories, err := s.filterAccessibleMemories(ctx, memoryIDs)if err != nil {return nil, common.CodeServerError, err}@@ -1368,7 +1366,7 @@ func (s *MemoryService) queryMessage(ctx context.Context, memories []*entity.Memreturn common.ConvertFloatsToPyFormat(messages).([]map[string]interface{}), common.CodeSuccess, nil}-func (s *MemoryService) filterAccessibleMemories(ctx context.Context, userID string, memoryIDs []string) ([]*entity.Memory, error) {+func (s *MemoryService) filterAccessibleMemories(ctx context.Context, memoryIDs []string) ([]*entity.Memory, error) {memoryIDs = splitFilterValues(memoryIDs)if len(memoryIDs) == 0 {return []*entity.Memory{}, nil@@ -1580,8 +1578,8 @@ func (s *MemoryService) memoryMessageDenseExpr(ctx context.Context, question str}, nil}-func (s *MemoryService) GetMessages(ctx context.Context, memoryIDs []string, userID, agentID, sessionID string, limit int) ([]map[string]interface{}, common.ErrorCode, error) {- memories, err := s.filterAccessibleMemories(ctx, userID, memoryIDs)+func (s *MemoryService) GetMessages(ctx context.Context, memoryIDs []string, agentID, sessionID string, limit int) ([]map[string]interface{}, common.ErrorCode, error) {+ memories, err := s.filterAccessibleMemories(ctx, memoryIDs)if err != nil {return nil, common.CodeServerError, err}@@ -1660,7 +1658,7 @@ func isMessageDocumentNotFound(err error) bool {return errors.Is(err, enginetypes.ErrDocumentNotFound)}-func (s *MemoryService) memoryWithAccess(ctx context.Context, userID, memoryID string, operation permission.Operation) (*entity.Memory, error) {+func (s *MemoryService) memoryWithAccess(ctx context.Context, memoryID string, operation permission.Operation) (*entity.Memory, error) {if err := ctx.Err(); err != nil {return nil, err}@@ -1681,7 +1679,6 @@ func (s *MemoryService) memoryWithAccess(ctx context.Context, userID, memoryID s// then applies optional tenant and business filters.//// Parameters:-// - userID: The authenticated user requesting the memories// - tenantIDs: Optional tenant IDs to filter the caller's authorized memories by// - memoryTypes: Array of memory type names to filter by (empty means all types)// - storageType: Storage type to filter by (empty means all types)@@ -1695,8 +1692,8 @@ func (s *MemoryService) memoryWithAccess(ctx context.Context, userID, memoryID s//// Example://-// resp, err := service.ListMemories("user123", []string{}, []string{"semantic"}, "table", "test", 1, 10)-func (s *MemoryService) ListMemories(ctx context.Context, userID string, tenantIDs []string, memoryTypes []string, storageType string, keywords string, page int, pageSize int, canvasID string) (*ListMemoryResponse, error) {+// resp, err := service.ListMemories(ctx, []string{}, []string{"semantic"}, "table", "test", 1, 10, "")+func (s *MemoryService) ListMemories(ctx context.Context, tenantIDs []string, memoryTypes []string, storageType string, keywords string, page int, pageSize int, canvasID string) (*ListMemoryResponse, error) {canvasID = strings.TrimSpace(canvasID)query := permission.ScopeQuery{Kind: permission.ResourceKindMemory,@@ -1806,7 +1803,6 @@ func ResolveTenantModelDisplayName(ctx context.Context, db *gorm.DB, tenantModel// verifying the caller's access.//// Parameters:-// - userID: The ID of the user requesting the configuration (access control)// - memoryID: The ID of the memory to retrieve//// Returns:@@ -1815,9 +1811,9 @@ func ResolveTenantModelDisplayName(ctx context.Context, db *gorm.DB, tenantModel//// Example://-// resp, err := service.GetMemoryConfig(ctx, "user123", "memory456")-func (s *MemoryService) GetMemoryConfig(ctx context.Context, userID, memoryID string) (*CreateMemoryResponse, error) {- if _, err := s.memoryWithAccess(ctx, userID, memoryID, permission.OperationRead); err != nil {+// resp, err := service.GetMemoryConfig(ctx, "memory456")+func (s *MemoryService) GetMemoryConfig(ctx context.Context, memoryID string) (*CreateMemoryResponse, error) {+ if _, err := s.memoryWithAccess(ctx, memoryID, permission.OperationRead); err != nil {return nil, err}response, err := s.getMemoryConfig(ctx, memoryID)@@ -1845,8 +1841,8 @@ func (s *MemoryService) getMemoryConfig(ctx context.Context, memoryID string) (*return formatRetDataFromMemoryListItem(memory), nil}-func (s *MemoryService) GetMemoryMessages(ctx context.Context, userID, memoryID string, agentIDs []string, keywords string, page int, pageSize int) (map[string]interface{}, error) {- memory, err := s.memoryWithAccess(ctx, userID, memoryID, permission.OperationRead)+func (s *MemoryService) GetMemoryMessages(ctx context.Context, memoryID string, agentIDs []string, keywords string, page int, pageSize int) (map[string]interface{}, error) {+ memory, err := s.memoryWithAccess(ctx, memoryID, permission.OperationRead)if err != nil {return nil, err}diff --git a/internal/service/memory_message_owner_tenant_test.go b/internal/service/memory_message_owner_tenant_test.goindex efa41f3fe2..ca996b3144 100644--- a/internal/service/memory_message_owner_tenant_test.go+++ b/internal/service/memory_message_owner_tenant_test.go@@ -54,7 +54,7 @@ func TestUpdateMemoryTeamMemberResolvesModelsAgainstOwnerTenant(t *testing.T) {}llmID := "gpt-4o@default@OpenAI"- if _, err := NewMemoryService(dao.DB, engine.Get()).UpdateMemory(ctx, "member-1", "mem-model", &UpdateMemoryRequest{LLMID: &llmID}); err != nil {+ if _, err := NewMemoryService(dao.DB, engine.Get()).UpdateMemory(ctx, "mem-model", &UpdateMemoryRequest{LLMID: &llmID}); err != nil {t.Fatalf("UpdateMemory model error = %v", err)}updated, err := dao.NewMemoryDAO().GetByID(t.Context(), dao.DB, "mem-model")diff --git a/internal/service/memory_message_test.go b/internal/service/memory_message_test.goindex 074c80e80f..7f861da572 100644--- a/internal/service/memory_message_test.go+++ b/internal/service/memory_message_test.go@@ -121,7 +121,7 @@ func TestMemoryWithAccessReturnsCanceledContext(t *testing.T) {cancel()err := ctx.Err()- if _, gotErr := NewMemoryService(dao.DB, engine.Get()).memoryWithAccess(ctx, "user-1", "memory-1", permission.OperationRead); !errors.Is(gotErr, err) {+ if _, gotErr := NewMemoryService(dao.DB, engine.Get()).memoryWithAccess(ctx, "memory-1", permission.OperationRead); !errors.Is(gotErr, err) {t.Fatalf("memoryWithAccess error = %v, want %v", gotErr, err)}}@@ -219,7 +219,7 @@ func TestListMemoryFiltersUsesAccessibleMemoryAggregates(t *testing.T) {}ctx := serviceTestContext(t, "user-1", "user-1")- filters, err := NewMemoryService(dao.DB, engine.Get()).ListMemoryFilters(ctx, "user-1")+ filters, err := NewMemoryService(dao.DB, engine.Get()).ListMemoryFilters(ctx)if err != nil {t.Fatalf("ListMemoryFilters: %v", err)}@@ -246,7 +246,7 @@ func TestListMemoryFiltersUsesAccessibleMemoryAggregates(t *testing.T) {t.Fatalf("storage type filter = %+v, want %+v", got, want)}- refreshed, err := NewMemoryService(dao.DB, engine.Get()).ListMemoryFilters(ctx, "user-1")+ refreshed, err := NewMemoryService(dao.DB, engine.Get()).ListMemoryFilters(ctx)if err != nil {t.Fatalf("ListMemoryFilters refresh: %v", err)}@@ -282,7 +282,7 @@ func TestListMemoryFiltersKeepsCanonicalFacetOrder(t *testing.T) {}ctx := serviceTestContext(t, "user-1", "user-1")- filters, err := NewMemoryService(dao.DB, engine.Get()).ListMemoryFilters(ctx, "user-1")+ filters, err := NewMemoryService(dao.DB, engine.Get()).ListMemoryFilters(ctx)if err != nil {t.Fatalf("ListMemoryFilters: %v", err)}@@ -310,7 +310,7 @@ func TestListMemoryFiltersKeepsCanonicalFacetOrder(t *testing.T) {if err := dao.DB.Model(&entity.Memory{ID: "mem-semantic"}).Update("update_time", bumped).Error; err != nil {t.Fatalf("bump update_time: %v", err)}- refreshed, err := NewMemoryService(dao.DB, engine.Get()).ListMemoryFilters(ctx, "user-1")+ refreshed, err := NewMemoryService(dao.DB, engine.Get()).ListMemoryFilters(ctx)if err != nil {t.Fatalf("ListMemoryFilters refresh: %v", err)}@@ -361,7 +361,7 @@ func TestForgetMessageKeepsCompanionFieldForNonOceanBaseEngines(t *testing.T) {service := NewMemoryService(dao.DB, engine.Get())service.docEngine = docEngine- if err := service.ForgetMessage(serviceTestContext(t, "user-1", "user-1"), "user-1", "memory-1", 42); err != nil {+ if err := service.ForgetMessage(serviceTestContext(t, "user-1", "user-1"), "memory-1", 42); err != nil {t.Fatalf("ForgetMessage() error = %v", err)}if docEngine.updateCond["id"] != "memory-1_42" {@@ -420,7 +420,7 @@ func TestUpdateMemoryTeamMemberCannotChangePermissions(t *testing.T) {svc := NewMemoryService(dao.DB, engine.Get())samePermission := " TEAM "- if _, err := svc.UpdateMemory(ctx, "member-1", "mem-team", &UpdateMemoryRequest{+ if _, err := svc.UpdateMemory(ctx, "mem-team", &UpdateMemoryRequest{Description: sptr("member edit"),Permissions: &samePermission,}); err != nil {@@ -428,7 +428,7 @@ func TestUpdateMemoryTeamMemberCannotChangePermissions(t *testing.T) {}nextPermission := "me"- if _, err := svc.UpdateMemory(ctx, "member-1", "mem-team", &UpdateMemoryRequest{+ if _, err := svc.UpdateMemory(ctx, "mem-team", &UpdateMemoryRequest{Permissions: &nextPermission,}); err == nil {t.Fatal("UpdateMemory permission change error = nil, want error")@@ -496,7 +496,7 @@ func TestListMemoriesUsesTenantModelIDForDisplayName(t *testing.T) {}ctx := serviceTestContext(t, "user-1", "user-1")- resp, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, "user-1", []string{"user-1"}, nil, "", "", 1, 10, "")+ resp, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, []string{"user-1"}, nil, "", "", 1, 10, "")if err != nil {t.Fatalf("ListMemories: %v", err)}@@ -533,7 +533,7 @@ func TestListMemoriesFallsBackToRawModelIDWithoutTenantModelID(t *testing.T) {}ctx := serviceTestContext(t, "user-1", "user-1")- resp, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, "user-1", []string{"user-1"}, nil, "", "", 1, 10, "")+ resp, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, []string{"user-1"}, nil, "", "", 1, 10, "")if err != nil {t.Fatalf("ListMemories: %v", err)}@@ -579,7 +579,7 @@ func TestListMemoriesRejectsUnjoinedTenantFilter(t *testing.T) {t.Fatalf("seed memory: %v", err)}- resp, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(serviceTestContext(t, "user-1", "user-1"), "user-1", []string{"tenant-2"}, nil, "", "", 1, 10, "")+ resp, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(serviceTestContext(t, "user-1", "user-1"), []string{"tenant-2"}, nil, "", "", 1, 10, "")if err != nil {t.Fatalf("ListMemories: %v", err)}@@ -643,7 +643,7 @@ func TestListMemoriesKeepsJoinedTenantFilter(t *testing.T) {ctx := serviceTestContext(t, "user-1", "tenant-2", "tenant-2")grantServiceTestResource(t, "tenant-2", "memory", "mem-joined-team", "user-1", testResourcePermissionRead)- resp, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, "user-1", []string{"tenant-2"}, nil, "", "", 1, 10, "")+ resp, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, []string{"tenant-2"}, nil, "", "", 1, 10, "")if err != nil {t.Fatalf("ListMemories: %v", err)}@@ -651,7 +651,7 @@ func TestListMemoriesKeepsJoinedTenantFilter(t *testing.T) {t.Fatalf("joined tenant filter must return its team memory, got total=%d list=%v", resp.TotalCount, resp.MemoryList)}- resp, err = NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, "user-1", []string{"tenant-2", "tenant-3"}, nil, "", "", 1, 10, "")+ resp, err = NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, []string{"tenant-2", "tenant-3"}, nil, "", "", 1, 10, "")if err != nil {t.Fatalf("ListMemories: %v", err)}@@ -702,7 +702,7 @@ func TestListMemoriesForCanvasUsesCallerOwnerIntersection(t *testing.T) {}}- response, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, "caller", nil, nil, "", "", 1, 30, canvas.ID)+ response, err := NewMemoryService(dao.DB, engine.Get()).ListMemories(ctx, nil, nil, "", "", 1, 30, canvas.ID)if err != nil {t.Fatalf("ListMemories(canvas): %v", err)}@@ -770,12 +770,12 @@ func TestSaveAgentMessageChecksMemoryAccess(t *testing.T) {AgentResponse: "hello",}- ok, detail, err := svc.AddMessage(t.Context(), "", []string{"mem-owned"}, msg)+ ok, detail, err := svc.AddMessage(t.Context(), []string{"mem-owned"}, msg)if ok || !errors.Is(err, permission.ErrUnauthenticated) {t.Fatalf("AddMessage with empty current user = (%v, %q, %v), want unauthenticated error", ok, detail, err)}- ok, detail, err = svc.saveAgentMessage(serviceTestContext(t, "user-2", "user-2"), "user-2", []string{"mem-owned"}, msg)+ ok, detail, err = svc.saveAgentMessage(serviceTestContext(t, "user-2", "user-2"), []string{"mem-owned"}, msg)if err != nil {t.Fatalf("saveAgentMessage as outsider: %v", err)}@@ -783,7 +783,7 @@ func TestSaveAgentMessageChecksMemoryAccess(t *testing.T) {t.Fatalf("saveAgentMessage as outsider = (%v, %q), want hidden memory not found", ok, detail)}- ok, detail, err = svc.saveAgentMessage(serviceTestContext(t, "user-1", "user-1"), "user-1", []string{"mem-owned"}, msg)+ ok, detail, err = svc.saveAgentMessage(serviceTestContext(t, "user-1", "user-1"), []string{"mem-owned"}, msg)if err != nil {t.Fatalf("saveAgentMessage as owner: %v", err)}@@ -821,7 +821,7 @@ func TestGetMessagesFiltersAccessibleMemoryAndBuildsRecentSearch(t *testing.T) {}svc := &MemoryService{memoryDAO: dao.NewMemoryDAO(), db: dao.DB, docEngine: docEngine}- got, code, err := svc.GetMessages(serviceTestContext(t, "user-1", "user-1"), []string{"mem-owned", "mem-other"}, "user-1", "agent-1", "session-1", 3)+ got, code, err := svc.GetMessages(serviceTestContext(t, "user-1", "user-1"), []string{"mem-owned", "mem-other"}, "agent-1", "session-1", 3)if err != nil {t.Fatalf("GetMessages error: %v", err)}@@ -903,7 +903,7 @@ func TestSearchMessageFiltersAccessibleMemoryAndDefaultsStatus(t *testing.T) {"top_n": 5,}- got, code, err := svc.SearchMessage(serviceTestContext(t, "user-1", "user-1"), "user-1", filter, params)+ got, code, err := svc.SearchMessage(serviceTestContext(t, "user-1", "user-1"), filter, params)if err != nil {t.Fatalf("SearchMessage error: %v", err)}@@ -942,7 +942,7 @@ func TestUpdateMessageUpdatesStatusByMessageDocID(t *testing.T) {docEngine := &memoryMessageDocEngine{}svc := &MemoryService{memoryDAO: dao.NewMemoryDAO(), db: dao.DB, docEngine: docEngine}- ok, err := svc.UpdateMessage(serviceTestContext(t, "user-1", "user-1"), "user-1", "mem-owned", 42, true)+ ok, err := svc.UpdateMessageStatus(serviceTestContext(t, "user-1", "user-1"), "mem-owned", 42, true)if err != nil {t.Fatalf("UpdateMessage error: %v", err)}@@ -977,7 +977,7 @@ func TestUpdateMessageRejectsMissingAndFailedReads(t *testing.T) {seedMemoryMessages(t)e := &missingMessageEngine{getErr: readErr}svc := &MemoryService{memoryDAO: dao.NewMemoryDAO(), db: dao.DB, docEngine: e}- ok, err := svc.UpdateMessage(serviceTestContext(t, "user-1", "user-1"), "user-1", "mem-owned", 42, true)+ ok, err := svc.UpdateMessageStatus(serviceTestContext(t, "user-1", "user-1"), "mem-owned", 42, true)if ok || err == nil || e.updateCond != nil {t.Fatalf("ok=%v error=%v update=%v", ok, err, e.updateCond)}@@ -995,7 +995,7 @@ func TestUpdateMessageRejectsMissingAndFailedReads(t *testing.T) {func TestMemorySearchRejectsInvalidSimilarityBeforeStorage(t *testing.T) {for _, field := range []string{"similarity_threshold", "keywords_similarity_weight"} {for _, value := range []interface{}{-0.1, 1.1, "invalid", math.NaN(), math.Inf(1), nil} {- _, code, err := (&MemoryService{}).SearchMessage(t.Context(), "user", nil, map[string]interface{}{field: value})+ _, code, err := (&MemoryService{}).SearchMessage(t.Context(), nil, map[string]interface{}{field: value})if code != common.CodeArgumentError || err == nil {t.Fatalf("%s=%v code=%v err=%v", field, value, code, err)}diff --git a/internal/service/memory_saver_adapter.go b/internal/service/memory_saver_adapter.goindex 43189da975..2f51a9a23d 100644--- a/internal/service/memory_saver_adapter.go+++ b/internal/service/memory_saver_adapter.go@@ -40,41 +40,37 @@ func NewMemorySaverAdapter(svc *MemoryService) component.MemorySaver {return &memorySaverAdapter{svc: svc}}-// Save implements component.MemorySaver. It checks the runtime user against-// each configured memory before queueing the message.+// Save checks the authenticated caller's access to each configured memory+// before queueing the message. Internal runs without a request identity use+// the identity carried by the canvas runtime state.func (a *memorySaverAdapter) Save(ctx context.Context, req component.MemorySaveRequest) error {if a == nil || a.svc == nil {return fmt.Errorf("memory: saver adapter not initialised")}- authorizationUserID := req.UserIDif len(req.MemoryIDs) > 0 {state, stateErr := runtime.GetStateFromContext(ctx)if stateErr != nil || state == nil {return fmt.Errorf("%w: canvas runtime state is required to use memory from an agent", permission.ErrInvalidPermission)}canvasID, _ := state.GetSysString("canvas_id")- userID, _ := state.GetSysString("user_id")- tenantID, _ := state.GetSysString("tenant_id")+ stateUserID, _ := state.GetSysString("user_id")+ stateTenantID, _ := state.GetSysString("tenant_id")canvasID = strings.TrimSpace(canvasID)- userID = strings.TrimSpace(userID)- tenantID = strings.TrimSpace(tenantID)- authorizationUserID = userID+ stateUserID = strings.TrimSpace(stateUserID)+ stateTenantID = strings.TrimSpace(stateTenantID)if canvasID == "" {return fmt.Errorf("%w: canvas id is required to use memory from an agent", permission.ErrInvalidPermission)}- if userID == "" {- return permission.ErrUnauthenticated- }contextUserID := permission.UserIDFromContext(ctx)- contextTenantID := permission.TenantIDFromContext(ctx)- if contextUserID != "" && contextUserID != userID {- return permission.ErrIdentityMismatch- }- if contextTenantID != "" && tenantID != "" && contextTenantID != tenantID {- return permission.ErrIdentityMismatch- }- if contextUserID == "" || contextTenantID == "" {- ctx = permission.WithIdentity(ctx, userID, tenantID)+ if contextUserID == "" {+ if stateUserID == "" {+ return permission.ErrUnauthenticated+ }+ tenantID := permission.TenantIDFromContext(ctx)+ if tenantID == "" {+ tenantID = stateTenantID+ }+ ctx = permission.WithIdentity(ctx, stateUserID, tenantID)}checker := permission.NewDatabaseChecker(a.svc.db)entry := permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: canvasID}@@ -97,7 +93,7 @@ func (a *memorySaverAdapter) Save(ctx context.Context, req component.MemorySaveRUserInput: req.UserInput,AgentResponse: req.AgentResponse,}- ok, detail, err := a.svc.saveAgentMessage(ctx, authorizationUserID, req.MemoryIDs, msg)+ ok, detail, err := a.svc.saveAgentMessage(ctx, req.MemoryIDs, msg)if err != nil {return err}diff --git a/web/src/pages/memories/hooks.ts b/web/src/pages/memories/hooks.tsindex c17f20b93b..a88e0abe52 100644--- a/web/src/pages/memories/hooks.ts+++ b/web/src/pages/memories/hooks.ts@@ -95,7 +95,7 @@ export const useFetchMemoryList = () => {};if (Array.isArray(owner) && owner.length > 0) {- requestParams.owner_ids = owner.join(',');+ requestParams.tenant_id = owner.join(',');}const { data, isLoading, isError, refetch } = useQuery<MemoryListResponse,diff --git a/web/src/pages/memories/interface.ts b/web/src/pages/memories/interface.tsindex 723731c675..8b9a42b704 100644--- a/web/src/pages/memories/interface.ts+++ b/web/src/pages/memories/interface.ts@@ -11,7 +11,7 @@ export interface MemoryListParams {page_size?: number;orderby?: string;desc?: boolean;- owner_ids?: string;+ tenant_id?: string;}export type MemoryType = 'raw' | 'semantic' | 'episodic' | 'procedural';export type StorageType = 'table' | 'graph';