Copilot commented on code in PR #1620: URL: https://github.com/apache/dubbo-admin/pull/1620#discussion_r4438214904
########## pkg/console/handler/mcp.go: ########## @@ -0,0 +1,274 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package handler + +import ( + "errors" + "net/http" + "strings" + + "github.com/gin-contrib/sessions" + "github.com/gin-gonic/gin" + + "github.com/apache/dubbo-admin/pkg/common/bizerror" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/console/service" + "github.com/apache/dubbo-admin/pkg/console/util" + "github.com/apache/dubbo-admin/pkg/core/logger" + "github.com/apache/dubbo-admin/pkg/core/store" +) + +func RequireMCPMesh() gin.HandlerFunc { + return func(c *gin.Context) { + if strings.TrimSpace(c.Query("mesh")) == "" { + c.AbortWithStatusJSON(http.StatusBadRequest, + model.NewBizErrorResp(bizerror.New(bizerror.InvalidArgument, "mesh is required"))) + } + } +} + +func ListMCPServers(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + servers, err := service.ListMCPServers(ctx, c.Query("mesh")) + if err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(servers)) + } +} + +func CreateMCPServer(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + req := new(model.MCPServerCreateReq) + if err := c.ShouldBindJSON(req); err != nil { + util.HandleArgumentError(c, err) + return + } + server, err := service.CreateMCPServer(ctx, req) + if err != nil { + writeMCPResult(c, nil, err) + return + } + auditMCPMutation(c, "server.create", req.Mesh, req.Name) + c.JSON(http.StatusOK, model.NewSuccessResp(server)) + } +} + +func GetMCPServer(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + server, err := service.GetMCPServerInMesh(ctx, c.Query("mesh"), c.Param("serverId")) + if err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(server)) + } +} + +func DeleteMCPServer(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + err := service.DeleteMCPServer(ctx, c.Query("mesh"), c.Param("serverId"), c.Query("expectedResourceVersion")) + if err == nil { + auditMCPMutation(c, "server.delete", c.Query("mesh"), c.Param("serverId")) + } + writeMCPResult(c, true, err) + } +} + +func ReplaceMCPDraft(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + req := new(model.MCPDraftReq) + if err := c.ShouldBindJSON(req); err != nil { + util.HandleArgumentError(c, err) + return + } + server, err := service.ReplaceMCPDraft(ctx, c.Query("mesh"), c.Param("serverId"), req) + if err == nil { + auditMCPMutation(c, "draft.replace", c.Query("mesh"), c.Param("serverId")) + } + writeMCPResult(c, server, err) + } +} + +func ValidateMCPServer(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + result, err := service.ValidateMCPServer(ctx, c.Query("mesh"), c.Param("serverId")) + if err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(result)) + } +} + +func CreateMCPTool(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + req := new(model.MCPToolReq) + if err := c.ShouldBindJSON(req); err != nil { + util.HandleArgumentError(c, err) + return + } + server, tool, err := service.CreateMCPTool(ctx, c.Query("mesh"), c.Param("serverId"), req) + if err != nil { + writeMCPResult(c, nil, err) + return + } + auditMCPMutation(c, "tool.create", c.Query("mesh"), c.Param("serverId")) + c.JSON(http.StatusOK, model.NewSuccessResp(map[string]any{"server": server, "tool": tool})) + } +} + +func ListMCPTools(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + server, err := service.GetMCPServerInMesh(ctx, c.Query("mesh"), c.Param("serverId")) + if err != nil { + util.HandleServiceError(c, err) + return + } + if server.Spec == nil || server.Spec.Draft == nil { + c.JSON(http.StatusOK, model.NewSuccessResp([]any{})) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(server.Spec.Draft.Tools)) + } +} + +func GetMCPTool(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + tool, err := service.GetMCPTool(ctx, c.Query("mesh"), c.Param("serverId"), c.Param("toolId")) + if err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(tool)) + } +} + +func ValidateMCPTool(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + result, err := service.ValidateMCPTool(ctx, c.Query("mesh"), c.Param("serverId"), c.Param("toolId")) + if err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(result)) + } +} + +func ListMCPCredentials(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + credentials, err := service.ListMCPCredentials(ctx, c.Query("mesh"), c.Param("serverId")) + if err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(credentials)) + } +} + +func CreateMCPCredential(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + req := new(model.MCPCredentialCreateReq) + if err := c.ShouldBindJSON(req); err != nil { + util.HandleArgumentError(c, err) + return + } + credential, err := service.CreateMCPCredential(ctx, c.Query("mesh"), c.Param("serverId"), req) + if err != nil { + util.HandleServiceError(c, err) + return + } + auditMCPMutation(c, "credential.create", c.Query("mesh"), c.Param("serverId")) + c.JSON(http.StatusOK, model.NewSuccessResp(credential)) + } +} + +func RevokeMCPCredential(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + credential, err := service.RevokeMCPCredential(ctx, c.Query("mesh"), c.Param("serverId"), c.Param("credentialId"), c.Query("expectedResourceVersion")) + if err == nil { + auditMCPMutation(c, "credential.revoke", c.Query("mesh"), c.Param("serverId")) + } + writeMCPResult(c, credential, err) + } +} + +func UpdateMCPTool(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + req := new(model.MCPToolReq) + if err := c.ShouldBindJSON(req); err != nil { + util.HandleArgumentError(c, err) + return + } + server, tool, err := service.UpdateMCPTool(ctx, c.Query("mesh"), c.Param("serverId"), c.Param("toolId"), req) + if err != nil { + writeMCPResult(c, nil, err) + return + } + auditMCPMutation(c, "tool.update", c.Query("mesh"), c.Param("serverId")) + c.JSON(http.StatusOK, model.NewSuccessResp(map[string]any{"server": server, "tool": tool})) + } +} + +func DeleteMCPTool(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + server, err := service.DeleteMCPTool(ctx, c.Query("mesh"), c.Param("serverId"), c.Param("toolId"), c.Query("expectedResourceVersion")) + if err == nil { + auditMCPMutation(c, "tool.delete", c.Query("mesh"), c.Param("serverId")) + } + writeMCPResult(c, server, err) + } +} + +func PublishMCPServer(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + req := new(model.MCPPublishReq) + if err := c.ShouldBindJSON(req); err != nil { + util.HandleArgumentError(c, err) + return + } + server, err := service.PublishMCPServer(ctx, c.Query("mesh"), c.Param("serverId"), req) + if err == nil { + auditMCPMutation(c, "server.publish", c.Query("mesh"), c.Param("serverId")) + } + writeMCPResult(c, server, err) + } +} + +func writeMCPResult(c *gin.Context, value any, err error) { + if err == nil { + c.JSON(http.StatusOK, model.NewSuccessResp(value)) + return + } + if errors.Is(err, store.ErrorResourceConflict("", "", "")) { + c.JSON(http.StatusConflict, model.NewErrorResp(err.Error())) + return + } + util.HandleServiceError(c, err) +} + +func auditMCPMutation(c *gin.Context, action, mesh, serverID string) { + logger.Sugar().Infow("MCP control-plane mutation", + "action", action, + "principal", sessions.Default(c).Get("user"), Review Comment: Normal password and OAuth login both call console/auth.PutPrincipal, which stores the principal under "principal" and explicitly deletes the legacy "user" entry. Consequently, successful mutations by newly logged-in users are audited with a nil principal. Read the authenticated principal with consoleauth.PrincipalFromContext(c) and record its stable Subject instead of reading the legacy session key. ########## pkg/console/service/mcp.go: ########## @@ -0,0 +1,603 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package service + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "google.golang.org/protobuf/proto" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/common/bizerror" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store/index" + "github.com/apache/dubbo-admin/pkg/mcp/availability" + "github.com/apache/dubbo-admin/pkg/mcp/business" +) + +func ListMCPServers(ctx consolectx.Context, mesh string) ([]*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + return manager.ListByIndexes[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) +} + +func GetMCPServerInMesh(ctx consolectx.Context, mesh, serverID string) (*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + server, exists, err := manager.GetByKey[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, coremodel.BuildResourceKey(mesh, serverID)) + if err != nil { + return nil, err + } + if !exists { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP server %q not found", serverID)) + } + return server, nil +} + +func DeleteMCPServer(ctx consolectx.Context, mesh, serverID, expectedVersion string) error { + if strings.TrimSpace(expectedVersion) == "" { + return bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + if _, err := GetMCPServerInMesh(ctx, mesh, serverID); err != nil { + return err + } + cascading, ok := ctx.ResourceManager().(manager.CascadingResourceManager) + if !ok { + return fmt.Errorf("resource manager does not support cascading deletion") + } + server := meshresource.NewMCPServerResourceWithAttributes(serverID, mesh) + return cascading.CompareAndDeleteWithDependents(server, expectedVersion, meshresource.MCPCredentialKind, []index.IndexCondition{ + {IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}, + {IndexName: index.ByMCPCredentialServerID, Value: serverID, Operator: index.Equals}, + }) +} + +func CreateMCPServer(ctx consolectx.Context, req *model.MCPServerCreateReq) (*meshresource.MCPServerResource, error) { + if req == nil || strings.TrimSpace(req.Mesh) == "" || strings.TrimSpace(req.Name) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "mesh and name are required") + } + draft := req.Draft + if draft == nil { + draft = &meshproto.MCPServerSnapshot{} + } + draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot) + for _, tool := range draft.Tools { + if tool != nil && strings.TrimSpace(tool.ToolId) == "" { + tool.ToolId = business.NewToolID() + } + } + prepared, err := prepareMCPDraft(ctx, req.Mesh, draft) + if err != nil { + return nil, err + } + server := meshresource.NewMCPServerResourceWithAttributes(req.Name, req.Mesh) + server.Spec.Draft = prepared + if err := ctx.ResourceManager().Add(server); err != nil { + return nil, err + } + return server, nil +} + +func ReplaceMCPDraft(ctx consolectx.Context, mesh, serverID string, req *model.MCPDraftReq) (*meshresource.MCPServerResource, error) { + if req == nil || req.Draft == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "draft and expectedResourceVersion are required") + } + prepared, err := prepareMCPDraft(ctx, mesh, req.Draft) + if err != nil { + return nil, err + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = prepared + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, err + } + return updated, nil +} + +func ValidateMCPServer(ctx consolectx.Context, mesh, serverID string) (*model.MCPValidationResult, error) { + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return invalidMCPValidationResult("InvalidArgument", "server draft is required", ""), nil + } + prepared, err := prepareMCPDraft(ctx, mesh, server.Spec.Draft) + if err != nil { + return mcpValidationResult(err, "") + } + errors, warnings, err := validateMCPProtocolEvidence(ctx, mesh, prepared) + if err != nil { + return nil, err + } + return mcpValidationIssues(errors, warnings), nil +} + +func CreateMCPTool(ctx consolectx.Context, mesh, serverID string, req *model.MCPToolReq) (*meshresource.MCPServerResource, *meshproto.MCPToolBinding, error) { + if req == nil || req.Tool == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "tool and expectedResourceVersion are required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + tool := proto.Clone(req.Tool).(*meshproto.MCPToolBinding) + tool.ToolId = business.NewToolID() + tool.Parameters = nil + if err := resolveMCPTool(ctx, mesh, tool); err != nil { + return nil, nil, err + } + draft := proto.Clone(server.Spec.Draft).(*meshproto.MCPServerSnapshot) + draft.Tools = append(draft.Tools, tool) + if err := business.ValidateToolIdentity(draft); err != nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, err.Error()) + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = draft + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, nil, err + } + return updated, tool, nil +} + +func UpdateMCPTool(ctx consolectx.Context, mesh, serverID, toolID string, req *model.MCPToolReq) (*meshresource.MCPServerResource, *meshproto.MCPToolBinding, error) { + if req == nil || req.Tool == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "tool and expectedResourceVersion are required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + index := business.FindToolIndex(server.Spec.Draft, toolID) + if index < 0 { + return nil, nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP tool %q not found", toolID)) + } + tool := proto.Clone(req.Tool).(*meshproto.MCPToolBinding) + tool.ToolId = toolID + if !proto.Equal(server.Spec.Draft.Tools[index].Operation, tool.Operation) { + tool.Parameters = nil + } Review Comment: Comparing the entire operation resets valid parameter aliases and descriptions even when only the protocol, group or version changes and the ordered parameter types are unchanged. This also happens when the PUT request explicitly includes those bindings, so a protocol-only edit can unexpectedly change the input schema from "orderId" to "arg0". Preserve provided bindings and let resolveMCPTool validate them against the new signature; omitted bindings can still receive defaults. ########## pkg/console/service/mcp.go: ########## @@ -0,0 +1,603 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package service + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "google.golang.org/protobuf/proto" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/common/bizerror" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store/index" + "github.com/apache/dubbo-admin/pkg/mcp/availability" + "github.com/apache/dubbo-admin/pkg/mcp/business" +) + +func ListMCPServers(ctx consolectx.Context, mesh string) ([]*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + return manager.ListByIndexes[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) +} + +func GetMCPServerInMesh(ctx consolectx.Context, mesh, serverID string) (*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + server, exists, err := manager.GetByKey[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, coremodel.BuildResourceKey(mesh, serverID)) + if err != nil { + return nil, err + } + if !exists { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP server %q not found", serverID)) + } + return server, nil +} + +func DeleteMCPServer(ctx consolectx.Context, mesh, serverID, expectedVersion string) error { + if strings.TrimSpace(expectedVersion) == "" { + return bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + if _, err := GetMCPServerInMesh(ctx, mesh, serverID); err != nil { + return err + } + cascading, ok := ctx.ResourceManager().(manager.CascadingResourceManager) + if !ok { + return fmt.Errorf("resource manager does not support cascading deletion") + } + server := meshresource.NewMCPServerResourceWithAttributes(serverID, mesh) + return cascading.CompareAndDeleteWithDependents(server, expectedVersion, meshresource.MCPCredentialKind, []index.IndexCondition{ + {IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}, + {IndexName: index.ByMCPCredentialServerID, Value: serverID, Operator: index.Equals}, + }) +} + +func CreateMCPServer(ctx consolectx.Context, req *model.MCPServerCreateReq) (*meshresource.MCPServerResource, error) { + if req == nil || strings.TrimSpace(req.Mesh) == "" || strings.TrimSpace(req.Name) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "mesh and name are required") + } + draft := req.Draft + if draft == nil { + draft = &meshproto.MCPServerSnapshot{} + } + draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot) + for _, tool := range draft.Tools { + if tool != nil && strings.TrimSpace(tool.ToolId) == "" { + tool.ToolId = business.NewToolID() + } + } + prepared, err := prepareMCPDraft(ctx, req.Mesh, draft) + if err != nil { + return nil, err + } + server := meshresource.NewMCPServerResourceWithAttributes(req.Name, req.Mesh) + server.Spec.Draft = prepared + if err := ctx.ResourceManager().Add(server); err != nil { + return nil, err + } + return server, nil +} + +func ReplaceMCPDraft(ctx consolectx.Context, mesh, serverID string, req *model.MCPDraftReq) (*meshresource.MCPServerResource, error) { + if req == nil || req.Draft == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "draft and expectedResourceVersion are required") + } + prepared, err := prepareMCPDraft(ctx, mesh, req.Draft) + if err != nil { + return nil, err + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = prepared + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, err + } + return updated, nil +} + +func ValidateMCPServer(ctx consolectx.Context, mesh, serverID string) (*model.MCPValidationResult, error) { + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return invalidMCPValidationResult("InvalidArgument", "server draft is required", ""), nil + } + prepared, err := prepareMCPDraft(ctx, mesh, server.Spec.Draft) + if err != nil { + return mcpValidationResult(err, "") + } + errors, warnings, err := validateMCPProtocolEvidence(ctx, mesh, prepared) + if err != nil { + return nil, err + } + return mcpValidationIssues(errors, warnings), nil +} + +func CreateMCPTool(ctx consolectx.Context, mesh, serverID string, req *model.MCPToolReq) (*meshresource.MCPServerResource, *meshproto.MCPToolBinding, error) { + if req == nil || req.Tool == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "tool and expectedResourceVersion are required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + tool := proto.Clone(req.Tool).(*meshproto.MCPToolBinding) + tool.ToolId = business.NewToolID() + tool.Parameters = nil Review Comment: This discards the parameter bindings supplied in the create request. A tool posted with position 0 aliased as "orderId" is instead saved with "arg0", and its parameter description is lost. ResolveOperation already supplies defaults when Parameters is nil; preserve supplied bindings so they are validated and included in the generated input schema rather than silently overwritten. ########## pkg/console/service/mcp.go: ########## @@ -0,0 +1,603 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package service + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "google.golang.org/protobuf/proto" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/common/bizerror" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store/index" + "github.com/apache/dubbo-admin/pkg/mcp/availability" + "github.com/apache/dubbo-admin/pkg/mcp/business" +) + +func ListMCPServers(ctx consolectx.Context, mesh string) ([]*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + return manager.ListByIndexes[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) +} + +func GetMCPServerInMesh(ctx consolectx.Context, mesh, serverID string) (*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + server, exists, err := manager.GetByKey[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, coremodel.BuildResourceKey(mesh, serverID)) + if err != nil { + return nil, err + } + if !exists { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP server %q not found", serverID)) + } + return server, nil +} + +func DeleteMCPServer(ctx consolectx.Context, mesh, serverID, expectedVersion string) error { + if strings.TrimSpace(expectedVersion) == "" { + return bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + if _, err := GetMCPServerInMesh(ctx, mesh, serverID); err != nil { + return err + } + cascading, ok := ctx.ResourceManager().(manager.CascadingResourceManager) + if !ok { + return fmt.Errorf("resource manager does not support cascading deletion") + } + server := meshresource.NewMCPServerResourceWithAttributes(serverID, mesh) + return cascading.CompareAndDeleteWithDependents(server, expectedVersion, meshresource.MCPCredentialKind, []index.IndexCondition{ + {IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}, + {IndexName: index.ByMCPCredentialServerID, Value: serverID, Operator: index.Equals}, + }) +} + +func CreateMCPServer(ctx consolectx.Context, req *model.MCPServerCreateReq) (*meshresource.MCPServerResource, error) { + if req == nil || strings.TrimSpace(req.Mesh) == "" || strings.TrimSpace(req.Name) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "mesh and name are required") + } + draft := req.Draft + if draft == nil { + draft = &meshproto.MCPServerSnapshot{} + } + draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot) + for _, tool := range draft.Tools { + if tool != nil && strings.TrimSpace(tool.ToolId) == "" { + tool.ToolId = business.NewToolID() + } + } + prepared, err := prepareMCPDraft(ctx, req.Mesh, draft) + if err != nil { + return nil, err + } + server := meshresource.NewMCPServerResourceWithAttributes(req.Name, req.Mesh) + server.Spec.Draft = prepared + if err := ctx.ResourceManager().Add(server); err != nil { + return nil, err + } + return server, nil +} + +func ReplaceMCPDraft(ctx consolectx.Context, mesh, serverID string, req *model.MCPDraftReq) (*meshresource.MCPServerResource, error) { + if req == nil || req.Draft == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "draft and expectedResourceVersion are required") + } + prepared, err := prepareMCPDraft(ctx, mesh, req.Draft) + if err != nil { + return nil, err + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = prepared + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, err + } + return updated, nil +} + +func ValidateMCPServer(ctx consolectx.Context, mesh, serverID string) (*model.MCPValidationResult, error) { + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return invalidMCPValidationResult("InvalidArgument", "server draft is required", ""), nil + } + prepared, err := prepareMCPDraft(ctx, mesh, server.Spec.Draft) + if err != nil { + return mcpValidationResult(err, "") + } + errors, warnings, err := validateMCPProtocolEvidence(ctx, mesh, prepared) + if err != nil { + return nil, err + } + return mcpValidationIssues(errors, warnings), nil +} + +func CreateMCPTool(ctx consolectx.Context, mesh, serverID string, req *model.MCPToolReq) (*meshresource.MCPServerResource, *meshproto.MCPToolBinding, error) { + if req == nil || req.Tool == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "tool and expectedResourceVersion are required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + tool := proto.Clone(req.Tool).(*meshproto.MCPToolBinding) + tool.ToolId = business.NewToolID() + tool.Parameters = nil + if err := resolveMCPTool(ctx, mesh, tool); err != nil { + return nil, nil, err + } + draft := proto.Clone(server.Spec.Draft).(*meshproto.MCPServerSnapshot) + draft.Tools = append(draft.Tools, tool) + if err := business.ValidateToolIdentity(draft); err != nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, err.Error()) + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = draft + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, nil, err + } + return updated, tool, nil +} + +func UpdateMCPTool(ctx consolectx.Context, mesh, serverID, toolID string, req *model.MCPToolReq) (*meshresource.MCPServerResource, *meshproto.MCPToolBinding, error) { + if req == nil || req.Tool == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "tool and expectedResourceVersion are required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + index := business.FindToolIndex(server.Spec.Draft, toolID) + if index < 0 { + return nil, nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP tool %q not found", toolID)) + } + tool := proto.Clone(req.Tool).(*meshproto.MCPToolBinding) + tool.ToolId = toolID + if !proto.Equal(server.Spec.Draft.Tools[index].Operation, tool.Operation) { + tool.Parameters = nil + } + if err := resolveMCPTool(ctx, mesh, tool); err != nil { + return nil, nil, err + } + draft := proto.Clone(server.Spec.Draft).(*meshproto.MCPServerSnapshot) + draft.Tools[index] = tool + if err := business.ValidateToolIdentity(draft); err != nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, err.Error()) + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = draft + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, nil, err + } + return updated, tool, nil +} + +func DeleteMCPTool(ctx consolectx.Context, mesh, serverID, toolID, expectedVersion string) (*meshresource.MCPServerResource, error) { + if strings.TrimSpace(expectedVersion) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + toolIndex := business.FindToolIndex(server.Spec.Draft, toolID) + if toolIndex < 0 { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP tool %q not found", toolID)) + } + draft := proto.Clone(server.Spec.Draft).(*meshproto.MCPServerSnapshot) + draft.Tools = append(draft.Tools[:toolIndex], draft.Tools[toolIndex+1:]...) + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = draft + if err := compareAndSwapMCPServer(ctx, updated, expectedVersion); err != nil { + return nil, err + } + return updated, nil +} + +func PublishMCPServer(ctx consolectx.Context, mesh, serverID string, req *model.MCPPublishReq) (*meshresource.MCPServerResource, error) { + if req == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + prepared, err := prepareMCPDraft(ctx, mesh, server.Spec.Draft) + if err != nil { + return nil, err + } + errors, _, err := validateMCPProtocolEvidence(ctx, mesh, prepared) + if err != nil { + return nil, err + } + if len(errors) > 0 { + return nil, bizerror.New(bizerror.InvalidArgument, errors[0].Message) + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + if updated.Spec.Published == nil { + updated.Spec.Published = &meshproto.MCPPublishedSnapshot{} + } + updated.Spec.Published.Revision++ + updated.Spec.Published.PublishedAt = time.Now().UTC().Format(time.RFC3339Nano) + updated.Spec.Published.Snapshot = prepared + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, err + } + return updated, nil +} + +func validateMCPProtocolEvidence(ctx consolectx.Context, mesh string, snapshot *meshproto.MCPServerSnapshot) ([]model.MCPValidationIssue, []model.MCPValidationIssue, error) { + validationErrors := make([]model.MCPValidationIssue, 0) + warnings := make([]model.MCPValidationIssue, 0) + metadata, err := manager.ListByIndexes[*meshresource.ServiceProviderMetadataResource]( + ctx.ResourceManager(), meshresource.ServiceProviderMetadataKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) + if err != nil { + return nil, nil, err + } + instances, err := manager.ListByIndexes[*meshresource.RPCInstanceResource]( + ctx.ResourceManager(), meshresource.RPCInstanceKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) + if err != nil { + return nil, nil, err + } + evidence := availability.Snapshot{ + Providers: metadata, + Instances: instances, + Sync: availability.SyncState{InitialSyncComplete: true, Healthy: true}, + } + for _, tool := range snapshot.Tools { + if tool == nil || tool.Operation == nil { + continue + } + identity := availability.Identity{ + Mesh: mesh, ServiceName: tool.Operation.ServiceName, + Group: tool.Operation.Group, Version: tool.Operation.Version, + } + result := availability.Evaluate(evidence, identity, tool.Operation.Protocol) + if availability.ConfirmedProtocolIncompatibility(result) { + validationErrors = append(validationErrors, model.MCPValidationIssue{ + Code: "ProtocolIncompatible", + Message: fmt.Sprintf("service %s has available providers, but none support protocol %q", + tool.Operation.ServiceName, tool.Operation.Protocol), + ToolID: tool.ToolId, + }) + continue + } + if !result.Evidence.Available { + warnings = append(warnings, model.MCPValidationIssue{ + Code: "NoAvailableProvider", + Message: fmt.Sprintf("service %s has no available provider; protocol compatibility cannot be confirmed", + tool.Operation.ServiceName), + ToolID: tool.ToolId, + }) + continue + } + if !result.Evidence.Complete { + warnings = append(warnings, model.MCPValidationIssue{ + Code: "ProtocolEvidenceIncomplete", + Message: fmt.Sprintf("service %s has incomplete protocol evidence; compatibility cannot be confirmed", + tool.Operation.ServiceName), + ToolID: tool.ToolId, + }) + } + } + return validationErrors, warnings, nil +} + +func compareAndSwapMCPServer(ctx consolectx.Context, updated *meshresource.MCPServerResource, expectedVersion string) error { + return compareAndSwapResource(ctx, updated, expectedVersion) +} + +func compareAndSwapResource(ctx consolectx.Context, updated coremodel.Resource, expectedVersion string) error { + conditional, ok := ctx.ResourceManager().(manager.ConditionalResourceManager) + if !ok { + return fmt.Errorf("resource manager does not support conditional mutations") + } + return conditional.CompareAndSwap(updated, expectedVersion) +} + +func resolveMCPTool(ctx consolectx.Context, mesh string, tool *meshproto.MCPToolBinding) error { + if tool == nil || tool.Operation == nil { + return bizerror.New(bizerror.InvalidArgument, "tool operation is required") + } + metadata, err := manager.ListByIndexes[*meshresource.ServiceProviderMetadataResource]( + ctx.ResourceManager(), meshresource.ServiceProviderMetadataKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) + if err != nil { + return err + } + contract, err := business.ResolveOperation(mesh, tool.Operation, tool.Parameters, metadata) + if err != nil { + return bizerror.New(bizerror.InvalidArgument, err.Error()) + } + tool.Parameters = contract.Parameters + tool.InputSchema = contract.InputSchema + tool.InputFingerprint = contract.InputFingerprint + tool.OutputFingerprint = contract.OutputFingerprint + tool.RelatedTypes = contract.RelatedTypes + tool.ReturnType = contract.ReturnType + return nil +} + +func prepareMCPDraft(ctx consolectx.Context, mesh string, draft *meshproto.MCPServerSnapshot) (*meshproto.MCPServerSnapshot, error) { + if draft == nil { + return nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + if strings.TrimSpace(draft.Description) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "server draft description is required") + } + prepared := proto.Clone(draft).(*meshproto.MCPServerSnapshot) + for _, tool := range prepared.Tools { + if tool != nil && strings.TrimSpace(tool.ToolId) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "toolId is required for existing draft tools") + } + if err := resolveMCPTool(ctx, mesh, tool); err != nil { + return nil, err + } + } + if err := business.ValidateToolIdentity(prepared); err != nil { + return nil, bizerror.New(bizerror.InvalidArgument, err.Error()) + } + return prepared, nil +} + +func GetMCPTool(ctx consolectx.Context, mesh, serverID, toolID string) (*meshproto.MCPToolBinding, error) { + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP tool %q not found", toolID)) + } + toolIndex := business.FindToolIndex(server.Spec.Draft, toolID) + if toolIndex < 0 { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP tool %q not found", toolID)) + } + return business.CloneTool(server.Spec.Draft.Tools[toolIndex]), nil +} + +func ValidateMCPTool(ctx consolectx.Context, mesh, serverID, toolID string) (*model.MCPValidationResult, error) { + tool, err := GetMCPTool(ctx, mesh, serverID, toolID) + if err != nil { + return nil, err + } + if err := resolveMCPTool(ctx, mesh, tool); err != nil { + return mcpValidationResult(err, toolID) + } + if err := business.ValidateToolIdentity(&meshproto.MCPServerSnapshot{Tools: []*meshproto.MCPToolBinding{tool}}); err != nil { + return mcpValidationResult(bizerror.New(bizerror.InvalidArgument, err.Error()), toolID) + } + validationErrors, warnings, err := validateMCPProtocolEvidence( + ctx, mesh, &meshproto.MCPServerSnapshot{Tools: []*meshproto.MCPToolBinding{tool}}, + ) + if err != nil { + return nil, err + } + for i := range validationErrors { + validationErrors[i].ToolID = toolID + } + for i := range warnings { + warnings[i].ToolID = toolID + } + return mcpValidationIssues(validationErrors, warnings), nil +} + +func mcpValidationResult(err error, toolID string) (*model.MCPValidationResult, error) { + result := &model.MCPValidationResult{ + Valid: err == nil, + Errors: make([]model.MCPValidationIssue, 0), + Warnings: make([]model.MCPValidationIssue, 0), + } + if err == nil { + return result, nil + } + var validationError bizerror.Error + if !errors.As(err, &validationError) || validationError.Code() != bizerror.InvalidArgument { + return nil, err + } + result.Errors = append(result.Errors, model.MCPValidationIssue{ + Code: string(validationError.Code()), + Message: validationError.Message(), + ToolID: toolID, + }) + return result, nil +} + +func mcpValidationIssues(errors, warnings []model.MCPValidationIssue) *model.MCPValidationResult { + if errors == nil { + errors = make([]model.MCPValidationIssue, 0) + } + if warnings == nil { + warnings = make([]model.MCPValidationIssue, 0) + } + return &model.MCPValidationResult{ + Valid: len(errors) == 0, + Errors: errors, + Warnings: warnings, + } +} + +func invalidMCPValidationResult(code, message, toolID string) *model.MCPValidationResult { + return &model.MCPValidationResult{ + Valid: false, + Errors: []model.MCPValidationIssue{{ + Code: code, + Message: message, + ToolID: toolID, + }}, + Warnings: make([]model.MCPValidationIssue, 0), + } +} + +func requireMCPMesh(mesh string) error { + if strings.TrimSpace(mesh) == "" { + return bizerror.New(bizerror.InvalidArgument, "mesh is required") + } + return nil +} + +type MCPCredentialToken struct { + Credential model.MCPCredentialView `json:"credential"` + Token string `json:"token"` +} + +func credentialView(credential *meshresource.MCPCredentialResource) model.MCPCredentialView { + return model.MCPCredentialView{ + ID: credential.Name, + Mesh: credential.Mesh, + ServerID: credential.Spec.ServerId, + ResourceVersion: credential.ResourceVersion, + DisplayName: credential.Spec.DisplayName, + Status: credential.Spec.Status, + ExpiresAt: credential.Spec.ExpiresAt, + CreatedAt: credential.Spec.CreatedAt, + } +} + +func ListMCPCredentials(ctx consolectx.Context, mesh, serverID string) ([]model.MCPCredentialView, error) { + if _, err := GetMCPServerInMesh(ctx, mesh, serverID); err != nil { + return nil, err + } + credentials, err := manager.ListByIndexes[*meshresource.MCPCredentialResource]( + ctx.ResourceManager(), meshresource.MCPCredentialKind, + []index.IndexCondition{ + {IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}, + {IndexName: index.ByMCPCredentialServerID, Value: serverID, Operator: index.Equals}, + }, + ) + if err != nil { + return nil, err + } + views := make([]model.MCPCredentialView, 0, len(credentials)) + for _, credential := range credentials { + if credential != nil && credential.Spec != nil { + views = append(views, credentialView(credential)) + } + } + return views, nil +} + +func CreateMCPCredential(ctx consolectx.Context, mesh, serverID string, req *model.MCPCredentialCreateReq) (*MCPCredentialToken, error) { + if req == nil || strings.TrimSpace(req.DisplayName) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "displayName is required") + } + if _, err := GetMCPServerInMesh(ctx, mesh, serverID); err != nil { + return nil, err + } + var expiresAt time.Time + if strings.TrimSpace(req.ExpiresAt) != "" { + parsed, err := time.Parse(time.RFC3339, req.ExpiresAt) + if err != nil || !parsed.After(time.Now().UTC()) { + return nil, bizerror.New(bizerror.InvalidArgument, "expiresAt must be a future RFC3339 timestamp when provided") + } + expiresAt = parsed + } + secretBytes := make([]byte, 32) + if _, err := rand.Read(secretBytes); err != nil { + return nil, fmt.Errorf("generate credential secret: %w", err) + } + credentialID := uuid.NewString() + secret := hex.EncodeToString(secretBytes) + digest := sha256.Sum256([]byte(secret)) + credential := meshresource.NewMCPCredentialResourceWithAttributes(credentialID, mesh) + credential.Spec = &meshproto.MCPCredential{ + ServerId: serverID, + DisplayName: req.DisplayName, + SecretHash: "sha256:" + hex.EncodeToString(digest[:]), + Status: "active", + ExpiresAt: formatMCPExpiration(expiresAt), + CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), + } + dependent, ok := ctx.ResourceManager().(manager.DependentResourceManager) + if !ok { + return nil, fmt.Errorf("resource manager does not support dependent creation") + } + if err := dependent.AddWithParent(meshresource.NewMCPServerResourceWithAttributes(serverID, mesh), credential); err != nil { + return nil, err + } + return &MCPCredentialToken{ + Credential: credentialView(credential), + Token: "mcp_" + credentialID + "." + secret, + }, nil +} + +func formatMCPExpiration(expiresAt time.Time) string { + if expiresAt.IsZero() { + return "" + } + return expiresAt.UTC().Format(time.RFC3339) Review Comment: RFC3339 formatting drops fractional seconds, although the request parser and future-expiration check accept them. An expiration at 01:21:58.600Z created at 01:21:58.100Z passes validation but is persisted as 01:21:58Z, so authentication considers the new credential already expired. Preserve the accepted timestamp precision with RFC3339Nano. ########## pkg/mcp/repository/credential.go: ########## @@ -0,0 +1,152 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package repository + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store/index" +) + +type Credentials struct { + resources manager.ResourceManager + conditional manager.ConditionalResourceManager + dependent manager.DependentResourceManager +} + +func NewCredentials(resources manager.ResourceManager) (*Credentials, error) { + conditional, ok := resources.(manager.ConditionalResourceManager) + if !ok { + return nil, fmt.Errorf("resource manager does not support conditional mutations") + } + dependent, ok := resources.(manager.DependentResourceManager) + if !ok { + return nil, fmt.Errorf("resource manager does not support dependent creation") + } + return &Credentials{resources: resources, conditional: conditional, dependent: dependent}, nil +} + +func (r *Credentials) Create(mesh, serverID, displayName string, expiresAt time.Time) (*meshresource.MCPCredentialResource, string, error) { + if mesh == "" || serverID == "" || strings.TrimSpace(displayName) == "" { + return nil, "", fmt.Errorf("mesh, server and display name are required") + } + if !expiresAt.IsZero() && !expiresAt.After(time.Now()) { + return nil, "", fmt.Errorf("expiresAt must be a future expiration or zero for no expiration") + } + secretBytes := make([]byte, 32) + if _, err := rand.Read(secretBytes); err != nil { + return nil, "", fmt.Errorf("generate credential secret: %w", err) + } + secret := hex.EncodeToString(secretBytes) + digest := sha256.Sum256([]byte(secret)) + credentialID := uuid.NewString() + credential := meshresource.NewMCPCredentialResourceWithAttributes(credentialID, mesh) + credential.Spec = &meshproto.MCPCredential{ + ServerId: serverID, + DisplayName: displayName, + SecretHash: "sha256:" + hex.EncodeToString(digest[:]), + Status: "active", + ExpiresAt: formatExpiration(expiresAt), + CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), + } + server := meshresource.NewMCPServerResourceWithAttributes(serverID, mesh) + if err := r.dependent.AddWithParent(server, credential); err != nil { + return nil, "", err + } + return credential, "mcp_" + credentialID + "." + secret, nil +} + +func (r *Credentials) List(mesh, serverID string) ([]*meshresource.MCPCredentialResource, error) { + return manager.ListByIndexes[*meshresource.MCPCredentialResource](r.resources, meshresource.MCPCredentialKind, []index.IndexCondition{ + {IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}, + {IndexName: index.ByMCPCredentialServerID, Value: serverID, Operator: index.Equals}, + }) +} + +func (r *Credentials) Revoke(mesh, serverID, credentialID, expectedVersion string) (*meshresource.MCPCredentialResource, error) { + credential, exists, err := manager.GetByKey[*meshresource.MCPCredentialResource]( + r.resources, meshresource.MCPCredentialKind, coremodel.BuildResourceKey(mesh, credentialID)) + if err != nil { + return nil, err + } + if !exists || credential.Spec == nil || credential.Spec.ServerId != serverID { + return nil, fmt.Errorf("MCP credential %q not found", credentialID) + } + updated := credential.DeepCopyObject().(*meshresource.MCPCredentialResource) + updated.Spec.Status = "revoked" + if err := r.conditional.CompareAndSwap(updated, expectedVersion); err != nil { + return nil, err + } + return updated, nil +} + +// Authenticate always reads the authoritative store, so a revoke made by +// another replica takes effect on the next authentication attempt. +func (r *Credentials) Authenticate(mesh, serverID, credentialID, secret string, now time.Time) (*meshresource.MCPCredentialResource, error) { + credential, exists, err := manager.GetByKey[*meshresource.MCPCredentialResource]( + r.resources, meshresource.MCPCredentialKind, coremodel.BuildResourceKey(mesh, credentialID)) + if err != nil { + return nil, err + } + if !exists || credential.Spec == nil { + return nil, fmt.Errorf("invalid MCP credential") + } + expiresAt, err := parseExpiration(credential.Spec.ExpiresAt) + if err != nil || credential.Spec.ServerId != serverID || credential.Spec.Status != "active" || (!expiresAt.IsZero() && !now.Before(expiresAt)) || !VerifySecretHash(credential.Spec.SecretHash, secret) { + return nil, fmt.Errorf("invalid MCP credential") + } + return credential, nil +} + +func formatExpiration(expiresAt time.Time) string { + if expiresAt.IsZero() { + return "" + } + return expiresAt.UTC().Format(time.RFC3339) Review Comment: This truncates the supplied expiration to whole seconds after Create has checked the original time. A future expiration later in the current second is therefore stored in the past and immediately rejected by Authenticate. Use RFC3339Nano here so the persisted expiration matches the time that passed validation. ########## pkg/console/service/mcp.go: ########## @@ -0,0 +1,603 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package service + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "google.golang.org/protobuf/proto" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/common/bizerror" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store/index" + "github.com/apache/dubbo-admin/pkg/mcp/availability" + "github.com/apache/dubbo-admin/pkg/mcp/business" +) + +func ListMCPServers(ctx consolectx.Context, mesh string) ([]*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + return manager.ListByIndexes[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) +} + +func GetMCPServerInMesh(ctx consolectx.Context, mesh, serverID string) (*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + server, exists, err := manager.GetByKey[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, coremodel.BuildResourceKey(mesh, serverID)) + if err != nil { + return nil, err + } + if !exists { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP server %q not found", serverID)) + } + return server, nil +} + +func DeleteMCPServer(ctx consolectx.Context, mesh, serverID, expectedVersion string) error { + if strings.TrimSpace(expectedVersion) == "" { + return bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + if _, err := GetMCPServerInMesh(ctx, mesh, serverID); err != nil { + return err + } + cascading, ok := ctx.ResourceManager().(manager.CascadingResourceManager) + if !ok { + return fmt.Errorf("resource manager does not support cascading deletion") + } + server := meshresource.NewMCPServerResourceWithAttributes(serverID, mesh) + return cascading.CompareAndDeleteWithDependents(server, expectedVersion, meshresource.MCPCredentialKind, []index.IndexCondition{ + {IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}, + {IndexName: index.ByMCPCredentialServerID, Value: serverID, Operator: index.Equals}, + }) +} + +func CreateMCPServer(ctx consolectx.Context, req *model.MCPServerCreateReq) (*meshresource.MCPServerResource, error) { + if req == nil || strings.TrimSpace(req.Mesh) == "" || strings.TrimSpace(req.Name) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "mesh and name are required") + } + draft := req.Draft + if draft == nil { + draft = &meshproto.MCPServerSnapshot{} + } + draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot) + for _, tool := range draft.Tools { + if tool != nil && strings.TrimSpace(tool.ToolId) == "" { + tool.ToolId = business.NewToolID() + } + } + prepared, err := prepareMCPDraft(ctx, req.Mesh, draft) + if err != nil { + return nil, err + } + server := meshresource.NewMCPServerResourceWithAttributes(req.Name, req.Mesh) + server.Spec.Draft = prepared + if err := ctx.ResourceManager().Add(server); err != nil { + return nil, err + } + return server, nil +} + +func ReplaceMCPDraft(ctx consolectx.Context, mesh, serverID string, req *model.MCPDraftReq) (*meshresource.MCPServerResource, error) { + if req == nil || req.Draft == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "draft and expectedResourceVersion are required") + } + prepared, err := prepareMCPDraft(ctx, mesh, req.Draft) + if err != nil { + return nil, err + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = prepared + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, err + } + return updated, nil +} + +func ValidateMCPServer(ctx consolectx.Context, mesh, serverID string) (*model.MCPValidationResult, error) { + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return invalidMCPValidationResult("InvalidArgument", "server draft is required", ""), nil + } + prepared, err := prepareMCPDraft(ctx, mesh, server.Spec.Draft) + if err != nil { + return mcpValidationResult(err, "") + } + errors, warnings, err := validateMCPProtocolEvidence(ctx, mesh, prepared) + if err != nil { + return nil, err + } + return mcpValidationIssues(errors, warnings), nil +} + +func CreateMCPTool(ctx consolectx.Context, mesh, serverID string, req *model.MCPToolReq) (*meshresource.MCPServerResource, *meshproto.MCPToolBinding, error) { + if req == nil || req.Tool == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "tool and expectedResourceVersion are required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + tool := proto.Clone(req.Tool).(*meshproto.MCPToolBinding) + tool.ToolId = business.NewToolID() + tool.Parameters = nil + if err := resolveMCPTool(ctx, mesh, tool); err != nil { + return nil, nil, err + } + draft := proto.Clone(server.Spec.Draft).(*meshproto.MCPServerSnapshot) + draft.Tools = append(draft.Tools, tool) + if err := business.ValidateToolIdentity(draft); err != nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, err.Error()) + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = draft + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, nil, err + } + return updated, tool, nil +} + +func UpdateMCPTool(ctx consolectx.Context, mesh, serverID, toolID string, req *model.MCPToolReq) (*meshresource.MCPServerResource, *meshproto.MCPToolBinding, error) { + if req == nil || req.Tool == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "tool and expectedResourceVersion are required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + index := business.FindToolIndex(server.Spec.Draft, toolID) + if index < 0 { + return nil, nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP tool %q not found", toolID)) + } + tool := proto.Clone(req.Tool).(*meshproto.MCPToolBinding) + tool.ToolId = toolID + if !proto.Equal(server.Spec.Draft.Tools[index].Operation, tool.Operation) { + tool.Parameters = nil + } + if err := resolveMCPTool(ctx, mesh, tool); err != nil { + return nil, nil, err + } + draft := proto.Clone(server.Spec.Draft).(*meshproto.MCPServerSnapshot) + draft.Tools[index] = tool + if err := business.ValidateToolIdentity(draft); err != nil { + return nil, nil, bizerror.New(bizerror.InvalidArgument, err.Error()) + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = draft + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, nil, err + } + return updated, tool, nil +} + +func DeleteMCPTool(ctx consolectx.Context, mesh, serverID, toolID, expectedVersion string) (*meshresource.MCPServerResource, error) { + if strings.TrimSpace(expectedVersion) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + toolIndex := business.FindToolIndex(server.Spec.Draft, toolID) + if toolIndex < 0 { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP tool %q not found", toolID)) + } + draft := proto.Clone(server.Spec.Draft).(*meshproto.MCPServerSnapshot) + draft.Tools = append(draft.Tools[:toolIndex], draft.Tools[toolIndex+1:]...) + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + updated.Spec.Draft = draft + if err := compareAndSwapMCPServer(ctx, updated, expectedVersion); err != nil { + return nil, err + } + return updated, nil +} + +func PublishMCPServer(ctx consolectx.Context, mesh, serverID string, req *model.MCPPublishReq) (*meshresource.MCPServerResource, error) { + if req == nil || strings.TrimSpace(req.ExpectedResourceVersion) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + server, err := GetMCPServerInMesh(ctx, mesh, serverID) + if err != nil { + return nil, err + } + if server.Spec == nil || server.Spec.Draft == nil { + return nil, bizerror.New(bizerror.InvalidArgument, "server draft is required") + } + prepared, err := prepareMCPDraft(ctx, mesh, server.Spec.Draft) + if err != nil { + return nil, err + } + errors, _, err := validateMCPProtocolEvidence(ctx, mesh, prepared) + if err != nil { + return nil, err + } + if len(errors) > 0 { + return nil, bizerror.New(bizerror.InvalidArgument, errors[0].Message) + } + updated := server.DeepCopyObject().(*meshresource.MCPServerResource) + if updated.Spec.Published == nil { + updated.Spec.Published = &meshproto.MCPPublishedSnapshot{} + } + updated.Spec.Published.Revision++ + updated.Spec.Published.PublishedAt = time.Now().UTC().Format(time.RFC3339Nano) + updated.Spec.Published.Snapshot = prepared + if err := compareAndSwapMCPServer(ctx, updated, req.ExpectedResourceVersion); err != nil { + return nil, err + } + return updated, nil +} + +func validateMCPProtocolEvidence(ctx consolectx.Context, mesh string, snapshot *meshproto.MCPServerSnapshot) ([]model.MCPValidationIssue, []model.MCPValidationIssue, error) { + validationErrors := make([]model.MCPValidationIssue, 0) + warnings := make([]model.MCPValidationIssue, 0) + metadata, err := manager.ListByIndexes[*meshresource.ServiceProviderMetadataResource]( + ctx.ResourceManager(), meshresource.ServiceProviderMetadataKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) + if err != nil { + return nil, nil, err + } + instances, err := manager.ListByIndexes[*meshresource.RPCInstanceResource]( + ctx.ResourceManager(), meshresource.RPCInstanceKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) + if err != nil { + return nil, nil, err + } + evidence := availability.Snapshot{ + Providers: metadata, + Instances: instances, + Sync: availability.SyncState{InitialSyncComplete: true, Healthy: true}, Review Comment: Both synchronization flags are hard-coded to true, so startup and discovery outages can never produce incomplete evidence here. For example, a partially synchronized catalog containing only a tri instance will reject a dubbo binding as incompatible, even if the remaining providers have not loaded yet. This contradicts #1577/#1578, which require a warning for incomplete synchronization. Pass the actual mesh discovery synchronization/health state into the evaluator, treating unavailable state as unknown. ########## pkg/console/service/mcp.go: ########## @@ -0,0 +1,603 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package service + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "google.golang.org/protobuf/proto" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/common/bizerror" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store/index" + "github.com/apache/dubbo-admin/pkg/mcp/availability" + "github.com/apache/dubbo-admin/pkg/mcp/business" +) + +func ListMCPServers(ctx consolectx.Context, mesh string) ([]*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + return manager.ListByIndexes[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}}, + ) +} + +func GetMCPServerInMesh(ctx consolectx.Context, mesh, serverID string) (*meshresource.MCPServerResource, error) { + if err := requireMCPMesh(mesh); err != nil { + return nil, err + } + server, exists, err := manager.GetByKey[*meshresource.MCPServerResource]( + ctx.ResourceManager(), meshresource.MCPServerKind, coremodel.BuildResourceKey(mesh, serverID)) + if err != nil { + return nil, err + } + if !exists { + return nil, bizerror.New(bizerror.NotFoundError, fmt.Sprintf("MCP server %q not found", serverID)) + } + return server, nil +} + +func DeleteMCPServer(ctx consolectx.Context, mesh, serverID, expectedVersion string) error { + if strings.TrimSpace(expectedVersion) == "" { + return bizerror.New(bizerror.InvalidArgument, "expectedResourceVersion is required") + } + if _, err := GetMCPServerInMesh(ctx, mesh, serverID); err != nil { + return err + } + cascading, ok := ctx.ResourceManager().(manager.CascadingResourceManager) + if !ok { + return fmt.Errorf("resource manager does not support cascading deletion") + } + server := meshresource.NewMCPServerResourceWithAttributes(serverID, mesh) + return cascading.CompareAndDeleteWithDependents(server, expectedVersion, meshresource.MCPCredentialKind, []index.IndexCondition{ + {IndexName: index.ByMeshIndex, Value: mesh, Operator: index.Equals}, + {IndexName: index.ByMCPCredentialServerID, Value: serverID, Operator: index.Equals}, + }) +} + +func CreateMCPServer(ctx consolectx.Context, req *model.MCPServerCreateReq) (*meshresource.MCPServerResource, error) { + if req == nil || strings.TrimSpace(req.Mesh) == "" || strings.TrimSpace(req.Name) == "" { + return nil, bizerror.New(bizerror.InvalidArgument, "mesh and name are required") + } Review Comment: Accepting '/' in these identifiers breaks the mesh-scoped lookup guarantee: BuildResourceKey("a", "b/c") and BuildResourceKey("a/b", "c") both produce "a/b/c", and GetMCPServerInMesh does not check the returned resource's mesh. A request for mesh a/b and server c can therefore resolve a server created in mesh a. Server names containing '/' also cannot be addressed normally by the /:serverId routes. Reject the key separator in mesh and name before storing the resource. ########## pkg/mcp/availability/index.go: ########## @@ -0,0 +1,309 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package availability + +import ( + "sort" + "strings" + "sync" + "time" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" +) + +type State string + +const ( + Active State = "ACTIVE" + Inactive State = "INACTIVE" + Unknown State = "UNKNOWN" +) + +type Identity struct { + Mesh string + ServiceName string + Group string + Version string +} + +type SyncState struct { + InitialSyncComplete bool + Healthy bool +} + +type Evidence struct { + Complete bool + Available bool + Protocols []string +} + +type Result struct { + Identity Identity + Protocol string + State State + InactiveSince time.Time + Evidence Evidence +} + +type Snapshot struct { + Services []*meshresource.ServiceResource + Providers []*meshresource.ServiceProviderMetadataResource + Instances []*meshresource.RPCInstanceResource + Sync SyncState + Now time.Time +} + +type LiveServiceIndex struct { + grace time.Duration + mu sync.Mutex + items map[string]Result +} + +func NewLiveServiceIndex(grace time.Duration) *LiveServiceIndex { + if grace <= 0 { + grace = 60 * time.Second + } + return &LiveServiceIndex{grace: grace, items: make(map[string]Result)} +} + +func (i *LiveServiceIndex) Refresh(snapshot Snapshot) []Result { + now := snapshot.Now + if now.IsZero() { + now = time.Now() + } + identities := make(map[Identity]struct{}) + for _, service := range snapshot.Services { + if service != nil && service.Spec != nil { + identities[Identity{ + Mesh: service.Mesh, ServiceName: service.Spec.Name, + Group: service.Spec.Group, Version: service.Spec.Version, + }] = struct{}{} + } + } + for _, provider := range snapshot.Providers { + if provider != nil && provider.Spec != nil { + identities[Identity{ + Mesh: provider.Mesh, ServiceName: provider.Spec.ServiceName, + Group: provider.Spec.Group, Version: provider.Spec.Version, + }] = struct{}{} + } + } + + next := make(map[string]Result) + i.mu.Lock() + previousItems := make(map[string]Result, len(i.items)) + for key, value := range i.items { + previousItems[key] = value + } + i.mu.Unlock() + for identity := range identities { + for _, protocol := range protocolsForIdentity(identity, snapshot.Providers, snapshot.Instances) { + result := evaluate(identity, protocol, snapshot) + key := resultKey(identity, protocol) + if result.State == Inactive { + if previous, ok := previousItems[key]; ok && !previous.InactiveSince.IsZero() { + result.InactiveSince = previous.InactiveSince + } else { + result.InactiveSince = now + } + } + next[key] = result + } + } + + i.mu.Lock() + i.items = next + i.mu.Unlock() + + results := make([]Result, 0, len(next)) + for _, result := range next { + results = append(results, result) + } + sort.Slice(results, func(a, b int) bool { + return resultKey(results[a].Identity, results[a].Protocol) < + resultKey(results[b].Identity, results[b].Protocol) + }) + return results +} + +func (i *LiveServiceIndex) Get(identity Identity, protocol string) (Result, bool) { + i.mu.Lock() + defer i.mu.Unlock() + result, ok := i.items[resultKey(identity, protocol)] + return result, ok +} + +func (i *LiveServiceIndex) Visible(result Result, now time.Time) bool { + if result.State != Inactive || result.InactiveSince.IsZero() { + return true + } + if now.IsZero() { + now = time.Now() + } + return now.Sub(result.InactiveSince) <= i.grace +} + +func Evaluate(snapshot Snapshot, identity Identity, protocol string) Result { + return evaluate(identity, protocol, snapshot) +} + +func ConfirmedProtocolIncompatibility(result Result) bool { + if !result.Evidence.Complete || !result.Evidence.Available { + return false + } + for _, protocol := range result.Evidence.Protocols { + if protocol == result.Protocol { + return false + } + } + return true +} + +func evaluate(identity Identity, protocol string, snapshot Snapshot) Result { + result := Result{ + Identity: identity, + Protocol: protocol, + State: Unknown, + } + result.Evidence = protocolEvidence(identity, snapshot) + if !snapshot.Sync.InitialSyncComplete || !snapshot.Sync.Healthy { + return result + } + + for _, provider := range snapshot.Providers { + if provider == nil || provider.Spec == nil || + provider.Mesh != identity.Mesh || + provider.Spec.ServiceName != identity.ServiceName || + provider.Spec.Group != identity.Group || + provider.Spec.Version != identity.Version { + continue + } + for _, instance := range snapshot.Instances { + if instance == nil || instance.Spec == nil || + instance.Mesh != identity.Mesh || + instance.Spec.AppName != provider.Spec.ProviderAppName || + instance.Spec.UnregisterTime != "" || + !supportsProtocol(instance.Spec.Protocol, instance.Spec.Endpoints, protocol) { + continue + } + result.State = Active + return result + } + } + result.State = Inactive + return result +} + +func protocolEvidence(identity Identity, snapshot Snapshot) Evidence { + result := Evidence{} + providerApps := make(map[string]struct{}) + protocols := make(map[string]struct{}) + complete := snapshot.Sync.InitialSyncComplete && snapshot.Sync.Healthy + available := false + for _, provider := range snapshot.Providers { + if provider == nil || provider.Spec == nil || + provider.Mesh != identity.Mesh || + provider.Spec.ServiceName != identity.ServiceName || + provider.Spec.Group != identity.Group || + provider.Spec.Version != identity.Version { + continue + } + providerApps[provider.Spec.ProviderAppName] = struct{}{} + } + if len(providerApps) == 0 { + return result + } + seenApps := make(map[string]struct{}) + for _, instance := range snapshot.Instances { + if instance == nil || instance.Spec == nil || instance.Mesh != identity.Mesh { + continue + } + if _, ok := providerApps[instance.Spec.AppName]; !ok { + continue + } + if instance.Spec.UnregisterTime != "" { + continue + } + available = true + seenApps[instance.Spec.AppName] = struct{}{} + for value := range instanceProtocols(instance.Spec.Protocol, instance.Spec.Endpoints) { + protocols[value] = struct{}{} + } Review Comment: A registered instance is counted as complete evidence even when both its protocol and endpoint protocol list are empty. With one matching provider app and such an instance, this produces Complete=true, Available=true and an empty protocol set, so ConfirmedProtocolIncompatibility rejects every selected protocol instead of returning the required incomplete-evidence warning. Mark evidence incomplete whenever a matching live instance has no known protocols, including when other instances do have protocol information. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
