Skip to content

Agent Mesh

node: use X-Sam-Authentication for sidecar auth, free Authorization for passthrough

Antonio Ojea68e4d518a36f
diff --git a/api/network.go b/api/network.go
index b52c46ce..42dc8a12 100644
--- a/api/network.go
+++ b/api/network.go
@@ -80,15 +80,19 @@ const (
// are forwarded to backend services.
HeaderSamBiscuit = "X-Sam-Biscuit"
- // HeaderSamAuthorization is the custom HTTP header that a client can pass to a local
- // SAM node's egress proxy to supply the Authorization header intended for the remote service.
+ // HeaderSamAuthentication is the custom HTTP header used to authenticate a local
+ // process to this node's sidecar API (the shared secret configured via
+ // "--api-token"). Using a SAM-specific header name — instead of the standard
+ // "Authorization" header — leaves "Authorization" free to always mean what
+ // every HTTP client expects: the credential for the destination being called.
+ // The sidecar strips this header before forwarding any request off-node, so
+ // it never leaks to a remote peer or backend service.
//
- // The egress proxy uses "Authorization: Bearer <token>" for its own local authentication.
- // By specifying the target service's auth token in HeaderSamAuthorization, the client avoids
- // stomping local authentication, and prevents the egress proxy from leaking the local sidecar
- // authentication token to the remote peer. The egress proxy maps this header back to
- // "Authorization" before transmitting the request to the destination node.
- HeaderSamAuthorization = "X-Sam-Authorization"
+ // For compatibility with MCP clients that only support a plain "Authorization"
+ // header, purely-local endpoints (that never forward it anywhere) also accept
+ // "Authorization" as an alias. The egress/inference proxy does NOT: there,
+ // "Authorization" is reserved exclusively for the destination's credential.
+ HeaderSamAuthentication = "X-Sam-Authentication"
// HeaderSamNoTrailingSlash is the custom HTTP header set by the ingress handler
// to indicate that the original request had no trailing slash.
diff --git a/cmd/mcp-client/main.go b/cmd/mcp-client/main.go
index a78a342a..39d89b24 100644
--- a/cmd/mcp-client/main.go
+++ b/cmd/mcp-client/main.go
@@ -30,6 +30,8 @@ import (
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
+
+ "github.com/google/sam/api"
)
func main() {
@@ -92,7 +94,7 @@ func main() {
}
if *tokenOpt != "" {
- req.Header.Set("Authorization", "Bearer "+*tokenOpt)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+*tokenOpt)
}
resp, err := http.DefaultClient.Do(req)
@@ -222,6 +224,6 @@ type authTransport struct {
func (t *authTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// Clone request to avoid mutating original request if shared/retried
reqCopy := req.Clone(req.Context())
- reqCopy.Header.Set("Authorization", "Bearer "+t.token)
+ reqCopy.Header.Set(api.HeaderSamAuthentication, "Bearer "+t.token)
return t.underlying.RoundTrip(reqCopy)
}
diff --git a/development/examples/code-reviewer-pool/manager/server.mjs b/development/examples/code-reviewer-pool/manager/server.mjs
index 2218c03a..12fc0284 100644
--- a/development/examples/code-reviewer-pool/manager/server.mjs
+++ b/development/examples/code-reviewer-pool/manager/server.mjs
@@ -138,7 +138,7 @@ app.post("/mcp", async (req, res) => {
app.listen(PORT, "0.0.0.0", async () => {
console.log(`pool-manager MCP server on :${PORT}/mcp (pooling '${POOL_SERVICE}')`);
const transport = new StreamableHTTPClientTransport(new URL(NODE_URL), {
- requestInit: { headers: { Authorization: `Bearer ${API_TOKEN}` } },
+ requestInit: { headers: { "X-Sam-Authentication": `Bearer ${API_TOKEN}` } },
});
await node.connect(transport);
await discover();
diff --git a/internal/node/mcp.go b/internal/node/mcp.go
index 47522ac3..1787ff44 100644
--- a/internal/node/mcp.go
+++ b/internal/node/mcp.go
@@ -45,7 +45,9 @@ To use these remote services and their tools, the client can use the following f
Other useful tools: discover_remote_services browses services by type (e.g. 'MCP' or 'Inference'), get_mesh_info reports connected peers and mesh state, list_local_services shows what this node hosts.
-Tools on remote services are identified via the format 'scheme://service-name/tool-name' (where 'scheme://service-name' represents the well-known local address of the service, and 'tool-name' is the individual tool to execute on it. Tool names themselves can contain any characters).`
+Tools on remote services are identified via the format 'scheme://service-name/tool-name' (where 'scheme://service-name' represents the well-known local address of the service, and 'tool-name' is the individual tool to execute on it. Tool names themselves can contain any characters).
+
+Inference services ('inference://...') are NOT called via call_remote_tool — they are plain OpenAI-compatible HTTP endpoints. Use discover_remote_services with type 'inference' to get each one's local_proxy_url, then send a normal HTTP request (e.g. POST <local_proxy_url>/chat/completions) directly to that URL: add header 'X-Sam-Authentication: Bearer <your local --api-token>' to authenticate to this node, and only add 'Authorization: Bearer <upstream-credential>' if the destination service itself requires its own credential — it passes straight through untouched and is never used to authenticate to this node.`
// NewMCPServer creates a new MCP server instance with all tools registered.
func NewMCPServer(node *SamNode) *mcp.Server {
@@ -69,7 +71,7 @@ func NewMCPServer(node *SamNode) *mcp.Server {
// Add discover_remote_services tool
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "discover_remote_services",
- Description: "Discover remote services in the mesh. Provide only `type` to browse every reachable service of that type (returns name + description for each); add `name` to target a specific service.",
+ Description: "Discover remote services in the mesh. Provide only `type` to browse every reachable service of that type (returns name + description for each); add `name` to target a specific service. For `type: inference`, each result's `local_proxy_url` is called directly over HTTP (NOT via call_remote_tool) — the response includes a usage hint with the exact headers required.",
}, node.handleDiscoverRemoteServices)
// Add the mesh_pubsub_broadcast tool.
diff --git a/internal/node/mcp_handlers.go b/internal/node/mcp_handlers.go
index 5dd9175f..bb19b3f5 100644
--- a/internal/node/mcp_handlers.go
+++ b/internal/node/mcp_handlers.go
@@ -59,6 +59,13 @@ func (n *SamNode) handleListLocalServices(ctx context.Context, req *mcp.CallTool
}, nil, nil
}
+// inferenceInvocationHint tells the calling agent how to call an inference://
+// service's local_proxy_url directly over HTTP. Inference services are plain
+// OpenAI-compatible endpoints, never invoked via call_remote_tool.
+const inferenceInvocationHint = `To call an inference service, send a normal HTTP request (e.g. POST <local_proxy_url>/chat/completions) directly to its "local_proxy_url" — do NOT use call_remote_tool. Required headers:
+ - "X-Sam-Authentication: Bearer <your local --api-token>" authenticates you to this node; it is never forwarded off-node.
+ - "Authorization: Bearer <upstream-credential>" is OPTIONAL and only needed if the destination service itself requires its own credential (e.g. a provider API key); it passes straight through untouched and plays no part in authenticating to this node.`
+
// DiscoverRemoteServicesParams defines the parameters for the discover_remote_services tool.
type DiscoverRemoteServicesParams struct {
Type string `json:"type" jsonschema:"Service type (mcp, inference, a2a)"`
@@ -101,10 +108,12 @@ func (n *SamNode) handleDiscoverRemoteServices(ctx context.Context, req *mcp.Cal
if err != nil {
return nil, nil, err
}
+ content := []mcp.Content{&mcp.TextContent{Text: string(respData)}}
+ if serviceType == api.ServiceType_SERVICE_TYPE_INFERENCE && len(providers) > 0 {
+ content = append(content, &mcp.TextContent{Text: inferenceInvocationHint})
+ }
return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: string(respData)},
- },
+ Content: content,
}, nil, nil
}
diff --git a/internal/node/proxy_test.go b/internal/node/proxy_test.go
index 9b57a04c..a18dcdf9 100644
--- a/internal/node/proxy_test.go
+++ b/internal/node/proxy_test.go
@@ -715,16 +715,16 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {
wantReceivedPathSuffix string
}{
{
- name: "Auth mapping with X-Sam-Authorization",
+ name: "Authorization passes through untouched to the destination",
pathSuffix: "/api/v1/test",
requestHeaders: map[string]string{
- "Authorization": "Bearer local-token",
- api.HeaderSamAuthorization: "Bearer upstream-token",
- "X-Test-Request": "yes",
+ "Authorization": "Bearer upstream-token",
+ api.HeaderSamAuthentication: "Bearer local-token",
+ "X-Test-Request": "yes",
},
wantReceivedHeaders: map[string]string{
"Authorization": "Bearer upstream-token",
- api.HeaderSamAuthorization: "", // Must be stripped
+ api.HeaderSamAuthentication: "", // Must be stripped, local-only
api.HeaderSamBiscuit: "", // Must be stripped
api.HeaderSamNoTrailingSlash: "", // Must be stripped
"X-Test-Request": "yes",
@@ -732,15 +732,15 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {
wantReceivedPathSuffix: "/api/v1/test",
},
{
- name: "Auth stripping when X-Sam-Authorization is absent",
+ name: "Local gate header stripped, no Authorization to pass through",
pathSuffix: "/api/v1/test",
requestHeaders: map[string]string{
- "Authorization": "Bearer local-token",
- "X-Test-Request": "yes",
+ api.HeaderSamAuthentication: "Bearer local-token",
+ "X-Test-Request": "yes",
},
wantReceivedHeaders: map[string]string{
- "Authorization": "", // Must be stripped to avoid leaking local sidecar token
- api.HeaderSamAuthorization: "",
+ "Authorization": "", // Nothing to pass through
+ api.HeaderSamAuthentication: "", // Must be stripped to avoid leaking local sidecar token
api.HeaderSamBiscuit: "",
api.HeaderSamNoTrailingSlash: "",
"X-Test-Request": "yes",
@@ -751,7 +751,7 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {
name: "Trailing slash handling with empty path",
pathSuffix: "", // Requesting the root of the service: .../dummy-tool
requestHeaders: map[string]string{
- "Authorization": "Bearer local-token",
+ api.HeaderSamAuthentication: "Bearer local-token",
},
wantReceivedHeaders: map[string]string{
api.HeaderSamNoTrailingSlash: "", // Must be stripped
diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go
index 61bf4e01..c77e7c1c 100644
--- a/internal/node/sidecar.go
+++ b/internal/node/sidecar.go
@@ -44,23 +44,26 @@ func StartSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile st
mux.HandleFunc("/healthz", handleHealthz)
mux.HandleFunc("/readyz", handleReadyz)
- // Protected endpoints
- mux.Handle("/sam/service/register", withAuth(token, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Protected endpoints. allowAuthorizationFallback=true is safe here: none of
+ // these ever forward the inbound Authorization header to another service.
+ mux.Handle("/sam/service/register", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handleRegisterService(node, w, r)
}))))
- mux.Handle("/sam/service/unregister", withAuth(token, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mux.Handle("/sam/service/unregister", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handleUnregisterService(node, w, r)
}))))
- mux.Handle("/sam/service/discover", withAuth(token, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mux.Handle("/sam/service/discover", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handleDiscoverService(node, w, r)
}))))
- // Mount Egress Proxy
- mux.Handle("/sam/", withAuth(token, withMeshConnection(node, createEgressProxy(node))))
+ // Mount Egress Proxy. allowAuthorizationFallback=false is required here: this
+ // handler forwards Authorization to the destination service, so it must never
+ // also accept it as the local gate credential (would leak the sidecar token off-node).
+ mux.Handle("/sam/", withAuth(token, false, withMeshConnection(node, createEgressProxy(node))))
// Mount MCP handler
mcpHandler := NewMCPHandler(node)
- mux.Handle("/", withAuth(token, withMeshConnection(node, mcpHandler)))
+ mux.Handle("/", withAuth(token, true, withMeshConnection(node, mcpHandler)))
server := &http.Server{
Handler: mux,
@@ -192,7 +195,15 @@ func withMeshConnection(node *SamNode, next http.Handler) http.Handler {
})
}
-func withAuth(token string, next http.Handler) http.Handler {
+// withAuth gates a handler behind the sidecar's shared-secret token.
+//
+// allowAuthorizationFallback additionally accepts the standard "Authorization"
+// header as the local gate credential, for endpoints that never forward it to
+// another service. It must be false for anything that proxies the request
+// onward (the egress/inference proxy), since there "Authorization" is reserved
+// exclusively for the destination's own credential and must never double as
+// (or leak) the local sidecar token.
+func withAuth(token string, allowAuthorizationFallback bool, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Debugf("[SidecarAuth] Incoming request: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
if token == "" {
@@ -202,16 +213,19 @@ func withAuth(token string, next http.Handler) http.Handler {
return
}
- authHeader := r.Header.Get("Authorization")
+ authHeader := r.Header.Get(api.HeaderSamAuthentication)
+ if authHeader == "" && allowAuthorizationFallback {
+ authHeader = r.Header.Get("Authorization")
+ }
if authHeader == "" {
- logger.Warnf("[SidecarAuth] Request %s %s rejected: missing Authorization header", r.Method, r.URL.Path)
- http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ logger.Warnf("[SidecarAuth] Request %s %s rejected: missing %s header", r.Method, r.URL.Path, api.HeaderSamAuthentication)
+ http.Error(w, fmt.Sprintf("Unauthorized: missing %q header, e.g. %q: \"Bearer <api-token>\"", api.HeaderSamAuthentication, api.HeaderSamAuthentication), http.StatusUnauthorized)
return
}
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
- http.Error(w, "Invalid authorization header format", http.StatusUnauthorized)
+ http.Error(w, fmt.Sprintf("Invalid %q header format, expected \"Bearer <api-token>\"", api.HeaderSamAuthentication), http.StatusUnauthorized)
return
}
@@ -486,14 +500,9 @@ func createEgressProxy(node *SamNode) http.Handler {
r.Header.Set(api.HeaderSamBiscuit, base64.StdEncoding.EncodeToString(biscuitBytes))
- // Map X-Sam-Authorization to Authorization header for the remote service,
- // and delete the local sidecar Authorization header to prevent leaking it.
- if upstreamAuth := r.Header.Get(api.HeaderSamAuthorization); upstreamAuth != "" {
- r.Header.Set("Authorization", upstreamAuth)
- r.Header.Del(api.HeaderSamAuthorization)
- } else {
- r.Header.Del("Authorization")
- }
+ // Strip the local sidecar gate header before forwarding off-node; a caller-supplied
+ // "Authorization" header passes straight through untouched as the destination's own credential.
+ r.Header.Del(api.HeaderSamAuthentication)
proxy.ServeHTTP(w, r)
})
diff --git a/internal/node/sidecar_test.go b/internal/node/sidecar_test.go
index 22203cad..d3e17a19 100644
--- a/internal/node/sidecar_test.go
+++ b/internal/node/sidecar_test.go
@@ -36,7 +36,7 @@ import (
func TestWithAuth(t *testing.T) {
token := "test-token"
- handler := withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := withAuth(token, true, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
@@ -71,7 +71,7 @@ func TestWithAuth(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/any", nil)
if tt.authHeader != "" {
- req.Header.Set("Authorization", tt.authHeader)
+ req.Header.Set(api.HeaderSamAuthentication, tt.authHeader)
}
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
@@ -82,12 +82,37 @@ func TestWithAuth(t *testing.T) {
})
}
+ t.Run("Authorization fallback accepted when allowed", func(t *testing.T) {
+ req := httptest.NewRequest("GET", "/any", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Errorf("expected status %d, got %d", http.StatusOK, rr.Code)
+ }
+ })
+
+ t.Run("Authorization fallback rejected in strict mode", func(t *testing.T) {
+ strictHandler := withAuth(token, false, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ req := httptest.NewRequest("GET", "/any", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+ rr := httptest.NewRecorder()
+ strictHandler.ServeHTTP(rr, req)
+
+ if rr.Code != http.StatusUnauthorized {
+ t.Errorf("expected status %d, got %d", http.StatusUnauthorized, rr.Code)
+ }
+ })
+
t.Run("Empty token configured", func(t *testing.T) {
- handlerEmpty := withAuth("", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handlerEmpty := withAuth("", true, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest("GET", "/any", nil)
- req.Header.Set("Authorization", "Bearer anything")
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer anything")
rr := httptest.NewRecorder()
handlerEmpty.ServeHTTP(rr, req)
@@ -161,7 +186,7 @@ func TestSidecarServerAuthEnforcement(t *testing.T) {
t.Fatalf("Failed to create request: %v", err)
}
if tt.needsToken {
- req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)
}
resp, err := client.Do(req)
@@ -179,6 +204,73 @@ func TestSidecarServerAuthEnforcement(t *testing.T) {
}
}
+// TestSidecarAuthorizationFallbackScope verifies that plain "Authorization" is
+// only accepted as a local-gate credential on endpoints that never forward it
+// (register/unregister/discover, mcp), and rejected on the egress proxy, which
+// must forward "Authorization" untouched to the destination service.
+func TestSidecarAuthorizationFallbackScope(t *testing.T) {
+ node := &SamNode{
+ BiscuitTimeout: 500 * time.Millisecond,
+ services: NewServiceRegistry(&fakeDHT{}),
+ }
+ token := "test-token"
+
+ sidecarSrv, err := StartSidecarServer(node, "127.0.0.1:0", token, "", "", "")
+ if err != nil {
+ t.Fatalf("Failed to start sidecar server: %v", err)
+ }
+ defer func() { _ = sidecarSrv.Close() }()
+
+ baseURL := "http://" + node.BoundHTTPAddr
+ client := &http.Client{Timeout: 2 * time.Second}
+ ready := false
+ for i := 0; i < 50; i++ {
+ time.Sleep(10 * time.Millisecond)
+ resp, err := client.Get(baseURL + "/healthz")
+ if err == nil {
+ _ = resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ ready = true
+ break
+ }
+ }
+ }
+ if !ready {
+ t.Fatalf("Sidecar server failed to become ready")
+ }
+
+ tests := []struct {
+ name string
+ method string
+ path string
+ expectedStatus int // status once past the auth gate (may still be a downstream error)
+ }{
+ {"discover accepts Authorization fallback", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusServiceUnavailable},
+ {"mcp root accepts Authorization fallback", "GET", "/mcp", http.StatusServiceUnavailable},
+ {"egress proxy rejects Authorization fallback", "GET", "/sam/", http.StatusUnauthorized},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req, err := http.NewRequest(tt.method, baseURL+tt.path, nil)
+ if err != nil {
+ t.Fatalf("Failed to create request: %v", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("Request failed: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != tt.expectedStatus {
+ t.Errorf("expected status %d for %s, got %d", tt.expectedStatus, tt.path, resp.StatusCode)
+ }
+ })
+ }
+}
+
func TestHandleRegisterService(t *testing.T) {
h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))
if err != nil {
diff --git a/sam-mcp-python/src/sam_mcp/client.py b/sam-mcp-python/src/sam_mcp/client.py
index c35f8193..7043d1bc 100644
--- a/sam-mcp-python/src/sam_mcp/client.py
+++ b/sam-mcp-python/src/sam_mcp/client.py
@@ -22,7 +22,7 @@ class SamClient:
import httpx
headers = {"Accept": "application/json, text/event-stream"}
if self.token:
- headers["Authorization"] = f"Bearer {self.token}"
+ headers["X-Sam-Authentication"] = f"Bearer {self.token}"
self._http_client = httpx.AsyncClient(headers=headers)
try:
diff --git a/site/content/docs/development/testnet-validation.md b/site/content/docs/development/testnet-validation.md
index eeaeb626..b4c6bec3 100644
--- a/site/content/docs/development/testnet-validation.md
+++ b/site/content/docs/development/testnet-validation.md
@@ -101,7 +101,7 @@ Initiate a handshake by sending a POST `initialize` JSON-RPC request. You must s
```bash
curl -i -X POST \
- -H "Authorization: Bearer secret-token" \
+ -H "X-Sam-Authentication: Bearer secret-token" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}' \
@@ -120,7 +120,7 @@ Use the returned session ID to query the remote service's resource list:
```bash
curl -s -X POST \
- -H "Authorization: Bearer secret-token" \
+ -H "X-Sam-Authentication: Bearer secret-token" \
-H "Mcp-Session-Id: 4616e90e-a1a9-4953-b7d3-6884ff502472" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
@@ -133,7 +133,7 @@ Request the contents of a specific resource URI (e.g. `demo://resource/static/do
```bash
curl -s -X POST \
- -H "Authorization: Bearer secret-token" \
+ -H "X-Sam-Authentication: Bearer secret-token" \
-H "Mcp-Session-Id: 4616e90e-a1a9-4953-b7d3-6884ff502472" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
diff --git a/site/content/docs/integrations/antigravity.md b/site/content/docs/integrations/antigravity.md
index 54b9b554..fd3c8907 100644
--- a/site/content/docs/integrations/antigravity.md
+++ b/site/content/docs/integrations/antigravity.md
@@ -26,7 +26,7 @@ Add the node directly using its HTTP endpoint (replace `<YOUR_TOKEN>` with your
"sam-mesh": {
"serverUrl": "http://localhost:8080/mcp",
"headers": {
- "Authorization": "Bearer <YOUR_TOKEN>"
+ "X-Sam-Authentication": "Bearer <YOUR_TOKEN>"
}
}
}
diff --git a/site/content/docs/integrations/claude-code.md b/site/content/docs/integrations/claude-code.md
index d4b1f204..d6bfda74 100644
--- a/site/content/docs/integrations/claude-code.md
+++ b/site/content/docs/integrations/claude-code.md
@@ -21,7 +21,7 @@ Register the node as an HTTP MCP server. Replace `<YOUR_TOKEN>` with your `--api
```bash
claude mcp add --transport http p2p-mesh-node \
http://localhost:8080/mcp \
- --header "Authorization: Bearer <YOUR_TOKEN>"
+ --header "X-Sam-Authentication: Bearer <YOUR_TOKEN>"
```
By default the server is added at *local* scope (the current project only). Add `--scope user` to make it available in all your projects, or `--scope project` to write a shareable `.mcp.json` into your repository.
@@ -35,7 +35,7 @@ Alternatively, add it to a project `.mcp.json` directly:
"type": "http",
"url": "http://localhost:8080/mcp",
"headers": {
- "Authorization": "Bearer <YOUR_TOKEN>"
+ "X-Sam-Authentication": "Bearer <YOUR_TOKEN>"
}
}
}
@@ -65,7 +65,7 @@ Claude Code calls the tools `sam-node` exposes like any other tool. The flow mir
## Troubleshooting
-* **Connection shows failed / 401**: verify the `Authorization` header matches the node's `--api-token`.
+* **Connection shows failed / 401**: verify the `X-Sam-Authentication` header matches the node's `--api-token`.
* **Server unreachable**: confirm `sam-node` is listening (default `http://localhost:8080`).
* **Tools not visible**: MCP servers load at session start — restart Claude Code and check `/mcp`.
* **Remove the server**: `claude mcp remove p2p-mesh-node -s user` (match the scope you used to add it).
diff --git a/site/content/docs/integrations/claude-desktop.md b/site/content/docs/integrations/claude-desktop.md
index 7acf2ed6..022c8b23 100644
--- a/site/content/docs/integrations/claude-desktop.md
+++ b/site/content/docs/integrations/claude-desktop.md
@@ -36,7 +36,7 @@ Add the node through the `mcp-remote` bridge (replace `<YOUR_TOKEN>` with your `
"http://localhost:8080/mcp",
"--allow-http",
"--header",
- "Authorization: Bearer <YOUR_TOKEN>"
+ "X-Sam-Authentication: Bearer <YOUR_TOKEN>"
]
}
}
diff --git a/site/content/docs/integrations/openclaw.md b/site/content/docs/integrations/openclaw.md
index a61a3b57..d5f82b8a 100644
--- a/site/content/docs/integrations/openclaw.md
+++ b/site/content/docs/integrations/openclaw.md
@@ -19,7 +19,7 @@ openclaw mcp set p2p-mesh-node '{
"url": "http://localhost:8080/mcp",
"transport": "sse",
"headers": {
- "Authorization": "Bearer <YOUR_TOKEN>"
+ "X-Sam-Authentication": "Bearer <YOUR_TOKEN>"
}
}'
```
@@ -55,5 +55,5 @@ Because these tools are surfaced automatically, no remote tool needs to be regis
## Troubleshooting
* Connection Issues: Ensure `sam-node` is reachable at the configured URL (default `http://localhost:8080/mcp`).
-* Authentication: Double-check that the `Authorization` header matches the `--api-token` provided to your `sam-node`.
+* Authentication: Double-check that the `X-Sam-Authentication` header matches the `--api-token` provided to your `sam-node`.
* Gateway Status: Use `openclaw status` to confirm the gateway is running and the MCP bridge is active.
diff --git a/site/content/docs/use-cases/gemini-buddy.md b/site/content/docs/use-cases/gemini-buddy.md
index 741b9dc7..5087ff07 100644
--- a/site/content/docs/use-cases/gemini-buddy.md
+++ b/site/content/docs/use-cases/gemini-buddy.md
@@ -112,7 +112,7 @@ but the settings are always the same:
- **Transport:** HTTP (Streamable HTTP / `http`)
- **URL:** `http://127.0.0.1:9099/mcp`
-- **Header:** `Authorization: Bearer devtoken`
+- **Header:** `X-Sam-Authentication: Bearer devtoken`
For example, harnesses that use the common `mcpServers` JSON config (Claude Code,
Cursor, and others) would add:
@@ -123,7 +123,7 @@ Cursor, and others) would add:
"sam-mesh": {
"type": "http",
"url": "http://127.0.0.1:9099/mcp",
- "headers": { "Authorization": "Bearer devtoken" }
+ "headers": { "X-Sam-Authentication": "Bearer devtoken" }
}
}
}
diff --git a/site/content/docs/use-cases/warm-agent-pool.md b/site/content/docs/use-cases/warm-agent-pool.md
index 3c423bde..f7a56f58 100644
--- a/site/content/docs/use-cases/warm-agent-pool.md
+++ b/site/content/docs/use-cases/warm-agent-pool.md
@@ -135,7 +135,7 @@ but the settings are always the same:
- **Transport:** HTTP (Streamable HTTP / `http`)
- **URL:** `http://127.0.0.1:9099/mcp`
-- **Header:** `Authorization: Bearer devtoken`
+- **Header:** `X-Sam-Authentication: Bearer devtoken`
For example, harnesses that use the common `mcpServers` JSON config (Claude Code,
Cursor, and others) would add:
@@ -146,7 +146,7 @@ Cursor, and others) would add:
"sam-mesh": {
"type": "http",
"url": "http://127.0.0.1:9099/mcp",
- "headers": { "Authorization": "Bearer devtoken" }
+ "headers": { "X-Sam-Authentication": "Bearer devtoken" }
}
}
}
diff --git a/site/content/docs/user/agent-usage.md b/site/content/docs/user/agent-usage.md
index 9e7043cc..5d25d8fc 100644
--- a/site/content/docs/user/agent-usage.md
+++ b/site/content/docs/user/agent-usage.md
@@ -30,7 +30,7 @@ sequenceDiagram
Note over User,Agent: Phase 2: Agent Tool Invocation
User->>Node: sam-node run --api-token "secret-key"
Node->>Node: Start local MCP server on 127.0.0.1:8080
- Agent->>Node: Connect to local MCP (with Bearer "secret-key")
+ Agent->>Node: Connect to local MCP (X-Sam-Authentication: Bearer "secret-key")
Agent->>Node: Call Remote P2P Tool
Node->>Hub: Verify Biscuit / Allowed Policies
Node-->>Agent: Execute tool and return result
@@ -91,10 +91,21 @@ The local MCP endpoint is served via **HTTP Server-Sent Events (SSE)** at:
`http://127.0.0.1:8080/mcp`
### Authentication
-When configuring your agent client, you must pass the API token in the headers:
+When configuring your agent client, you must pass the API token in a SAM-specific
+header — not the standard `Authorization` header:
```http
-Authorization: Bearer my-agent-super-token-123
+X-Sam-Authentication: Bearer my-agent-super-token-123
```
+This leaves `Authorization` free to always mean the credential for whatever
+remote service you're calling *through* the node (e.g. a `mcp://` or
+`inference://` service that requires its own upstream credential) — it passes
+straight through untouched and is never used to authenticate to the node itself.
+
+> For MCP clients that only support a plain `Authorization` header, the `/mcp`
+> endpoint (and the `/sam/service/*` control endpoints) also accept it as a
+> compatibility alias, since they never forward it anywhere. The egress/inference
+> proxy (`/sam/<peer>/...`) does **not** accept this fallback — there,
+> `Authorization` is reserved exclusively for the destination's own credential.
### Specific Integration Guides
Explore our step-by-step guides for integrating your node with popular agent clients:
diff --git a/tests/e2e/datapath.bats b/tests/e2e/datapath.bats
index f5fd9a07..5dfa7c75 100644
--- a/tests/e2e/datapath.bats
+++ b/tests/e2e/datapath.bats
@@ -98,7 +98,7 @@ req = urllib.request.Request(
\"http://${node1_name}:8080/sam/service/register\",
data=json.dumps(data).encode(\"utf-8\"),
headers={
- \"Authorization\": \"Bearer secret-token\",
+ \"X-Sam-Authentication\": \"Bearer secret-token\",
\"Content-Type\": \"application/json\"
}
)
@@ -131,7 +131,7 @@ req = urllib.request.Request(
'http://${node2_name}:8080/sam/service/register',
data=json.dumps(data).encode('utf-8'),
headers={
- 'Authorization': 'Bearer secret-token',
+ 'X-Sam-Authentication': 'Bearer secret-token',
'Content-Type': 'application/json'
}
)
@@ -154,7 +154,7 @@ with urllib.request.urlopen(req) as response:
import urllib.request
req = urllib.request.Request(
\"http://${node2_name}:8080/sam/${node1_peer_id}/mcp/http-tool/\",
- headers={\"Authorization\": \"Bearer secret-token\"}
+ headers={\"X-Sam-Authentication\": \"Bearer secret-token\"}
)
with urllib.request.urlopen(req) as response:
print(response.read().decode(\"utf-8\"))
@@ -180,7 +180,7 @@ with urllib.request.urlopen(req) as response:
import urllib.request
req = urllib.request.Request(
\"http://${node1_name}:8080/sam/${node2_peer_id}/mcp/stdio-tool/\",
- headers={\"Authorization\": \"Bearer secret-token\"}
+ headers={\"X-Sam-Authentication\": \"Bearer secret-token\"}
)
try:
with urllib.request.urlopen(req) as response:
@@ -210,7 +210,7 @@ req = urllib.request.Request(
\"http://${node1_name}:8080/sam/${node2_peer_id}/mcp/stdio-tool/\",
data=os.environ['MSG'].encode('utf-8'),
headers={
- \"Authorization\": \"Bearer secret-token\",
+ \"X-Sam-Authentication\": \"Bearer secret-token\",
\"Content-Type\": \"application/json\"
}
)
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index 0b5982bb..789d22bd 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -96,7 +96,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
local timeout_s="${2:-20}"
local i
for ((i=0; i<timeout_s; i++)); do
- if docker run --rm --network "${MESH_NETWORK}" python:3.12 curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer secret-token" -d '{"jsonrpc":"2.0","method":"ping","id":1}' --max-time 5 -D - http://${MESH_PREFIX}-node-${idx}:8080/mcp | grep -q "200 OK"; then
+ if docker run --rm --network "${MESH_NETWORK}" python:3.12 curl -s -X POST -H "Content-Type: application/json" -H "X-Sam-Authentication: Bearer secret-token" -d '{"jsonrpc":"2.0","method":"ping","id":1}' --max-time 5 -D - http://${MESH_PREFIX}-node-${idx}:8080/mcp | grep -q "200 OK"; then
return 0
fi
sleep 1
diff --git a/tests/e2e/relay.bats b/tests/e2e/relay.bats
index ad0d6d92..8b37af96 100644
--- a/tests/e2e/relay.bats
+++ b/tests/e2e/relay.bats
@@ -144,7 +144,7 @@ req = urllib.request.Request(
data=json.dumps(data).encode('utf-8'),
headers={
\"Content-Type\": \"application/json\",
- \"Authorization\": \"Bearer secret-token\"
+ \"X-Sam-Authentication\": \"Bearer secret-token\"
},
method=\"POST\"
)
@@ -160,7 +160,7 @@ with urllib.request.urlopen(req) as response:
import urllib.request
req = urllib.request.Request(
\"http://${MESH_PREFIX}-node-2:8080/sam/${node1_peer_id}/mcp/http-tool/\",
- headers={\"Authorization\": \"Bearer secret-token\"}
+ headers={\"X-Sam-Authentication\": \"Bearer secret-token\"}
)
with urllib.request.urlopen(req) as response:
print(response.read().decode(\"utf-8\"))
diff --git a/tests/integration/auth_test.go b/tests/integration/auth_test.go
index 54a12782..b51ef636 100644
--- a/tests/integration/auth_test.go
+++ b/tests/integration/auth_test.go
@@ -22,6 +22,8 @@ import (
"path/filepath"
"testing"
"time"
+
+ "github.com/google/sam/api"
)
func TestNodeAuthEnforcementIntegration(t *testing.T) {
@@ -109,7 +111,7 @@ func TestNodeAuthEnforcementIntegration(t *testing.T) {
t.Fatalf("Failed to create request: %v", err)
}
if tt.needsToken {
- req.Header.Set("Authorization", "Bearer "+apiToken)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)
}
resp, err := client.Do(req)
diff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.go
index 9fe87fe8..44e7bbd3 100644
--- a/tests/integration/catalog_test.go
+++ b/tests/integration/catalog_test.go
@@ -11,6 +11,7 @@ import (
"testing"
"time"
+ "github.com/google/sam/api"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
@@ -121,7 +122,7 @@ type authRoundTripper struct {
func (a *authRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
clone := req.Clone(req.Context())
- clone.Header.Set("Authorization", "Bearer "+a.token)
+ clone.Header.Set(api.HeaderSamAuthentication, "Bearer "+a.token)
return a.rt.RoundTrip(clone)
}
diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.go
index 1e8de91e..10335f45 100644
--- a/tests/integration/datapath_test.go
+++ b/tests/integration/datapath_test.go
@@ -93,7 +93,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {
}
req, _ := http.NewRequest("POST", "http://"+actualApiAddrA+"/sam/service/register", bytes.NewBuffer(body))
- req.Header.Set("Authorization", "Bearer "+apiToken)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
@@ -121,7 +121,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {
var postResp *http.Response
for i := 0; i < 3; i++ {
postReq, _ := http.NewRequest("POST", postURL, bytes.NewBufferString(testMessage))
- postReq.Header.Set("Authorization", "Bearer "+apiToken)
+ postReq.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)
postReq.Header.Set("Content-Type", "application/json")
postReq.Header.Set("Accept", "application/json")
@@ -223,7 +223,7 @@ func TestIntegrationHTTPDatapath(t *testing.T) {
}
req, _ := http.NewRequest("POST", "http://"+actualApiAddrA+"/sam/service/register", bytes.NewBuffer(body))
- req.Header.Set("Authorization", "Bearer "+apiToken)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
@@ -245,7 +245,7 @@ func TestIntegrationHTTPDatapath(t *testing.T) {
var httpResp *http.Response
for i := 0; i < 3; i++ {
req, _ := http.NewRequest("GET", url, nil)
- req.Header.Set("Authorization", "Bearer "+apiToken)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)
req.Close = true // Force close the connection so the libp2p stream terminates and flushed accounting logs
httpResp, err = client.Do(req)
if err == nil && httpResp.StatusCode == http.StatusOK {
diff --git a/tests/integration/federation_test.go b/tests/integration/federation_test.go
index 30c2a0f1..f9d42562 100644
--- a/tests/integration/federation_test.go
+++ b/tests/integration/federation_test.go
@@ -304,7 +304,7 @@ roles:
// The proxy path on Node B is /sam/<peerID>/mcp/federated-tool
proxyURL := fmt.Sprintf("http://127.0.0.1:%d/sam/%s/mcp/federated-tool", apiPortB, peerIDA_node)
req, _ := http.NewRequest("POST", proxyURL, bytes.NewBuffer([]byte(`{"jsonrpc": "2.0", "id": 1, "method": "test"}`)))
- req.Header.Set("Authorization", "Bearer tokenB")
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer tokenB")
resp, err := http.DefaultClient.Do(req)
if err != nil {
diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.go
index f01450dd..93164bc8 100644
--- a/tests/integration/service_discovery_test.go
+++ b/tests/integration/service_discovery_test.go
@@ -214,7 +214,7 @@ func TestServiceDiscoveryStreaming(t *testing.T) {
// Call streaming endpoint with invalid timeout first to verify validation
t.Log("Testing invalid timeout query parameter...")
badReq, _ := http.NewRequest("GET", "http://"+actualApiAddrB+"/sam/service/discover?type=mcp&name="+serviceName+"&stream=true&timeout=invalid", nil)
- badReq.Header.Set("Authorization", "Bearer "+apiToken)
+ badReq.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)
badResp, err := http.DefaultClient.Do(badReq)
if err != nil {
t.Fatal(err)
@@ -227,7 +227,7 @@ func TestServiceDiscoveryStreaming(t *testing.T) {
// Agent B queries the streaming endpoint via HTTP Sidecar
t.Log("Agent B discovering service via SSE stream...")
req, _ := http.NewRequest("GET", "http://"+actualApiAddrB+"/sam/service/discover?type=mcp&name="+serviceName+"&stream=true&timeout=5s", nil)
- req.Header.Set("Authorization", "Bearer "+apiToken)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
@@ -313,7 +313,7 @@ func registerService(t *testing.T, apiAddr, token, serviceName, targetURL string
t.Fatal(err)
}
req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/register", bytes.NewBuffer(body))
- req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
@@ -332,7 +332,7 @@ func unregisterService(t *testing.T, apiAddr, token, serviceName string) {
reqBody := map[string]string{"Name": serviceName}
body, _ := json.Marshal(reqBody)
req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/unregister", bytes.NewBuffer(body))
- req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
@@ -348,7 +348,7 @@ func unregisterService(t *testing.T, apiAddr, token, serviceName string) {
func discoverService(t *testing.T, apiAddr, token, serviceName string) []peer.AddrInfo {
t.Helper()
req, _ := http.NewRequest("GET", "http://"+apiAddr+"/sam/service/discover?type=mcp&name="+serviceName, nil)
- req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {