Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(agent): scope the @Skill and @MCP pickers to the agent that will run (#3475)
Leo Dawna3c7be10ca6f
diff --git a/frontend/src/api/mcp-service.ts b/frontend/src/api/mcp-service.tsindex 0f0699de4..106446d86 100644--- a/frontend/src/api/mcp-service.ts+++ b/frontend/src/api/mcp-service.ts@@ -90,8 +90,27 @@ export interface MCPTestResult {}// List all MCP services-export async function listMCPServices(): Promise<MCPService[]> {- const response: any = await get('/api/v1/mcp-services')+/** Locates a shared agent's source workspace, same parameters as a chat request. */+export interface MCPAgentScope {+ agentId?: string+ /** Set only for a shared agent; left empty for this workspace's own agents. */+ sourceTenantId?: string | number+}++// Lists MCP services.+//+// With a shared agent, the result is the services THAT agent can be @mentioned+// with: they live in its owner's workspace and none of their ids match anything+// in the caller's. Those rows also carry a narrowed field set — no URL,+// headers or credential metadata, which describe how the owner wired the+// service up — since the picker needs nothing more.+export async function listMCPServices(agent?: MCPAgentScope): Promise<MCPService[]> {+ const params: Record<string, string> = {}+ if (agent?.agentId && agent?.sourceTenantId) {+ params.agent_id = agent.agentId+ params.agent_source_tenant_id = String(agent.sourceTenantId)+ }+ const response: any = await get('/api/v1/mcp-services', { params })return response.data || []}diff --git a/frontend/src/api/skill/index.ts b/frontend/src/api/skill/index.tsindex f4a24fd8c..48cc6c9ff 100644--- a/frontend/src/api/skill/index.ts+++ b/frontend/src/api/skill/index.ts@@ -41,12 +41,28 @@ export interface SkillCatalogRegisterResult {description?: string;}-// 获取当前沙箱配置上可执行的 Skills;未传 sandboxConfigId 或-// skills_available 为 false 时,前端应隐藏/禁用 Skills 配置-export function listSkills(sandboxConfigId?: string) {- return get<{ data: SkillInfo[]; skills_available?: boolean }>('/api/v1/skills', {- params: sandboxConfigId ? { sandbox_config_id: sandboxConfigId } : {},- });+/** Locates a shared agent's source workspace, same parameters as a chat request. */+export interface AgentScope {+ agentId?: string;+ /** Set only for a shared agent; left empty for this workspace's own agents. */+ sourceTenantId?: string | number;+}++// Lists the skills executable on the current sandbox config. Without a+// sandboxConfigId, or when skills_available is false, the caller should hide or+// disable the skills UI.+//+// Pass the agent for a shared one: its skills are installed on a sandbox config+// in the OWNER's workspace, so looking them up in the caller's returns nothing.+// The backend then reads the config off that agent and ignores sandboxConfigId.+export function listSkills(sandboxConfigId?: string, agent?: AgentScope) {+ const params: Record<string, string> = {};+ if (sandboxConfigId) params.sandbox_config_id = sandboxConfigId;+ if (agent?.agentId && agent?.sourceTenantId) {+ params.agent_id = agent.agentId;+ params.agent_source_tenant_id = String(agent.sourceTenantId);+ }+ return get<{ data: SkillInfo[]; skills_available?: boolean }>('/api/v1/skills', { params });}export function listSkillCatalog() {diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vueindex ca7fcb7ca..51285d8fb 100644--- a/frontend/src/components/Input-field.vue+++ b/frontend/src/components/Input-field.vue@@ -809,15 +809,41 @@ const loadFiles = async () => {}};+// A shared agent @mentions its OWNER's MCP services; this workspace's service+// ids match none of its preset, and the backend drops such a mention outright.+// So the list follows the selected agent and is refetched when it changes.+const currentAgentScope = computed(() => {+ const sourceTenantId = settingsStore.selectedAgentSourceTenantId;+ if (!sourceTenantId || !selectedAgentId.value) return undefined;+ return { agentId: selectedAgentId.value, sourceTenantId };+});++const agentScopeKey = (scope?: { agentId: string; sourceTenantId: string | number }) =>+ scope ? `${scope.sourceTenantId}:${scope.agentId}` : '';++// Guards against a slow response for a previously selected agent overwriting+// the list with another workspace's services after the user switched away.+let mcpServicesRequestKey = '';+const loadMCPServices = async () => {+ const scope = currentAgentScope.value;+ const requestKey = agentScopeKey(scope);+ mcpServicesRequestKey = requestKey;try {- mcpServices.value = await listMCPServices();+ const list = await listMCPServices(scope);+ if (mcpServicesRequestKey !== requestKey) return;+ mcpServices.value = list;} catch (error) {console.error('Failed to load MCP services:', error);+ if (mcpServicesRequestKey !== requestKey) return;mcpServices.value = [];}};+watch(currentAgentScope, () => {+ void loadMCPServices();+});+watch(selectedFileIds, () => {loadFiles();}, { immediate: true });@@ -1373,7 +1399,12 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>const skillsMode = agentSkillsSelectionMode.value;if (skillsMode !== 'none') {- await editorResources.ensureSkills(currentAgentConfig.value?.sandbox_config_id);+ // The scope makes a shared agent's skills resolve in its owner's+ // workspace, where they are actually installed.+ await editorResources.ensureSkills(+ currentAgentConfig.value?.sandbox_config_id,+ currentAgentScope.value,+ );skillItems = editorResources.skills.filter(skill => isSkillAllowedByAgent(skill.name)).map(skill => ({diff --git a/frontend/src/stores/editorResources.ts b/frontend/src/stores/editorResources.tsindex 080f204c8..225ab93cd 100644--- a/frontend/src/stores/editorResources.ts+++ b/frontend/src/stores/editorResources.ts@@ -12,7 +12,13 @@ import {type SystemInfo,} from '@/api/system'import { listMCPServices, type MCPService } from '@/api/mcp-service'-import { listSkillCatalog, listSkills, type SkillCatalogItem, type SkillInfo } from '@/api/skill'+import {+ listSkillCatalog,+ listSkills,+ type AgentScope,+ type SkillCatalogItem,+ type SkillInfo,+} from '@/api/skill'import { getAgentTypePresets, getPlaceholders, type AgentTypePreset, type PlaceholdersResponse } from '@/api/agent'import { getTenantRetrievalConfig } from '@/api/retrieval'import { isStorageConfigDenied } from './storageEngineAccess'@@ -57,6 +63,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {const storageStatus = ref<StorageEngineStatusItem[]>([])const storageAllowedProviders = ref<string[]>([])const mcpServices = ref<MCPService[]>([])+ const mcpServicesScope = ref('')const skills = ref<SkillInfo[]>([])const skillsAvailable = ref(false)const skillsConfigId = ref('')@@ -114,21 +121,44 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {)}- async function ensureMcpServices(force = false): Promise<void> {+ async function ensureMcpServices(agent?: AgentScope, force = false): Promise<void> {+ const key = scopeKey('', agent)+ if (key !== mcpServicesScope.value) {+ force = true+ }return runOnce('mcpServices', force, async () => {- const list = await listMCPServices()+ mcpServicesScope.value = key+ const list = await listMCPServices(agent)mcpServices.value = Array.isArray(list) ? list : []loadedAt.value.mcpServices = Date.now()})}- async function ensureSkills(sandboxConfigId?: string, force = false): Promise<void> {+ // A shared agent's skills and MCP services live in its owner's workspace and+ // are an entirely different set from this workspace's. The cache key has to+ // carry the agent, or switching agents would leave another workspace's+ // entries in the @ picker.+ function scopeKey(configId: string, agent?: AgentScope): string {+ if (!agent?.agentId || !agent?.sourceTenantId) return configId+ return `${configId}@${agent.sourceTenantId}:${agent.agentId}`+ }++ async function ensureSkills(+ sandboxConfigId?: string,+ agent?: AgentScope,+ force = false,+ ): Promise<void> {const configId = sandboxConfigId?.trim() || ''- if (configId !== skillsConfigId.value) {+ const key = scopeKey(configId, agent)+ if (key !== skillsConfigId.value) {force = true}return runOnce('skills', force, async () => {- skillsConfigId.value = configId+ skillsConfigId.value = key+ // No sandbox config means no skills, for a shared agent too: its config+ // id is part of the agent config this caller already holds. The backend+ // re-reads it from the agent, so what is sent here only has to be+ // non-empty when the agent actually has one.if (!configId) {skillsAvailable.value = falseskills.value = []@@ -136,7 +166,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {return}try {- const skillsRes = await listSkills(configId)+ const skillsRes = await listSkills(configId, agent)skillsAvailable.value = skillsRes.skills_available !== falseskills.value = skillsRes.data && skillsRes.data.length > 0 ? skillsRes.data : []} catch {@@ -206,7 +236,9 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {/** 智能体编辑器打开时预取的依赖(不含 IM channels / 单 KB shares) */async function prefetchAgentEditorDeps(force = false): Promise<void> {await Promise.all([- ensureMcpServices(force),+ // The editor only edits this workspace's agents, so its MCP services+ // are this workspace's too.+ ensureMcpServices(undefined, force),ensureAgentTypePresets(force),ensurePromptTemplates(force),ensureStorageEngine(force),@@ -222,6 +254,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {storageStatus.value = []storageAllowedProviders.value = []mcpServices.value = []+ mcpServicesScope.value = ''skills.value = []skillsAvailable.value = falseskillsConfigId.value = ''diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vueindex a947ffd8e..3ae5e24d9 100644--- a/frontend/src/views/agent/AgentEditorModal.vue+++ b/frontend/src/views/agent/AgentEditorModal.vue@@ -2294,7 +2294,9 @@ function pruneSelectedSkills() {async function syncInstalledSkills(force = false) {autoBindSoleSandbox()const configId = formData.value.config.sandbox_config_id || ''- await editorResources.ensureSkills(configId, force)+ // The editor only edits this workspace's agents, so the sandbox config is+ // local and needs no source-workspace scope.+ await editorResources.ensureSkills(configId, undefined, force)try {await editorResources.ensureSkillCatalog(force)skillCatalog.value = [...editorResources.skillCatalog]diff --git a/internal/container/container.go b/internal/container/container.goindex a8936d48c..04fc0b6b7 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -549,8 +549,10 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Provide(handler.NewStorageBackendHandler))must(container.Provide(handler.NewCustomAgentHandler))must(container.Provide(handler.NewUserResourceFavoriteHandler))- must(container.Provide(func(s *service.TenantSkillService) *handler.SkillHandler {- return handler.NewSkillHandler(s, s)+ must(container.Provide(func(+ s *service.TenantSkillService, agents interfaces.AgentShareService,+ ) *handler.SkillHandler {+ return handler.NewSkillHandler(s, s, agents)}))must(container.Provide(handler.NewOrganizationHandler))must(container.Provide(handler.NewMemoryHandler))diff --git a/internal/handler/dto/mcp.go b/internal/handler/dto/mcp.goindex f70f2526a..1ac08fd53 100644--- a/internal/handler/dto/mcp.go+++ b/internal/handler/dto/mcp.go@@ -148,6 +148,36 @@ func NewMCPServiceResponses(ctx context.Context, svcs []*types.MCPService) []*MCreturn out}+// NewSharedAgentMCPServiceResponses is the cross-workspace list shape: the+// @MCP picker of a borrowed agent needs a service's identity and how many+// tools it offers, and nothing else.+//+// It fills the fields explicitly instead of reusing NewMCPServiceResponse and+// blanking the rest, so a field added to MCPServiceResponse later is absent+// here until someone decides it may cross a workspace boundary. Endpoint URLs,+// headers, env vars, stdio commands, auth config and credential metadata all+// describe how the OWNER wired the service up; the borrower never configures+// it and must not see it.+func NewSharedAgentMCPServiceResponses(svcs []*types.MCPService) []*MCPServiceResponse {+ out := make([]*MCPServiceResponse, 0, len(svcs))+ for _, s := range svcs {+ if s == nil {+ continue+ }+ out = append(out, &MCPServiceResponse{+ ID: s.ID,+ TenantID: s.TenantID,+ Name: s.Name,+ Description: s.Description,+ UsageInstructions: s.UsageInstructions,+ Enabled: s.Enabled,+ TransportType: s.TransportType,+ IsBuiltin: s.IsBuiltin,+ })+ }+ return out+}+// AttachMCPCatalogs copies persisted directory counts onto list/detail responses.func AttachMCPCatalogs(resp []*MCPServiceResponse,diff --git a/internal/handler/mcp_service.go b/internal/handler/mcp_service.goindex ab2ac9131..4165e68f8 100644--- a/internal/handler/mcp_service.go+++ b/internal/handler/mcp_service.go@@ -9,6 +9,7 @@ import ("unicode/utf8""github.com/Tencent/WeKnora/internal/agent/approval"+ "github.com/Tencent/WeKnora/internal/application/access""github.com/Tencent/WeKnora/internal/errors""github.com/Tencent/WeKnora/internal/handler/dto""github.com/Tencent/WeKnora/internal/logger"@@ -25,6 +26,9 @@ type MCPServiceHandler struct {mcpToolApprovalService interfaces.MCPToolApprovalServicetoolApprovalGate *approval.GatemodelService interfaces.ModelService+ // agents resolves a shared agent so the @MCP picker can list the services+ // that agent can actually reach, which live in ITS OWNER's workspace.+ agents access.SharedAgentLookup}// NewMCPServiceHandler creates a new MCP service handler@@ -33,12 +37,14 @@ func NewMCPServiceHandler(mcpToolApprovalService interfaces.MCPToolApprovalService,toolApprovalGate *approval.Gate,modelService interfaces.ModelService,+ agents access.SharedAgentLookup,) *MCPServiceHandler {return &MCPServiceHandler{mcpServiceService: mcpServiceService,mcpToolApprovalService: mcpToolApprovalService,toolApprovalGate: toolApprovalGate,modelService: modelService,+ agents: agents,}}@@ -124,8 +130,11 @@ func (h *MCPServiceHandler) CreateMCPService(c *gin.Context) {// @Tags MCP服务// @Accept json// @Produce json+// @Param agent_id query string false "Agent ID; needs agent_source_tenant_id"+// @Param agent_source_tenant_id query int false "Shared agent source workspace"// @Success 200 {object} map[string]interface{} "MCP服务列表"// @Failure 400 {object} errors.AppError "请求参数错误"+// @Failure 403 {object} errors.AppError "无权使用该共享智能体"// @Security Bearer// @Security ApiKeyAuth// @Router /mcp-services [get]@@ -139,6 +148,20 @@ func (h *MCPServiceHandler) ListMCPServices(c *gin.Context) {return}+ // A shared agent reaches its OWNER's MCP services, so the picker has to+ // list them there. Without this the picker showed the caller's own+ // services, whose ids can never match the agent's preset — the backend+ // dropped every such @mention with only a warning in the log.+ agent, err := sharedAgentPickerScope(c, h.agents)+ if err != nil {+ _ = c.Error(err)+ return+ }+ if agent != nil {+ h.listSharedAgentMCPServices(c, agent)+ return+ }+services, err := h.mcpServiceService.ListMCPServices(ctx, tenantID)if err != nil {logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": tenantID})@@ -152,6 +175,48 @@ func (h *MCPServiceHandler) ListMCPServices(c *gin.Context) {})}+// listSharedAgentMCPServices serves the @MCP picker for a borrowed agent.+//+// The set is the agent's explicit preset resolved in its owner's workspace —+// see sharedAgentMCPScope for why it is the preset and not the owner's whole+// inventory. The response uses the narrowed cross-workspace shape, and the+// tool-count summaries are read under the owner too, since that is where the+// services and their saved directories live.+func (h *MCPServiceHandler) listSharedAgentMCPServices(c *gin.Context, agent *types.CustomAgent) {+ ctx := c.Request.Context()+ ids := sharedAgentMCPScope(agent)+ if len(ids) == 0 {+ c.JSON(http.StatusOK, gin.H{"success": true, "data": []*dto.MCPServiceResponse{}})+ return+ }++ services, err := h.mcpServiceService.ListMCPServicesByIDs(ctx, agent.TenantID, ids)+ if err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": agent.TenantID})+ _ = c.Error(errors.NewInternalServerError("Failed to list MCP services: " + err.Error()))+ return+ }+ enabled := make([]*types.MCPService, 0, len(services))+ for _, svc := range services {+ // Mirror registerMCPTools: a disabled service is not registered, so it+ // must not be offered either.+ if svc != nil && svc.Enabled {+ enabled = append(enabled, svc)+ }+ }++ resp := dto.NewSharedAgentMCPServiceResponses(enabled)+ if summaries, err := h.mcpServiceService.ListMCPMetadataSummaries(+ ctx, agent.TenantID, enabled,+ ); err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": agent.TenantID})+ } else {+ dto.AttachMCPCatalogs(resp, enabled, summaries)+ }++ c.JSON(http.StatusOK, gin.H{"success": true, "data": resp})+}+// GetMCPService godoc// @Summary 获取MCP服务详情// @Description 根据ID获取MCP服务详情diff --git a/internal/handler/shared_agent_access.go b/internal/handler/shared_agent_access.goindex dfcd47f06..e89494f0f 100644--- a/internal/handler/shared_agent_access.go+++ b/internal/handler/shared_agent_access.go@@ -2,6 +2,7 @@ package handlerimport (stderrors "errors"+ "strings""github.com/Tencent/WeKnora/internal/agent/tools""github.com/Tencent/WeKnora/internal/application/access"@@ -48,6 +49,85 @@ func resolveSharedAgentForRequest(return agent, nil}+// sharedAgentPickerScope resolves the shared agent a chat-input picker is+// filling for, or (nil, nil) when the request names none.+//+// The @Skill and @MCP pickers offer what the SELECTED agent can invoke, and a+// shared agent invokes its owner's skills and MCP services — its sandbox config+// and service ids do not exist in the caller's own workspace, so listing them+// there returns nothing. A request that names no source workspace is an+// ordinary own-agent request and keeps reading the caller's own resources.+//+// Only an explicit source workspace enters the share path. Built-in agent ids+// exist in every workspace, so falling back to a share lookup without one would+// let an org member take over the caller's default agent, exactly as+// session.Handler.resolveAgent documents.+func sharedAgentPickerScope(+ c *gin.Context,+ agents access.SharedAgentLookup,+) (*types.CustomAgent, error) {+ agentID := strings.TrimSpace(c.Query("agent_id"))+ source, err := types.ParseAgentSourceTenantID(c.Query(types.AgentSourceTenantIDParam))+ if err != nil {+ return nil, apperrors.NewBadRequestError(err.Error())+ }+ if agentID == "" || source == 0 {+ return nil, nil+ }+ return resolveSharedAgentForRequest(c, agentID, agents)+}++// sharedAgentSkillScope reports which installed skills an already-authorized+// shared agent may invoke. It mirrors sessionService.configureSkillsFromAgent:+// an unknown or empty mode disables skills, so an agent whose owner turned them+// off never exposes the workspace's skill inventory to a borrower.+//+// A nil allowed set means "every installed skill"; enabled is false when no+// skill can be offered at all, which is not the same thing.+func sharedAgentSkillScope(agent *types.CustomAgent) (allowed map[string]bool, enabled bool) {+ if agent == nil {+ return nil, false+ }+ switch agent.Config.SkillsSelectionMode {+ case "all":+ return nil, true+ case "selected":+ if len(agent.Config.SelectedSkills) == 0 {+ return nil, false+ }+ allowed = make(map[string]bool, len(agent.Config.SelectedSkills))+ for _, name := range agent.Config.SelectedSkills {+ if name != "" {+ allowed[name] = true+ }+ }+ return allowed, len(allowed) > 0+ default:+ return nil, false+ }+}++// sharedAgentMCPScope returns the MCP services a borrower may @mention on an+// already-authorized shared agent.+//+// It is deliberately the agent's explicit preset and nothing else, because that+// is exactly what resolvePerRequestMCPScope accepts for a shared agent: it+// intersects the mention against Config.MCPServices, which is empty under the+// "all" and "none" modes. Offering the owner's whole inventory under "all"+// would put services in the picker that the backend silently drops.+func sharedAgentMCPScope(agent *types.CustomAgent) []string {+ if agent == nil || agent.Config.MCPSelectionMode != "selected" {+ return nil+ }+ ids := make([]string, 0, len(agent.Config.MCPServices))+ for _, id := range agent.Config.MCPServices {+ if strings.TrimSpace(id) != "" {+ ids = append(ids, id)+ }+ }+ return ids+}+func filterKnowledgeByAgentScope(knowledges []*types.Knowledge, scope types.SharedAgentKBScope) []*types.Knowledge {filtered := make([]*types.Knowledge, 0, len(knowledges))for _, knowledge := range knowledges {diff --git a/internal/handler/shared_agent_picker_test.go b/internal/handler/shared_agent_picker_test.gonew file mode 100644index 000000000..1bfd566a9--- /dev/null+++ b/internal/handler/shared_agent_picker_test.go@@ -0,0 +1,359 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/internal/handler/dto"+ "github.com/Tencent/WeKnora/internal/middleware"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+)++// A shared agent invokes skills and MCP services that live in ITS OWNER's+// workspace. The @ pickers used to read the caller's own workspace, so they+// came up empty (skills, and MCP in "selected" mode) or offered the caller's+// own services under "all", which the backend then dropped from the mention.+const lenderWorkspace = uint64(84)++func pickerAuth(c *gin.Context) {+ c.Set(types.TenantIDContextKey.String(), testSkillTenantID)+ c.Set(types.UserIDContextKey.String(), "user-1")+ c.Next()+}++func sharedSkillAgent(mode string, selected ...string) *types.CustomAgent {+ return &types.CustomAgent{+ ID: "agent-1", TenantID: lenderWorkspace,+ Config: types.CustomAgentConfig{+ SandboxConfigID: "cfg-of-lender",+ SkillsSelectionMode: mode,+ SelectedSkills: selected,+ },+ }+}++func newPickerSkillRouter(h *SkillHandler) *gin.Engine {+ gin.SetMode(gin.TestMode)+ r := gin.New()+ r.Use(middleware.ErrorHandler())+ r.Use(pickerAuth)+ r.GET("/skills", h.ListSkills)+ return r+}++type skillPickerBody struct {+ Success bool `json:"success"`+ Data []SkillInfoResponse `json:"data"`+ SkillsAvailable bool `json:"skills_available"`+}++func getSkills(t *testing.T, r *gin.Engine, query string) (int, skillPickerBody) {+ t.Helper()+ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/skills"+query, nil))+ var body skillPickerBody+ if w.Code == http.StatusOK {+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))+ }+ return w.Code, body+}++func TestListSkillsReadsASharedAgentsOwnWorkspace(t *testing.T) {+ lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{+ {Name: "ppt-generator", Description: "make ppt"},+ {Name: "xlsx", Description: "spreadsheets"},+ }}+ agents := &scopedAgentStub{agent: sharedSkillAgent("all")}+ router := newPickerSkillRouter(NewSkillHandler(lister, nil, agents))++ code, body := getSkills(t, router, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusOK, code)+ require.True(t, body.SkillsAvailable)+ require.Len(t, body.Data, 2)+ require.Equal(t, lenderWorkspace, lister.tenantID,+ "installed skills are looked up where the agent runs")+ require.Equal(t, "cfg-of-lender", lister.configID)+ require.Equal(t, testSkillTenantID, agents.caller)+ require.Equal(t, lenderWorkspace, agents.source)+}++// The config comes from the agent, never from the query string: otherwise a+// borrower could name any config id in the owner's workspace and enumerate the+// skills installed on it.+func TestListSkillsIgnoresTheQueryConfigForASharedAgent(t *testing.T) {+ lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{{Name: "ppt-generator"}}}+ agents := &scopedAgentStub{agent: sharedSkillAgent("all")}+ router := newPickerSkillRouter(NewSkillHandler(lister, nil, agents))++ code, _ := getSkills(t, router,+ "?agent_id=agent-1&agent_source_tenant_id=84&sandbox_config_id=cfg-somebody-elses")++ require.Equal(t, http.StatusOK, code)+ require.Equal(t, "cfg-of-lender", lister.configID)+}++func TestListSkillsNarrowsToASharedAgentsSelection(t *testing.T) {+ lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{+ {Name: "ppt-generator"}, {Name: "xlsx"}, {Name: "internal-only"},+ }}+ agents := &scopedAgentStub{agent: sharedSkillAgent("selected", "xlsx")}+ router := newPickerSkillRouter(NewSkillHandler(lister, nil, agents))++ code, body := getSkills(t, router, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusOK, code)+ require.Len(t, body.Data, 1)+ require.Equal(t, "xlsx", body.Data[0].Name,+ "a borrower only sees the skills the agent was configured with")+}++// An owner who turned skills off must not have their skill inventory listed to+// borrowers, so the lookup does not even run.+func TestListSkillsStaysEmptyWhenASharedAgentDisabledSkills(t *testing.T) {+ for _, mode := range []string{"", "none", "nonsense"} {+ lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{{Name: "ppt-generator"}}}+ agents := &scopedAgentStub{agent: sharedSkillAgent(mode)}+ router := newPickerSkillRouter(NewSkillHandler(lister, nil, agents))++ code, body := getSkills(t, router, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusOK, code, mode)+ require.Empty(t, body.Data, mode)+ require.False(t, body.SkillsAvailable, mode)+ require.Zero(t, lister.tenantID, "skills mode %q must not reach the owner's inventory", mode)+ }+}++// Without a source workspace the request is an ordinary own-agent one and must+// keep reading the caller's own workspace, agent_id or not.+func TestListSkillsKeepsTheOwnWorkspacePathUnchanged(t *testing.T) {+ lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{{Name: "ppt-generator"}}}+ agents := &scopedAgentStub{agent: sharedSkillAgent("all")}+ router := newPickerSkillRouter(NewSkillHandler(lister, nil, agents))++ code, body := getSkills(t, router, "?agent_id=agent-1&sandbox_config_id=cfg-mine")++ require.Equal(t, http.StatusOK, code)+ require.Len(t, body.Data, 1)+ require.Equal(t, testSkillTenantID, lister.tenantID)+ require.Equal(t, "cfg-mine", lister.configID)+ require.Zero(t, agents.caller, "no share lookup for an own agent")+}++func TestListSkillsRefusesAnUnreachableShare(t *testing.T) {+ lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{{Name: "ppt-generator"}}}+ agents := &scopedAgentStub{agent: nil}+ router := newPickerSkillRouter(NewSkillHandler(lister, nil, agents))++ code, _ := getSkills(t, router, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusForbidden, code)+ require.Zero(t, lister.tenantID)+}++// ---- @MCP ----++type pickerMCPStub struct {+ interfaces.MCPServiceService+ listedTenant uint64+ listedIDs []string+ ownListCalls int+ services []*types.MCPService+ summaryTenant uint64+}++func (s *pickerMCPStub) ListMCPServices(+ _ context.Context, tenantID uint64,+) ([]*types.MCPService, error) {+ s.ownListCalls+++ s.listedTenant = tenantID+ return s.services, nil+}++func (s *pickerMCPStub) ListMCPServicesByIDs(+ _ context.Context, tenantID uint64, ids []string,+) ([]*types.MCPService, error) {+ s.listedTenant, s.listedIDs = tenantID, ids+ out := make([]*types.MCPService, 0, len(ids))+ for _, id := range ids {+ for _, svc := range s.services {+ if svc.ID == id {+ out = append(out, svc)+ }+ }+ }+ return out, nil+}++func (s *pickerMCPStub) ListMCPMetadataSummaries(+ _ context.Context, tenantID uint64, _ []*types.MCPService,+) (map[string]*types.MCPMetadataSummary, error) {+ s.summaryTenant = tenantID+ return nil, nil+}++func newPickerMCPRouter(h *MCPServiceHandler) *gin.Engine {+ gin.SetMode(gin.TestMode)+ r := gin.New()+ r.Use(middleware.ErrorHandler())+ r.Use(pickerAuth)+ r.GET("/mcp-services", h.ListMCPServices)+ return r+}++func sharedMCPAgent(mode string, ids ...string) *types.CustomAgent {+ return &types.CustomAgent{+ ID: "agent-1", TenantID: lenderWorkspace,+ Config: types.CustomAgentConfig{MCPSelectionMode: mode, MCPServices: ids},+ }+}++func lenderService(id, name string) *types.MCPService {+ url := "https://internal.lender.example/mcp"+ return &types.MCPService{+ ID: id, TenantID: lenderWorkspace, Name: name, Enabled: true,+ URL: &url, Headers: types.MCPHeaders{"X-Secret": "nope"},+ AuthConfig: &types.MCPAuthConfig{APIKey: "sk-lender"},+ }+}++func getMCP(t *testing.T, r *gin.Engine, query string) (int, []*dto.MCPServiceResponse, []byte) {+ t.Helper()+ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/mcp-services"+query, nil))+ var body struct {+ Data []*dto.MCPServiceResponse `json:"data"`+ }+ if w.Code == http.StatusOK {+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))+ }+ return w.Code, body.Data, w.Body.Bytes()+}++func TestListMCPServicesServesASharedAgentsPresetFromItsOwnWorkspace(t *testing.T) {+ mcp := &pickerMCPStub{services: []*types.MCPService{+ lenderService("svc-a", "Lender A"),+ lenderService("svc-b", "Lender B"),+ }}+ agents := &scopedAgentStub{agent: sharedMCPAgent("selected", "svc-b")}+ router := newPickerMCPRouter(NewMCPServiceHandler(mcp, nil, nil, nil, agents))++ code, data, raw := getMCP(t, router, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusOK, code)+ require.Len(t, data, 1)+ require.Equal(t, "svc-b", data[0].ID)+ require.Equal(t, "Lender B", data[0].Name)+ require.Equal(t, lenderWorkspace, mcp.listedTenant)+ require.Equal(t, []string{"svc-b"}, mcp.listedIDs)+ require.Zero(t, mcp.ownListCalls, "the caller's own services are irrelevant here")+ require.Equal(t, lenderWorkspace, mcp.summaryTenant)++ // The borrower configures none of this and must not see how the owner+ // wired the service up.+ require.Nil(t, data[0].URL)+ require.Nil(t, data[0].Headers)+ require.Nil(t, data[0].AuthConfig)+ require.Nil(t, data[0].Credentials)+ require.NotContains(t, string(raw), "internal.lender.example")+ require.NotContains(t, string(raw), "sk-lender")+}++// resolvePerRequestMCPScope intersects a shared agent's @mention against its+// explicit preset, which is empty under "all" and "none". Offering the owner's+// whole inventory there would put services in the picker that every mention+// then silently drops.+func TestListMCPServicesOffersNothingOutsideASharedAgentsPreset(t *testing.T) {+ for _, mode := range []string{"all", "none", ""} {+ mcp := &pickerMCPStub{services: []*types.MCPService{lenderService("svc-a", "Lender A")}}+ agents := &scopedAgentStub{agent: sharedMCPAgent(mode, "svc-a")}+ router := newPickerMCPRouter(NewMCPServiceHandler(mcp, nil, nil, nil, agents))++ code, data, _ := getMCP(t, router, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusOK, code, mode)+ require.Empty(t, data, "mode %q pins nothing, so it offers nothing", mode)+ require.Zero(t, mcp.ownListCalls, mode)+ }+}++func TestListMCPServicesSkipsADisabledSharedService(t *testing.T) {+ disabled := lenderService("svc-a", "Lender A")+ disabled.Enabled = false+ mcp := &pickerMCPStub{services: []*types.MCPService{disabled}}+ agents := &scopedAgentStub{agent: sharedMCPAgent("selected", "svc-a")}+ router := newPickerMCPRouter(NewMCPServiceHandler(mcp, nil, nil, nil, agents))++ code, data, _ := getMCP(t, router, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusOK, code)+ require.Empty(t, data, "registerMCPTools skips disabled services, so the picker must too")+}++func TestListMCPServicesKeepsTheOwnWorkspacePathUnchanged(t *testing.T) {+ own := lenderService("svc-own", "Mine")+ own.TenantID = testSkillTenantID+ mcp := &pickerMCPStub{services: []*types.MCPService{own}}+ agents := &scopedAgentStub{agent: sharedMCPAgent("selected", "svc-b")}+ router := newPickerMCPRouter(NewMCPServiceHandler(mcp, nil, nil, nil, agents))++ code, data, _ := getMCP(t, router, "?agent_id=agent-1")++ require.Equal(t, http.StatusOK, code)+ require.Len(t, data, 1)+ require.Equal(t, 1, mcp.ownListCalls)+ require.Equal(t, testSkillTenantID, mcp.listedTenant)+ require.Zero(t, agents.caller, "no share lookup for an own agent")+ // The full shape is unchanged for a workspace's own services: credential+ // metadata is what the settings UI renders its badges from.+ require.NotNil(t, data[0].Credentials)+}++// NewMCPServiceResponse reveals URL / headers / env vars to an Admin, and a+// borrower can be an Admin of their OWN workspace. The cross-workspace shape+// must therefore be narrow by construction, not by role.+func TestListMCPServicesNeverRevealsOwnerConfigToAnAdminBorrower(t *testing.T) {+ mcp := &pickerMCPStub{services: []*types.MCPService{lenderService("svc-a", "Lender A")}}+ agents := &scopedAgentStub{agent: sharedMCPAgent("selected", "svc-a")}+ h := NewMCPServiceHandler(mcp, nil, nil, nil, agents)++ gin.SetMode(gin.TestMode)+ r := gin.New()+ r.Use(middleware.ErrorHandler())+ r.Use(func(c *gin.Context) {+ pickerAuth(c)+ c.Request = c.Request.WithContext(context.WithValue(+ c.Request.Context(), types.TenantRoleContextKey, types.TenantRoleOwner))+ c.Next()+ })+ r.GET("/mcp-services", h.ListMCPServices)++ code, data, raw := getMCP(t, r, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusOK, code)+ require.Len(t, data, 1)+ require.Nil(t, data[0].URL)+ require.Nil(t, data[0].Headers)+ require.Nil(t, data[0].Credentials)+ require.NotContains(t, string(raw), "internal.lender.example")+ require.NotContains(t, string(raw), "sk-lender")+}++func TestListMCPServicesRefusesAnUnreachableShare(t *testing.T) {+ mcp := &pickerMCPStub{services: []*types.MCPService{lenderService("svc-a", "Lender A")}}+ agents := &scopedAgentStub{agent: nil}+ router := newPickerMCPRouter(NewMCPServiceHandler(mcp, nil, nil, nil, agents))++ code, _, _ := getMCP(t, router, "?agent_id=agent-1&agent_source_tenant_id=84")++ require.Equal(t, http.StatusForbidden, code)+ require.Zero(t, mcp.ownListCalls)+}diff --git a/internal/handler/skill_catalog_test.go b/internal/handler/skill_catalog_test.goindex 6a19b1d24..65cd3bb2d 100644--- a/internal/handler/skill_catalog_test.go+++ b/internal/handler/skill_catalog_test.go@@ -90,7 +90,7 @@ func TestListCatalogReturnsDefinitionsAndInstallations(t *testing.T) {}},}},}- router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog, nil))w := httptest.NewRecorder()router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/skills/catalog", nil))@@ -109,7 +109,7 @@ func TestListCatalogReturnsDefinitionsAndInstallations(t *testing.T) {func TestRegisterCatalogFromSource(t *testing.T) {catalog := &fakeSkillCatalog{registerID: "cat-9"}- router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog, nil))body, err := json.Marshal(map[string]string{"source": "@owner/pdf"})require.NoError(t, err)@@ -123,7 +123,7 @@ func TestRegisterCatalogFromSource(t *testing.T) {func TestRegisterCatalogFromSourceRejectsAnOversizedJSONBody(t *testing.T) {catalog := &fakeSkillCatalog{registerID: "cat-9"}- router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog, nil))req := httptest.NewRequest(http.MethodPost, "/skills/catalog",bytes.NewReader(oversizedSkillSourceJSON(1)))@@ -138,7 +138,7 @@ func TestRegisterCatalogFromSourceRejectsAnOversizedJSONBody(t *testing.T) {func TestInstallCatalogRejectsAnOversizedJSONBody(t *testing.T) {catalog := &fakeSkillCatalog{installs: map[string]string{"cfg-1": "sk-1"}}- router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog, nil))req := httptest.NewRequest(http.MethodPost, "/skills/catalog/cat-1/install",bytes.NewReader(oversizedSkillSourceJSON(1)))@@ -153,7 +153,7 @@ func TestInstallCatalogRejectsAnOversizedJSONBody(t *testing.T) {func TestInstallCatalogAcceptsPerConfigIDs(t *testing.T) {catalog := &fakeSkillCatalog{installs: map[string]string{"cfg-1": "sk-1"}}- router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog, nil))body, err := json.Marshal(map[string][]string{"sandbox_config_ids": {"cfg-1"}})require.NoError(t, err)@@ -169,7 +169,7 @@ func TestInstallCatalogIncludesPerConfigErrors(t *testing.T) {installs: map[string]string{"cfg-1": "sk-1"},installErrs: map[string]string{"cfg-2": "sandbox config not found"},}- router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog, nil))body, err := json.Marshal(map[string][]string{"sandbox_config_ids": {"cfg-1", "cfg-2"}})require.NoError(t, err)@@ -196,7 +196,7 @@ func TestDeleteCatalogRefusesWhileInstalled(t *testing.T) {catalog := &fakeSkillCatalog{deleteErr: apperrors.NewConflictError("remove this skill from every sandbox"),}- router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog, nil))w := httptest.NewRecorder()router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete, "/skills/catalog/cat-1", nil))diff --git a/internal/handler/skill_handler.go b/internal/handler/skill_handler.goindex 9f84c86cf..f4f8d04dd 100644--- a/internal/handler/skill_handler.go+++ b/internal/handler/skill_handler.go@@ -4,6 +4,7 @@ import ("context""net/http"+ "github.com/Tencent/WeKnora/internal/application/access""github.com/Tencent/WeKnora/internal/application/service""github.com/Tencent/WeKnora/internal/types""github.com/gin-gonic/gin"@@ -20,6 +21,11 @@ type usableSkillLister interface {type SkillHandler struct {usableSkills usableSkillListercatalog skillCatalogService+ // agents resolves a shared agent so the @ picker can list the skills that+ // agent can actually invoke, which live in ITS OWNER's workspace. Nil+ // disables the shared-agent path (and with it the @Skill picker for shared+ // agents) rather than falling back to the caller's own workspace.+ agents access.SharedAgentLookup}type skillCatalogService interface {@@ -34,10 +40,15 @@ type skillCatalogService interface {// NewSkillHandler creates a new skill handler. catalog may be nil in tests// that only exercise the chat picker.-func NewSkillHandler(usableSkills usableSkillLister, catalog skillCatalogService) *SkillHandler {+func NewSkillHandler(+ usableSkills usableSkillLister,+ catalog skillCatalogService,+ agents access.SharedAgentLookup,+) *SkillHandler {return &SkillHandler{usableSkills: usableSkills,catalog: catalog,+ agents: agents,}}@@ -53,14 +64,41 @@ type SkillInfoResponse struct {// @Tags Skills// @Accept json// @Produce json-// @Param sandbox_config_id query string false "Sandbox config ID"+// @Param sandbox_config_id query string false "Sandbox config ID; ignored for a shared agent"+// @Param agent_id query string false "Agent ID; needs agent_source_tenant_id"+// @Param agent_source_tenant_id query int false "Shared agent source workspace"// @Success 200 {object} map[string]interface{} "Skills列表"+// @Failure 403 {object} errors.AppError "无权使用该共享智能体"// @Security Bearer// @Security ApiKeyAuth// @Router /skills [get]func (h *SkillHandler) ListSkills(c *gin.Context) {+ // A shared agent runs its skills in its OWNER's workspace, on the sandbox+ // config that agent selected. Reading either from the caller's workspace+ // (or from the query string) would list nothing, which is why the @Skill+ // picker used to come up empty for every shared agent.+ agent, err := sharedAgentPickerScope(c, h.agents)+ if err != nil {+ _ = c.Error(err)+ return+ }+configID := c.Query("sandbox_config_id")- if configID == "" || h.usableSkills == nil {+ tenantID := sandboxConfigTenantID(c)+ // allowed nil means "no name filter"; anyAllowed false means the agent can+ // invoke no skill at all, so nothing is looked up.+ var allowed map[string]bool+ anyAllowed := true+ if agent != nil {+ // Take the config from the agent, never from the query: the caller+ // could otherwise name any config id in the owner's workspace and+ // enumerate skills the shared agent does not use.+ configID = agent.Config.SandboxConfigID+ tenantID = agent.TenantID+ allowed, anyAllowed = sharedAgentSkillScope(agent)+ }++ if configID == "" || tenantID == 0 || !anyAllowed || h.usableSkills == nil {c.JSON(http.StatusOK, gin.H{"success": true,"data": []SkillInfoResponse{},@@ -69,14 +107,15 @@ func (h *SkillHandler) ListSkills(c *gin.Context) {return}- rows := h.usableSkills.ListUsableSkills(- c.Request.Context(), sandboxConfigTenantID(c), configID,- )+ rows := h.usableSkills.ListUsableSkills(c.Request.Context(), tenantID, configID)response := make([]SkillInfoResponse, 0, len(rows))for _, row := range rows {if row == nil {continue}+ if allowed != nil && !allowed[row.Name] {+ continue+ }response = append(response, SkillInfoResponse{Name: row.Name,Description: row.Description,diff --git a/internal/handler/skill_handler_test.go b/internal/handler/skill_handler_test.goindex 5448bf4fe..b94fe1c02 100644--- a/internal/handler/skill_handler_test.go+++ b/internal/handler/skill_handler_test.go@@ -47,7 +47,7 @@ func TestListSkillsHidesThePickerWhenNoSandboxConfigIsSelected(t *testing.T) {lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{{Name: "ppt-generator", Description: "make ppt"}},}- router := newChatSkillRouter(NewSkillHandler(lister, nil))+ router := newChatSkillRouter(NewSkillHandler(lister, nil, nil))w := httptest.NewRecorder()router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/skills", nil))@@ -71,7 +71,7 @@ func TestListSkillsReturnsUsableInstalledSkillsForTheSelectedConfig(t *testing.T{Name: "ppt-generator", Description: "make ppt"},},}- router := newChatSkillRouter(NewSkillHandler(lister, nil))+ router := newChatSkillRouter(NewSkillHandler(lister, nil, nil))w := httptest.NewRecorder()router.ServeHTTP(w, httptest.NewRequest(