Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node: attribute tool calls to their agent, as inference already was
Antonio Ojead204616256ca
diff --git a/api/sam.pb.go b/api/sam.pb.goindex 6dd40d98..432aacc2 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -189,6 +189,11 @@ type AuthFrame struct {state protoimpl.MessageState `protogen:"open.v1"`Biscuit []byte `protobuf:"bytes,1,opt,name=biscuit,proto3" json:"biscuit,omitempty"`TargetService string `protobuf:"bytes,2,opt,name=target_service,json=targetService,proto3" json:"target_service,omitempty"` // Optional: specific service requested+ // The agent this request is made for, as a canonical agent identifier (see+ // api/agent.go). It is the calling node's claim, carried beside the token+ // because Biscuit hides an appended block's facts from the authorizer; the+ // HTTP datapath carries the same claim in HeaderSamAgent.+ Agent string `protobuf:"bytes,3,opt,name=agent,proto3" json:"agent,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -237,6 +242,13 @@ func (x *AuthFrame) GetTargetService() string {return ""}+func (x *AuthFrame) GetAgent() string {+ if x != nil {+ return x.Agent+ }+ return ""+}+type AuthResponse struct {state protoimpl.MessageState `protogen:"open.v1"`Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"`@@ -2674,10 +2686,11 @@ var File_api_sam_proto protoreflect.FileDescriptorconst file_api_sam_proto_rawDesc = "" +"\n" +- "\rapi/sam.proto\x12\x06sam.v1\"L\n" ++ "\rapi/sam.proto\x12\x06sam.v1\"b\n" +"\tAuthFrame\x12\x18\n" +"\abiscuit\x18\x01 \x01(\fR\abiscuit\x12%\n" +- "\x0etarget_service\x18\x02 \x01(\tR\rtargetService\"X\n" ++ "\x0etarget_service\x18\x02 \x01(\tR\rtargetService\x12\x14\n" ++ "\x05agent\x18\x03 \x01(\tR\x05agent\"X\n" +"\fAuthResponse\x12\x18\n" +"\asuccess\x18\x01 \x01(\bR\asuccess\x12\x14\n" +"\x05error\x18\x02 \x01(\tR\x05error\x12\x18\n" +diff --git a/api/sam.proto b/api/sam.protoindex c879f327..5bf90237 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -21,6 +21,12 @@ option go_package = "github.com/google/sam/api";message AuthFrame {bytes biscuit = 1;string target_service = 2; // Optional: specific service requested++ // The agent this request is made for, as a canonical agent identifier (see+ // api/agent.go). It is the calling node's claim, carried beside the token+ // because Biscuit hides an appended block's facts from the authorizer; the+ // HTTP datapath carries the same claim in HeaderSamAgent.+ string agent = 3;}message AuthResponse {diff --git a/internal/node/agent.go b/internal/node/agent.goindex b0201293..f24a6de8 100644--- a/internal/node/agent.go+++ b/internal/node/agent.go@@ -15,6 +15,7 @@package nodeimport (+ "context""net/http""github.com/google/sam/api"@@ -24,23 +25,23 @@ import (// sandbox a mesh identity is the cost this design exists to avoid. So the node// it runs behind speaks for it, naming the agent alongside its own token.//-// What this covers: attribution and policy on the HTTP datapath. A peer can+// What this covers: attribution and policy on both datapaths. A peer can// authorize and audit "agent reviewer-7 called me", not merely "some node did",// and it can do so with the existing vocabulary because the claim is injected-// as an ordinary agent() fact.+// as an ordinary agent() fact. HTTP requests carry it in api.HeaderSamAgent;+// libp2p streams carry it in the AuthFrame, bound to the MCP session rather+// than the request, since the SDK gives a tool handler the session's context.//// What it does not cover, and cannot://// - Proof. The claim is the calling node's word. A node that lies can name// any agent, so a mesh that cares must also constrain which peers may speak// for which agent namespaces. This is not a weakness of carrying the claim-// in a header: an appended Biscuit block would be exactly as forgeable by-// the same party, and is invisible to the authorizer besides (see+// beside the token: an appended Biscuit block would be exactly as forgeable+// by the same party, and is invisible to the authorizer besides (see// internal/identity's TestAttenuationBlockFactsAreInvisibleToTheAuthorizer).// Only a block signed by the agent's own key would be proof, which needs// third-party blocks that biscuit-go does not implement.-// - The stream datapath. MCP tool calls authenticate over a libp2p stream-// with an AuthFrame rather than HTTP headers, and carry no agent yet.// - Anything an agent does that never leaves its node.//// One consequence worth knowing before writing such a policy: a node's own@@ -79,3 +80,26 @@ func agentClaim(agentID string) string {}return agentID}++type agentContextKey struct{}++// contextWithAgent carries the agent an MCP session belongs to down to the code+// that opens streams on its behalf.+//+// The MCP SDK hands a tool handler the session's context, not the HTTP+// request's, so the agent is bound once when the session's server is built+// (NewMCPHandler) rather than read per request. That matches how sandboxes+// work: one gateway serves one agent, so one session belongs to one agent for+// its whole life.+func contextWithAgent(ctx context.Context, agentID string) context.Context {+ if agentID == "" {+ return ctx+ }+ return context.WithValue(ctx, agentContextKey{}, agentID)+}++// agentFromContext returns the agent a request is being made for, if any.+func agentFromContext(ctx context.Context) string {+ agentID, _ := ctx.Value(agentContextKey{}).(string)+ return agentID+}diff --git a/internal/node/mcp.go b/internal/node/mcp.goindex 1af9dcee..f2bd8d19 100644--- a/internal/node/mcp.go+++ b/internal/node/mcp.go@@ -21,6 +21,7 @@ import ("fmt""net/http""strings"+ "sync""time""github.com/google/sam/api"@@ -218,11 +219,13 @@ func NewUnauthenticatedMCPHandler(controlPlaneURL string) http.Handler {// NewMCPHandler creates a new HTTP handler for the MCP server using the official SDK.func NewMCPHandler(node *SamNode) http.Handler {- mcpServer := NewMCPServer(node)+ servers := &agentMCPServers{node: node}- // Create the Streamable handler using the SDK+ // Per agent, not per node: the SDK gives a tool handler the session's+ // context rather than the request's, so the only place to bind who the+ // session belongs to is where the session's server is chosen.streamableHandler := mcp.NewStreamableHTTPHandler(func(request *http.Request) *mcp.Server {- return mcpServer+ return servers.forAgent(agentFromLocalGateway(request))}, nil)mux := http.NewServeMux()@@ -237,6 +240,40 @@ func NewMCPHandler(node *SamNode) http.Handler {return wrappedHandler}+// agentMCPServers hands out one server per agent, built on first use. A node+// serves a handful of sandboxes, so this stays small; without it every request+// would rebuild the whole tool set.+type agentMCPServers struct {+ node *SamNode++ mu sync.Mutex+ servers map[string]*mcp.Server+}++func (s *agentMCPServers) forAgent(agentID string) *mcp.Server {+ s.mu.Lock()+ defer s.mu.Unlock()++ if server, ok := s.servers[agentID]; ok {+ return server+ }++ server := NewMCPServer(s.node)+ if agentID != "" {+ server.AddReceivingMiddleware(func(next mcp.MethodHandler) mcp.MethodHandler {+ return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {+ return next(contextWithAgent(ctx, agentID), method, req)+ }+ })+ }++ if s.servers == nil {+ s.servers = make(map[string]*mcp.Server)+ }+ s.servers[agentID] = server+ return server+}+// CallMCPTool opens a stream to a remote peer, performs the handshake, and calls a tool.// CallMCPTool opens a stream to a remote peer, performs the handshake, and calls a tool.// requiredLabels, when non-empty, fail-closed verifies the peer's control-plane-attested@@ -259,6 +296,13 @@ func (n *SamNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, toolNamelogger.Warnf("[MCP] Tool call failed with timeout or cancellation, not retrying: %v", err)return nil, err}+ // A denial is an answer, not a failure to reach anyone. Retrying it+ // just delays the same reply and knocks on the remote peer three times+ // for one call.+ if errors.Is(err, ErrAuthRejected) {+ logger.Warnf("[MCP] Tool call denied, not retrying: %v", err)+ return nil, err+ }logger.Warnf("[MCP] Tool call failed, retrying in %v: %v", backoff, err)timer := time.NewTimer(backoff)select {@@ -329,6 +373,7 @@ func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, tarauthFrame := api.AuthFrame{Biscuit: biscuitBytes,TargetService: targetService,+ Agent: agentFromContext(ctx),}authBytes, _ := proto.Marshal(&authFrame)diff --git a/internal/node/middleware.go b/internal/node/middleware.goindex ba49c3fc..b41ac712 100644--- a/internal/node/middleware.go+++ b/internal/node/middleware.go@@ -133,6 +133,7 @@ func (n *SamNode) WithBiscuitAuth(next func(network.Stream, RequestContext)) netUser: "", // Not used in AuthorizeProtocol: string(ts.Protocol()),Target: authFrame.TargetService,+ Agent: agentClaim(authFrame.GetAgent()),}writer := msgio.NewVarintWriter(ts)diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.mdindex 95503870..97abe752 100644--- a/site/content/docs/agent-architecture.md+++ b/site/content/docs/agent-architecture.md@@ -531,12 +531,20 @@ and non-repudiation arrives without a wire break.### 10.2.1 What the agent claim covers, and what it does not-**Covers.** Attribution and policy on the HTTP datapath. A peer can authorize+**Covers.** Attribution and policy on **both** datapaths. A peer can authorizeand audit "agent `reviewer-7` called me" rather than only "some node did", usingthe existing vocabulary, because the claim is injected as an ordinary `agent()`fact. `TestAgentPolicyCUJ` shows two agents behind two gateways on one node-being told apart by the provider's policy, including a lookalike authority being-refused and an unidentified sandbox being refused.+being told apart by the provider's policy — over HTTP for inference and over the+libp2p stream for tool calls — including a lookalike authority being refused and+an unidentified sandbox being refused.++The two paths carry it differently because they authenticate differently: HTTP+requests carry `X-Sam-Agent`, and streams carry `AuthFrame.agent`. On the stream+path the claim is bound to the MCP *session* rather than the request, since the+SDK hands a tool handler the session's context and not the request's. That fits+how sandboxes work anyway: one gateway serves one agent, so a session belongs to+one agent for its whole life.**Does not cover.**@@ -544,9 +552,6 @@ refused and an unidentified sandbox being refused.agent, so a mesh that cares must also constrain which peers may speak forwhich agent namespaces. Carrying it in a header rather than a block costsnothing here: an appended block is exactly as forgeable by the same party.-* **The stream datapath.** MCP tool calls authenticate over a libp2p stream with- an `AuthFrame`, not HTTP headers, and carry no agent yet. Inference does;- tools do not.* **Anything that never leaves the node**, which the boundary already gateslocally.diff --git a/tests/integration/agent_policy_test.go b/tests/integration/agent_policy_test.goindex 1a4b5175..d5d3669c 100644--- a/tests/integration/agent_policy_test.go+++ b/tests/integration/agent_policy_test.go@@ -15,14 +15,18 @@package integration_testimport (+ "context""encoding/json""net/http""net/http/httptest""os""path/filepath"+ "strings""testing""time"+ "github.com/modelcontextprotocol/go-sdk/mcp"+"github.com/google/sam/api")@@ -144,6 +148,61 @@ attenuation:}})}++ // The same policy, over the stream datapath. Tool calls authenticate with an+ // AuthFrame rather than HTTP headers, so this is a genuinely separate path+ // and used to be unattributed while inference was not.+ t.Run("tool calls carry the agent too", func(t *testing.T) {+ tools := httptest.NewServer(newBoundaryMCPHandler(t))+ defer tools.Close()+ registerService(t, apiAddrA, apiToken, "calc", tools.URL)++ peerA := extractPeerID(addrA)++ for i, tc := range []struct {+ name string+ agentID string+ wantAllow bool+ }{+ {name: "an agent the provider accepts", agentID: "reviewer-9.prod.acme.example", wantAllow: true},+ {name: "an agent it does not", agentID: "auditor-2.staging.acme.example"},+ {name: "an unidentified sandbox"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ agentSocket := filepath.Join(sockDir, "tool"+string(rune('a'+i))+".sock")+ startBoundaryForAgent(t, agentSocket, nodeSocket, tc.agentID)++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()++ session := connectMCPThroughBoundary(t, ctx, boundaryClient(t, agentSocket))+ defer func() { _ = session.Close() }()++ res, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "call_remote_tool",+ Arguments: map[string]any{+ "peer_id": peerA,+ "tool_name": "mcp://calc/add",+ "arguments": map[string]any{},+ },+ })+ if err != nil {+ t.Fatalf("call_remote_tool: %v", err)+ }++ var got string+ for _, content := range res.Content {+ if text, ok := content.(*mcp.TextContent); ok {+ got += text.Text+ }+ }+ reached := strings.Contains(got, "fake-result:add")+ if reached != tc.wantAllow {+ t.Errorf("tool reached = %v, want %v; result was %q", reached, tc.wantAllow, got)+ }+ })+ }+ })}// waitForDiscoverableService polls until a peer offering the service is visible,