Skip to content

Agent Mesh

refactor: enforce explicit hierarchical URIs for service namespaces

Antonio Ojea9eb21eb8b429
diff --git a/.github/k8s/sam-hub-template.yaml b/.github/k8s/sam-hub-template.yaml
index 6d029684..a72da18a 100644
--- a/.github/k8s/sam-hub-template.yaml
+++ b/.github/k8s/sam-hub-template.yaml
@@ -116,9 +116,9 @@ data:
roles:
sam-canary:
allowed_services:
- - "*:*"
+ - "*"
allowed_targets:
- - "*:*"
+ - "*"
---
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
diff --git a/api/types.go b/api/types.go
index e4cf5111..44109a1f 100644
--- a/api/types.go
+++ b/api/types.go
@@ -17,32 +17,62 @@ package api
import (
"fmt"
"maps"
+ "net/url"
"strings"
"github.com/libp2p/go-libp2p/core/protocol"
)
-const EnrollProtocolID protocol.ID = "/sam/enroll/1.0.0"
-const MCPProtocolID protocol.ID = "/sam/mcp/1.0.0"
-const GossipEvents = "/sam/mesh/events/v1"
-const GossipHubSync = "/sam/hub/sync/v1"
-const AuthProtocolID protocol.ID = "/sam/auth/1.0.0"
+// ============================================================================
+// Libp2p Protocol & Network Constants
+// ============================================================================
-// CatalogTarget is the special target service name used to retrieve tool catalogs from remote nodes.
-const CatalogTarget = "sam.catalog"
+const (
+ // EnrollProtocolID is the libp2p protocol identifier for node enrollment.
+ EnrollProtocolID protocol.ID = "/sam/enroll/1.0.0"
+
+ // MCPProtocolID is the libp2p protocol identifier for Model Context Protocol streams.
+ MCPProtocolID protocol.ID = "/sam/mcp/1.0.0"
+
+ // AuthProtocolID is the libp2p protocol identifier for the zero-trust auth handshake.
+ AuthProtocolID protocol.ID = "/sam/auth/1.0.0"
+
+ // GossipEvents is the GossipSub topic used to broadcast mesh event updates (e.g., node bans).
+ GossipEvents = "/sam/mesh/events/v1"
+
+ // GossipHubSync is the GossipSub topic used by the Hub to sync cluster state.
+ GossipHubSync = "/sam/hub/sync/v1"
+
+ // DefaultAudience is the default audience string used in OIDC token validation.
+ DefaultAudience = "sam-mesh-audience"
+)
+
+// ============================================================================
+// Service Classification & Namespaces
+// ============================================================================
-// DefaultServiceType is the default type for services without a namespace.
-const DefaultServiceType = "system"
+const (
+ // SystemNamespace is the namespace reserved for built-in mesh services and protocols.
+ SystemNamespace = "system"
+
+ // CatalogTarget is the special system service name used to retrieve tool catalogs.
+ // In policy rules, it must be referred to explicitly as: system://sam.catalog
+ CatalogTarget = "sam.catalog"
-const DefaultAudience = "sam-mesh-audience"
+ // MCPServicePrefix is the scheme prefix for Model Context Protocol services.
+ // Fully qualified MCP services use the URI format: mcp://<service-name>
+ MCPServicePrefix = "mcp://"
+
+ // InferenceServicePrefix is the scheme prefix for LLM Inference services.
+ // Fully qualified inference services use the URI format: inference://<service-name>
+ InferenceServicePrefix = "inference://"
+)
-// MCPServicePrefix is the conventional prefix (namespace + separator) used for Model Context Protocol (MCP) services.
-// When an MCP client attempts to connect to an MCP service on a remote peer, and the target service name
-// does not contain a namespace separator (':'), this prefix is automatically prepended to the service name
-// prior to routing and policy evaluation.
-const MCPServicePrefix = "mcp:"
+// ============================================================================
+// Biscuit Authorization Facts
+// ============================================================================
-// Biscuit fact names
+// Biscuit fact names represent the Datalog predicates used in auth tokens and policy evaluation.
const (
FactExpiration = "expiration"
FactNode = "node"
@@ -74,7 +104,7 @@ const (
// https://doc.biscuitsec.org/reference/specifications.html#symbol-table
//
// How to add a new translation:
-// 1. Define a constant for the Biscuit fact name in the "Biscuit fact names" block above
+// 1. Define a constant for the Biscuit fact name in the constants block above
// (e.g., FactMyNewClaim = "my_new_fact").
// 2. Add an entry to the oidcClaimToFact map below (e.g., "my_oidc_claim": FactMyNewClaim).
// 3. Update translateClaimsToFacts in cmd/sam-hub/biscuit.go to handle parsing/type conversion
@@ -92,30 +122,18 @@ func OIDCClaimToFact() map[string]string {
return maps.Clone(oidcClaimToFact)
}
-// ParseServiceTarget parses a service target string into its type and name components.
-// The target convention is "type:name" (e.g., "mcp:my_tool").
-// If no colon is present, the type defaults to the "system" namespace.
-// The global wildcard "*" is a special case that maps to type "*" and name "*".
-func ParseServiceTarget(target string) (svcType, svcName string) {
- if target == "*" {
- return "*", "*"
- }
- parts := strings.SplitN(target, ":", 2)
- if len(parts) == 2 {
- return parts[0], parts[1]
- }
- return DefaultServiceType, target
-}
+// ============================================================================
+// Protocol Types & String Mappings
+// ============================================================================
-// Protocol Type strings for REST and JSON mapping.
const (
- ServiceTypeStringMCP = "mcp"
+ // ServiceTypeStringMCP is the string identifier for MCP services.
+ ServiceTypeStringMCP = "mcp"
+
+ // ServiceTypeStringInference is the string identifier for Inference services.
ServiceTypeStringInference = "inference"
)
-// InferenceServicePrefix is the conventional prefix used for LLM gateway inference services.
-const InferenceServicePrefix = "inference:"
-
// ParseServiceType converts a string identifier (e.g. from JSON or REST) to the ServiceType protobuf enum.
func ParseServiceType(s string) (ServiceType, error) {
switch strings.ToLower(s) {
@@ -139,3 +157,33 @@ func ServiceTypeToString(t ServiceType) (string, error) {
return "", fmt.Errorf("invalid or unspecified service type")
}
}
+
+// ============================================================================
+// Parsing & Routing Utilities
+// ============================================================================
+
+// ParseServiceTarget parses a service target string into its type (scheme) and name components.
+//
+// Expected formats:
+// - Hierarchical service URIs: "scheme://name" (e.g., "mcp://my_service") or "scheme://name/path" (e.g., "mcp://my_service/tool").
+// - Target facts: "fact:value" (e.g., "group:backend" or "user:bob").
+// - Wildcards: "*" (maps type to "*" and name to "*").
+//
+// If no scheme/colon is present, it returns an empty string for the type and the full target as the name.
+// No fallback namespace is applied; callers must be explicit.
+func ParseServiceTarget(target string) (svcType, svcName string) {
+ if target == "*" {
+ return "*", "*"
+ }
+ u, err := url.Parse(target)
+ if err != nil || u.Scheme == "" {
+ return "", target
+ }
+ name := u.Host
+ if u.Opaque != "" {
+ name = u.Opaque
+ } else if u.Path != "" {
+ name = u.Host + u.Path
+ }
+ return u.Scheme, name
+}
diff --git a/api/types_test.go b/api/types_test.go
index cdbf320c..76666f26 100644
--- a/api/types_test.go
+++ b/api/types_test.go
@@ -47,13 +47,13 @@ func TestParseServiceTarget(t *testing.T) {
{
name: "System fallback (no colon)",
target: "catalog",
- wantType: DefaultServiceType,
+ wantType: "",
wantName: "catalog",
},
{
name: "Empty string",
target: "",
- wantType: DefaultServiceType,
+ wantType: "",
wantName: "",
},
{
diff --git a/api/validation.go b/api/validation.go
index a04768bf..35f58d51 100644
--- a/api/validation.go
+++ b/api/validation.go
@@ -2,34 +2,78 @@ package api
import (
"fmt"
- "regexp"
+ "net/url"
"strings"
-)
-// The value can be a domain label, allowing prefix/suffix wildcards (e.g. *.foo.bar or foo.*)
-var domainLabelRegex = regexp.MustCompile(`^(?:\*\.)?(?:[a-zA-Z0-9-]+\.)*(?:[a-zA-Z0-9-]+)(?:\.\*)?$|^\*$`)
+ "github.com/asaskevich/govalidator"
+)
-// ValidateServiceFormat ensures the service string follows the explicit type:value format.
+// ValidateServiceFormat ensures the service string follows the explicit URI format.
func ValidateServiceFormat(svc string) error {
- parts := strings.SplitN(svc, ":", 2)
- if len(parts) != 2 {
- return fmt.Errorf("invalid service format %q: must be type:value (e.g., mcp:foo)", svc)
+ if svc == "*" {
+ return nil
+ }
+ // We parse the service string as a URL to enforce hierarchical URIs (e.g., mcp://name).
+ // - If no scheme is present (e.g., "mcp-service"), u.Scheme will be empty.
+ // - If a legacy non-hierarchical format is used (e.g., "mcp:my-service"), url.Parse will parse the
+ // part after the colon into u.Opaque. We reject u.Opaque != "" to ensure that the hierarchical
+ // separator "://" is explicitly present (which maps the target name to u.Host instead of u.Opaque).
+ // Without this check, "mcp:my-service.local" would parse successfully and be accepted since
+ // "my-service.local" is a valid DNS name.
+ u, err := url.Parse(svc)
+ if err != nil || u.Scheme == "" || u.Opaque != "" {
+ return fmt.Errorf("invalid service format %q: must follow explicit URI format (e.g., mcp://name)", svc)
}
- typ, val := parts[0], parts[1]
+ if u.User != nil {
+ return fmt.Errorf("invalid service format %q: userinfo is not allowed in service URIs", svc)
+ }
+ typ, val := ParseServiceTarget(svc)
if typ == "" {
return fmt.Errorf("invalid service format %q: type cannot be empty", svc)
}
if val == "" {
return fmt.Errorf("invalid service format %q: value cannot be empty", svc)
}
- if !domainLabelRegex.MatchString(val) {
- return fmt.Errorf("invalid service format %q: value must be a valid domain label with optional prefix/suffix wildcard", svc)
+
+ if val == "*" {
+ return nil
+ }
+
+ // Split val into host and path (if any)
+ parts := strings.SplitN(val, "/", 2)
+ host := parts[0]
+
+ // Host validation
+ if strings.Contains(host, "_") {
+ return fmt.Errorf("invalid service format %q: host cannot contain underscores", svc)
+ }
+
+ // Normalize wildcards for DNS validation.
+ // Note: We only support prefix wildcards starting with "*." (e.g., "*.service")
+ // and suffix wildcards ending with ".*" (e.g., "service.*"). Both formats
+ // strictly require a dot separator at the domain boundary.
+ // Arbitrary partial matching (e.g., "dev-*", "*-prod", or "service*") is not
+ // supported because the unnormalized "*" character will fail the DNS validation.
+ h := host
+ if strings.HasPrefix(h, "*.") {
+ h = "wildcard." + h[2:]
+ }
+ if strings.HasSuffix(h, ".*") {
+ h = h[:len(h)-2] + ".wildcard"
}
+
+ if !govalidator.IsDNSName(h) {
+ return fmt.Errorf("invalid service format %q: %q is not a valid DNS name", svc, host)
+ }
+
return nil
}
// ValidateTargetFormat ensures the target string follows the explicit fact:value format.
func ValidateTargetFormat(target string) error {
+ if target == "*" {
+ return nil
+ }
parts := strings.SplitN(target, ":", 2)
if len(parts) != 2 {
return fmt.Errorf("invalid target format %q: must be fact:value (e.g., group:backend)", target)
diff --git a/api/validation_test.go b/api/validation_test.go
index d8d57c62..bb91126d 100644
--- a/api/validation_test.go
+++ b/api/validation_test.go
@@ -10,17 +10,19 @@ func TestValidateServiceFormat(t *testing.T) {
svc string
wantErr bool
}{
- {"valid exact", "mcp:my-service.local", false},
- {"valid prefix wildcard", "mcp:*.service.local", false},
- {"valid suffix wildcard", "mcp:service.*", false},
- {"valid just wildcard", "mcp:*", false},
- {"valid subdomains", "mcp:a.b.c.d", false},
- {"invalid no type", ":my-service", true},
- {"invalid no colon", "mcp-service", true},
- {"invalid consecutive dots", "mcp:my..service", true},
- {"invalid wildcard middle", "mcp:my.*.service", true},
- {"invalid invalid chars", "mcp:service_name", true},
- {"invalid exact with path", "mcp:my-service/local", true},
+ {"valid exact", "mcp://my-service.local", false},
+ {"valid prefix wildcard", "mcp://*.service.local", false},
+ {"valid suffix wildcard", "mcp://service.*", false},
+ {"valid just wildcard", "mcp://*", false},
+ {"valid subdomains", "mcp://a.b.c.d", false},
+ {"invalid no type", "://my-service", true},
+ {"invalid fallback", "mcp-service", true},
+ {"invalid consecutive dots", "mcp://my..service", true},
+ {"invalid wildcard middle", "mcp://my.*.service", true},
+ {"invalid invalid chars", "mcp://service_name", true},
+ {"invalid suffix wildcard without dot", "mcp://service.inc*", true},
+ {"valid exact with path", "mcp://my-service/local", false},
+ {"invalid legacy mcp: format", "mcp:my-service.local", true},
}
for _, tt := range tests {
@@ -41,6 +43,7 @@ func TestValidateTargetFormat(t *testing.T) {
}{
{"valid target", "group:backend", false},
{"valid email", "email:[email protected]", false},
+ {"valid wildcard", "*", false},
{"invalid no colon", "group-backend", true},
{"invalid empty fact", ":backend", true},
{"invalid empty value", "group:", true},
diff --git a/cmd/sam-hub/config_test.go b/cmd/sam-hub/config_test.go
index 9bd56270..2875ced9 100644
--- a/cmd/sam-hub/config_test.go
+++ b/cmd/sam-hub/config_test.go
@@ -1,190 +1,170 @@
+// Copyright 2026 Google LLC
+//
+// Licensed 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 main
import (
"os"
"path/filepath"
"testing"
+
+ "github.com/google/sam/api"
)
func TestLoadPolicyConfig(t *testing.T) {
- // 1. Test valid YAML
- validYAML := `
+ tests := []struct {
+ name string
+ yamlContent string
+ nonexistent bool
+ wantErr bool
+ verify func(t *testing.T, config *api.PolicyConfig)
+ }{
+ {
+ name: "Valid config with exact services",
+ yamlContent: `
version: "v1alpha1"
roles:
data-scientist:
allowed_targets: ["node:db-agent.data-mesh"]
- allowed_services: ["system:query-database"]
+ allowed_services: ["system://query-database", "mcp://db-agent"]
custom_datalog:
- 'department("analytics");'
-`
- dir := t.TempDir()
- validFile := filepath.Join(dir, "valid.yaml")
- if err := os.WriteFile(validFile, []byte(validYAML), 0644); err != nil {
- t.Fatal(err)
- }
-
- config, err := LoadPolicyConfig(validFile)
- if err != nil {
- t.Fatalf("expected no error, got %v", err)
- }
- if config.Version != "v1alpha1" {
- t.Errorf("expected version v1alpha1, got %s", config.Version)
- }
- role, ok := config.Roles["data-scientist"]
- if !ok {
- t.Fatal("expected role data-scientist to exist")
- }
- if len(role.AllowedTargets) != 1 || role.AllowedTargets[0] != "node:db-agent.data-mesh" {
- t.Errorf("unexpected allowed targets: %v", role.AllowedTargets)
- }
- if len(role.AllowedServices) != 1 || role.AllowedServices[0] != "system:query-database" {
- t.Errorf("unexpected allowed tools: %v", role.AllowedServices)
- }
- if len(role.CustomDatalog) != 1 || role.CustomDatalog[0] != `department("analytics");` {
- t.Errorf("unexpected custom datalog: %v", role.CustomDatalog)
- }
-
- // 2. Test invalid YAML
- invalidYAML := `
+`,
+ wantErr: false,
+ verify: func(t *testing.T, config *api.PolicyConfig) {
+ if config.Version != "v1alpha1" {
+ t.Errorf("expected version v1alpha1, got %s", config.Version)
+ }
+ role, ok := config.Roles["data-scientist"]
+ if !ok {
+ t.Fatal("expected role data-scientist to exist")
+ }
+ if len(role.AllowedTargets) != 1 || role.AllowedTargets[0] != "node:db-agent.data-mesh" {
+ t.Errorf("unexpected allowed targets: %v", role.AllowedTargets)
+ }
+ if len(role.AllowedServices) != 2 || role.AllowedServices[0] != "system://query-database" || role.AllowedServices[1] != "mcp://db-agent" {
+ t.Errorf("unexpected allowed services: %v", role.AllowedServices)
+ }
+ if len(role.CustomDatalog) != 1 || role.CustomDatalog[0] != `department("analytics");` {
+ t.Errorf("unexpected custom datalog: %v", role.CustomDatalog)
+ }
+ },
+ },
+ {
+ name: "Invalid YAML syntax",
+ yamlContent: `
version: "v1alpha1"
roles:
data-scientist:
allowed_targets: [missing closing bracket
-`
- invalidFile := filepath.Join(dir, "invalid.yaml")
- if err := os.WriteFile(invalidFile, []byte(invalidYAML), 0644); err != nil {
- t.Fatal(err)
- }
-
- _, err = LoadPolicyConfig(invalidFile)
- if err == nil {
- t.Error("expected error for invalid YAML, got nil")
- }
-
- // 3. Test missing file
- missingFile := filepath.Join(dir, "nonexistent.yaml")
- config, err = LoadPolicyConfig(missingFile)
- if err != nil {
- t.Fatalf("expected no error for missing file, got %v", err)
- }
- if config == nil {
- t.Fatal("expected non-nil config for missing file")
- }
- if len(config.Roles) != 0 {
- t.Errorf("expected empty roles, got %d", len(config.Roles))
- }
-
- // 4. Test invalid custom datalog
- invalidDatalogYAML := `
+`,
+ wantErr: true,
+ },
+ {
+ name: "Nonexistent file loads empty config",
+ nonexistent: true,
+ wantErr: false,
+ verify: func(t *testing.T, config *api.PolicyConfig) {
+ if config == nil {
+ t.Fatal("expected non-nil config for missing file")
+ }
+ if len(config.Roles) != 0 {
+ t.Errorf("expected empty roles, got %d", len(config.Roles))
+ }
+ },
+ },
+ {
+ name: "Invalid custom datalog fact syntax",
+ yamlContent: `
version: "v1alpha1"
roles:
data-scientist:
custom_datalog:
- 'invalid fact syntax'
-`
- invalidDatalogFile := filepath.Join(dir, "invalid_datalog.yaml")
- if err := os.WriteFile(invalidDatalogFile, []byte(invalidDatalogYAML), 0644); err != nil {
- t.Fatal(err)
- }
-
- _, err = LoadPolicyConfig(invalidDatalogFile)
- if err == nil {
- t.Error("expected error for invalid custom datalog, got nil")
- }
-
- // 6. Test valid bindings
- bindingsYAML := `
+`,
+ wantErr: true,
+ },
+ {
+ name: "Valid group binding",
+ yamlContent: `
version: "v1alpha1"
bindings:
- group: "system:serviceaccounts:sam-canary-bananas"
role: "mesh-member"
roles:
mesh-member:
- allowed_services: ["mcp:1.0.0"]
-`
- bindingsFile := filepath.Join(dir, "bindings.yaml")
- if err := os.WriteFile(bindingsFile, []byte(bindingsYAML), 0644); err != nil {
- t.Fatal(err)
- }
-
- config, err = LoadPolicyConfig(bindingsFile)
- if err != nil {
- t.Fatalf("expected no error for valid bindings, got %v", err)
- }
- if len(config.Bindings) != 1 {
- t.Errorf("expected 1 binding, got %d", len(config.Bindings))
- }
- if config.Bindings[0].Group != "system:serviceaccounts:sam-canary-bananas" || config.Bindings[0].Role != "mesh-member" {
- t.Errorf("unexpected binding values: %+v", config.Bindings[0])
- }
-
- // 7. Test invalid binding mapping (non-existent role)
- invalidBindingYAML := `
+ allowed_services: ["mcp://1.0.0"]
+`,
+ wantErr: false,
+ verify: func(t *testing.T, config *api.PolicyConfig) {
+ if len(config.Bindings) != 1 {
+ t.Errorf("expected 1 binding, got %d", len(config.Bindings))
+ }
+ if config.Bindings[0].Group != "system:serviceaccounts:sam-canary-bananas" || config.Bindings[0].Role != "mesh-member" {
+ t.Errorf("unexpected binding values: %+v", config.Bindings[0])
+ }
+ },
+ },
+ {
+ name: "Invalid binding mapping to nonexistent role",
+ yamlContent: `
version: "v1alpha1"
bindings:
- group: "system:serviceaccounts:sam-canary-bananas"
role: "non-existent-role"
roles:
mesh-member:
- allowed_services: ["mcp:1.0.0"]
-`
- invalidBindingFile := filepath.Join(dir, "invalid_binding.yaml")
- if err := os.WriteFile(invalidBindingFile, []byte(invalidBindingYAML), 0644); err != nil {
- t.Fatal(err)
- }
-
- _, err = LoadPolicyConfig(invalidBindingFile)
- if err == nil {
- t.Error("expected error for invalid binding referencing a nonexistent role, got nil")
- }
-
- // 8. Test valid user binding
- userBindingYAML := `
+ allowed_services: ["mcp://1.0.0"]
+`,
+ wantErr: true,
+ },
+ {
+ name: "Valid user binding",
+ yamlContent: `
version: "v1alpha1"
bindings:
- user: "system:serviceaccount:sam-canary:sam-node-sa"
role: "mesh-member"
roles:
mesh-member:
- allowed_services: ["mcp:1.0.0"]
-`
- userBindingFile := filepath.Join(dir, "user_binding.yaml")
- if err := os.WriteFile(userBindingFile, []byte(userBindingYAML), 0644); err != nil {
- t.Fatal(err)
- }
-
- config, err = LoadPolicyConfig(userBindingFile)
- if err != nil {
- t.Fatalf("expected no error for valid user binding, got %v", err)
- }
- if len(config.Bindings) != 1 {
- t.Errorf("expected 1 binding, got %d", len(config.Bindings))
- }
- if config.Bindings[0].User != "system:serviceaccount:sam-canary:sam-node-sa" || config.Bindings[0].Role != "mesh-member" {
- t.Errorf("unexpected binding values: %+v", config.Bindings[0])
- }
-
- // 9. Test invalid binding with both group and user missing
- missingBothYAML := `
+ allowed_services: ["mcp://1.0.0"]
+`,
+ wantErr: false,
+ verify: func(t *testing.T, config *api.PolicyConfig) {
+ if len(config.Bindings) != 1 {
+ t.Errorf("expected 1 binding, got %d", len(config.Bindings))
+ }
+ if config.Bindings[0].User != "system:serviceaccount:sam-canary:sam-node-sa" || config.Bindings[0].Role != "mesh-member" {
+ t.Errorf("unexpected binding values: %+v", config.Bindings[0])
+ }
+ },
+ },
+ {
+ name: "Invalid binding with both group and user missing",
+ yamlContent: `
version: "v1alpha1"
bindings:
- role: "mesh-member"
roles:
mesh-member:
- allowed_services: ["mcp:1.0.0"]
-`
- missingBothFile := filepath.Join(dir, "missing_both.yaml")
- if err := os.WriteFile(missingBothFile, []byte(missingBothYAML), 0644); err != nil {
- t.Fatal(err)
- }
-
- _, err = LoadPolicyConfig(missingBothFile)
- if err == nil {
- t.Error("expected error for binding with both group and user missing, got nil")
- }
-
- // 10. Test invalid binding with both group and user populated
- bothPopulatedYAML := `
+ allowed_services: ["mcp://1.0.0"]
+`,
+ wantErr: true,
+ },
+ {
+ name: "Invalid binding with both group and user populated",
+ yamlContent: `
version: "v1alpha1"
bindings:
- group: "some-group"
@@ -192,15 +172,93 @@ bindings:
role: "mesh-member"
roles:
mesh-member:
- allowed_services: ["mcp:1.0.0"]
-`
- bothPopulatedFile := filepath.Join(dir, "both_populated.yaml")
- if err := os.WriteFile(bothPopulatedFile, []byte(bothPopulatedYAML), 0644); err != nil {
- t.Fatal(err)
+ allowed_services: ["mcp://1.0.0"]
+`,
+ wantErr: true,
+ },
+ {
+ name: "Valid wildcard - global wildcard",
+ yamlContent: `
+version: "v1alpha1"
+roles:
+ admin:
+ allowed_services: ["*"]
+`,
+ wantErr: false,
+ },
+ {
+ name: "Valid wildcard - type wildcard",
+ yamlContent: `
+version: "v1alpha1"
+roles:
+ admin:
+ allowed_services: ["mcp://*"]
+`,
+ wantErr: false,
+ },
+ {
+ name: "Valid wildcard - domain prefix wildcard",
+ yamlContent: `
+version: "v1alpha1"
+roles:
+ admin:
+ allowed_services: ["mcp://*.service.local"]
+`,
+ wantErr: false,
+ },
+ {
+ name: "Valid wildcard - domain suffix wildcard",
+ yamlContent: `
+version: "v1alpha1"
+roles:
+ admin:
+ allowed_services: ["mcp://service.*"]
+`,
+ wantErr: false,
+ },
+ {
+ name: "Invalid wildcard - arbitrary partial prefix matching",
+ yamlContent: `
+version: "v1alpha1"
+roles:
+ admin:
+ allowed_services: ["mcp://dev-*"]
+`,
+ wantErr: true,
+ },
+ {
+ name: "Invalid wildcard - arbitrary partial suffix matching",
+ yamlContent: `
+version: "v1alpha1"
+roles:
+ admin:
+ allowed_services: ["mcp://*-prod"]
+`,
+ wantErr: true,
+ },
}
- _, err = LoadPolicyConfig(bothPopulatedFile)
- if err == nil {
- t.Error("expected error for binding specifying both group and user, got nil")
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var path string
+ if tt.nonexistent {
+ path = filepath.Join(t.TempDir(), "nonexistent.yaml")
+ } else {
+ dir := t.TempDir()
+ path = filepath.Join(dir, "policy.yaml")
+ if err := os.WriteFile(path, []byte(tt.yamlContent), 0644); err != nil {
+ t.Fatalf("failed to write temp policy file: %v", err)
+ }
+ }
+
+ config, err := LoadPolicyConfig(path)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("LoadPolicyConfig() error = %v, wantErr %v", err, tt.wantErr)
+ }
+
+ if !tt.wantErr && tt.verify != nil {
+ tt.verify(t, config)
+ }
+ })
}
}
diff --git a/cmd/sam-node/config.go b/cmd/sam-node/config.go
index ccbe6cbd..994baf2d 100644
--- a/cmd/sam-node/config.go
+++ b/cmd/sam-node/config.go
@@ -40,7 +40,7 @@ func LoadNodeConfig(path string) (*NodeConfigComplete, error) {
}
for i, svc := range config.Services {
- if err := api.ValidateServiceFormat(svc.Type + ":" + svc.Name); err != nil {
+ if err := api.ValidateServiceFormat(svc.Type + "://" + svc.Name); err != nil {
return nil, fmt.Errorf("invalid service config at index %d: %w", i, err)
}
}
diff --git a/cmd/sam-node/config_test.go b/cmd/sam-node/config_test.go
index 4eeae0d6..ea554ce1 100644
--- a/cmd/sam-node/config_test.go
+++ b/cmd/sam-node/config_test.go
@@ -7,8 +7,16 @@ import (
)
func TestLoadNodeConfig(t *testing.T) {
- // 1. Test valid YAML with policies and services
- validYAML := `
+ tests := []struct {
+ name string
+ yamlContent string
+ nonexistent bool
+ wantErr bool
+ verify func(t *testing.T, config *NodeConfigComplete)
+ }{
+ {
+ name: "Valid config with multiple services and attenuation",
+ yamlContent: `
version: "v1alpha1"
attenuation:
policies:
@@ -26,49 +34,147 @@ services:
command: ["python3", "-m", "llama"]
env:
MODEL_PATH: "/models/llama"
-`
- dir := t.TempDir()
- validFile := filepath.Join(dir, "sam-node.yaml")
- if err := os.WriteFile(validFile, []byte(validYAML), 0644); err != nil {
- t.Fatal(err)
- }
-
- config, err := LoadNodeConfig(validFile)
- if err != nil {
- t.Fatalf("expected no error, got %v", err)
- }
- if len(config.Policies) != 1 {
- t.Errorf("expected 1 policy, got %d", len(config.Policies))
- }
- if len(config.Checks) != 1 {
- t.Errorf("expected 1 check, got %d", len(config.Checks))
- }
- if len(config.Services) != 2 {
- t.Errorf("expected 2 services, got %d", len(config.Services))
+`,
+ wantErr: false,
+ verify: func(t *testing.T, config *NodeConfigComplete) {
+ if len(config.Policies) != 1 {
+ t.Errorf("expected 1 policy, got %d", len(config.Policies))
+ }
+ if len(config.Checks) != 1 {
+ t.Errorf("expected 1 check, got %d", len(config.Checks))
+ }
+ if len(config.Services) != 2 {
+ t.Errorf("expected 2 services, got %d", len(config.Services))
+ }
+ s1 := config.Services[0]
+ if s1.Type != "mcp" || s1.Name != "test-mcp" || s1.TargetURL != "http://localhost:8080" {
+ t.Errorf("unexpected service 1: %+v", s1)
+ }
+ s2 := config.Services[1]
+ if s2.Type != "inference" || s2.Name != "test-inference" || len(s2.Command) != 3 || s2.Env["MODEL_PATH"] != "/models/llama" {
+ t.Errorf("unexpected service 2: %+v", s2)
+ }
+ },
+ },
+ {
+ name: "Invalid service name containing underscores",
+ yamlContent: `
+version: "v1alpha1"
+services:
+ - type: "mcp"
+ name: "invalid_mcp_name"
+ target_url: "http://localhost:8080"
+`,
+ wantErr: true,
+ },
+ {
+ name: "Invalid service name containing invalid DNS characters",
+ yamlContent: `
+version: "v1alpha1"
+services:
+ - type: "mcp"
+ name: "service@123"
+ target_url: "http://localhost:8080"
+`,
+ wantErr: true,
+ },
+ {
+ name: "Invalid service type empty",
+ yamlContent: `
+version: "v1alpha1"
+services:
+ - type: ""
+ name: "valid-name"
+ target_url: "http://localhost:8080"
+`,
+ wantErr: true,
+ },
+ {
+ name: "Invalid service name empty",
+ yamlContent: `
+version: "v1alpha1"
+services:
+ - type: "mcp"
+ name: ""
+ target_url: "http://localhost:8080"
+`,
+ wantErr: true,
+ },
+ {
+ name: "Invalid YAML syntax",
+ yamlContent: `
+version: "v1alpha1"
+services:
+ - type: [unclosed list
+`,
+ wantErr: true,
+ },
+ {
+ name: "Nonexistent config file returns empty config",
+ nonexistent: true,
+ wantErr: false,
+ verify: func(t *testing.T, config *NodeConfigComplete) {
+ if config == nil {
+ t.Fatal("expected non-nil config")
+ }
+ if len(config.Services) != 0 || len(config.Policies) != 0 || len(config.Checks) != 0 {
+ t.Errorf("expected empty config, got: %+v", config)
+ }
+ },
+ },
+ {
+ name: "Invalid local attenuation policy syntax",
+ yamlContent: `
+version: "v1alpha1"
+attenuation:
+ policies:
+ - "deny if invalid datalog syntax"
+`,
+ wantErr: true,
+ },
+ {
+ name: "Invalid local attenuation check syntax",
+ yamlContent: `
+version: "v1alpha1"
+attenuation:
+ checks:
+ - "check if invalid check syntax"
+`,
+ wantErr: true,
+ },
+ {
+ name: "Invalid local attenuation rule syntax",
+ yamlContent: `
+version: "v1alpha1"
+attenuation:
+ rules:
+ - "invalid rule syntax"
+`,
+ wantErr: true,
+ },
}
- // Verify service 1
- s1 := config.Services[0]
- if s1.Type != "mcp" || s1.Name != "test-mcp" || s1.TargetURL != "http://localhost:8080" {
- t.Errorf("unexpected service 1: %+v", s1)
- }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var path string
+ if tt.nonexistent {
+ path = filepath.Join(t.TempDir(), "nonexistent.yaml")
+ } else {
+ dir := t.TempDir()
+ path = filepath.Join(dir, "sam-node.yaml")
+ if err := os.WriteFile(path, []byte(tt.yamlContent), 0644); err != nil {
+ t.Fatalf("failed to write temp config file: %v", err)
+ }
+ }
- // Verify service 2
- s2 := config.Services[1]
- if s2.Type != "inference" || s2.Name != "test-inference" || len(s2.Command) != 3 || s2.Env["MODEL_PATH"] != "/models/llama" {
- t.Errorf("unexpected service 2: %+v", s2)
- }
+ config, err := LoadNodeConfig(path)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("LoadNodeConfig() error = %v, wantErr %v", err, tt.wantErr)
+ }
- // 2. Test missing file
- missingFile := filepath.Join(dir, "nonexistent.yaml")
- config, err = LoadNodeConfig(missingFile)
- if err != nil {
- t.Fatalf("expected no error for missing file, got %v", err)
- }
- if config == nil {
- t.Fatal("expected non-nil config for missing file")
- }
- if len(config.Policies) != 0 {
- t.Errorf("expected empty policies, got %d", len(config.Policies))
+ if !tt.wantErr && tt.verify != nil {
+ tt.verify(t, config)
+ }
+ })
}
}
diff --git a/cmd/sam-node/gate.go b/cmd/sam-node/gate.go
index f3e9b635..8772e406 100644
--- a/cmd/sam-node/gate.go
+++ b/cmd/sam-node/gate.go
@@ -77,13 +77,13 @@ func (g *nodeConnGate) InterceptSecured(dir network.Direction, p peer.ID, n netw
func (n *SamNode) HandleMCPStream(s network.Stream, reqCtx RequestContext) {
// If the TargetService is for a registered local backend, dumb-pipe proxy to it.
target := reqCtx.Target
- if target != "" && target != api.CatalogTarget {
+ _, targetName := api.ParseServiceTarget(target)
+ if target != "" && targetName != api.CatalogTarget {
if n.services == nil {
logger.Errorf("[MCP] Service registry is not initialized")
_ = s.Reset()
return
}
- _, targetName := api.ParseServiceTarget(target)
svc, ok := n.services.Get(targetName)
if !ok && targetName != target {
svc, ok = n.services.Get(target)
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index 55e695d8..99360089 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -20,6 +20,7 @@ import (
"errors"
"fmt"
"net/http"
+ "net/url"
"strings"
"time"
@@ -44,7 +45,7 @@ Reach into the mesh only when the needed tool isn't available locally. To do so:
Other useful tools: discover_remote_services browses services by type, get_mesh_info reports connected peers and mesh state, list_local_services shows what this node hosts.
-Remote tool names are namespaced as '<service>/<tool>' (e.g. 'code-reviewer/review_pr'). Prefer discovering and describing a tool before calling it rather than guessing arguments.`
+Remote tool names are namespaced as 'scheme://service/tool' (e.g. 'mcp://code-reviewer/review_pr'). Prefer discovering and describing a tool before calling it rather than guessing arguments.`
// NewMCPServer creates a new MCP server instance with all tools registered.
func NewMCPServer(node *SamNode) *mcp.Server {
@@ -116,7 +117,7 @@ func NewMCPServer(node *SamNode) *mcp.Server {
// Add the describe_remote_tool tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "describe_remote_tool",
- Description: "Return the description, input schema, and output schema for a specific aggregated tool on a specific peer. peer_id and tool_name are both required; tool_name must be a namespaced '<service>.<tool>' name as returned by find_remote_tools.",
+ Description: "Return the description, input schema, and output schema for a specific aggregated tool on a specific peer. peer_id and tool_name are both required; tool_name must be a namespaced 'scheme://service/tool' name as returned by find_remote_tools.",
}, node.handleDescribeRemoteTool)
// Add the check_connectivity tool.
@@ -363,11 +364,9 @@ func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, tar
}
func (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolName string, params any) (*mcp.CallToolResult, error) {
- targetService := api.CatalogTarget
- originalToolName := toolName
- if parts := strings.SplitN(toolName, "/", 2); len(parts) == 2 {
- targetService = parts[0]
- originalToolName = parts[1]
+ targetService, originalToolName, err := splitToolName(toolName)
+ if err != nil {
+ return nil, err
}
session, cleanup, err := n.ConnectMCPSession(ctx, targetPeer, targetService)
@@ -396,7 +395,7 @@ func (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolN
func (n *SamNode) fetchRemoteServiceCatalog(ctx context.Context, peerID peer.ID, typeStr string) ([]*api.ServiceInfo, error) {
n.preparePeerAddrs(ctx, peerID)
- session, cleanup, err := n.ConnectMCPSession(ctx, peerID, api.CatalogTarget)
+ session, cleanup, err := n.ConnectMCPSession(ctx, peerID, "system://"+api.CatalogTarget)
if err != nil {
return nil, err
}
@@ -555,3 +554,23 @@ func (n *SamNode) preparePeerAddrs(ctx context.Context, targetPeer peer.ID) {
logger.Debugf("[Discovery] Replaced addrs for %s with %d routable/circuit addrs", targetPeer, len(validAddrs))
}
}
+
+// splitToolName splits a fully qualified MCP tool name into its target service URI
+// and the original tool name to be invoked on that service.
+//
+// Expected format: "scheme://service-name/tool-name" (e.g., "mcp://my-service/my-tool").
+// If the input is empty or invalid, it returns an error. No default fallback is applied.
+func splitToolName(toolName string) (targetService, originalToolName string, err error) {
+ if toolName == "" {
+ return "", "", fmt.Errorf("tool name cannot be empty")
+ }
+
+ u, parseErr := url.Parse(toolName)
+ if parseErr != nil || u.Scheme == "" || u.Host == "" || u.Path == "" || u.Opaque != "" {
+ return "", "", fmt.Errorf("invalid namespaced tool name %q: must follow explicit URI format 'scheme://service/tool'", toolName)
+ }
+
+ targetService = u.Scheme + "://" + u.Host
+ originalToolName = strings.TrimPrefix(u.Path, "/")
+ return targetService, originalToolName, nil
+}
diff --git a/cmd/sam-node/mcp_handlers.go b/cmd/sam-node/mcp_handlers.go
index 1bef0aef..b1fc0a3f 100644
--- a/cmd/sam-node/mcp_handlers.go
+++ b/cmd/sam-node/mcp_handlers.go
@@ -338,7 +338,7 @@ func (n *SamNode) fetchRemoteToolCatalogue(ctx context.Context, targetPeer peer.
targetService := svc.Name
connectService := targetService
- if !strings.Contains(connectService, ":") {
+ if !strings.Contains(connectService, "://") && !strings.Contains(connectService, ":") {
connectService = api.MCPServicePrefix + connectService
}
@@ -453,7 +453,7 @@ type remoteToolDescription struct {
// sidecar tool.
type DescribeRemoteToolParams struct {
PeerID string `json:"peer_id" jsonschema:"Peer ID of the node hosting the server. Required."`
- ToolName string `json:"tool_name" jsonschema:"Namespaced server name as returned by find_remote_tools (e.g. 'code-reviewer/review_pr'). Required."`
+ ToolName string `json:"tool_name" jsonschema:"Namespaced server name as returned by find_remote_tools (e.g. 'mcp://code-reviewer/review_pr'). Required."`
}
// handleDescribeRemoteTool implements the describe_remote_tool client-facing tool.
@@ -470,12 +470,13 @@ func (n *SamNode) handleDescribeRemoteTool(ctx context.Context, req *mcp.CallToo
return nil, nil, fmt.Errorf("invalid peer_id: %w", err)
}
- parts := strings.SplitN(params.ToolName, "/", 2)
- if len(parts) != 2 {
- return nil, nil, fmt.Errorf("invalid tool_name format, expected 'service/tool'")
+ serviceName, actualToolName, err := splitToolName(params.ToolName)
+ if err != nil {
+ return nil, nil, err
+ }
+ if serviceName == "system://"+api.CatalogTarget {
+ return nil, nil, fmt.Errorf("cannot describe system catalog tools via describe_remote_tool")
}
- serviceName := parts[0]
- actualToolName := parts[1]
n.preparePeerAddrs(ctx, pid)
session, cleanup, err := n.ConnectMCPSession(ctx, pid, serviceName)
diff --git a/cmd/sam-node/mcp_handlers_test.go b/cmd/sam-node/mcp_handlers_test.go
index acfe4079..7d9c3e4a 100644
--- a/cmd/sam-node/mcp_handlers_test.go
+++ b/cmd/sam-node/mcp_handlers_test.go
@@ -161,8 +161,8 @@ func TestHandleFindRemoteTools_SinglePeer(t *testing.T) {
}
wantNames := map[string]bool{
- "mcp:code-reviewer/review_pr": false,
- "mcp:code-reviewer/add_comment": false,
+ "mcp://code-reviewer/review_pr": false,
+ "mcp://code-reviewer/add_comment": false,
}
for _, row := range rows {
if row.PeerID != nodeB.Host.ID().String() {
@@ -233,13 +233,13 @@ func TestHandleFindRemoteTools_MeshWide(t *testing.T) {
t.Fatalf("RegisterService B: %v", err)
}
if err := nodeC.RegisterService(ctx, &api.RegisterServiceRequest{
- Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "mcp:summarizer"},
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "mcp://summarizer"},
Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: cSrv.URL},
}); err != nil {
t.Fatalf("RegisterService C: %v", err)
}
if err := nodeD.RegisterService(ctx, &api.RegisterServiceRequest{
- Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "plugin:linter"},
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "plugin://linter"},
Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: dSrv.URL},
}); err != nil {
t.Fatalf("RegisterService D: %v", err)
@@ -265,17 +265,17 @@ func TestHandleFindRemoteTools_MeshWide(t *testing.T) {
gotNames[tool.ToolName] = true
}
- // Test permutation 1: no prefix gets "mcp:" automatically prepended.
- if !gotNames["mcp:code-reviewer/review_pr"] {
- t.Errorf("missing mcp:code-reviewer/review_pr; got %v", gotNames)
+ // Test permutation 1: no prefix gets "mcp://" automatically prepended.
+ if !gotNames["mcp://code-reviewer/review_pr"] {
+ t.Errorf("missing mcp://code-reviewer/review_pr; got %v", gotNames)
}
- // Test permutation 2: "mcp:" prefix is preserved.
- if !gotNames["mcp:summarizer/summarize"] {
- t.Errorf("missing mcp:summarizer/summarize; got %v", gotNames)
+ // Test permutation 2: "mcp://" prefix is preserved.
+ if !gotNames["mcp://summarizer/summarize"] {
+ t.Errorf("missing mcp://summarizer/summarize; got %v", gotNames)
}
// Test permutation 3: custom namespace prefix is preserved.
- if !gotNames["plugin:linter/lint"] {
- t.Errorf("missing plugin:linter/lint; got %v", gotNames)
+ if !gotNames["plugin://linter/lint"] {
+ t.Errorf("missing plugin://linter/lint; got %v", gotNames)
}
}
@@ -333,12 +333,12 @@ func TestHandleFindRemoteTools_PartialFailure(t *testing.T) {
gotSummarizer := false
for _, r := range rows {
- if r.ToolName == "mcp:summarizer/summarize" {
+ if r.ToolName == "mcp://summarizer/summarize" {
gotSummarizer = true
}
}
if !gotSummarizer {
- t.Errorf("expected mcp:summarizer/summarize from C even with B unreachable; got %+v", rows)
+ t.Errorf("expected mcp://summarizer/summarize from C even with B unreachable; got %+v", rows)
}
}
@@ -438,8 +438,8 @@ func TestFetchRemoteToolCatalogue_AuthRejected(t *testing.T) {
}
row := rows[0]
- if row.ToolName != "mcp:summarizer" {
- t.Errorf("expected ToolName 'mcp:summarizer', got %q", row.ToolName)
+ if row.ToolName != "mcp://summarizer" {
+ t.Errorf("expected ToolName 'mcp://summarizer', got %q", row.ToolName)
}
if !strings.Contains(row.Error, "auth rejected") {
t.Errorf("expected Error to contain 'auth rejected', got %q", row.Error)
@@ -541,7 +541,7 @@ func TestHandleDescribeRemoteTool_SelfPeerRejected(t *testing.T) {
_, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
PeerID: node.Host.ID().String(),
- ToolName: "code-reviewer/review_pr",
+ ToolName: "mcp://code-reviewer/review_pr",
})
if err == nil {
t.Fatal("expected error when peer_id equals self peer ID")
@@ -557,7 +557,7 @@ func TestHandleDescribeRemoteTool_InvalidPeerID(t *testing.T) {
_, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
PeerID: "not-a-valid-peer-id",
- ToolName: "code-reviewer/review_pr",
+ ToolName: "mcp://code-reviewer/review_pr",
})
if err == nil {
t.Fatal("expected error for malformed peer_id")
@@ -621,7 +621,7 @@ func TestHandleDescribeRemoteTool_RoundTrip(t *testing.T) {
res, _, err := nodeA.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
PeerID: nodeB.Host.ID().String(),
- ToolName: "code-reviewer/review_pr",
+ ToolName: "mcp://code-reviewer/review_pr",
})
if err != nil {
t.Fatalf("handleDescribeRemoteTool: %v", err)
@@ -638,8 +638,8 @@ func TestHandleDescribeRemoteTool_RoundTrip(t *testing.T) {
if desc.PeerID != nodeB.Host.ID().String() {
t.Errorf("PeerID = %q, want %q", desc.PeerID, nodeB.Host.ID().String())
}
- if desc.ToolName != "code-reviewer/review_pr" {
- t.Errorf("ToolName = %q, want %q", desc.ToolName, "code-reviewer/review_pr")
+ if desc.ToolName != "mcp://code-reviewer/review_pr" {
+ t.Errorf("ToolName = %q, want %q", desc.ToolName, "mcp://code-reviewer/review_pr")
}
if desc.Description != "Run a code review" {
t.Errorf("Description = %q, want %q", desc.Description, "Run a code review")
@@ -699,7 +699,7 @@ func TestHandleDescribeRemoteTool_RoundTrip_UnknownTool(t *testing.T) {
_, _, err = nodeA.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
PeerID: nodeB.Host.ID().String(),
- ToolName: "code-reviewer/does-not-exist",
+ ToolName: "mcp://code-reviewer/does-not-exist",
})
if err == nil {
t.Fatal("expected error from peer when tool is not registered")
diff --git a/cmd/sam-node/mcp_test.go b/cmd/sam-node/mcp_test.go
index fdb5f183..e7ca95d6 100644
--- a/cmd/sam-node/mcp_test.go
+++ b/cmd/sam-node/mcp_test.go
@@ -153,3 +153,70 @@ func TestResolveRelayAddresses(t *testing.T) {
t.Errorf("Expected generic circuit address %s not found in peerstore. Got: %v", expectedDirectAddrStr, addrs)
}
}
+
+func TestSplitToolName(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ wantService string
+ wantTool string
+ wantErr bool
+ }{
+ {
+ name: "Empty input",
+ input: "",
+ wantErr: true,
+ },
+ {
+ name: "Modern URI format",
+ input: "mcp://my-service/my-tool",
+ wantService: "mcp://my-service",
+ wantTool: "my-tool",
+ wantErr: false,
+ },
+ {
+ name: "Modern URI format with path depth",
+ input: "mcp://my-service/my-tool/sub-tool",
+ wantService: "mcp://my-service",
+ wantTool: "my-tool/sub-tool",
+ wantErr: false,
+ },
+ {
+ name: "Missing tool path",
+ input: "mcp://my-service",
+ wantErr: true,
+ },
+ {
+ name: "No scheme path",
+ input: "sam.catalog/some-tool",
+ wantErr: true,
+ },
+ {
+ name: "Just tool name",
+ input: "some-tool",
+ wantErr: true,
+ },
+ {
+ name: "Strict system catalog URI",
+ input: "system://sam.catalog/some-tool",
+ wantService: "system://sam.catalog",
+ wantTool: "some-tool",
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotSvc, gotTool, err := splitToolName(tt.input)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("splitToolName(%q) returned error: %v, wantErr: %v", tt.input, err, tt.wantErr)
+ }
+ if !tt.wantErr {
+ if gotSvc != tt.wantService || gotTool != tt.wantTool {
+ t.Errorf("splitToolName(%q) = (%q, %q), want (%q, %q)",
+ tt.input, gotSvc, gotTool, tt.wantService, tt.wantTool)
+ }
+ }
+ })
+ }
+}
diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.go
index 54b977f0..05e87c4b 100644
--- a/cmd/sam-node/middleware.go
+++ b/cmd/sam-node/middleware.go
@@ -239,7 +239,9 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
// Inject the current action context (Standard Vocabulary)
var opType, opName string
if req.Target == "" {
- opType = api.DefaultServiceType
+ // When no explicit target is requested, the operation is scoped to the connection protocol itself,
+ // which resides in the "system" namespace.
+ opType = api.SystemNamespace
opName = req.Protocol
} else {
opType, opName = api.ParseServiceTarget(req.Target)
diff --git a/cmd/sam-node/middleware_test.go b/cmd/sam-node/middleware_test.go
index 35cc5ee7..142fcd6b 100644
--- a/cmd/sam-node/middleware_test.go
+++ b/cmd/sam-node/middleware_test.go
@@ -184,7 +184,7 @@ func TestBaselineRules(t *testing.T) {
_ = builder.AddAuthorityFact(fact)
},
protocol: "test_tool",
- target: "mcp:test_tool",
+ target: "mcp://test_tool",
expectSuccess: true,
},
{
@@ -195,7 +195,7 @@ func TestBaselineRules(t *testing.T) {
_ = builder.AddAuthorityFact(fact)
},
protocol: "anything",
- target: "mcp:anything",
+ target: "mcp://anything",
expectSuccess: true,
},
{
@@ -204,7 +204,7 @@ func TestBaselineRules(t *testing.T) {
// No specific allowed_service facts needed
},
protocol: api.CatalogTarget, // "catalog"
- target: "system:" + api.CatalogTarget,
+ target: "system://" + api.CatalogTarget,
expectSuccess: true,
},
{
@@ -215,7 +215,7 @@ func TestBaselineRules(t *testing.T) {
_ = builder.AddAuthorityFact(fact)
},
protocol: "test_tool",
- target: "mcp:test_tool",
+ target: "mcp://test_tool",
expectSuccess: true,
},
{
@@ -226,7 +226,7 @@ func TestBaselineRules(t *testing.T) {
_ = builder.AddAuthorityFact(fact)
},
protocol: "test_tool",
- target: "system:test_tool",
+ target: "system://test_tool",
expectSuccess: false,
},
{
@@ -242,7 +242,7 @@ func TestBaselineRules(t *testing.T) {
}})
},
protocol: "test_tool",
- target: "mcp:test_tool",
+ target: "mcp://test_tool",
expectSuccess: false, // Should fail the connection_peer_id check
},
}
@@ -604,7 +604,7 @@ func TestMiddlewareTargetChecks(t *testing.T) {
req: RequestContext{
PeerID: dummyPeer,
Protocol: "test_tool",
- Target: "mcp:test_tool",
+ Target: "mcp://test_tool",
User: "bob",
},
expectSuccess: true,
@@ -620,7 +620,7 @@ func TestMiddlewareTargetChecks(t *testing.T) {
req: RequestContext{
PeerID: dummyPeer,
Protocol: "test_tool",
- Target: "mcp:test_tool",
+ Target: "mcp://test_tool",
User: "bob",
},
expectSuccess: false,
@@ -636,7 +636,7 @@ func TestMiddlewareTargetChecks(t *testing.T) {
req: RequestContext{
PeerID: dummyPeer,
Protocol: "test_tool",
- Target: "mcp:test_tool",
+ Target: "mcp://test_tool",
Group: "eng",
},
expectSuccess: true,
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index 47e5279e..757326a8 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -1540,7 +1540,7 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
PeerID: remotePeer,
User: "", // Extracted implicitly if needed, or left empty
Protocol: "/libp2p-http",
- Target: strings.ToLower(serviceTypeStr) + ":" + serviceName,
+ Target: strings.ToLower(serviceTypeStr) + "://" + serviceName,
}
// Verify authorization
diff --git a/development/kind/test-mesh-e2e.sh b/development/kind/test-mesh-e2e.sh
index 828a4a02..c4efc4e8 100755
--- a/development/kind/test-mesh-e2e.sh
+++ b/development/kind/test-mesh-e2e.sh
@@ -67,7 +67,7 @@ for i in $(seq 1 90); do
done
[ -n "$peer" ] || {
- echo "mcp:calculator.add not discovered after 90s"
+ echo "mcp:calculator/add not discovered after 90s"
echo "final find_remote_tools:"
mcp -tool find_remote_tools -args '{}' || true
echo "final mesh info:"
diff --git a/go.mod b/go.mod
index 73343ddf..1da3ea21 100644
--- a/go.mod
+++ b/go.mod
@@ -36,6 +36,7 @@ require (
filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5 // indirect
filippo.io/keygen v0.0.0-20260114151900-8e2790ea4c5b // indirect
github.com/alecthomas/participle/v2 v2.1.4 // indirect
+ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/benbjohnson/clock v1.3.5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
diff --git a/go.sum b/go.sum
index 3966b25e..3a74c782 100644
--- a/go.sum
+++ b/go.sum
@@ -8,6 +8,8 @@ github.com/alecthomas/participle/v2 v2.1.4 h1:W/H79S8Sat/krZ3el6sQMvMaahJ+XcM9WS
github.com/alecthomas/participle/v2 v2.1.4/go.mod h1:8tqVbpTX20Ru4NfYQgZf4mP18eXPTBViyMWiArNEgGI=
github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=
github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
+github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
+github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o=
github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
diff --git a/site/content/docs/development/policy.md b/site/content/docs/development/policy.md
index dfa597fc..179c83bd 100644
--- a/site/content/docs/development/policy.md
+++ b/site/content/docs/development/policy.md
@@ -68,10 +68,10 @@ allow if group("engineering");
Admins define central permissions by mapping OIDC roles to specific capabilities.
* **`allowed_targets`**: Defines which logical groups or specific peers a user can route messages to, analogous to Active Directory security groups. Target definitions must be formatted as resolved facts (e.g., `group:<name>`, `user:<sub-id>`, `email:<email>`, `role:<role-name>`, or `node:<peer-id>`). *Note: These are evaluated dynamically at the destination node using its own identity (see Section 3.1).*
-* **`allowed_services`**: Defines the application-level tools or endpoints a user can access. Services use a strict `type:name` convention (e.g., `mcp:db-agent` or `inference:openrouter`).
- * **Strict Namespaces**: There are no implicit fallbacks. `system:...` is used for internal services, `mcp:...` for node services, `inference:...` for AI models, etc. Service names must be valid domain labels (e.g. `value1.value2.value3`).
- * **Wildcards**: SAM natively supports prefix and suffix wildcards to build complex policies. The hub generates specific facts like `granted_service_exact($type, $name)`, `granted_service_prefix($type, $prefix)`, `granted_service_suffix($type, $suffix)`, `granted_service_all_in_type($type)`, or `granted_service_all_types()`. You can grant access to an entire type via `mcp:*`, allow prefix matching like `mcp:dev-*`, suffix matching like `mcp:*-prod`, or global access to everything via `*`.
- * **MCP Namespace Convention**: The `mcp:` prefix (`api.MCPServicePrefix`) is the explicit convention for all Model Context Protocol targets. When remote nodes query local nodes for tool catalogs, if the local service is an MCP server, the proxy layer strictly enforces the authorization policy against the `mcp:` prefix.
+* **`allowed_services`**: Defines the application-level tools or endpoints a user can access. Services use a strict `type://name` convention (e.g., `mcp://db-agent` or `inference://openrouter`).
+ * **Strict Namespaces**: There are no implicit fallbacks. `system://...` is used for internal services, `mcp://...` for node services, `inference://...` for AI models, etc. Service names must be valid domain labels (e.g. `value1.value2.value3`).
+ * **Wildcards**: SAM natively supports domain-level wildcards to build complex policies. The hub generates specific facts like `granted_service_exact($type, $name)`, `granted_service_prefix($type, $prefix)`, `granted_service_suffix($type, $suffix)`, `granted_service_all_in_type($type)`, or `granted_service_all_types()`. You can grant access to an entire type via `mcp://*`, allow prefix-based wildcard matching like `mcp://*.service.local` (which matches services ending in `.service.local`), suffix-based wildcard matching like `mcp://service.*` (which matches services starting with `service.`), or global access to everything via `*`. Note that arbitrary partial matches (e.g., `dev-*` or `*-prod`) are not supported because they do not align with domain boundaries and will fail DNS name validation.
+ * **MCP Namespace Convention**: The `mcp://` prefix (`api.MCPServicePrefix`) is the explicit convention for all Model Context Protocol targets. When remote nodes query local nodes for tool catalogs, if the local service is an MCP server, the proxy layer strictly enforces the authorization policy against the `mcp://` prefix.
> [!NOTE]
> The `*` global wildcard is a special case. It grants `granted_service_all_types()` fact, allowing the caller to invoke any tool regardless of its namespace or name.
@@ -86,9 +86,9 @@ roles:
- "user:auth0|123456" # Node bound to a specific user sub
- "email:[email protected]" # Node bound to a specific email
allowed_services:
- - "mcp:db-agent" # Access to specific MCP server
- - "inference:openrouter" # Access to inference endpoints
- - "mcp:*" # Wildcard access to all MCP servers
+ - "mcp://db-agent" # Access to specific MCP server
+ - "inference://openrouter" # Access to inference endpoints
+ - "mcp://*" # Wildcard access to all MCP servers
custom_datalog:
- 'department("analytics");' # Raw injected facts
```
diff --git a/site/content/docs/user/hub-configuration.md b/site/content/docs/user/hub-configuration.md
index d4f80334..10fa348b 100644
--- a/site/content/docs/user/hub-configuration.md
+++ b/site/content/docs/user/hub-configuration.md
@@ -43,10 +43,10 @@ The hub dynamically issues permissions inside the Biscuit token based on identit
The policy defines what endpoints and services agents are permitted to use:
* **`allowed_targets`**: Acts similar to Active Directory network groups. This restricts which logical endpoints the agent can route connections to. **Note: IP address ranges are not allowed.** Instead, use the format of the resolved Biscuit facts: `group:<name>`, `user:<sub-id>`, `email:<email>`, `role:<role-name>`, or `node:<peer-id>`.
-* **`allowed_services`**: Restricts the application-level services the agent can invoke. Services are prefixed by their protocol type (e.g., `mcp:local-shell-tools` or `inference:openrouter`).
+* **`allowed_services`**: Restricts the application-level services the agent can invoke. Services are prefixed by their protocol type and URI scheme (e.g., `mcp://local-shell-tools` or `inference://openrouter`).
> [!NOTE]
-> SAM natively supports prefix and suffix wildcards in `allowed_services`. You can grant access to an entire type via `mcp:*`, allow prefix matching like `mcp:dev-*`, suffix matching like `mcp:*-prod`, or grant global access to everything via `*`.
+> SAM natively supports domain-level prefix and suffix wildcards in `allowed_services`. You can grant access to an entire type via `mcp://*`, allow prefix wildcard matching like `mcp://*.service.local` (matching services ending in `.service.local`), suffix wildcard matching like `mcp://service.*` (matching services starting with `service.`), or grant global access to everything via `*`. Note that arbitrary partial matches (e.g., `dev-*` or `*-prod`) are not supported because they do not align with domain boundaries and will fail DNS name validation.
### Example Policy Mapping
Create a `policies.yaml` file in the directory where you run `sam-hub`:
@@ -63,18 +63,18 @@ roles:
- "user:auth0|123456"
- "node:12D3KooWSpecificDevNodeId"
allowed_services:
- - "mcp:local-shell-tools"
- - "mcp:git-helper"
- - "inference:openrouter"
+ - "mcp://local-shell-tools"
+ - "mcp://git-helper"
+ - "inference://openrouter"
admin-role:
allowed_targets:
- "group:all-nodes"
- "role:admin"
allowed_services:
- - "mcp:*"
- - "inference:*"
- - "system:*"
+ - "mcp://*"
+ - "inference://*"
+ - "system://*"
# Bind OIDC user subs, emails, or group claims to roles
bindings:
diff --git a/site/content/docs/user/node-configuration.md b/site/content/docs/user/node-configuration.md
index 21bbf115..491bb16f 100644
--- a/site/content/docs/user/node-configuration.md
+++ b/site/content/docs/user/node-configuration.md
@@ -56,7 +56,7 @@ The `services` array allows you to register endpoints that remote peers in the S
| Property | Description |
| :--- | :--- |
| `type` | The protocol protocol type. Supported values are `mcp` (Model Context Protocol), `inference`, or `a2a`. |
-| `name` | The unique name of the service (e.g., `git-helper`). This must exactly match the name authorized by the Hub's `policies.yaml` (e.g., `mcp:git-helper`). |
+| `name` | The unique name of the service (e.g., `git-helper`). This must exactly match the name authorized by the Hub's `policies.yaml` (e.g., `mcp://git-helper`). |
| `description` | A human-readable description published to the mesh discovery catalogue. |
| `command` | *(For MCP)* The executable command array to spawn as a local subprocess (e.g. `["node", "index.js"]`). |
| `env` | *(For MCP)* Key-value environment variables passed to the subprocess. |
diff --git a/tests/e2e/find_remote_tools.bats b/tests/e2e/find_remote_tools.bats
index 21e7e254..3f29ef40 100644
--- a/tests/e2e/find_remote_tools.bats
+++ b/tests/e2e/find_remote_tools.bats
@@ -80,7 +80,7 @@ teardown() {
local match_count
match_count=$(echo "$catalog" | jq --arg pid "${node2_peer_id}" '
[.[] | select(.peer_id == $pid
- and (.tool_name | startswith("mcp:calculator.")))] | length
+ and (.tool_name | startswith("mcp://calculator/")))] | length
')
echo "Matching calculator tool entries: ${match_count}"
[[ "${match_count}" -ge 1 ]]
@@ -124,7 +124,7 @@ teardown() {
echo "[$(date +%T)] Calling call_remote_tool for calculator.add"
local call_args
- call_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"mcp:calculator.add\",\"arguments\":{\"a\":2,\"b\":3}}"
+ call_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"mcp://calculator/add\",\"arguments\":{\"a\":2,\"b\":3}}"
run docker run --rm --network "${MESH_NETWORK}" \
"${MESH_RUNTIME_IMAGE}" mcp-client \
-url "http://sam-node-1:8080/mcp" \
@@ -175,7 +175,7 @@ teardown() {
echo "[$(date +%T)] Calling describe_remote_tool for calculator.add"
local describe_args
- describe_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"mcp:calculator.add\"}"
+ describe_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"mcp://calculator/add\"}"
run docker run --rm --network "${MESH_NETWORK}" \
"${MESH_RUNTIME_IMAGE}" mcp-client \
-url "http://sam-node-1:8080/mcp" \
@@ -195,7 +195,7 @@ teardown() {
local got_name
got_name=$(echo "$payload" | jq -r '.tool_name')
- [[ "${got_name}" == "mcp:calculator.add" ]]
+ [[ "${got_name}" == "mcp://calculator/add" ]]
local got_input_type
got_input_type=$(echo "$payload" | jq -r '.input_schema.type')
@@ -240,7 +240,7 @@ teardown() {
echo "[$(date +%T)] Calling describe_remote_tool for an unknown tool"
local describe_args
- describe_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"mcp:calculator.does-not-exist\"}"
+ describe_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"mcp://calculator/does-not-exist\"}"
run docker run --rm --network "${MESH_NETWORK}" \
"${MESH_RUNTIME_IMAGE}" mcp-client \
-url "http://sam-node-1:8080/mcp" \
diff --git a/tests/e2e/fixtures/default-policy.yaml b/tests/e2e/fixtures/default-policy.yaml
index 0050fe06..9d1c5c3c 100644
--- a/tests/e2e/fixtures/default-policy.yaml
+++ b/tests/e2e/fixtures/default-policy.yaml
@@ -5,6 +5,6 @@ bindings:
roles:
admin:
allowed_services:
- - "*:*"
+ - "*"
allowed_targets:
- - "*:*"
+ - "*"
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index a9669cd4..cb73172e 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -14,21 +14,19 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
# Best-effort cleanup of leaked resources from prior failed runs.
mesh_cleanup_stale_resources() {
- local ids
- ids="$(docker ps -aq --filter "name=mesh-")"
- if [[ -n "${ids}" ]]; then
- # shellcheck disable=SC2086
- docker rm -f ${ids} >/dev/null 2>&1 || true
- fi
+ local id
+ for id in $(docker ps -aq --filter "name=mesh-"); do
+ docker rm -f "${id}" >/dev/null 2>&1 || true
+ done
- local nets
- nets="$(docker network ls --format '{{.Name}}' | grep '^mesh-.*-net$' || true)"
- if [[ -n "${nets}" ]]; then
- while IFS= read -r net; do
- [[ -z "${net}" ]] && continue
- docker network rm "${net}" >/dev/null 2>&1 || true
- done <<< "${nets}"
- fi
+ local net
+ for net in $(docker network ls --format '{{.Name}}'); do
+ case "${net}" in
+ mesh-*-net)
+ docker network rm "${net}" >/dev/null 2>&1 || true
+ ;;
+ esac
+ done
}
mesh_require_docker() {
diff --git a/tests/e2e/policy.bats b/tests/e2e/policy.bats
index 7e4164e4..89a4f6eb 100644
--- a/tests/e2e/policy.bats
+++ b/tests/e2e/policy.bats
@@ -2,6 +2,27 @@
load "lib/container_mesh.bash"
+CALC_MCP_IMAGE="sam-calc-mcp:local"
+
+build_calc_mcp_image() {
+ if ! docker image inspect "${CALC_MCP_IMAGE}" >/dev/null 2>&1; then
+ docker build -t "${CALC_MCP_IMAGE}" \
+ -f tests/e2e/docker/calc-mcp/Dockerfile \
+ tests/e2e/docker/calc-mcp >/dev/null
+ fi
+}
+
+start_calc_mcp() {
+ local name="${MESH_PREFIX}-calc-mcp"
+ docker run -d \
+ --name "${name}" \
+ --network "${MESH_NETWORK}" \
+ --network-alias calc-mcp \
+ "${CALC_MCP_IMAGE}" >/dev/null
+ MESH_CONTAINERS+=("${name}")
+ mesh_wait_for_log "${name}" "Uvicorn running on" 20
+}
+
# Custom mock OIDC server that returns 'data-scientist' role
mesh_start_mock_oidc_custom() {
local name="${MESH_PREFIX}-oidc"
@@ -124,18 +145,11 @@ EOF
mesh_wait_for_log "${name}" "Mock OIDC server ready" 30
}
-mesh_call_remote_tool() {
- local caller_idx="$1"
- local target_peer_id="$2"
- local tool_name="$3"
-
- local args="{\"peer_id\":\"${target_peer_id}\",\"tool_name\":\"${tool_name}\",\"arguments\":{}}"
-
- docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://sam-node-${caller_idx}:8080/mcp" -tool "call_remote_tool" -args "${args}"
-}
+
setup() {
mesh_setup_env
+ build_calc_mcp_image
mkdir -p tests/e2e/logs
# Create volume for policies
@@ -150,13 +164,22 @@ bindings:
roles:
mesh-member:
allowed_services:
- - \"mcp:query_database\"
- - \"mcp:delete_tables\""
+ - \"mcp://calculator\"
+ - \"mcp://db-agent\""
local node_policy="version: \"v1alpha1\"
+services:
+ - type: \"mcp\"
+ name: \"calculator\"
+ description: \"Simple math operations\"
+ target_url: \"http://calc-mcp:7777/mcp\"
+ - type: \"mcp\"
+ name: \"db-agent\"
+ description: \"Database operations\"
+ target_url: \"http://calc-mcp:7777/mcp\"
attenuation:
policies:
- - 'deny if service(\"mcp\", \"delete_tables\");'"
+ - 'deny if service(\"mcp\", \"db-agent\");'"
docker run --rm -v "${POLICY_VOL}:/policies" busybox sh -c "cat <<'EOF' > /policies/policies.yaml
${hub_policy}
@@ -169,6 +192,8 @@ EOF"
run mesh_start_mock_oidc_custom
[[ "$status" -eq 0 ]]
+ start_calc_mcp
+
# Start Hub with policy file
local hub_name="${MESH_PREFIX}-hub"
local key
@@ -271,19 +296,23 @@ teardown() {
}
@test "Policy E2E: Positive Path (Allowed by Hub, Not blocked by Node)" {
- run mesh_call_remote_tool 2 "${TARGET_PEER_ID}" "query_database"
+ local call_args="{\"peer_id\":\"${TARGET_PEER_ID}\",\"tool_name\":\"mcp://calculator/add\",\"arguments\":{\"a\":2,\"b\":3}}"
+ run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://sam-node-2:8080/mcp" -tool "call_remote_tool" -args "${call_args}"
echo "Output: $output"
[ "$status" -eq 0 ]
+ [[ "$output" == *"5"* ]]
}
@test "Policy E2E: Negative Path (Denied by Hub)" {
- run mesh_call_remote_tool 2 "${TARGET_PEER_ID}" "reboot_server"
+ local call_args="{\"peer_id\":\"${TARGET_PEER_ID}\",\"tool_name\":\"mcp://unauthorized-service/reboot_server\",\"arguments\":{}}"
+ run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://sam-node-2:8080/mcp" -tool "call_remote_tool" -args "${call_args}"
echo "Output: $output"
[[ "$output" == *"denied"* ]]
}
@test "Policy E2E: Attenuation Path (Allowed by Hub, Blocked by Node)" {
- run mesh_call_remote_tool 2 "${TARGET_PEER_ID}" "delete_tables"
+ local call_args="{\"peer_id\":\"${TARGET_PEER_ID}\",\"tool_name\":\"mcp://db-agent/delete_tables\",\"arguments\":{}}"
+ run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://sam-node-2:8080/mcp" -tool "call_remote_tool" -args "${call_args}"
echo "Output: $output"
[[ "$output" == *"denied"* ]]
}
diff --git a/tests/e2e/setup_suite.bash b/tests/e2e/setup_suite.bash
index 58301f96..5cce475c 100644
--- a/tests/e2e/setup_suite.bash
+++ b/tests/e2e/setup_suite.bash
@@ -3,6 +3,7 @@
set -eu
function setup_suite {
+ export PATH="${HOME}/go/bin:$PATH"
export BATS_TEST_TIMEOUT=150
if ! command -v docker >/dev/null 2>&1 || ! docker info >/dev/null 2>&1; then
diff --git a/tests/integration/federation_test.go b/tests/integration/federation_test.go
index b153deee..6a1add8e 100644
--- a/tests/integration/federation_test.go
+++ b/tests/integration/federation_test.go
@@ -35,7 +35,7 @@ bindings:
roles:
admin:
allowed_services:
- - "mcp:*"
+ - "mcp://*"
`
if err := os.WriteFile(policyFile, []byte(policyContent), 0644); err != nil {
t.Fatal(err)
diff --git a/tests/integration/policy_permutations_test.go b/tests/integration/policy_permutations_test.go
index bbdbc999..610fe544 100644
--- a/tests/integration/policy_permutations_test.go
+++ b/tests/integration/policy_permutations_test.go
@@ -80,22 +80,22 @@ func TestPolicyPermutations(t *testing.T) {
hubPolicyYAML := `version: "v1alpha1"
roles:
role-user:
- allowed_services: ["mcp:test-user"]
+ allowed_services: ["mcp://test-user"]
allowed_targets: ["user:bob-subject"]
role-email:
- allowed_services: ["mcp:test-email"]
+ allowed_services: ["mcp://test-email"]
allowed_targets: ["email:[email protected]"]
role-group:
- allowed_services: ["mcp:test-group"]
+ allowed_services: ["mcp://test-group"]
allowed_targets: ["group:compute"]
role-node:
- allowed_services: ["mcp:test-node"]
+ allowed_services: ["mcp://test-node"]
allowed_targets: ["group:backend"]
role-direct:
- allowed_services: ["mcp:test-role"]
+ allowed_services: ["mcp://test-role"]
allowed_targets: ["group:compute"]
admin:
- allowed_services: ["*:*"]
+ allowed_services: ["*"]
allowed_targets: ["*:*"]
bindings:
@@ -209,37 +209,37 @@ services:
{
name: "Fact sub: user(bob-subject)",
jwtClaims: map[string]interface{}{"sub": "bob-subject"},
- targetSvc: "mcp:test-user",
+ targetSvc: "mcp://test-user",
expectAllow: true,
},
{
name: "Fact email: email([email protected])",
jwtClaims: map[string]interface{}{"sub": "some-id", "email": "[email protected]"},
- targetSvc: "mcp:test-email",
+ targetSvc: "mcp://test-email",
expectAllow: true,
},
{
name: "Fact groups: group(eng-team)",
jwtClaims: map[string]interface{}{"sub": "some-id", "groups": []string{"eng-team"}},
- targetSvc: "mcp:test-group",
+ targetSvc: "mcp://test-group",
expectAllow: true,
},
{
name: "Fact roles: role(role-direct)",
jwtClaims: map[string]interface{}{"sub": "some-id", "roles": []string{"role-direct"}},
- targetSvc: "mcp:test-role",
+ targetSvc: "mcp://test-role",
expectAllow: true,
},
{
name: "Fact node: node(peerID)",
jwtClaims: map[string]interface{}{"sub": "node-user"},
- targetSvc: "mcp:test-node",
+ targetSvc: "mcp://test-node",
expectAllow: true,
},
{
name: "Unknown User / No Roles -> Hub Error",
jwtClaims: map[string]interface{}{"sub": "unknown"},
- targetSvc: "mcp:test-user",
+ targetSvc: "mcp://test-user",
expectAllow: false,
},
}