Copilot commented on code in PR #1619:
URL: https://github.com/apache/dubbo-admin/pull/1619#discussion_r4438212395
##########
api/mesh/v1alpha1/mcp_server.proto:
##########
@@ -0,0 +1,86 @@
+syntax = "proto3";
+
+package dubbo.mesh.v1alpha1;
+
+option go_package = "github.com/apache/dubbo-admin/api/mesh/v1alpha1";
+
+import "api/mesh/options.proto";
+import "google/protobuf/struct.proto";
+
+message MCPServer {
+ option (dubbo.mesh.resource).name = "MCPServer";
+ option (dubbo.mesh.resource).plural_name = "MCPServers";
+ option (dubbo.mesh.resource).package = "mesh";
+ option (dubbo.mesh.resource).is_experimental = true;
+
+ MCPServerSnapshot draft = 1;
+ MCPPublishedSnapshot published = 2;
+}
+
+message MCPServerSnapshot {
+ string display_name = 1;
+ string description = 2;
+ repeated string required_oauth_scopes = 3;
+ repeated MCPToolBinding tools = 4;
+}
+
+message MCPPublishedSnapshot {
+ int64 revision = 1;
+ string published_at = 2;
+ MCPServerSnapshot snapshot = 3;
+}
+
+message MCPToolBinding {
+ string tool_name = 1;
+ string description = 2;
+ MCPOperation operation = 3;
+ repeated MCPParameterBinding parameters = 4;
+ google.protobuf.Struct input_schema = 5;
+ string input_fingerprint = 6;
+ string output_fingerprint = 7;
+ repeated MCPTypeDefinition related_types = 8;
+ string return_type = 9;
+ optional bool read_only_hint = 10;
+ optional bool destructive_hint = 11;
+ optional bool idempotent_hint = 12;
+ bool timeout_enabled = 13;
+ int64 timeout_millis = 14;
+ // Stable backend-generated identifier. The tool name remains user-editable.
+ string tool_id = 15;
+}
+
+message MCPOperation {
+ string service_name = 1;
+ string group = 2;
+ string version = 3;
+ string method_name = 4;
+ repeated string parameter_types = 5;
+ string protocol = 6;
+}
+
+message MCPParameterBinding {
+ int32 position = 1;
+ string alias = 2;
+ string description = 3;
+}
+
+message MCPTypeDefinition {
+ string type = 1;
+ repeated string items = 2;
+ repeated string enums = 3;
+ map<string, string> properties = 4;
Review Comment:
Preserve an explicit object-kind discriminator rather than relying on map
presence. `buildDefinition` and `decodeValue` identify closed objects using
`Properties != nil`, but protobuf maps have no presence and the generated JSON
tag omits empty maps. A closed empty POJO/struct with `Properties:
map[string]string{}` resolves successfully, yet storing and reloading its
published binding turns that map into nil. Its valid `{}` argument then fails
decoding as “open or unresolved” despite matching the frozen schema. Persist
the type shape explicitly, or use the frozen schema to retain this distinction.
##########
pkg/core/manager/manager.go:
##########
@@ -176,3 +200,68 @@ func (rm *resourcesManager) DeleteByKey(rk
model.ResourceKind, mesh string, key
}
return gov.DeleteRule(r)
}
+
+func (rm *resourcesManager) CompareAndSwap(r model.Resource, expectedVersion
string) error {
+ if !store.IsVersionedResourceKind(r.ResourceKind()) {
+ return bizerror.New(bizerror.InvalidArgument, "resource does
not support conditional mutations")
+ }
+ rs, err := rm.storeRouter.ResourceRoute(r)
+ if err != nil {
+ return err
+ }
+ conditional, ok := rs.(store.ConditionalResourceStore)
+ if !ok {
+ return fmt.Errorf("resource store for %s does not support
conditional mutations", r.ResourceKind())
+ }
+ return conditional.CompareAndSwap(r, expectedVersion)
+}
+
+func (rm *resourcesManager) CompareAndDelete(r model.Resource, expectedVersion
string) error {
+ if !store.IsVersionedResourceKind(r.ResourceKind()) {
+ return bizerror.New(bizerror.InvalidArgument, "resource does
not support conditional mutations")
+ }
+ rs, err := rm.storeRouter.ResourceRoute(r)
+ if err != nil {
+ return err
+ }
+ conditional, ok := rs.(store.ConditionalResourceStore)
+ if !ok {
+ return fmt.Errorf("resource store for %s does not support
conditional mutations", r.ResourceKind())
+ }
+ return conditional.CompareAndDelete(r, expectedVersion)
+}
+
+func (rm *resourcesManager) CompareAndDeleteWithDependents(r model.Resource,
expectedVersion string, dependentKind model.ResourceKind, conditions
[]index.IndexCondition) error {
+ if !store.IsVersionedResourceKind(r.ResourceKind()) ||
!store.IsVersionedResourceKind(dependentKind) {
+ return bizerror.New(bizerror.InvalidArgument, "resources do not
support cascading conditional mutations")
+ }
+ parent, err := rm.storeRouter.ResourceRoute(r)
+ if err != nil {
+ return err
+ }
+ dependents, err := rm.storeRouter.ResourceKindRoute(dependentKind)
+ if err != nil {
+ return err
+ }
+ cascading, ok := parent.(store.CascadingResourceStore)
+ if !ok {
+ return fmt.Errorf("resource store for %s does not support
cascading mutations", r.ResourceKind())
+ }
+ return cascading.CompareAndDeleteWithDependents(r, expectedVersion,
dependents, conditions)
+}
+
+func (rm *resourcesManager) AddWithParent(parent model.Resource, child
model.Resource) error {
+ parentStore, err := rm.storeRouter.ResourceRoute(parent)
+ if err != nil {
+ return err
+ }
Review Comment:
Unlike `CompareAndSwap`, `CompareAndDelete` and
`CompareAndDeleteWithDependents`, `AddWithParent` never checks that the
resource kinds are versioned. Both store implementations end with an unchecked
`child.(store.VersionedResource).SetResourceVersion(...)`. In the memory store,
a non-versioned child gets past `PrepareInitialVersion` (it does nothing for
that type), is written by `rs.add(candidate)`, and then the assertion panics
after the store has already changed. In the Gorm store, the code tries to
insert a `version` column that the child's table doesn't have. Please add the
same guard here that the other conditional methods use (mandatory).
##########
pkg/core/store/store.go:
##########
@@ -50,6 +51,68 @@ type ManagedResourceStore interface {
ResourceStore
}
+// VersionedResource is implemented by resources that opt into optimistic
+// concurrency. Existing resources keep their current store semantics.
+type VersionedResource interface {
+ model.Resource
+ SetResourceVersion(string)
+ SupportsConditionalMutations() bool
+}
+
+// ConditionalResourceStore is an optional store capability for resources that
+// require atomic compare-and-swap mutations.
+type ConditionalResourceStore interface {
+ CompareAndSwap(obj model.Resource, expectedVersion string) error
+ CompareAndDelete(obj model.Resource, expectedVersion string) error
+}
+
+// CascadingResourceStore removes a versioned parent and its indexed dependent
+// resources as one store mutation. Both stores must use the same backend.
+type CascadingResourceStore interface {
+ CompareAndDeleteWithDependents(obj model.Resource, expectedVersion
string, dependents ResourceStore, conditions []index.IndexCondition) error
+}
+
+// DependentResourceStore creates a child only while its parent exists. This
+// serializes credential creation with a server's cascading deletion.
+type DependentResourceStore interface {
+ AddWithParent(parent model.Resource, parentStore ResourceStore, child
model.Resource) error
+}
+
+func IsVersionedResourceKind(kind model.ResourceKind) bool {
+ newResource, err := model.ResourceSchemaRegistry().NewResourceFunc(kind)
+ if err != nil {
+ return false
+ }
+ _, ok := newResource().(VersionedResource)
+ return ok
Review Comment:
`VersionedResource.SupportsConditionalMutations()` is declared as an opt-in
switch, but nothing ever calls it. `IsVersionedResourceKind` only checks that
the type assertion succeeds, so a resource returning `false` would still be
treated as versioned. Either honor the method here or drop it from the
interface.
##########
pkg/core/store/store.go:
##########
@@ -50,6 +51,68 @@ type ManagedResourceStore interface {
ResourceStore
}
+// VersionedResource is implemented by resources that opt into optimistic
+// concurrency. Existing resources keep their current store semantics.
+type VersionedResource interface {
+ model.Resource
+ SetResourceVersion(string)
+ SupportsConditionalMutations() bool
+}
+
+// ConditionalResourceStore is an optional store capability for resources that
+// require atomic compare-and-swap mutations.
+type ConditionalResourceStore interface {
+ CompareAndSwap(obj model.Resource, expectedVersion string) error
+ CompareAndDelete(obj model.Resource, expectedVersion string) error
+}
+
+// CascadingResourceStore removes a versioned parent and its indexed dependent
+// resources as one store mutation. Both stores must use the same backend.
+type CascadingResourceStore interface {
+ CompareAndDeleteWithDependents(obj model.Resource, expectedVersion
string, dependents ResourceStore, conditions []index.IndexCondition) error
+}
+
+// DependentResourceStore creates a child only while its parent exists. This
+// serializes credential creation with a server's cascading deletion.
+type DependentResourceStore interface {
+ AddWithParent(parent model.Resource, parentStore ResourceStore, child
model.Resource) error
+}
+
+func IsVersionedResourceKind(kind model.ResourceKind) bool {
+ newResource, err := model.ResourceSchemaRegistry().NewResourceFunc(kind)
+ if err != nil {
+ return false
+ }
+ _, ok := newResource().(VersionedResource)
+ return ok
+}
+
+func PrepareInitialVersion(resource model.Resource) error {
+ versioned, ok := resource.(VersionedResource)
+ if !ok {
+ return nil
+ }
+ if resource.ResourceMeta().ResourceVersion != "" {
+ return &PreconditionError{Reason: "resourceVersion must be
empty when creating a resource"}
+ }
+ versioned.SetResourceVersion("1")
+ return nil
+}
+
+func NextResourceVersion(resource model.Resource, expectedVersion string)
(string, error) {
+ if _, ok := resource.(VersionedResource); !ok {
+ return "", &PreconditionError{Reason: "resource does not
support conditional mutations"}
+ }
+ expected, err := strconv.ParseUint(expectedVersion, 10, 64)
+ if err != nil || expected == 0 {
Review Comment:
The expected version is accepted in non-canonical forms such as "01" or
"001", because `ParseUint` tolerates leading zeros. The two backends then
disagree. The memory store compares version strings (`"1" != "01"`, so it
reports a conflict), while the Gorm store compares the parsed integers (`1 ==
1`, so the swap succeeds). Require the canonical decimal form here so both
backends behave identically.
##########
pkg/mcp/business/arguments.go:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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 business
+
+import (
+ "encoding/json"
+ "fmt"
+ "strconv"
+
+ meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+ "github.com/apache/dubbo-admin/pkg/common/util/genericinvoke"
+)
+
+func RestoreArguments(contract *ResolvedContract, arguments map[string]any)
([]any, error) {
+ if contract == nil || contract.Operation == nil {
+ return nil, fmt.Errorf("resolved contract is required")
+ }
+ if err := ValidateParameterBindings(contract.Parameters,
contract.Operation.ParameterTypes); err != nil {
+ return nil, err
+ }
+ validator, err := CompileInputSchema(contract.InputSchema)
+ if err != nil {
+ return nil, err
+ }
+ if err := validator.Validate(arguments); err != nil {
+ return nil, fmt.Errorf("arguments do not match input schema:
%w", err)
+ }
+
+ types := make(map[string]*meshproto.MCPTypeDefinition,
len(contract.RelatedTypes))
+ for _, typ := range contract.RelatedTypes {
+ if typ != nil {
+ types[typ.Type] = typ
+ }
+ }
+ result := make([]any, len(contract.Operation.ParameterTypes))
+ for _, binding := range contract.Parameters {
+ value, exists := arguments[binding.Alias]
+ if !exists {
+ return nil, fmt.Errorf("required argument %q is
missing", binding.Alias)
+ }
+ position := int(binding.Position)
+ decoded, err :=
decodeValue(contract.Operation.ParameterTypes[position], value, types)
+ if err != nil {
+ return nil, fmt.Errorf("argument %q: %w",
binding.Alias, err)
+ }
+ result[position] = decoded
+ }
+ return result, nil
+}
+
+func decodeValue(typeName string, value any, types
map[string]*meshproto.MCPTypeDefinition) (any, error) {
+ if value == nil {
+ if isNullableType(typeName) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("null is not valid for %s", typeName)
+ }
+ if isScalarType(typeName) {
+ if typeName == "long" || typeName == "java.lang.Long" {
+ text, ok := value.(string)
+ if !ok {
+ return nil, fmt.Errorf("expected decimal string
for %s", typeName)
+ }
+ if _, err := strconv.ParseInt(text, 10, 64); err != nil
{
+ return nil, fmt.Errorf("invalid %s value: %w",
typeName, err)
+ }
+ return text, nil
+ }
+ raw, err := json.Marshal(value)
+ if err != nil {
+ return nil, err
+ }
+ return genericinvoke.DecodeValue(typeName, raw)
+ }
+
+ definition, exists := types[typeName]
+ if !exists {
+ return nil, fmt.Errorf("type definition %q is missing",
typeName)
+ }
+ switch {
+ case len(definition.Enums) > 0:
+ return value, nil
+ case len(definition.Items) == 1:
+ items, ok := value.([]any)
+ if !ok {
+ return nil, fmt.Errorf("expected array for %s",
typeName)
+ }
+ decoded := make([]any, len(items))
+ for i, item := range items {
+ converted, err := decodeValue(definition.Items[0],
item, types)
+ if err != nil {
+ return nil, fmt.Errorf("item %d: %w", i, err)
+ }
+ decoded[i] = converted
+ }
+ return decoded, nil
+ case len(definition.Items) == 2:
+ object, ok := value.(map[string]any)
+ if !ok {
+ return nil, fmt.Errorf("expected object for %s",
typeName)
+ }
+ decoded := make(map[string]any, len(object))
+ for key, item := range object {
+ converted, err := decodeValue(definition.Items[1],
item, types)
+ if err != nil {
+ return nil, fmt.Errorf("map value %q: %w", key,
err)
+ }
+ decoded[key] = converted
+ }
+ return decoded, nil
+ case definition.Properties != nil:
Review Comment:
A zero-field POJO/struct compiles successfully when `Properties` is a
non-nil empty map, but `MCPTypeDefinition.Properties` has `omitempty`. Saving
it through `FromResource` drops that map, and loading it leaves `Properties`
nil. This branch is then skipped, so the published Tool rejects `{}` as “open
or unresolved” even though its saved input schema accepts it. Preserve the
object kind independently of map presence, or reconstruct empty-object
definitions when loading the snapshot.
##########
pkg/mcp/business/contract.go:
##########
@@ -0,0 +1,436 @@
+/*
+ * 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 business
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "sort"
+ "strings"
+
+ "google.golang.org/protobuf/types/known/structpb"
+
+ meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+ meshresource
"github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1"
+)
+
+type ResolvedContract struct {
+ Operation *meshproto.MCPOperation
+ Parameters []*meshproto.MCPParameterBinding
+ ReturnType string
+ RelatedTypes []*meshproto.MCPTypeDefinition
+ InputSchema *structpb.Struct
+ InputFingerprint string
+ OutputFingerprint string
+}
+
+func DefaultParameterBindings(parameterTypes []string)
[]*meshproto.MCPParameterBinding {
+ result := make([]*meshproto.MCPParameterBinding, len(parameterTypes))
+ for i := range parameterTypes {
+ result[i] = &meshproto.MCPParameterBinding{
+ Position: int32(i),
+ Alias: fmt.Sprintf("arg%d", i),
+ }
+ }
+ return result
+}
+
+func ResolveOperation(
+ mesh string,
+ operation *meshproto.MCPOperation,
+ bindings []*meshproto.MCPParameterBinding,
+ resources []*meshresource.ServiceProviderMetadataResource,
+) (*ResolvedContract, error) {
+ if operation == nil {
+ return nil, fmt.Errorf("operation is required")
+ }
+ if err := validateOperation(operation); err != nil {
+ return nil, err
+ }
+ if bindings == nil {
+ bindings = DefaultParameterBindings(operation.ParameterTypes)
+ }
+ if err := ValidateParameterBindings(bindings,
operation.ParameterTypes); err != nil {
+ return nil, err
+ }
+
+ var resolved *ResolvedContract
+ matchedDefinitions := 0
+ for _, resource := range resources {
+ if !matchesService(resource, mesh, operation) {
+ continue
+ }
+ matchedDefinitions++
+ contract, err := resolveDefinition(operation, bindings,
resource.Spec)
+ if err != nil {
+ return nil, fmt.Errorf("provider definition %s: %w",
resource.ResourceKey(), err)
+ }
+ if resolved == nil {
+ resolved = contract
+ continue
+ }
+ if contract.InputFingerprint != resolved.InputFingerprint ||
+ contract.OutputFingerprint !=
resolved.OutputFingerprint {
+ return nil, fmt.Errorf("provider definitions disagree
for operation %s", operationName(operation))
+ }
+ }
+ if matchedDefinitions == 0 {
+ return nil, fmt.Errorf("no provider definition found for
operation %s", operationName(operation))
+ }
+ return resolved, nil
+}
+
+func ValidateParameterBindings(bindings []*meshproto.MCPParameterBinding,
parameterTypes []string) error {
+ if len(bindings) != len(parameterTypes) {
+ return fmt.Errorf("parameter binding count %d does not match
parameter type count %d", len(bindings), len(parameterTypes))
+ }
+ positions := make([]bool, len(parameterTypes))
+ aliases := make(map[string]struct{}, len(bindings))
+ for _, binding := range bindings {
+ if binding == nil {
+ return fmt.Errorf("parameter binding is nil")
+ }
+ position := int(binding.Position)
+ if position < 0 || position >= len(parameterTypes) {
+ return fmt.Errorf("parameter position %d is out of
range", position)
+ }
+ if positions[position] {
+ return fmt.Errorf("parameter position %d is
duplicated", position)
+ }
+ positions[position] = true
+ alias := strings.TrimSpace(binding.Alias)
+ if alias == "" {
+ return fmt.Errorf("parameter alias at position %d is
empty", position)
+ }
+ if _, exists := aliases[alias]; exists {
+ return fmt.Errorf("parameter alias %q is duplicated",
alias)
+ }
+ aliases[alias] = struct{}{}
+ }
+ return nil
+}
+
+func validateOperation(operation *meshproto.MCPOperation) error {
+ if strings.TrimSpace(operation.ServiceName) == "" {
+ return fmt.Errorf("service name is required")
+ }
+ if strings.TrimSpace(operation.MethodName) == "" {
+ return fmt.Errorf("method name is required")
+ }
+ if operation.Protocol != "dubbo" && operation.Protocol != "tri" {
+ return fmt.Errorf("unsupported protocol %q", operation.Protocol)
+ }
+ for i, parameterType := range operation.ParameterTypes {
+ if strings.TrimSpace(parameterType) == "" {
+ return fmt.Errorf("parameter type at position %d is
empty", i)
+ }
+ }
+ return nil
+}
+
+func matchesService(
+ resource *meshresource.ServiceProviderMetadataResource,
+ mesh string,
+ operation *meshproto.MCPOperation,
+) bool {
+ if resource == nil || resource.Spec == nil || resource.Mesh != mesh {
+ return false
+ }
+ return resource.Spec.ServiceName == operation.ServiceName &&
+ resource.Spec.Group == operation.Group &&
+ resource.Spec.Version == operation.Version
+}
+
+func resolveDefinition(
+ operation *meshproto.MCPOperation,
+ bindings []*meshproto.MCPParameterBinding,
+ definition *meshproto.ServiceProviderMetadata,
+) (*ResolvedContract, error) {
+ method, err := findMethod(definition.Methods, operation.MethodName,
operation.ParameterTypes)
+ if err != nil {
+ return nil, err
+ }
+ if method == nil {
+ return nil, fmt.Errorf("method %s with the selected parameter
types is missing", operation.MethodName)
+ }
+ types, err := buildTypeIndex(definition.Types)
+ if err != nil {
+ return nil, err
+ }
+ inputTypes, err := reachableTypes(operation.ParameterTypes, types)
+ if err != nil {
+ return nil, err
+ }
+ outputTypes, err := reachableTypes([]string{method.ReturnType}, types)
+ if err != nil {
+ return nil, err
+ }
+ allTypes := mergeTypes(inputTypes, outputTypes)
+
+ schema, err := BuildInputSchema(operation.ParameterTypes, bindings,
types)
+ if err != nil {
+ return nil, err
+ }
+ if method.ReturnType != "void" && method.ReturnType != "java.lang.Void"
{
+ if _, err := BuildInputSchema(
+ []string{method.ReturnType},
+ DefaultParameterBindings([]string{method.ReturnType}),
+ types,
+ ); err != nil {
+ return nil, fmt.Errorf("return type: %w", err)
+ }
+ }
+ inputFingerprint, err := fingerprint(struct {
+ ServiceName string
+ Group string
+ Version string
+ MethodName string
+ ParameterTypes []string
+ Types []canonicalType
+ }{operation.ServiceName, operation.Group, operation.Version,
operation.MethodName, operation.ParameterTypes, canonicalTypes(inputTypes)})
Review Comment:
Normalize zero-argument signatures before hashing: `encoding/json` hashes a
nil `ParameterTypes` slice as `null` and an empty slice as `[]`, although both
identify the same operation. The generated protobuf JSON omits an empty slice,
so a published zero-argument tool can acquire a different input fingerprint
after a store round trip and be reported as drifted.
##########
pkg/mcp/business/contract.go:
##########
@@ -0,0 +1,436 @@
+/*
+ * 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 business
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "sort"
+ "strings"
+
+ "google.golang.org/protobuf/types/known/structpb"
+
+ meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+ meshresource
"github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1"
+)
+
+type ResolvedContract struct {
+ Operation *meshproto.MCPOperation
+ Parameters []*meshproto.MCPParameterBinding
+ ReturnType string
+ RelatedTypes []*meshproto.MCPTypeDefinition
+ InputSchema *structpb.Struct
+ InputFingerprint string
+ OutputFingerprint string
+}
+
+func DefaultParameterBindings(parameterTypes []string)
[]*meshproto.MCPParameterBinding {
+ result := make([]*meshproto.MCPParameterBinding, len(parameterTypes))
+ for i := range parameterTypes {
+ result[i] = &meshproto.MCPParameterBinding{
+ Position: int32(i),
+ Alias: fmt.Sprintf("arg%d", i),
+ }
+ }
+ return result
+}
+
+func ResolveOperation(
+ mesh string,
+ operation *meshproto.MCPOperation,
+ bindings []*meshproto.MCPParameterBinding,
+ resources []*meshresource.ServiceProviderMetadataResource,
+) (*ResolvedContract, error) {
+ if operation == nil {
+ return nil, fmt.Errorf("operation is required")
+ }
+ if err := validateOperation(operation); err != nil {
+ return nil, err
+ }
+ if bindings == nil {
+ bindings = DefaultParameterBindings(operation.ParameterTypes)
+ }
+ if err := ValidateParameterBindings(bindings,
operation.ParameterTypes); err != nil {
+ return nil, err
+ }
+
+ var resolved *ResolvedContract
+ matchedDefinitions := 0
+ for _, resource := range resources {
+ if !matchesService(resource, mesh, operation) {
+ continue
+ }
+ matchedDefinitions++
+ contract, err := resolveDefinition(operation, bindings,
resource.Spec)
+ if err != nil {
+ return nil, fmt.Errorf("provider definition %s: %w",
resource.ResourceKey(), err)
+ }
+ if resolved == nil {
+ resolved = contract
+ continue
+ }
+ if contract.InputFingerprint != resolved.InputFingerprint ||
+ contract.OutputFingerprint !=
resolved.OutputFingerprint {
+ return nil, fmt.Errorf("provider definitions disagree
for operation %s", operationName(operation))
+ }
+ }
+ if matchedDefinitions == 0 {
+ return nil, fmt.Errorf("no provider definition found for
operation %s", operationName(operation))
+ }
+ return resolved, nil
+}
+
+func ValidateParameterBindings(bindings []*meshproto.MCPParameterBinding,
parameterTypes []string) error {
+ if len(bindings) != len(parameterTypes) {
+ return fmt.Errorf("parameter binding count %d does not match
parameter type count %d", len(bindings), len(parameterTypes))
+ }
+ positions := make([]bool, len(parameterTypes))
+ aliases := make(map[string]struct{}, len(bindings))
+ for _, binding := range bindings {
+ if binding == nil {
+ return fmt.Errorf("parameter binding is nil")
+ }
+ position := int(binding.Position)
+ if position < 0 || position >= len(parameterTypes) {
+ return fmt.Errorf("parameter position %d is out of
range", position)
+ }
+ if positions[position] {
+ return fmt.Errorf("parameter position %d is
duplicated", position)
+ }
+ positions[position] = true
+ alias := strings.TrimSpace(binding.Alias)
+ if alias == "" {
+ return fmt.Errorf("parameter alias at position %d is
empty", position)
+ }
+ if _, exists := aliases[alias]; exists {
+ return fmt.Errorf("parameter alias %q is duplicated",
alias)
+ }
+ aliases[alias] = struct{}{}
+ }
+ return nil
+}
+
+func validateOperation(operation *meshproto.MCPOperation) error {
+ if strings.TrimSpace(operation.ServiceName) == "" {
+ return fmt.Errorf("service name is required")
+ }
+ if strings.TrimSpace(operation.MethodName) == "" {
+ return fmt.Errorf("method name is required")
+ }
+ if operation.Protocol != "dubbo" && operation.Protocol != "tri" {
+ return fmt.Errorf("unsupported protocol %q", operation.Protocol)
+ }
+ for i, parameterType := range operation.ParameterTypes {
+ if strings.TrimSpace(parameterType) == "" {
+ return fmt.Errorf("parameter type at position %d is
empty", i)
+ }
+ }
+ return nil
+}
+
+func matchesService(
+ resource *meshresource.ServiceProviderMetadataResource,
+ mesh string,
+ operation *meshproto.MCPOperation,
+) bool {
+ if resource == nil || resource.Spec == nil || resource.Mesh != mesh {
+ return false
+ }
+ return resource.Spec.ServiceName == operation.ServiceName &&
+ resource.Spec.Group == operation.Group &&
+ resource.Spec.Version == operation.Version
+}
+
+func resolveDefinition(
+ operation *meshproto.MCPOperation,
+ bindings []*meshproto.MCPParameterBinding,
+ definition *meshproto.ServiceProviderMetadata,
+) (*ResolvedContract, error) {
+ method, err := findMethod(definition.Methods, operation.MethodName,
operation.ParameterTypes)
+ if err != nil {
+ return nil, err
+ }
+ if method == nil {
+ return nil, fmt.Errorf("method %s with the selected parameter
types is missing", operation.MethodName)
+ }
+ types, err := buildTypeIndex(definition.Types)
+ if err != nil {
+ return nil, err
+ }
+ inputTypes, err := reachableTypes(operation.ParameterTypes, types)
+ if err != nil {
+ return nil, err
+ }
+ outputTypes, err := reachableTypes([]string{method.ReturnType}, types)
+ if err != nil {
+ return nil, err
Review Comment:
A return-only change to a missing or unsupported type makes resolution fail
before the input fingerprint is returned. The same happens for output-only
disagreements between providers at lines 90–92, so a runtime consumer cannot
distinguish return drift from an incompatible input contract and keep the tool
callable as required. Separate input resolution from output diagnostics, while
still rejecting invalid output contracts at publish time.
##########
pkg/mcp/business/contract.go:
##########
@@ -0,0 +1,436 @@
+/*
+ * 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 business
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "sort"
+ "strings"
+
+ "google.golang.org/protobuf/types/known/structpb"
+
+ meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+ meshresource
"github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1"
+)
+
+type ResolvedContract struct {
+ Operation *meshproto.MCPOperation
+ Parameters []*meshproto.MCPParameterBinding
+ ReturnType string
+ RelatedTypes []*meshproto.MCPTypeDefinition
+ InputSchema *structpb.Struct
+ InputFingerprint string
+ OutputFingerprint string
+}
+
+func DefaultParameterBindings(parameterTypes []string)
[]*meshproto.MCPParameterBinding {
+ result := make([]*meshproto.MCPParameterBinding, len(parameterTypes))
+ for i := range parameterTypes {
+ result[i] = &meshproto.MCPParameterBinding{
+ Position: int32(i),
+ Alias: fmt.Sprintf("arg%d", i),
+ }
+ }
+ return result
+}
+
+func ResolveOperation(
+ mesh string,
+ operation *meshproto.MCPOperation,
+ bindings []*meshproto.MCPParameterBinding,
+ resources []*meshresource.ServiceProviderMetadataResource,
+) (*ResolvedContract, error) {
+ if operation == nil {
+ return nil, fmt.Errorf("operation is required")
+ }
+ if err := validateOperation(operation); err != nil {
+ return nil, err
+ }
+ if bindings == nil {
+ bindings = DefaultParameterBindings(operation.ParameterTypes)
+ }
+ if err := ValidateParameterBindings(bindings,
operation.ParameterTypes); err != nil {
+ return nil, err
+ }
+
+ var resolved *ResolvedContract
+ matchedDefinitions := 0
+ for _, resource := range resources {
+ if !matchesService(resource, mesh, operation) {
+ continue
+ }
+ matchedDefinitions++
+ contract, err := resolveDefinition(operation, bindings,
resource.Spec)
+ if err != nil {
+ return nil, fmt.Errorf("provider definition %s: %w",
resource.ResourceKey(), err)
+ }
+ if resolved == nil {
+ resolved = contract
+ continue
+ }
+ if contract.InputFingerprint != resolved.InputFingerprint ||
+ contract.OutputFingerprint !=
resolved.OutputFingerprint {
+ return nil, fmt.Errorf("provider definitions disagree
for operation %s", operationName(operation))
+ }
+ }
+ if matchedDefinitions == 0 {
+ return nil, fmt.Errorf("no provider definition found for
operation %s", operationName(operation))
+ }
+ return resolved, nil
+}
+
+func ValidateParameterBindings(bindings []*meshproto.MCPParameterBinding,
parameterTypes []string) error {
+ if len(bindings) != len(parameterTypes) {
+ return fmt.Errorf("parameter binding count %d does not match
parameter type count %d", len(bindings), len(parameterTypes))
+ }
+ positions := make([]bool, len(parameterTypes))
+ aliases := make(map[string]struct{}, len(bindings))
+ for _, binding := range bindings {
+ if binding == nil {
+ return fmt.Errorf("parameter binding is nil")
+ }
+ position := int(binding.Position)
+ if position < 0 || position >= len(parameterTypes) {
+ return fmt.Errorf("parameter position %d is out of
range", position)
+ }
+ if positions[position] {
+ return fmt.Errorf("parameter position %d is
duplicated", position)
+ }
+ positions[position] = true
+ alias := strings.TrimSpace(binding.Alias)
+ if alias == "" {
+ return fmt.Errorf("parameter alias at position %d is
empty", position)
+ }
+ if _, exists := aliases[alias]; exists {
+ return fmt.Errorf("parameter alias %q is duplicated",
alias)
+ }
+ aliases[alias] = struct{}{}
+ }
+ return nil
+}
+
+func validateOperation(operation *meshproto.MCPOperation) error {
+ if strings.TrimSpace(operation.ServiceName) == "" {
+ return fmt.Errorf("service name is required")
+ }
+ if strings.TrimSpace(operation.MethodName) == "" {
+ return fmt.Errorf("method name is required")
+ }
+ if operation.Protocol != "dubbo" && operation.Protocol != "tri" {
+ return fmt.Errorf("unsupported protocol %q", operation.Protocol)
+ }
+ for i, parameterType := range operation.ParameterTypes {
+ if strings.TrimSpace(parameterType) == "" {
+ return fmt.Errorf("parameter type at position %d is
empty", i)
+ }
+ }
+ return nil
+}
+
+func matchesService(
+ resource *meshresource.ServiceProviderMetadataResource,
+ mesh string,
+ operation *meshproto.MCPOperation,
+) bool {
+ if resource == nil || resource.Spec == nil || resource.Mesh != mesh {
+ return false
+ }
+ return resource.Spec.ServiceName == operation.ServiceName &&
+ resource.Spec.Group == operation.Group &&
+ resource.Spec.Version == operation.Version
+}
+
+func resolveDefinition(
+ operation *meshproto.MCPOperation,
+ bindings []*meshproto.MCPParameterBinding,
+ definition *meshproto.ServiceProviderMetadata,
+) (*ResolvedContract, error) {
+ method, err := findMethod(definition.Methods, operation.MethodName,
operation.ParameterTypes)
+ if err != nil {
+ return nil, err
+ }
+ if method == nil {
+ return nil, fmt.Errorf("method %s with the selected parameter
types is missing", operation.MethodName)
+ }
+ types, err := buildTypeIndex(definition.Types)
+ if err != nil {
+ return nil, err
+ }
+ inputTypes, err := reachableTypes(operation.ParameterTypes, types)
+ if err != nil {
+ return nil, err
+ }
+ outputTypes, err := reachableTypes([]string{method.ReturnType}, types)
+ if err != nil {
+ return nil, err
+ }
+ allTypes := mergeTypes(inputTypes, outputTypes)
+
+ schema, err := BuildInputSchema(operation.ParameterTypes, bindings,
types)
+ if err != nil {
+ return nil, err
+ }
+ if method.ReturnType != "void" && method.ReturnType != "java.lang.Void"
{
+ if _, err := BuildInputSchema(
+ []string{method.ReturnType},
+ DefaultParameterBindings([]string{method.ReturnType}),
+ types,
+ ); err != nil {
+ return nil, fmt.Errorf("return type: %w", err)
+ }
+ }
+ inputFingerprint, err := fingerprint(struct {
+ ServiceName string
+ Group string
+ Version string
+ MethodName string
+ ParameterTypes []string
+ Types []canonicalType
+ }{operation.ServiceName, operation.Group, operation.Version,
operation.MethodName, operation.ParameterTypes, canonicalTypes(inputTypes)})
+ if err != nil {
+ return nil, err
+ }
+ outputFingerprint, err := fingerprint(struct {
+ ReturnType string
+ Types []canonicalType
+ }{method.ReturnType, canonicalTypes(outputTypes)})
+ if err != nil {
+ return nil, err
+ }
+
+ return &ResolvedContract{
+ Operation: cloneOperation(operation),
+ Parameters: cloneBindings(bindings),
+ ReturnType: method.ReturnType,
+ RelatedTypes: toProtoTypes(allTypes),
+ InputSchema: schema,
+ InputFingerprint: inputFingerprint,
+ OutputFingerprint: outputFingerprint,
+ }, nil
+}
+
+func findMethod(methods []*meshproto.Method, name string, parameterTypes
[]string) (*meshproto.Method, error) {
+ var match *meshproto.Method
+ for _, method := range methods {
+ if method != nil && method.Name == name &&
slices.Equal(method.ParameterTypes, parameterTypes) {
+ if match != nil && match.ReturnType !=
method.ReturnType {
+ return nil, fmt.Errorf("method %s has
conflicting return types", name)
+ }
+ match = method
+ }
+ }
+ return match, nil
+}
+
+func buildTypeIndex(types []*meshproto.Type)
(map[string]*meshproto.MCPTypeDefinition, error) {
+ result := make(map[string]*meshproto.MCPTypeDefinition, len(types))
+ for _, typ := range types {
+ if typ == nil || strings.TrimSpace(typ.Type) == "" {
+ continue
+ }
+ candidate := &meshproto.MCPTypeDefinition{
+ Type: typ.Type,
+ Items: slices.Clone(typ.Items),
+ Enums: slices.Clone(typ.Enums),
+ Properties: cloneStringMap(typ.Properties),
+ }
+ if previous, exists := result[typ.Type]; exists &&
!equalType(previous, candidate) {
+ return nil, fmt.Errorf("type %q has conflicting
definitions", typ.Type)
Review Comment:
This checks duplicate definitions for every type in the provider metadata,
including types unrelated to the selected method. If another method has
conflicting definitions for type `B`, resolving a method whose input and output
use only type `A` fails too, disabling an unaffected tool. Restrict conflict
detection to definitions reachable from the selected operation's input/output
closures.
##########
pkg/mcp/business/schema.go:
##########
@@ -0,0 +1,294 @@
+/*
+ * 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 business
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/google/jsonschema-go/jsonschema"
+ "google.golang.org/protobuf/types/known/structpb"
+
+ meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+)
+
+const jsonSchema202012 = "https://json-schema.org/draft/2020-12/schema"
+
+type schemaBuilder struct {
+ types map[string]*meshproto.MCPTypeDefinition
+ defs map[string]*jsonschema.Schema
+ building map[string]bool
+}
+
+func BuildInputSchema(
+ parameterTypes []string,
+ bindings []*meshproto.MCPParameterBinding,
+ types map[string]*meshproto.MCPTypeDefinition,
+) (*structpb.Struct, error) {
+ if err := ValidateParameterBindings(bindings, parameterTypes); err !=
nil {
+ return nil, err
+ }
+ builder := &schemaBuilder{
+ types: types,
+ defs: make(map[string]*jsonschema.Schema),
+ building: make(map[string]bool),
+ }
+ root := &jsonschema.Schema{
+ Schema: jsonSchema202012,
+ Type: "object",
+ Properties: make(map[string]*jsonschema.Schema,
len(bindings)),
+ AdditionalProperties: denySchema(),
+ Required: make([]string, len(bindings)),
+ PropertyOrder: make([]string, len(bindings)),
+ }
+ for _, binding := range bindings {
+ position := int(binding.Position)
+ property, err := builder.schemaForType(parameterTypes[position])
+ if err != nil {
+ return nil, fmt.Errorf("parameter %q: %w",
binding.Alias, err)
+ }
+ property.Description = binding.Description
+ root.Properties[binding.Alias] = property
+ root.Required[position] = binding.Alias
+ root.PropertyOrder[position] = binding.Alias
+ }
+ root.Defs = builder.defs
+ if _, err := root.Resolve(nil); err != nil {
+ return nil, fmt.Errorf("resolve input schema: %w", err)
+ }
+ data, err := json.Marshal(root)
+ if err != nil {
+ return nil, err
+ }
+ var object map[string]any
+ if err := json.Unmarshal(data, &object); err != nil {
+ return nil, err
+ }
+ return structpb.NewStruct(object)
+}
+
+func CompileInputSchema(schema *structpb.Struct) (*jsonschema.Resolved, error)
{
+ if schema == nil {
+ return nil, fmt.Errorf("input schema is required")
+ }
+ data, err := schema.MarshalJSON()
+ if err != nil {
+ return nil, err
+ }
+ var parsed jsonschema.Schema
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ return nil, err
+ }
+ resolved, err := parsed.Resolve(nil)
+ if err != nil {
+ return nil, fmt.Errorf("resolve input schema: %w", err)
+ }
+ return resolved, nil
+}
+
+func (b *schemaBuilder) schemaForType(typeName string) (*jsonschema.Schema,
error) {
+ if schema, known, err := primitiveSchema(typeName); known || err != nil
{
+ return schema, err
+ }
+ if isUnsupportedType(typeName) {
+ return nil, fmt.Errorf("type %q is not supported", typeName)
+ }
+ if _, exists := b.types[typeName]; !exists {
+ return nil, fmt.Errorf("type definition %q is missing",
typeName)
+ }
+ if err := b.buildDefinition(typeName); err != nil {
+ return nil, err
+ }
+ return nullableSchema(&jsonschema.Schema{Ref: "#/$defs/" +
definitionKey(typeName)}), nil
+}
+
+func (b *schemaBuilder) buildDefinition(typeName string) error {
+ key := definitionKey(typeName)
+ if _, exists := b.defs[key]; exists {
+ return nil
+ }
+ definition := b.types[typeName]
+ placeholder := &jsonschema.Schema{}
+ b.defs[key] = placeholder
+ if b.building[typeName] {
+ return nil
+ }
+ b.building[typeName] = true
+ defer delete(b.building, typeName)
+
+ switch {
+ case len(definition.Enums) > 0:
+ placeholder.Type = "string"
+ placeholder.Enum = make([]any, len(definition.Enums))
+ for i, value := range definition.Enums {
+ placeholder.Enum[i] = value
+ }
+ case len(definition.Items) == 1:
+ itemSchema, err := b.schemaForType(definition.Items[0])
+ if err != nil {
+ return fmt.Errorf("type %q item: %w", typeName, err)
+ }
+ placeholder.Type = "array"
+ placeholder.Items = itemSchema
+ case len(definition.Items) == 2:
+ if !isStringType(definition.Items[0]) {
+ return fmt.Errorf("map type %q has non-string key %q",
typeName, definition.Items[0])
+ }
+ valueSchema, err := b.schemaForType(definition.Items[1])
+ if err != nil {
+ return fmt.Errorf("map type %q value: %w", typeName,
err)
+ }
+ placeholder.Type = "object"
+ placeholder.AdditionalProperties = valueSchema
+ case len(definition.Items) > 2:
+ return fmt.Errorf("type %q has invalid item arity %d",
typeName, len(definition.Items))
+ case definition.Properties != nil:
+ placeholder.Type = "object"
+ placeholder.Properties = make(map[string]*jsonschema.Schema,
len(definition.Properties))
+ placeholder.AdditionalProperties = denySchema()
+ for propertyName, propertyType := range definition.Properties {
+ propertySchema, err := b.schemaForType(propertyType)
+ if err != nil {
+ return fmt.Errorf("type %q property %q: %w",
typeName, propertyName, err)
+ }
+ placeholder.Properties[propertyName] = propertySchema
+ }
+ default:
+ return fmt.Errorf("type %q is open or unresolved", typeName)
+ }
+ return nil
+}
+
+func primitiveSchema(typeName string) (*jsonschema.Schema, bool, error) {
+ switch typeName {
+ case "boolean":
+ return &jsonschema.Schema{Type: "boolean"}, true, nil
+ case "java.lang.Boolean":
+ return nullableSchema(&jsonschema.Schema{Type: "boolean"}),
true, nil
+ case "byte":
+ return integerSchema(-128, 127, false), true, nil
+ case "java.lang.Byte":
+ return integerSchema(-128, 127, true), true, nil
+ case "short":
+ return integerSchema(-32768, 32767, false), true, nil
+ case "java.lang.Short":
+ return integerSchema(-32768, 32767, true), true, nil
+ case "int":
+ return integerSchema(-2147483648, 2147483647, false), true, nil
+ case "java.lang.Integer":
+ return integerSchema(-2147483648, 2147483647, true), true, nil
+ case "long":
+ return longSchema(false), true, nil
+ case "java.lang.Long":
+ return longSchema(true), true, nil
+ case "float", "double":
+ return &jsonschema.Schema{Type: "number"}, true, nil
+ case "java.lang.Float", "java.lang.Double":
+ return nullableSchema(&jsonschema.Schema{Type: "number"}),
true, nil
Review Comment:
A `float` parameter or nested field accepts values such as `1e100` under
this unbounded number schema. `RestoreArguments` then calls the shared float
decoder, whose unchecked `float32` conversion returns positive infinity without
an error. The RPC therefore receives a non-finite value or fails during
serialization instead of rejecting the argument. Give `float`/`java.lang.Float`
their finite float32 bounds rather than sharing the double schema.
##########
pkg/mcp/business/schema.go:
##########
@@ -0,0 +1,294 @@
+/*
+ * 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 business
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/google/jsonschema-go/jsonschema"
+ "google.golang.org/protobuf/types/known/structpb"
+
+ meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+)
+
+const jsonSchema202012 = "https://json-schema.org/draft/2020-12/schema"
+
+type schemaBuilder struct {
+ types map[string]*meshproto.MCPTypeDefinition
+ defs map[string]*jsonschema.Schema
+ building map[string]bool
+}
+
+func BuildInputSchema(
+ parameterTypes []string,
+ bindings []*meshproto.MCPParameterBinding,
+ types map[string]*meshproto.MCPTypeDefinition,
+) (*structpb.Struct, error) {
+ if err := ValidateParameterBindings(bindings, parameterTypes); err !=
nil {
+ return nil, err
+ }
+ builder := &schemaBuilder{
+ types: types,
+ defs: make(map[string]*jsonschema.Schema),
+ building: make(map[string]bool),
+ }
+ root := &jsonschema.Schema{
+ Schema: jsonSchema202012,
+ Type: "object",
+ Properties: make(map[string]*jsonschema.Schema,
len(bindings)),
+ AdditionalProperties: denySchema(),
+ Required: make([]string, len(bindings)),
+ PropertyOrder: make([]string, len(bindings)),
+ }
+ for _, binding := range bindings {
+ position := int(binding.Position)
+ property, err := builder.schemaForType(parameterTypes[position])
+ if err != nil {
+ return nil, fmt.Errorf("parameter %q: %w",
binding.Alias, err)
+ }
+ property.Description = binding.Description
+ root.Properties[binding.Alias] = property
+ root.Required[position] = binding.Alias
+ root.PropertyOrder[position] = binding.Alias
+ }
+ root.Defs = builder.defs
+ if _, err := root.Resolve(nil); err != nil {
+ return nil, fmt.Errorf("resolve input schema: %w", err)
+ }
+ data, err := json.Marshal(root)
+ if err != nil {
+ return nil, err
+ }
+ var object map[string]any
+ if err := json.Unmarshal(data, &object); err != nil {
+ return nil, err
+ }
+ return structpb.NewStruct(object)
+}
+
+func CompileInputSchema(schema *structpb.Struct) (*jsonschema.Resolved, error)
{
+ if schema == nil {
+ return nil, fmt.Errorf("input schema is required")
+ }
+ data, err := schema.MarshalJSON()
+ if err != nil {
+ return nil, err
+ }
+ var parsed jsonschema.Schema
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ return nil, err
+ }
+ resolved, err := parsed.Resolve(nil)
+ if err != nil {
+ return nil, fmt.Errorf("resolve input schema: %w", err)
+ }
+ return resolved, nil
+}
+
+func (b *schemaBuilder) schemaForType(typeName string) (*jsonschema.Schema,
error) {
+ if schema, known, err := primitiveSchema(typeName); known || err != nil
{
+ return schema, err
+ }
+ if isUnsupportedType(typeName) {
+ return nil, fmt.Errorf("type %q is not supported", typeName)
+ }
+ if _, exists := b.types[typeName]; !exists {
+ return nil, fmt.Errorf("type definition %q is missing",
typeName)
+ }
+ if err := b.buildDefinition(typeName); err != nil {
+ return nil, err
+ }
+ return nullableSchema(&jsonschema.Schema{Ref: "#/$defs/" +
definitionKey(typeName)}), nil
+}
+
+func (b *schemaBuilder) buildDefinition(typeName string) error {
+ key := definitionKey(typeName)
+ if _, exists := b.defs[key]; exists {
+ return nil
+ }
+ definition := b.types[typeName]
+ placeholder := &jsonschema.Schema{}
+ b.defs[key] = placeholder
+ if b.building[typeName] {
+ return nil
+ }
+ b.building[typeName] = true
+ defer delete(b.building, typeName)
+
+ switch {
+ case len(definition.Enums) > 0:
+ placeholder.Type = "string"
+ placeholder.Enum = make([]any, len(definition.Enums))
+ for i, value := range definition.Enums {
+ placeholder.Enum[i] = value
+ }
+ case len(definition.Items) == 1:
+ itemSchema, err := b.schemaForType(definition.Items[0])
+ if err != nil {
+ return fmt.Errorf("type %q item: %w", typeName, err)
+ }
+ placeholder.Type = "array"
+ placeholder.Items = itemSchema
+ case len(definition.Items) == 2:
+ if !isStringType(definition.Items[0]) {
+ return fmt.Errorf("map type %q has non-string key %q",
typeName, definition.Items[0])
+ }
+ valueSchema, err := b.schemaForType(definition.Items[1])
+ if err != nil {
+ return fmt.Errorf("map type %q value: %w", typeName,
err)
+ }
+ placeholder.Type = "object"
+ placeholder.AdditionalProperties = valueSchema
+ case len(definition.Items) > 2:
+ return fmt.Errorf("type %q has invalid item arity %d",
typeName, len(definition.Items))
+ case definition.Properties != nil:
+ placeholder.Type = "object"
+ placeholder.Properties = make(map[string]*jsonschema.Schema,
len(definition.Properties))
+ placeholder.AdditionalProperties = denySchema()
+ for propertyName, propertyType := range definition.Properties {
+ propertySchema, err := b.schemaForType(propertyType)
+ if err != nil {
+ return fmt.Errorf("type %q property %q: %w",
typeName, propertyName, err)
+ }
+ placeholder.Properties[propertyName] = propertySchema
+ }
+ default:
+ return fmt.Errorf("type %q is open or unresolved", typeName)
+ }
+ return nil
+}
+
+func primitiveSchema(typeName string) (*jsonschema.Schema, bool, error) {
+ switch typeName {
+ case "boolean":
+ return &jsonschema.Schema{Type: "boolean"}, true, nil
+ case "java.lang.Boolean":
+ return nullableSchema(&jsonschema.Schema{Type: "boolean"}),
true, nil
+ case "byte":
+ return integerSchema(-128, 127, false), true, nil
+ case "java.lang.Byte":
+ return integerSchema(-128, 127, true), true, nil
+ case "short":
+ return integerSchema(-32768, 32767, false), true, nil
+ case "java.lang.Short":
+ return integerSchema(-32768, 32767, true), true, nil
+ case "int":
+ return integerSchema(-2147483648, 2147483647, false), true, nil
+ case "java.lang.Integer":
+ return integerSchema(-2147483648, 2147483647, true), true, nil
+ case "long":
+ return longSchema(false), true, nil
+ case "java.lang.Long":
+ return longSchema(true), true, nil
+ case "float", "double":
+ return &jsonschema.Schema{Type: "number"}, true, nil
+ case "java.lang.Float", "java.lang.Double":
+ return nullableSchema(&jsonschema.Schema{Type: "number"}),
true, nil
+ case "char":
+ return charSchema(false), true, nil
+ case "java.lang.Character":
+ return charSchema(true), true, nil
+ case "java.lang.String", "String", "string":
+ return nullableSchema(&jsonschema.Schema{Type: "string"}),
true, nil
+ case "void", "java.lang.Void":
+ return nil, true, fmt.Errorf("void is not a valid parameter
type")
+ default:
+ return nil, false, nil
Review Comment:
Go scalar names such as `bool`, `int64`, and `float64` fall through this
switch. Consequently, a Go struct containing one of these fields fails
`reachableTypes` with a missing definition, or is rejected as open/unresolved
if a scalar definition is present. This prevents those Go operations from being
published despite the Go-struct support required by #1576. Add explicit Go
scalar handling to both schema generation and argument decoding while
preserving the original RPC parameter types.
##########
pkg/mcp/repository/server.go:
##########
@@ -0,0 +1,133 @@
+/*
+ * 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 (
+ "fmt"
+ "time"
+
+ "google.golang.org/protobuf/proto"
+
+ 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"
+)
+
+// Servers persists the editable Draft and effective Published snapshot as one
+// CAS-protected aggregate. Contract validation is supplied by the caller.
+type Servers struct {
+ resources manager.ResourceManager
+ conditional manager.ConditionalResourceManager
+ cascading manager.CascadingResourceManager
+}
+
+func NewServers(resources manager.ResourceManager) (*Servers, error) {
+ conditional, ok := resources.(manager.ConditionalResourceManager)
+ if !ok {
+ return nil, fmt.Errorf("resource manager does not support
conditional mutations")
+ }
+ cascading, ok := resources.(manager.CascadingResourceManager)
+ if !ok {
+ return nil, fmt.Errorf("resource manager does not support
cascading deletion")
+ }
+ return &Servers{resources: resources, conditional: conditional,
cascading: cascading}, nil
+}
+
+func (r *Servers) Create(mesh, name string, draft
*meshproto.MCPServerSnapshot) (*meshresource.MCPServerResource, error) {
+ if mesh == "" || name == "" || draft == nil {
+ return nil, fmt.Errorf("mesh, name and draft are required")
+ }
+ server := meshresource.NewMCPServerResourceWithAttributes(name, mesh)
+ server.Spec.Draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot)
+ if err := r.resources.Add(server); err != nil {
+ return nil, err
+ }
+ return server, nil
+}
+
+func (r *Servers) Get(mesh, name string) (*meshresource.MCPServerResource,
error) {
+ server, exists, err :=
manager.GetByKey[*meshresource.MCPServerResource](
+ r.resources, meshresource.MCPServerKind,
coremodel.BuildResourceKey(mesh, name))
+ if err != nil {
+ return nil, err
+ }
+ if !exists {
+ return nil, fmt.Errorf("MCP server %q not found", name)
+ }
+ return server, nil
+}
+
+func (r *Servers) UpdateDraft(mesh, name, expectedVersion string, draft
*meshproto.MCPServerSnapshot) (*meshresource.MCPServerResource, error) {
+ if draft == nil {
+ return nil, fmt.Errorf("draft is required")
+ }
+ server, err := r.Get(mesh, name)
+ if err != nil {
+ return nil, err
+ }
+ updated := server.DeepCopyObject().(*meshresource.MCPServerResource)
+ updated.Spec.Draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot)
Review Comment:
Replacing the draft without comparing existing bindings lets a client swap
their `position` fields while retaining their aliases. Both positions remain
unique and in range, so later validation accepts the update and
`RestoreArguments` sends the aliases to the opposite RPC parameters. Preserve
each existing binding's position across draft updates, while allowing its alias
and description to change.
##########
pkg/mcp/repository/server.go:
##########
@@ -0,0 +1,133 @@
+/*
+ * 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 (
+ "fmt"
+ "time"
+
+ "google.golang.org/protobuf/proto"
+
+ 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"
+)
+
+// Servers persists the editable Draft and effective Published snapshot as one
+// CAS-protected aggregate. Contract validation is supplied by the caller.
+type Servers struct {
+ resources manager.ResourceManager
+ conditional manager.ConditionalResourceManager
+ cascading manager.CascadingResourceManager
+}
+
+func NewServers(resources manager.ResourceManager) (*Servers, error) {
+ conditional, ok := resources.(manager.ConditionalResourceManager)
+ if !ok {
+ return nil, fmt.Errorf("resource manager does not support
conditional mutations")
+ }
+ cascading, ok := resources.(manager.CascadingResourceManager)
+ if !ok {
+ return nil, fmt.Errorf("resource manager does not support
cascading deletion")
+ }
+ return &Servers{resources: resources, conditional: conditional,
cascading: cascading}, nil
+}
+
+func (r *Servers) Create(mesh, name string, draft
*meshproto.MCPServerSnapshot) (*meshresource.MCPServerResource, error) {
+ if mesh == "" || name == "" || draft == nil {
+ return nil, fmt.Errorf("mesh, name and draft are required")
+ }
+ server := meshresource.NewMCPServerResourceWithAttributes(name, mesh)
+ server.Spec.Draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot)
+ if err := r.resources.Add(server); err != nil {
+ return nil, err
+ }
+ return server, nil
+}
+
+func (r *Servers) Get(mesh, name string) (*meshresource.MCPServerResource,
error) {
+ server, exists, err :=
manager.GetByKey[*meshresource.MCPServerResource](
+ r.resources, meshresource.MCPServerKind,
coremodel.BuildResourceKey(mesh, name))
Review Comment:
`BuildResourceKey` concatenates mesh and name with `/`, but neither
identifier is restricted and this lookup never verifies the returned resource's
mesh/name. For example, a server created as mesh `a`, name `b/c` is also
accessible as mesh `a/b`, name `c`; `UpdateDraft` can then modify the other
mesh's server. Validate identifiers and verify the retrieved resource's
identity on all lookup/mutation paths.
##########
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:
`Create` accepts any future `expiresAt`, including fractional seconds, but
RFC3339 formatting truncates that fraction. An expiration later in the current
second therefore becomes an already-expired timestamp, and the newly created
credential immediately fails authentication. Preserve fractional seconds when
storing the expiration; the existing RFC3339 parser accepts them.
##########
pkg/mcp/repository/server.go:
##########
@@ -0,0 +1,133 @@
+/*
+ * 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 (
+ "fmt"
+ "time"
+
+ "google.golang.org/protobuf/proto"
+
+ 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"
+)
+
+// Servers persists the editable Draft and effective Published snapshot as one
+// CAS-protected aggregate. Contract validation is supplied by the caller.
+type Servers struct {
+ resources manager.ResourceManager
+ conditional manager.ConditionalResourceManager
+ cascading manager.CascadingResourceManager
+}
+
+func NewServers(resources manager.ResourceManager) (*Servers, error) {
+ conditional, ok := resources.(manager.ConditionalResourceManager)
+ if !ok {
+ return nil, fmt.Errorf("resource manager does not support
conditional mutations")
+ }
+ cascading, ok := resources.(manager.CascadingResourceManager)
+ if !ok {
+ return nil, fmt.Errorf("resource manager does not support
cascading deletion")
+ }
+ return &Servers{resources: resources, conditional: conditional,
cascading: cascading}, nil
+}
+
+func (r *Servers) Create(mesh, name string, draft
*meshproto.MCPServerSnapshot) (*meshresource.MCPServerResource, error) {
+ if mesh == "" || name == "" || draft == nil {
+ return nil, fmt.Errorf("mesh, name and draft are required")
+ }
+ server := meshresource.NewMCPServerResourceWithAttributes(name, mesh)
+ server.Spec.Draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot)
+ if err := r.resources.Add(server); err != nil {
+ return nil, err
+ }
+ return server, nil
+}
+
+func (r *Servers) Get(mesh, name string) (*meshresource.MCPServerResource,
error) {
+ server, exists, err :=
manager.GetByKey[*meshresource.MCPServerResource](
+ r.resources, meshresource.MCPServerKind,
coremodel.BuildResourceKey(mesh, name))
+ if err != nil {
+ return nil, err
+ }
+ if !exists {
+ return nil, fmt.Errorf("MCP server %q not found", name)
+ }
+ return server, nil
+}
+
+func (r *Servers) UpdateDraft(mesh, name, expectedVersion string, draft
*meshproto.MCPServerSnapshot) (*meshresource.MCPServerResource, error) {
+ if draft == nil {
+ return nil, fmt.Errorf("draft is required")
+ }
+ server, err := r.Get(mesh, name)
+ if err != nil {
+ return nil, err
+ }
+ updated := server.DeepCopyObject().(*meshresource.MCPServerResource)
+ updated.Spec.Draft = proto.Clone(draft).(*meshproto.MCPServerSnapshot)
+ if err := r.conditional.CompareAndSwap(updated, expectedVersion); err
!= nil {
+ return nil, err
+ }
+ return updated, nil
+}
+
+// Publish validates a copy of the current Draft and replaces the complete
+// Published snapshot in one conditional write. The validator may add compiled
+// schema fields to the copy; a failure leaves the stored resource untouched.
+func (r *Servers) Publish(mesh, name, expectedVersion string, validate
func(*meshproto.MCPServerSnapshot) error) (*meshresource.MCPServerResource,
error) {
+ if validate == nil {
+ return nil, fmt.Errorf("publish validator is required")
+ }
+ server, err := r.Get(mesh, name)
+ if err != nil {
+ return nil, err
+ }
+ if server.Spec == nil || server.Spec.Draft == nil {
+ return nil, fmt.Errorf("server draft is required")
+ }
+ snapshot :=
proto.Clone(server.Spec.Draft).(*meshproto.MCPServerSnapshot)
+ if err := validate(snapshot); err != nil {
+ return nil, err
+ }
Review Comment:
No production validator in this change resolves the tools or populates their
schema and fingerprints, so a no-op callback publishes bindings with missing or
invalid contracts. Wire a validator to the current complete provider catalog
and populate each binding's immutable contract before committing the snapshot;
unsupported or conflicting definitions must fail publication.
##########
pkg/store/dbcommon/gorm_store.go:
##########
@@ -246,16 +313,189 @@ func (gs *GormStore) Delete(obj interface{}) error {
})
}
+func (gs *GormStore) CompareAndSwap(obj model.Resource, expectedVersion
string) error {
+ if obj.ResourceKind() != gs.kind {
+ return fmt.Errorf("resource kind mismatch: expected %s, got
%s", gs.kind, obj.ResourceKind())
+ }
+ nextVersion, err := store.NextResourceVersion(obj, expectedVersion)
+ if err != nil {
+ return err
+ }
+ expected, _ := strconv.ParseUint(expectedVersion, 10, 64)
+
+ db := gs.pool.GetDB()
+ err = db.Transaction(func(tx *gorm.DB) error {
+ var current VersionedResourceModel
+ err := tx.Scopes(TableScope(gs.kind.ToString())).
+ Where("resource_key = ?", obj.ResourceKey()).
+ First(¤t).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return
store.ErrorResourceNotFound(obj.ResourceKind().ToString(),
obj.ResourceMeta().Name, obj.ResourceMesh())
+ }
+ if err != nil {
+ return err
+ }
+ if current.Version != expected {
+ return
store.ErrorResourceConflict(obj.ResourceKind().ToString(),
obj.ResourceMeta().Name, obj.ResourceMesh())
+ }
+
+ oldResource, err := current.ResourceModel.ToResource()
+ if err != nil {
+ return err
+ }
+ candidate, ok := obj.DeepCopyObject().(model.Resource)
+ if !ok {
+ return bizerror.NewAssertionError("Resource",
reflect.TypeOf(obj.DeepCopyObject()).Name())
+ }
+ candidateVersioned, ok := candidate.(store.VersionedResource)
+ if !ok {
+ return &store.PreconditionError{Reason: "resource does
not support conditional mutations"}
+ }
+ candidateVersioned.SetResourceVersion(nextVersion)
+ updated, err := FromResource(candidate)
+ if err != nil {
+ return err
+ }
+
+ result :=
tx.Scopes(TableScope(gs.kind.ToString())).Model(&VersionedResourceModel{}).
+ Where("resource_key = ? AND version = ?",
obj.ResourceKey(), expected).
+ Updates(map[string]interface{}{
+ "name": updated.Name,
+ "mesh": updated.Mesh,
+ "data": updated.Data,
+ "version": expected + 1,
+ })
+ if result.Error != nil {
+ return result.Error
+ }
+ if result.RowsAffected == 0 {
+ return
store.ErrorResourceConflict(obj.ResourceKind().ToString(),
obj.ResourceMeta().Name, obj.ResourceMesh())
+ }
+ if err := gs.persistIndexEntriesTx(tx, candidate, oldResource);
err != nil {
+ return fmt.Errorf("failed to persist index entries for
%s: %w", candidate.ResourceKey(), err)
+ }
+ return nil
+ })
+ if err == nil {
+ obj.(store.VersionedResource).SetResourceVersion(nextVersion)
+ }
+ return err
+}
+
+func (gs *GormStore) CompareAndDelete(obj model.Resource, expectedVersion
string) error {
+ if obj.ResourceKind() != gs.kind {
+ return fmt.Errorf("resource kind mismatch: expected %s, got
%s", gs.kind, obj.ResourceKind())
+ }
+ if _, err := store.NextResourceVersion(obj, expectedVersion); err !=
nil {
+ return err
+ }
+ expected, _ := strconv.ParseUint(expectedVersion, 10, 64)
+
+ db := gs.pool.GetDB()
+ return db.Transaction(func(tx *gorm.DB) error {
+ result := tx.Scopes(TableScope(gs.kind.ToString())).
+ Where("resource_key = ? AND version = ?",
obj.ResourceKey(), expected).
+ Delete(&VersionedResourceModel{})
+ if result.Error != nil {
+ return result.Error
+ }
+ if result.RowsAffected == 0 {
+ var count int64
+ if err :=
tx.Scopes(TableScope(gs.kind.ToString())).Model(&VersionedResourceModel{}).
+ Where("resource_key = ?",
obj.ResourceKey()).Count(&count).Error; err != nil {
+ return err
+ }
+ if count == 0 {
+ return
store.ErrorResourceNotFound(obj.ResourceKind().ToString(),
obj.ResourceMeta().Name, obj.ResourceMesh())
+ }
+ return
store.ErrorResourceConflict(obj.ResourceKind().ToString(),
obj.ResourceMeta().Name, obj.ResourceMesh())
+ }
+ return tx.Where("resource_kind = ? AND resource_key = ?",
gs.kind.ToString(), obj.ResourceKey()).
+ Delete(&ResourceIndexModel{}).Error
+ })
+}
+
+func (gs *GormStore) CompareAndDeleteWithDependents(obj model.Resource,
expectedVersion string, dependents store.ResourceStore, conditions
[]index.IndexCondition) error {
+ childStore, ok := dependents.(*GormStore)
+ if !ok || childStore.pool != gs.pool || childStore == gs ||
obj.ResourceKind() != gs.kind {
+ return &store.PreconditionError{Reason: "parent and dependent
must use distinct Gorm stores sharing one connection pool"}
+ }
+ if len(conditions) != 2 || conditions[0].IndexName != index.ByMeshIndex
|| conditions[0].Value != obj.ResourceMesh() || conditions[1].IndexName !=
index.ByMCPCredentialServerID || conditions[1].Value != obj.ResourceMeta().Name
{
+ return &store.PreconditionError{Reason: "dependent query must
be scoped to server mesh and ID"}
+ }
Review Comment:
`CompareAndDeleteWithDependents` accepts a generic `conditions
[]index.IndexCondition`, but the Gorm implementation rejects anything except
the exact MCP shape (`ByMeshIndex` + `ByMCPCredentialServerID`). This
hard-codes an MCP-specific index into the generic `dbcommon` store and makes
the parameter effectively decorative. The memory store implementation has no
such check and deletes whatever `getKeysByIndexes(conditions)` returns, so the
two backends behave differently for the same `CascadingResourceStore` contract.
Either make the contract explicit (e.g. pass the dependent index name and
parent-ID value rather than free-form conditions) or apply the same validation
in both implementations.
##########
pkg/store/dbcommon/gorm_store.go:
##########
@@ -289,6 +529,23 @@ func (gs *GormStore) Get(obj interface{}) (item
interface{}, exists bool, err er
// GetByKey retrieves a resource by its unique key
func (gs *GormStore) GetByKey(key string) (item interface{}, exists bool, err
error) {
+ if store.IsVersionedResourceKind(gs.kind) {
Review Comment:
`store.IsVersionedResourceKind(gs.kind)` is evaluated on every `GetByKey`
(and also in `List`/`GetByKeys`) for all resource kinds, not just MCP ones.
Each call looks up the registry and instantiates a fresh resource (with a new
proto Spec) only to do a type assertion, adding avoidable allocations to the
hottest read path used by discovery and the console. The answer is constant per
store, so compute it once in `NewGormStore` (e.g. a `versioned bool` field) and
reuse it.
##########
pkg/mcp/business/contract.go:
##########
@@ -0,0 +1,436 @@
+/*
+ * 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 business
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "sort"
+ "strings"
+
+ "google.golang.org/protobuf/types/known/structpb"
+
+ meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+ meshresource
"github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1"
+)
+
+type ResolvedContract struct {
+ Operation *meshproto.MCPOperation
+ Parameters []*meshproto.MCPParameterBinding
+ ReturnType string
+ RelatedTypes []*meshproto.MCPTypeDefinition
+ InputSchema *structpb.Struct
+ InputFingerprint string
+ OutputFingerprint string
+}
+
+func DefaultParameterBindings(parameterTypes []string)
[]*meshproto.MCPParameterBinding {
+ result := make([]*meshproto.MCPParameterBinding, len(parameterTypes))
+ for i := range parameterTypes {
+ result[i] = &meshproto.MCPParameterBinding{
+ Position: int32(i),
+ Alias: fmt.Sprintf("arg%d", i),
+ }
+ }
+ return result
+}
+
+func ResolveOperation(
+ mesh string,
+ operation *meshproto.MCPOperation,
+ bindings []*meshproto.MCPParameterBinding,
+ resources []*meshresource.ServiceProviderMetadataResource,
+) (*ResolvedContract, error) {
+ if operation == nil {
+ return nil, fmt.Errorf("operation is required")
+ }
+ if err := validateOperation(operation); err != nil {
+ return nil, err
+ }
+ if bindings == nil {
+ bindings = DefaultParameterBindings(operation.ParameterTypes)
+ }
+ if err := ValidateParameterBindings(bindings,
operation.ParameterTypes); err != nil {
+ return nil, err
+ }
+
+ var resolved *ResolvedContract
+ matchedDefinitions := 0
+ for _, resource := range resources {
+ if !matchesService(resource, mesh, operation) {
+ continue
+ }
+ matchedDefinitions++
+ contract, err := resolveDefinition(operation, bindings,
resource.Spec)
+ if err != nil {
+ return nil, fmt.Errorf("provider definition %s: %w",
resource.ResourceKey(), err)
+ }
+ if resolved == nil {
+ resolved = contract
+ continue
+ }
+ if contract.InputFingerprint != resolved.InputFingerprint ||
+ contract.OutputFingerprint !=
resolved.OutputFingerprint {
+ return nil, fmt.Errorf("provider definitions disagree
for operation %s", operationName(operation))
+ }
+ }
+ if matchedDefinitions == 0 {
+ return nil, fmt.Errorf("no provider definition found for
operation %s", operationName(operation))
+ }
+ return resolved, nil
+}
+
+func ValidateParameterBindings(bindings []*meshproto.MCPParameterBinding,
parameterTypes []string) error {
+ if len(bindings) != len(parameterTypes) {
+ return fmt.Errorf("parameter binding count %d does not match
parameter type count %d", len(bindings), len(parameterTypes))
+ }
+ positions := make([]bool, len(parameterTypes))
+ aliases := make(map[string]struct{}, len(bindings))
+ for _, binding := range bindings {
+ if binding == nil {
+ return fmt.Errorf("parameter binding is nil")
+ }
+ position := int(binding.Position)
+ if position < 0 || position >= len(parameterTypes) {
+ return fmt.Errorf("parameter position %d is out of
range", position)
+ }
+ if positions[position] {
+ return fmt.Errorf("parameter position %d is
duplicated", position)
+ }
+ positions[position] = true
+ alias := strings.TrimSpace(binding.Alias)
+ if alias == "" {
+ return fmt.Errorf("parameter alias at position %d is
empty", position)
+ }
+ if _, exists := aliases[alias]; exists {
+ return fmt.Errorf("parameter alias %q is duplicated",
alias)
+ }
+ aliases[alias] = struct{}{}
+ }
+ return nil
+}
+
+func validateOperation(operation *meshproto.MCPOperation) error {
+ if strings.TrimSpace(operation.ServiceName) == "" {
+ return fmt.Errorf("service name is required")
+ }
+ if strings.TrimSpace(operation.MethodName) == "" {
+ return fmt.Errorf("method name is required")
+ }
+ if operation.Protocol != "dubbo" && operation.Protocol != "tri" {
+ return fmt.Errorf("unsupported protocol %q", operation.Protocol)
+ }
+ for i, parameterType := range operation.ParameterTypes {
+ if strings.TrimSpace(parameterType) == "" {
+ return fmt.Errorf("parameter type at position %d is
empty", i)
+ }
+ }
+ return nil
+}
+
+func matchesService(
+ resource *meshresource.ServiceProviderMetadataResource,
+ mesh string,
+ operation *meshproto.MCPOperation,
+) bool {
+ if resource == nil || resource.Spec == nil || resource.Mesh != mesh {
+ return false
+ }
+ return resource.Spec.ServiceName == operation.ServiceName &&
+ resource.Spec.Group == operation.Group &&
+ resource.Spec.Version == operation.Version
+}
+
+func resolveDefinition(
+ operation *meshproto.MCPOperation,
+ bindings []*meshproto.MCPParameterBinding,
+ definition *meshproto.ServiceProviderMetadata,
+) (*ResolvedContract, error) {
+ method, err := findMethod(definition.Methods, operation.MethodName,
operation.ParameterTypes)
+ if err != nil {
+ return nil, err
+ }
+ if method == nil {
+ return nil, fmt.Errorf("method %s with the selected parameter
types is missing", operation.MethodName)
+ }
+ types, err := buildTypeIndex(definition.Types)
+ if err != nil {
+ return nil, err
+ }
+ inputTypes, err := reachableTypes(operation.ParameterTypes, types)
+ if err != nil {
+ return nil, err
+ }
+ outputTypes, err := reachableTypes([]string{method.ReturnType}, types)
+ if err != nil {
+ return nil, err
+ }
+ allTypes := mergeTypes(inputTypes, outputTypes)
+
+ schema, err := BuildInputSchema(operation.ParameterTypes, bindings,
types)
+ if err != nil {
+ return nil, err
+ }
+ if method.ReturnType != "void" && method.ReturnType != "java.lang.Void"
{
+ if _, err := BuildInputSchema(
+ []string{method.ReturnType},
+ DefaultParameterBindings([]string{method.ReturnType}),
+ types,
+ ); err != nil {
+ return nil, fmt.Errorf("return type: %w", err)
+ }
+ }
+ inputFingerprint, err := fingerprint(struct {
+ ServiceName string
+ Group string
+ Version string
+ MethodName string
+ ParameterTypes []string
+ Types []canonicalType
+ }{operation.ServiceName, operation.Group, operation.Version,
operation.MethodName, operation.ParameterTypes, canonicalTypes(inputTypes)})
+ if err != nil {
+ return nil, err
+ }
+ outputFingerprint, err := fingerprint(struct {
+ ReturnType string
+ Types []canonicalType
+ }{method.ReturnType, canonicalTypes(outputTypes)})
+ if err != nil {
+ return nil, err
+ }
+
+ return &ResolvedContract{
+ Operation: cloneOperation(operation),
+ Parameters: cloneBindings(bindings),
+ ReturnType: method.ReturnType,
+ RelatedTypes: toProtoTypes(allTypes),
+ InputSchema: schema,
+ InputFingerprint: inputFingerprint,
+ OutputFingerprint: outputFingerprint,
+ }, nil
+}
+
+func findMethod(methods []*meshproto.Method, name string, parameterTypes
[]string) (*meshproto.Method, error) {
+ var match *meshproto.Method
+ for _, method := range methods {
+ if method != nil && method.Name == name &&
slices.Equal(method.ParameterTypes, parameterTypes) {
+ if match != nil && match.ReturnType !=
method.ReturnType {
+ return nil, fmt.Errorf("method %s has
conflicting return types", name)
+ }
+ match = method
+ }
+ }
+ return match, nil
+}
+
+func buildTypeIndex(types []*meshproto.Type)
(map[string]*meshproto.MCPTypeDefinition, error) {
+ result := make(map[string]*meshproto.MCPTypeDefinition, len(types))
+ for _, typ := range types {
+ if typ == nil || strings.TrimSpace(typ.Type) == "" {
+ continue
+ }
+ candidate := &meshproto.MCPTypeDefinition{
+ Type: typ.Type,
+ Items: slices.Clone(typ.Items),
+ Enums: slices.Clone(typ.Enums),
+ Properties: cloneStringMap(typ.Properties),
+ }
+ if previous, exists := result[typ.Type]; exists &&
!equalType(previous, candidate) {
+ return nil, fmt.Errorf("type %q has conflicting
definitions", typ.Type)
+ }
+ result[typ.Type] = candidate
+ }
+ return result, nil
+}
+
+func reachableTypes(roots []string, types
map[string]*meshproto.MCPTypeDefinition)
(map[string]*meshproto.MCPTypeDefinition, error) {
+ result := make(map[string]*meshproto.MCPTypeDefinition)
+ visiting := make(map[string]bool)
+ var visit func(string) error
+ visit = func(name string) error {
+ if name == "" || isPrimitiveOrVoid(name) {
+ return nil
+ }
+ if _, done := result[name]; done {
+ return nil
+ }
+ definition, exists := types[name]
+ if !exists {
+ return fmt.Errorf("type definition %q is missing", name)
+ }
+ if visiting[name] {
+ return nil
+ }
+ visiting[name] = true
+ result[name] = definition
+ for _, item := range definition.Items {
+ if err := visit(item); err != nil {
+ return err
+ }
+ }
+ for _, propertyType := range definition.Properties {
+ if err := visit(propertyType); err != nil {
+ return err
+ }
+ }
+ visiting[name] = false
+ return nil
+ }
+ for _, root := range roots {
+ if err := visit(root); err != nil {
+ return nil, err
+ }
+ }
+ return result, nil
+}
+
+func mergeTypes(groups ...map[string]*meshproto.MCPTypeDefinition)
map[string]*meshproto.MCPTypeDefinition {
+ result := make(map[string]*meshproto.MCPTypeDefinition)
+ for _, group := range groups {
+ for name, typ := range group {
+ result[name] = typ
+ }
+ }
+ return result
+}
+
+type canonicalType struct {
+ Type string
+ Items []string
+ Enums []string
+ Properties []canonicalProperty
+}
+
+type canonicalProperty struct {
+ Name string
+ Type string
+}
+
+func canonicalTypes(types map[string]*meshproto.MCPTypeDefinition)
[]canonicalType {
+ names := make([]string, 0, len(types))
+ for name := range types {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ result := make([]canonicalType, 0, len(names))
+ for _, name := range names {
+ typ := types[name]
+ properties := make([]canonicalProperty, 0, len(typ.Properties))
+ for propertyName, propertyType := range typ.Properties {
+ properties = append(properties,
canonicalProperty{propertyName, propertyType})
+ }
+ sort.Slice(properties, func(i, j int) bool { return
properties[i].Name < properties[j].Name })
+ items := slices.Clone(typ.Items)
+ enums := slices.Clone(typ.Enums)
Review Comment:
Normalize empty `Items` and `Enums` slices before hashing. Provider metadata
with `items: []` and otherwise identical metadata omitting `items` have the
same schema, but `slices.Clone` preserves nil versus empty and JSON hashes them
as `null` versus `[]`. Consequently identical providers can be rejected as
conflicting, or an unchanged contract can drift after serialization.
--
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]