Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk/meshnet: address PR review comments and add developer guide + examples
Antonio Ojea1a7874c351e5
diff --git a/AGENTS.md b/AGENTS.mdindex 9cf4156f..3f1f4ff9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,7 +10,7 @@ You are an expert software engineering assistant helping to develop, maintain, a* **Datalog text is the policy contract:** the control plane renders the mesh policy as Datalog rules (`PolicyConfigGetResponse.datalog_rules`); every member, in any language, adds that text to its authorizer and none derives rules from roles and bindings itself. Datalog must stay in the form every Biscuit implementation parses: a predicate carries at least one term (presence-only facts are `name(true)`, see `api.MarkerFact`).* **Secrets never travel as flag values:** binaries read credentials from a file (`--*-path`) or the environment, never from a command-line argument that would sit in `ps` output and shell history. Banners and logs name the source of an operator-supplied secret instead of echoing it.* **Task-Scoped Authorization & Safe Biscuit Attenuation (`tar_block`):** Agent Mesh acts as the Authority, Policy Decision Point (PDP), and Task-Scoped Credential Layer (`site/content/docs/contributing/security-architecture.md`). Never add Datalog rules or checks to non-authority Biscuit blocks (`block_idx >= 1`). Appended blocks must contain 0 rules, 0 checks, and exactly 1 `tar_block("<base64url-proto>")` fact encoding a serialized `api.TaskAuthorizationRule`. Verifiers enforce the intersection of Block 0 Datalog RBAC and every appended `TaskAuthorizationRule` in Go, TypeScript, and Python.-* **Two-Token Model & Complementary Gateway/PEP Integration:** Inside the mesh, credentials are Biscuits; at both borders, credentials are standard JWTs (`site/content/docs/contributing/security-architecture.md`). Inbound platform credentials (OIDC, K8s SA, SPIFFE JWT-SVID) exchange into delegated Biscuits (`POST /token/exchange`); outbound verified Biscuits mint short-lived ES256 JWTs at the control plane (`POST /sts/token`) that the egress node exchanges at cloud STS endpoints (`CloudTokenExchanger`). `agentmesh-node` integrates with existing gateways (`agentgateway`, Istio, Envoy) via Envoy `ext_authz` / `ext_proc` and RFC 8693 `/oauth/token`, while native SDKs (`sdk/js`, `sdk/python`) attenuate and seal Biscuits in memory.+* **Two-Token Model & Complementary Gateway/PEP Integration:** Inside the mesh, credentials are Biscuits; at both borders, credentials are standard JWTs (`site/content/docs/contributing/security-architecture.md`). Inbound platform credentials (OIDC, K8s SA, SPIFFE JWT-SVID) exchange into delegated Biscuits (`POST /token/exchange`); outbound verified Biscuits mint short-lived ES256 JWTs at the control plane (`POST /sts/token`) that the egress node exchanges at cloud STS endpoints (`CloudTokenExchanger`). `agentmesh-node` integrates with existing gateways (`agentgateway`, Istio, Envoy) via Envoy `ext_authz` / `ext_proc` and RFC 8693 `/oauth/token`, while native SDKs (`sdk/meshnet`, `sdk/js`, `sdk/python`) attenuate and seal Biscuits in memory.* **Policy on Names:** egress policy, secret injection and routing decisions are made on the destination *name*, never on an IP. Deny by default.* **Zero Trust:** Enforce a Zero Trust architecture. Assume no implicit trust between nodes, control planes, routers, or external actors. All data passing through the API must be authenticated, authorized, and validated.* **Nothing interacts with the mesh unauthenticated:** a router or a member serves a mesh protocol (the DHT, gossip, the relay, the data plane) only to a peer that completed the mesh handshake on that connection and whose credential has not lapsed; a stream from any other peer is reset and counted. The only protocols open to a peer that has not authenticated yet are the ones the handshake itself needs: the transport security handshake, identify, and `/mesh/auth`. A libp2p library that registers its own stream handlers (kad-dht, gossipsub) is built on a host wrapper that installs this check in front of every handler, and its routing table admits only authenticated peers. A connection that has not authenticated within the deadline is closed. This holds for reads as much as for writes: a directory lookup or a gossip subscription is mesh data.diff --git a/sdk/README.md b/sdk/README.mdindex b8659b26..6f800ef7 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -21,16 +21,25 @@ tracing between the agent and the network layer. An earlier attempt at aPython package (`sam-mcp-python`) only wrapped the sidecar's HTTP API and wasremoved in favour of this work.-Both SDKs speak the mesh protocol directly. There is no SDK-specific+All three SDKs speak the mesh protocol directly. There is no SDK-specificendpoint anywhere in the mesh; a member built with an SDK is, to every other-member and to the control plane, a peer like a `agentmesh-node`.--An SDK member is an agent, not a service provider. It calls what the mesh-offers: MCP tools, inference and A2A services that `agentmesh-node`s publish and+member and to the control plane, a peer like an `agentmesh-node`.++The Go SDK (`sdk/meshnet`) embeds a full Go member runtime (`tailscale.com/tsnet`+style): `Server.ListenA2A` announces `a2a://<name>` (and optional external HTTP+ingress) to the router directory unless `NoAnnounce: true`, answers+`system://mesh.catalog`, and exposes `WhoIs`, `HTTPClient()`, `Discover()`,+`AttenuateToken()`, `MCPHandler()`, and `InferenceHandler()` in-process; see+[`sdk/meshnet/README.md`](meshnet/README.md).++In JavaScript (`sdk/js`) and Python (`sdk/python`), an SDK member is an agent,+not a service provider. It calls what the mesh+offers: MCP tools, inference and A2A services that `agentmesh-node`s (or+`sdk/meshnet` Go servers) publish andthe discovery table names. Inbound, it accepts one thing: A2A requests foritself, as `a2a://<name>`, reached by peer ID through a router. It publishesno service, writes no directory record and reports no catalog; a tool, a-model or a named agent that others should find by name runs behind a+model or a named agent in JS/Python that others should find by name runs behind an`agentmesh-node`. The reasons are in [Agents, not services](#agents-not-services).## What exists todaydiff --git a/sdk/meshnet/README.md b/sdk/meshnet/README.mdindex a43ff562..ce40199f 100644--- a/sdk/meshnet/README.md+++ b/sdk/meshnet/README.md@@ -2,117 +2,305 @@Package `meshnet` (`github.com/google/agentmesh/sdk/meshnet`) embeds an Agent Mesh member directly inside a Go binary—modeled on [`tailscale.com/tsnet`](https://pkg.go.dev/tailscale.com/tsnet)—with zero external `agentmesh-node` sidecar process, zero loopback bearer token, and byte-for-byte state directory compatibility (`identity.key` + `credential.json`) with `agentmesh-node`, `sdk/js`, and `sdk/python`.+For a full walkthrough, see the [Embedded Go SDK guide](../../site/content/docs/guides/go-sdk.md).+## Capabilities- **Lifecycle & State Compatibility (`Server.Up`, `WriteStateDir`, `ReadStateDir`):** Resumes cached credentials from `StateDir`, enrolls via `BootstrapTokenPath` / `BootstrapToken` / `JWTPath` / `TokenSource`, refreshes credentials proactively in the background, verifies signed `/keys` sets, and enforces live `/mesh/events/v1` FloodSub revocations and bans.-- **In-Process A2A Serving (`Server.ListenA2A`):** Returns in-memory `net.Listener`s (`PrivateListener` over `/libp2p-http` and optional `PublicListener` over `/mesh/ingress/1.0.0` in `EDGE` or `PASSTHROUGH` mode) plus canonical `PrivateURL` and `PublicURL` endpoints. Automatically relativizes and rewrites A2A `AgentCard` `supportedInterfaces` URLs per caller.-- **Unspoofable Caller Inspection (`Server.WhoIs`):** Maps `http.Request.RemoteAddr` on `PrivateListener` and `PublicListener` to the cryptographically verified `CallerInfo` (`PeerID`, `Principal`, `Roles`, `Labels`, `Task`) without trusting HTTP headers.+- **In-Process A2A Serving (`Server.ListenA2A`):** Announces `a2a://<name>` to the router directory (unless `NoAnnounce: true`) and returns in-memory `net.Listener`s (`PrivateListener` over `/libp2p-http` and optional `PublicListener` over `/mesh/ingress/1.0.0` in `EDGE` or `PASSTHROUGH` mode) plus canonical `PrivateURL` and `PublicURL` endpoints. Automatically relativizes and rewrites A2A `AgentCard` `supportedInterfaces` URLs per caller.+- **Unspoofable Caller Inspection (`Server.WhoIs`):** Maps `http.Request.RemoteAddr` on `PrivateListener` and `PublicListener` to the cryptographically verified `*CallerInfo` (`PeerID`, `Principal`, `Roles`, `Labels`, `Task`) without trusting HTTP headers.- **Outbound Mesh `*http.Client` (`Server.HTTPClient`, `Server.Discover`):** Routes `http://agentmesh.local/mesh/<peer_id>/<type>/<name>[/<rest>]` over authenticated libp2p streams, verifying provider Biscuits, `allowed_publish` Datalog grants, `EgressRequireLabels`, and `X-Mesh-Required-Labels` before sending request bytes.- **Offline Task-Scoped Attenuation (`Server.AttenuateToken`):** Appends a validated `TaskAuthorizationRule` (`tar_block` fact, 0 Datalog rules, 0 checks) and optionally seals the Biscuit in memory to delegate task-scoped credentials to sub-agents or external workers without their own mesh client.-- **Local Progressive-Discovery MCP Server (`Server.MCPServer`, `Server.MCPHandler`):** Exposes the 6 mesh-operating tools (`list_local_services`, `discover_remote_services`, `get_mesh_info`, `find_remote_tools`, `describe_remote_tool`, `call_remote_tool`) in-process or over Streamable HTTP (e.g. a local Unix domain socket).+- **Local Progressive-Discovery MCP Server (`Server.MCPServer`, `Server.MCPHandler`):** Exposes the 6 mesh-operating tools (`list_local_services`, `discover_remote_services`, `get_mesh_info`, `find_remote_tools`, `describe_remote_tool`, `call_remote_tool`) in-process or over Streamable HTTP (for example over a local Unix domain socket).- **Zero-Secret OpenAI `/v1` Inference (`Server.InferenceHandler`):** Serves `GET /v1/models`, `POST /v1/chat/completions`, and `POST /v1/completions` routed over mesh `inference://*` providers with automatic Biscuit injection and streaming SSE pass-through.-## Quickstart+## Examples-### 1. Serve an A2A Agent (Private P2P + Public HTTPS Ingress)+### 1. Serve an A2A Agent (`examples/agent`)+<!-- embed: sdk/meshnet/examples/agent/main.go -->```go+// 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.++// Command agent embeds an Agent Mesh member in-process with sdk/meshnet and+// serves an A2A agent over private P2P (/libp2p-http) and router external HTTP+// ingress (/mesh/ingress/1.0.0), optionally exposing the local MCP and /v1+// inference handlers on a Unix domain socket.package mainimport (+ "cmp""context"+ "errors""fmt"+ "iter""log"+ "net""net/http"+ "os"+ "os/signal"+ "syscall"+ "time"+ "github.com/a2aproject/a2a-go/v2/a2a""github.com/a2aproject/a2a-go/v2/a2asrv""github.com/google/agentmesh/api""github.com/google/agentmesh/sdk/meshnet")func main() {- ctx := context.Background()+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()srv := &meshnet.Server{- StateDir: "/var/lib/my-agent/agentmesh",- ControlPlaneURL: "https://bananas.sam-mesh.dev",- BootstrapTokenPath: "/run/secrets/agentmesh-join-token",+ StateDir: cmp.Or(os.Getenv("AGENTMESH_STATE_DIR"), "./state-agent"),+ ControlPlaneURL: os.Getenv("AGENTMESH_CONTROL_PLANE_URL"),+ BootstrapTokenPath: os.Getenv("AGENTMESH_BOOTSTRAP_TOKEN_PATH"),+ JWTPath: os.Getenv("AGENTMESH_JWT_PATH"),+ AllowInsecure: os.Getenv("AGENTMESH_INSECURE_CONTROL_PLANE") == "1",}status, err := srv.Up(ctx)if err != nil {- log.Fatal(err)+ log.Fatalf("meshnet.Up: %v", err)}- defer srv.Close()+ defer func() {+ if err := srv.Close(); err != nil {+ log.Printf("meshnet.Close: %v", err)+ }+ }()+ agentName := cmp.Or(os.Getenv("AGENTMESH_AGENT_NAME"), "coder")ep, err := srv.ListenA2A(ctx, meshnet.A2AOptions{- Name: "coder",- Description: "Repository coding agent",- Public: true,- IngressAuth: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,- IngressAllow: []string{"email:[email protected]"},+ Name: agentName,+ Description: "Echo coding agent embedded via sdk/meshnet",+ Public: true,+ IngressAuth: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,})if err != nil {- log.Fatal(err)+ log.Fatalf("ListenA2A: %v", err)}- defer ep.Close()+ defer func() {+ if err := ep.Close(); err != nil {+ log.Printf("Endpoints.Close: %v", err)+ }+ }()- fmt.Printf("Peer ID: %s\n", status.PeerID)- fmt.Printf("Private A2A: %s\n", ep.PrivateURL)- if ep.PublicURL != nil {- fmt.Printf("Public A2A: %s\n", ep.PublicURL)+ exec := a2asrv.AgentExecutorFunc(func(_ context.Context, ec *a2asrv.ExecutorContext) iter.Seq2[a2a.Event, error] {+ return func(yield func(a2a.Event, error) bool) {+ var prompt string+ if ec.Message != nil && len(ec.Message.Parts) > 0 {+ prompt = ec.Message.Parts[0].Text()+ }+ yield(a2a.NewMessageForTask(a2a.MessageRoleAgent, ec, a2a.NewTextPart("echo: "+prompt)), nil)+ }+ })+ card := &a2a.AgentCard{+ Name: agentName,+ Description: "Echo coding agent embedded via sdk/meshnet",+ Version: "1.0.0",+ SupportedInterfaces: []*a2a.AgentInterface{+ {+ URL: ep.PrivateURL.String() + "/invoke",+ ProtocolBinding: a2a.TransportProtocolJSONRPC,+ ProtocolVersion: "1.0",+ },+ },}+ rpcHandler := a2asrv.NewJSONRPCHandler(a2asrv.NewHandler(exec))mux := http.NewServeMux()- mux.Handle(a2asrv.WellKnownAgentCardPath, cardHandler)+ mux.Handle(a2asrv.WellKnownAgentCardPath, a2asrv.NewStaticAgentCardHandler(card))mux.Handle("/invoke", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if caller, ok := srv.WhoIs(r.RemoteAddr); ok {+ if caller, ok := srv.WhoIs(r.RemoteAddr); ok && caller != nil {log.Printf("verified caller principal=%s peer=%s task=%s", caller.Principal, caller.PeerID, caller.Task)}rpcHandler.ServeHTTP(w, r)}))- go http.Serve(ep.PrivateListener, mux)+ privHTTP := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = privHTTP.Close() }()+ go func() {+ if err := privHTTP.Serve(ep.PrivateListener); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("private listener: %v", err)+ }+ }()+if ep.PublicListener != nil {- go http.Serve(ep.PublicListener, mux)+ pubHTTP := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = pubHTTP.Close() }()+ go func() {+ if err := pubHTTP.Serve(ep.PublicListener); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("public listener: %v", err)+ }+ }()}- select {}++ if sockPath := os.Getenv("AGENTMESH_SOCKET_PATH"); sockPath != "" {+ _ = os.Remove(sockPath)+ var lc net.ListenConfig+ unixLn, err := lc.Listen(ctx, "unix", sockPath)+ if err != nil {+ log.Fatalf("listen unix %s: %v", sockPath, err)+ }+ defer func() {+ _ = unixLn.Close()+ _ = os.Remove(sockPath)+ }()+ localMux := http.NewServeMux()+ localMux.Handle("/mcp", srv.MCPHandler())+ localMux.Handle("/v1/", srv.InferenceHandler())+ localHTTP := &http.Server{Handler: localMux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = localHTTP.Close() }()+ go func() {+ if err := localHTTP.Serve(unixLn); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("unix socket listener: %v", err)+ }+ }()+ fmt.Printf("Local Socket: %s (/mcp, /v1/)\n", sockPath)+ }++ fmt.Printf("Peer ID: %s\n", status.PeerID)+ fmt.Printf("Private A2A: %s\n", ep.PrivateURL)+ if ep.PublicURL != nil {+ fmt.Printf("Public A2A: %s\n", ep.PublicURL)+ }+ <-ctx.Done()}```+<!-- /embed -->-### 2. Discover & Call Remote Mesh Agents with Stock `a2a-go`+### 2. Discover & Call Remote Mesh Agents (`examples/call`)+<!-- embed: sdk/meshnet/examples/call/main.go -->```go-providers, err := srv.Discover(ctx, api.ServiceType_SERVICE_TYPE_A2A, "coder")-if err != nil || len(providers) == 0 {- log.Fatalf("coder not found: %v", err)-}+// 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.-meshHTTP := srv.HTTPClient()-card, err := agentcard.NewResolver(meshHTTP).Resolve(ctx, providers[0].GetLocalProxyUrl())-if err != nil {- log.Fatal(err)-}-client, err := a2aclient.NewFromCard(ctx, card, a2aclient.WithJSONRPCTransport(meshHTTP))-```+// Command call joins an Agent Mesh in-process with sdk/meshnet, discovers an+// A2A service by name (or dials an explicit mesh URL), and sends a message+// using the unmodified official a2a-go client over srv.HTTPClient().+package main-### 3. Expose Mesh MCP & Zero-Secret OpenAI `/v1` Over a Local Unix Socket+import (+ "cmp"+ "context"+ "fmt"+ "log"+ "os"+ "os/signal"+ "strings"+ "syscall"+ "time"-```go-unixLn, err := net.Listen("unix", "/run/agent/mesh.sock")-if err != nil {- log.Fatal(err)+ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"+ "github.com/google/agentmesh/api"+ "github.com/google/agentmesh/sdk/meshnet"+)++func main() {+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ target := "coder"+ prompt := "hello from meshnet"+ if len(os.Args) > 1 {+ target = os.Args[1]+ }+ if len(os.Args) > 2 {+ prompt = strings.Join(os.Args[2:], " ")+ }++ srv := &meshnet.Server{+ StateDir: cmp.Or(os.Getenv("AGENTMESH_STATE_DIR"), "./state-caller"),+ ControlPlaneURL: os.Getenv("AGENTMESH_CONTROL_PLANE_URL"),+ BootstrapTokenPath: os.Getenv("AGENTMESH_BOOTSTRAP_TOKEN_PATH"),+ JWTPath: os.Getenv("AGENTMESH_JWT_PATH"),+ AllowInsecure: os.Getenv("AGENTMESH_INSECURE_CONTROL_PLANE") == "1",+ }+ if _, err := srv.Up(ctx); err != nil {+ log.Fatalf("meshnet.Up: %v", err)+ }+ defer func() {+ if err := srv.Close(); err != nil {+ log.Printf("meshnet.Close: %v", err)+ }+ }()++ baseURL := target+ if !strings.HasPrefix(target, "http://") {+ providers, err := srv.Discover(ctx, api.ServiceType_SERVICE_TYPE_A2A, target)+ if err != nil {+ log.Fatalf("Discover(%q): %v", target, err)+ }+ if len(providers) == 0 {+ log.Fatalf("no providers found in mesh directory for a2a://%s", target)+ }+ baseURL = providers[0].GetLocalProxyUrl()+ }++ callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ meshHTTP := srv.HTTPClient()+ card, err := agentcard.NewResolver(meshHTTP).Resolve(callCtx, baseURL)+ if err != nil {+ log.Fatalf("Resolve(%q): %v", baseURL, err)+ }+ client, err := a2aclient.NewFromCard(callCtx, card, a2aclient.WithJSONRPCTransport(meshHTTP))+ if err != nil {+ log.Fatalf("NewFromCard: %v", err)+ }+ res, err := client.SendMessage(callCtx, &a2a.SendMessageRequest{+ Message: a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart(prompt)),+ })+ if err != nil {+ log.Fatalf("SendMessage: %v", err)+ }++ if msg, ok := res.(*a2a.Message); ok {+ for _, part := range msg.Parts {+ if text := part.Text(); text != "" {+ fmt.Println(text)+ }+ }+ return+ }+ fmt.Printf("%+v\n", res)}-mux := http.NewServeMux()-mux.Handle("/mcp", srv.MCPHandler())-mux.Handle("/v1/", srv.InferenceHandler())-go http.Serve(unixLn, mux)```+<!-- /embed -->-### 4. Interoperate with `agentmesh-node` State Directories+### 3. Interoperate with `agentmesh-node` State DirectoriesAn operator can enroll interactively once with `agentmesh-node` and hand the resulting state directory directly to a Go binary embedding `meshnet.Server`:```bashagentmesh-node join --hub https://bananas.sam-mesh.devagentmesh-node state export ~/.config/my-agent/agentmesh+AGENTMESH_STATE_DIR=~/.config/my-agent/agentmesh go run ./sdk/meshnet/examples/agent```diff --git a/sdk/meshnet/a2a.go b/sdk/meshnet/a2a.goindex 1f2466d0..26f80aa6 100644--- a/sdk/meshnet/a2a.go+++ b/sdk/meshnet/a2a.go@@ -297,7 +297,9 @@ func (s *Server) ListenA2A(ctx context.Context, opts A2AOptions) (*Endpoints, erif !opts.NoAnnounce {s.announceA2AEntry(ctx, entry)peerCtx, cancel := context.WithTimeout(ctx, 5*time.Second)- _ = s.dir.provide(peerCtx, api.PeerKey(s.peerID), "")+ if err := s.dir.provide(peerCtx, api.PeerKey(s.peerID), ""); err != nil && ctx.Err() == nil && !errors.Is(err, errNoDirectoryRouter) {+ s.log().Debug("peer directory announcement failed during ListenA2A", "error", err)+ }cancel()} else if opts.Public {entry.setPublicState(true, s.computePublicURL(name))@@ -407,11 +409,15 @@ func (s *Server) unregisterA2A(name string, entry *a2aEntry) {wCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()if nameKey, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, name); err == nil {- _ = s.dir.withdraw(wCtx, nameKey)+ if wErr := s.dir.withdraw(wCtx, nameKey); wErr != nil && !errors.Is(wErr, errNoDirectoryRouter) {+ s.log().Debug("failed withdrawing A2A service key", "service", name, "error", wErr)+ }}if !stillHasA2A {if typeKey, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, ""); err == nil {- _ = s.dir.withdraw(wCtx, typeKey)+ if wErr := s.dir.withdraw(wCtx, typeKey); wErr != nil && !errors.Is(wErr, errNoDirectoryRouter) {+ s.log().Debug("failed withdrawing A2A service type key", "error", wErr)+ }}}}@@ -855,15 +861,20 @@ func (s *Server) externalIngressHandler() http.Handler {"path", backendPath,)+ actorPeerID := remotePeer.String()+ if callerRes.ActorNodeID != "" {+ if id, err := peer.Decode(callerRes.ActorNodeID); err == nil {+ actorPeerID = id.String()+ } else {+ s.log().Debug("ignoring invalid actor_node in external ingress biscuit", "actor_node", callerRes.ActorNodeID, "error", err)+ }+ }caller := &CallerInfo{- PeerID: callerRes.ActorNodeID,+ PeerID: actorPeerID,Principal: callerRes.Principal,Roles: slices.Clone(callerRes.Roles),Task: callerRes.TaskName,}- if caller.PeerID == "" {- caller.PeerID = remotePeer.String()- }rewriteInboundRequestPath(r, parts, upstreamPath)s.deliverHTTP(w, r, entry.publicLn, caller, relativizeAgentCardResponse(entry.name, roots))})diff --git a/sdk/meshnet/authorizer.go b/sdk/meshnet/authorizer.goindex 92609ab5..7405d5ce 100644--- a/sdk/meshnet/authorizer.go+++ b/sdk/meshnet/authorizer.go@@ -177,8 +177,14 @@ func (s *Server) authorizeInboundWithKey(rawToken []byte, remotePeer peer.ID, tacase user != "":principal = usercase nodeFact != "":+ if id, err := peer.Decode(nodeFact); err == nil {+ nodeFact = id.String()+ }principal = "node:" + nodeFactcase clientPeer != "":+ if id, err := peer.Decode(clientPeer); err == nil {+ clientPeer = id.String()+ }principal = "peer:" + clientPeerdefault:principal = "node:" + remotePeer.String()diff --git a/sdk/meshnet/examples/agent/main.go b/sdk/meshnet/examples/agent/main.gonew file mode 100644index 00000000..31170c44--- /dev/null+++ b/sdk/meshnet/examples/agent/main.go@@ -0,0 +1,158 @@+// 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.++// Command agent embeds an Agent Mesh member in-process with sdk/meshnet and+// serves an A2A agent over private P2P (/libp2p-http) and router external HTTP+// ingress (/mesh/ingress/1.0.0), optionally exposing the local MCP and /v1+// inference handlers on a Unix domain socket.+package main++import (+ "cmp"+ "context"+ "errors"+ "fmt"+ "iter"+ "log"+ "net"+ "net/http"+ "os"+ "os/signal"+ "syscall"+ "time"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2asrv"+ "github.com/google/agentmesh/api"+ "github.com/google/agentmesh/sdk/meshnet"+)++func main() {+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ srv := &meshnet.Server{+ StateDir: cmp.Or(os.Getenv("AGENTMESH_STATE_DIR"), "./state-agent"),+ ControlPlaneURL: os.Getenv("AGENTMESH_CONTROL_PLANE_URL"),+ BootstrapTokenPath: os.Getenv("AGENTMESH_BOOTSTRAP_TOKEN_PATH"),+ JWTPath: os.Getenv("AGENTMESH_JWT_PATH"),+ AllowInsecure: os.Getenv("AGENTMESH_INSECURE_CONTROL_PLANE") == "1",+ }+ status, err := srv.Up(ctx)+ if err != nil {+ log.Fatalf("meshnet.Up: %v", err)+ }+ defer func() {+ if err := srv.Close(); err != nil {+ log.Printf("meshnet.Close: %v", err)+ }+ }()++ agentName := cmp.Or(os.Getenv("AGENTMESH_AGENT_NAME"), "coder")+ ep, err := srv.ListenA2A(ctx, meshnet.A2AOptions{+ Name: agentName,+ Description: "Echo coding agent embedded via sdk/meshnet",+ Public: true,+ IngressAuth: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,+ })+ if err != nil {+ log.Fatalf("ListenA2A: %v", err)+ }+ defer func() {+ if err := ep.Close(); err != nil {+ log.Printf("Endpoints.Close: %v", err)+ }+ }()++ exec := a2asrv.AgentExecutorFunc(func(_ context.Context, ec *a2asrv.ExecutorContext) iter.Seq2[a2a.Event, error] {+ return func(yield func(a2a.Event, error) bool) {+ var prompt string+ if ec.Message != nil && len(ec.Message.Parts) > 0 {+ prompt = ec.Message.Parts[0].Text()+ }+ yield(a2a.NewMessageForTask(a2a.MessageRoleAgent, ec, a2a.NewTextPart("echo: "+prompt)), nil)+ }+ })+ card := &a2a.AgentCard{+ Name: agentName,+ Description: "Echo coding agent embedded via sdk/meshnet",+ Version: "1.0.0",+ SupportedInterfaces: []*a2a.AgentInterface{+ {+ URL: ep.PrivateURL.String() + "/invoke",+ ProtocolBinding: a2a.TransportProtocolJSONRPC,+ ProtocolVersion: "1.0",+ },+ },+ }++ rpcHandler := a2asrv.NewJSONRPCHandler(a2asrv.NewHandler(exec))+ mux := http.NewServeMux()+ mux.Handle(a2asrv.WellKnownAgentCardPath, a2asrv.NewStaticAgentCardHandler(card))+ mux.Handle("/invoke", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if caller, ok := srv.WhoIs(r.RemoteAddr); ok && caller != nil {+ log.Printf("verified caller principal=%s peer=%s task=%s", caller.Principal, caller.PeerID, caller.Task)+ }+ rpcHandler.ServeHTTP(w, r)+ }))++ privHTTP := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = privHTTP.Close() }()+ go func() {+ if err := privHTTP.Serve(ep.PrivateListener); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("private listener: %v", err)+ }+ }()++ if ep.PublicListener != nil {+ pubHTTP := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = pubHTTP.Close() }()+ go func() {+ if err := pubHTTP.Serve(ep.PublicListener); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("public listener: %v", err)+ }+ }()+ }++ if sockPath := os.Getenv("AGENTMESH_SOCKET_PATH"); sockPath != "" {+ _ = os.Remove(sockPath)+ var lc net.ListenConfig+ unixLn, err := lc.Listen(ctx, "unix", sockPath)+ if err != nil {+ log.Fatalf("listen unix %s: %v", sockPath, err)+ }+ defer func() {+ _ = unixLn.Close()+ _ = os.Remove(sockPath)+ }()+ localMux := http.NewServeMux()+ localMux.Handle("/mcp", srv.MCPHandler())+ localMux.Handle("/v1/", srv.InferenceHandler())+ localHTTP := &http.Server{Handler: localMux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = localHTTP.Close() }()+ go func() {+ if err := localHTTP.Serve(unixLn); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("unix socket listener: %v", err)+ }+ }()+ fmt.Printf("Local Socket: %s (/mcp, /v1/)\n", sockPath)+ }++ fmt.Printf("Peer ID: %s\n", status.PeerID)+ fmt.Printf("Private A2A: %s\n", ep.PrivateURL)+ if ep.PublicURL != nil {+ fmt.Printf("Public A2A: %s\n", ep.PublicURL)+ }+ <-ctx.Done()+}diff --git a/sdk/meshnet/examples/call/main.go b/sdk/meshnet/examples/call/main.gonew file mode 100644index 00000000..7f482606--- /dev/null+++ b/sdk/meshnet/examples/call/main.go@@ -0,0 +1,107 @@+// 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.++// Command call joins an Agent Mesh in-process with sdk/meshnet, discovers an+// A2A service by name (or dials an explicit mesh URL), and sends a message+// using the unmodified official a2a-go client over srv.HTTPClient().+package main++import (+ "cmp"+ "context"+ "fmt"+ "log"+ "os"+ "os/signal"+ "strings"+ "syscall"+ "time"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"+ "github.com/google/agentmesh/api"+ "github.com/google/agentmesh/sdk/meshnet"+)++func main() {+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ target := "coder"+ prompt := "hello from meshnet"+ if len(os.Args) > 1 {+ target = os.Args[1]+ }+ if len(os.Args) > 2 {+ prompt = strings.Join(os.Args[2:], " ")+ }++ srv := &meshnet.Server{+ StateDir: cmp.Or(os.Getenv("AGENTMESH_STATE_DIR"), "./state-caller"),+ ControlPlaneURL: os.Getenv("AGENTMESH_CONTROL_PLANE_URL"),+ BootstrapTokenPath: os.Getenv("AGENTMESH_BOOTSTRAP_TOKEN_PATH"),+ JWTPath: os.Getenv("AGENTMESH_JWT_PATH"),+ AllowInsecure: os.Getenv("AGENTMESH_INSECURE_CONTROL_PLANE") == "1",+ }+ if _, err := srv.Up(ctx); err != nil {+ log.Fatalf("meshnet.Up: %v", err)+ }+ defer func() {+ if err := srv.Close(); err != nil {+ log.Printf("meshnet.Close: %v", err)+ }+ }()++ baseURL := target+ if !strings.HasPrefix(target, "http://") {+ providers, err := srv.Discover(ctx, api.ServiceType_SERVICE_TYPE_A2A, target)+ if err != nil {+ log.Fatalf("Discover(%q): %v", target, err)+ }+ if len(providers) == 0 {+ log.Fatalf("no providers found in mesh directory for a2a://%s", target)+ }+ baseURL = providers[0].GetLocalProxyUrl()+ }++ callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ meshHTTP := srv.HTTPClient()+ card, err := agentcard.NewResolver(meshHTTP).Resolve(callCtx, baseURL)+ if err != nil {+ log.Fatalf("Resolve(%q): %v", baseURL, err)+ }+ client, err := a2aclient.NewFromCard(callCtx, card, a2aclient.WithJSONRPCTransport(meshHTTP))+ if err != nil {+ log.Fatalf("NewFromCard: %v", err)+ }+ res, err := client.SendMessage(callCtx, &a2a.SendMessageRequest{+ Message: a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart(prompt)),+ })+ if err != nil {+ log.Fatalf("SendMessage: %v", err)+ }++ if msg, ok := res.(*a2a.Message); ok {+ for _, part := range msg.Parts {+ if text := part.Text(); text != "" {+ fmt.Println(text)+ }+ }+ return+ }+ fmt.Printf("%+v\n", res)+}diff --git a/sdk/meshnet/inference.go b/sdk/meshnet/inference.goindex 7b957b31..cc1c1a10 100644--- a/sdk/meshnet/inference.go+++ b/sdk/meshnet/inference.go@@ -43,7 +43,7 @@ const ()type modelProvider struct {- peerID string+ peerID peer.IDservice string}@@ -93,7 +93,7 @@ func (f *inferenceFacade) handleModels(w http.ResponseWriter, r *http.Request) {for id, providers := range view {ownedBy := "mesh"if len(providers) > 0 && providers[0].peerID != "" {- ownedBy = providers[0].peerID+ ownedBy = providers[0].peerID.String()}data = append(data, openAIModel{ID: id, Object: "model", OwnedBy: ownedBy})}@@ -155,13 +155,10 @@ func (f *inferenceFacade) handleCompletions(w http.ResponseWriter, r *http.RequeverifiedAny := falsefor i := range maxAttempts {p := ranked[i]- pid, err := peer.Decode(p.peerID)- if err != nil {- continue- }- if err := f.s.verifyProvider(r.Context(), pid, requiredLabels, api.ServiceTypeStringInference+"://"+p.service); err != nil {+ peerStr := p.peerID.String()+ if err := f.s.verifyProvider(r.Context(), p.peerID, requiredLabels, api.ServiceTypeStringInference+"://"+p.service); err != nil {f.s.log().Warn("inference provider failed verification; trying next",- "peer_id", p.peerID,+ "peer_id", peerStr,"service", p.service,"error", err,)@@ -169,7 +166,7 @@ func (f *inferenceFacade) handleCompletions(w http.ResponseWriter, r *http.Reque}verifiedAny = true- targetURL := fmt.Sprintf("http://agentmesh.local/mesh/%s/%s/%s%s", p.peerID, api.ServiceTypeStringInference, p.service, r.URL.Path)+ targetURL := fmt.Sprintf("http://agentmesh.local/mesh/%s/%s/%s%s", peerStr, api.ServiceTypeStringInference, p.service, r.URL.Path)if r.URL.RawQuery != "" {targetURL += "?" + r.URL.RawQuery}@@ -185,14 +182,14 @@ func (f *inferenceFacade) handleCompletions(w http.ResponseWriter, r *http.Requeresp, err := f.client.Do(outReq)if err != nil {f.recordBackoff(p)- f.s.log().Warn("inference request failed; trying next provider", "peer_id", p.peerID, "service", p.service, "error", err)+ f.s.log().Warn("inference request failed; trying next provider", "peer_id", peerStr, "service", p.service, "error", err)continue}if retryableStatus(resp.StatusCode) {_ = resp.Body.Close()f.recordBackoff(p)f.s.log().Warn("inference provider returned retryable status; trying next",- "peer_id", p.peerID,+ "peer_id", peerStr,"service", p.service,"status", resp.StatusCode,)@@ -283,8 +280,13 @@ func (f *inferenceFacade) collectModels(ctx context.Context) map[string][]modelPsem = make(chan struct{}, remoteProbeConcurrency))for _, p := range providers {+ pid, err := peer.Decode(p.GetPeerId())+ if err != nil {+ f.s.log().Debug("skipping inference provider with invalid peer ID", "peer_id", p.GetPeerId(), "error", err)+ continue+ }wg.Add(1)- go func(peerID, srvName string) {+ go func(peerID peer.ID, srvName string) {defer wg.Done()select {case sem <- struct{}{}:@@ -294,7 +296,7 @@ func (f *inferenceFacade) collectModels(ctx context.Context) map[string][]modelP}ids, err := f.probeRemoteModels(ctx, peerID, srvName)if err != nil {- f.s.log().Debug("remote model probe failed", "peer_id", peerID, "service", srvName, "error", err)+ f.s.log().Debug("remote model probe failed", "peer_id", peerID.String(), "service", srvName, "error", err)return}mu.Lock()@@ -302,20 +304,16 @@ func (f *inferenceFacade) collectModels(ctx context.Context) map[string][]modelPmodels[id] = append(models[id], modelProvider{peerID: peerID, service: srvName})}mu.Unlock()- }(p.GetPeerId(), p.GetSrvName())+ }(pid, p.GetSrvName())}wg.Wait()return models}-func (f *inferenceFacade) probeRemoteModels(ctx context.Context, peerID, srvName string) ([]string, error) {+func (f *inferenceFacade) probeRemoteModels(ctx context.Context, pid peer.ID, srvName string) ([]string, error) {if f.s.host == nil {return nil, errors.New("server not running")}- pid, err := peer.Decode(peerID)- if err != nil {- return nil, err- }biscuitBytes := f.s.currentBiscuit()if len(biscuitBytes) == 0 {return nil, errors.New("missing local credential")@@ -342,7 +340,7 @@ func (f *inferenceFacade) probeRemoteModels(ctx context.Context, peerID, srvName}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("provider %s/%s returned status %d for /v1/models", peerID, srvName, resp.StatusCode)+ return nil, fmt.Errorf("provider %s/%s returned status %d for /v1/models", pid.String(), srvName, resp.StatusCode)}var list struct {Data []struct {@@ -364,8 +362,7 @@ func (f *inferenceFacade) probeRemoteModels(ctx context.Context, peerID, srvNamefunc (f *inferenceFacade) rankProviders(providers []modelProvider) []modelProvider {var remotes []modelProviderfor _, p := range providers {- pid, err := peer.Decode(p.peerID)- if err != nil || f.s.isPeerBanned(pid) || f.inBackoff(p) {+ if f.s.isPeerBanned(p.peerID) || f.inBackoff(p) {continue}remotes = append(remotes, p)@@ -381,7 +378,7 @@ func (f *inferenceFacade) rankProviders(providers []modelProvider) []modelProvid}func (f *inferenceFacade) inBackoff(p modelProvider) bool {- key := p.peerID + "|" + p.service+ key := p.peerID.String() + "|" + p.servicef.backoffMu.Lock()defer f.backoffMu.Unlock()until, ok := f.backoff[key]@@ -396,7 +393,7 @@ func (f *inferenceFacade) inBackoff(p modelProvider) bool {}func (f *inferenceFacade) recordBackoff(p modelProvider) {- key := p.peerID + "|" + p.service+ key := p.peerID.String() + "|" + p.servicef.backoffMu.Lock()if f.backoff == nil {f.backoff = map[string]time.Time{}diff --git a/sdk/meshnet/mcp.go b/sdk/meshnet/mcp.goindex 0f8491a9..bdb81bdb 100644--- a/sdk/meshnet/mcp.go+++ b/sdk/meshnet/mcp.go@@ -369,10 +369,6 @@ func (s *Server) handleFindRemoteTools(ctx context.Context, _ *mcp.CallToolRequeif s.host == nil {return nil, nil, errors.New("meshnet: Server is not running")}- selfID := s.peerID.String()- if params.PeerID != "" && params.PeerID == selfID {- return nil, nil, fmt.Errorf("peer_id %q is this member; find_remote_tools searches remote peers", params.PeerID)- }serviceFilter, err := normalizeMCPServiceFilter(params.ServiceName)if err != nil {return nil, nil, err@@ -384,6 +380,9 @@ func (s *Server) handleFindRemoteTools(ctx context.Context, _ *mcp.CallToolRequeif err != nil {return nil, nil, fmt.Errorf("invalid peer_id %q: %w", params.PeerID, err)}+ if pid == s.peerID {+ return nil, nil, fmt.Errorf("peer_id %q is this member; find_remote_tools searches remote peers", params.PeerID)+ }rows, err = s.fetchRemoteToolCatalogue(ctx, pid, serviceFilter)if err != nil {return nil, nil, err@@ -393,16 +392,19 @@ func (s *Server) handleFindRemoteTools(ctx context.Context, _ *mcp.CallToolRequeif err != nil {return nil, nil, fmt.Errorf("discover MCP providers: %w", err)}- seen := map[string]bool{}+ seen := make(map[peer.ID]bool, len(providers))var peerIDs []peer.IDfor _, p := range providers {- if p.GetPeerId() == selfID || seen[p.GetPeerId()] {+ pid, err := peer.Decode(p.GetPeerId())+ if err != nil {+ s.log().Debug("skipping MCP provider with invalid peer ID", "peer_id", p.GetPeerId(), "error", err)continue}- seen[p.GetPeerId()] = true- if pid, err := peer.Decode(p.GetPeerId()); err == nil {- peerIDs = append(peerIDs, pid)+ if pid == s.peerID || seen[pid] {+ continue}+ seen[pid] = true+ peerIDs = append(peerIDs, pid)}rows = s.fanOutFetchTools(ctx, peerIDs, serviceFilter)}diff --git a/sdk/meshnet/meshnet_test.go b/sdk/meshnet/meshnet_test.goindex 12133afe..3600b158 100644--- a/sdk/meshnet/meshnet_test.go+++ b/sdk/meshnet/meshnet_test.go@@ -30,6 +30,7 @@ import ("time""github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/eclipse-biscuit/biscuit-go/v2""github.com/google/agentmesh/api""github.com/google/agentmesh/internal/identity""github.com/libp2p/go-libp2p"@@ -337,8 +338,11 @@ func TestListenA2AWhoIsDiscoverAndHTTPClient(t *testing.T) {if err != nil {t.Fatalf("GET agent-card.json: %v", err)}- cardBody, _ := io.ReadAll(cardResp.Body)+ cardBody, err := io.ReadAll(cardResp.Body)_ = cardResp.Body.Close()+ if err != nil {+ t.Fatalf("io.ReadAll(agent-card.json): %v", err)+ }if cardResp.StatusCode != http.StatusOK {t.Fatalf("agent-card status = %d: %s", cardResp.StatusCode, cardBody)}@@ -354,7 +358,10 @@ func TestListenA2AWhoIsDiscoverAndHTTPClient(t *testing.T) {t.Fatal("missing ETag header on regenerated AgentCard")}- req304, _ := http.NewRequestWithContext(ctx, http.MethodGet, ep.PrivateURL.String()+"/.well-known/agent-card.json", nil)+ req304, err := http.NewRequestWithContext(ctx, http.MethodGet, ep.PrivateURL.String()+"/.well-known/agent-card.json", nil)+ if err != nil {+ t.Fatalf("NewRequestWithContext(304): %v", err)+ }req304.Header.Set("If-None-Match", etag)resp304, err := hc.Do(req304)if err != nil {@@ -366,14 +373,20 @@ func TestListenA2AWhoIsDiscoverAndHTTPClient(t *testing.T) {}// 3. POST /invoke verifies WhoIs caller identity, defensive copy, and post-close cleanup.- invReq, _ := http.NewRequestWithContext(ctx, http.MethodPost, ep.PrivateURL.String()+"/invoke", strings.NewReader(`{}`))+ invReq, err := http.NewRequestWithContext(ctx, http.MethodPost, ep.PrivateURL.String()+"/invoke", strings.NewReader(`{}`))+ if err != nil {+ t.Fatalf("NewRequestWithContext(invoke): %v", err)+ }invReq.Header.Set(api.HeaderMeshRequiredLabels, "env=prod")invResp, err := hc.Do(invReq)if err != nil {t.Fatalf("POST /invoke: %v", err)}- _, _ = io.ReadAll(invResp.Body)+ _, readErr := io.ReadAll(invResp.Body)_ = invResp.Body.Close()+ if readErr != nil {+ t.Fatalf("io.ReadAll(invoke): %v", readErr)+ }if invResp.StatusCode != http.StatusOK {t.Fatalf("POST /invoke status = %d, want 200", invResp.StatusCode)}@@ -409,7 +422,10 @@ func TestListenA2AWhoIsDiscoverAndHTTPClient(t *testing.T) {}// 4. Required-label mismatch fails closed BEFORE sending request bytes.- badLabelReq, _ := http.NewRequestWithContext(ctx, http.MethodPost, ep.PrivateURL.String()+"/invoke", strings.NewReader(`{}`))+ badLabelReq, err := http.NewRequestWithContext(ctx, http.MethodPost, ep.PrivateURL.String()+"/invoke", strings.NewReader(`{}`))+ if err != nil {+ t.Fatalf("NewRequestWithContext(badLabel): %v", err)+ }badLabelReq.Header.Set(api.HeaderMeshRequiredLabels, "env=staging")badLabelResp, err := hc.Do(badLabelReq)if err != nil {@@ -475,6 +491,16 @@ func TestLocalMCPAndInferenceHandlers(t *testing.T) {t.Fatalf("list_local_services failed: err=%v res=%+v", err, localRes)}+ // CIDv1 representation of self PeerID is canonicalized and rejected by find_remote_tools.+ selfCIDv1 := peer.ToCid(mesh.caller.peerID).String()+ selfToolRes, selfToolErr := sess.CallTool(ctx, &mcp.CallToolParams{+ Name: "find_remote_tools",+ Arguments: map[string]any{"peer_id": selfCIDv1},+ })+ if selfToolErr == nil && (selfToolRes == nil || !selfToolRes.IsError) {+ t.Fatalf("find_remote_tools accepted CIDv1 self peer_id %q, want error", selfCIDv1)+ }+// 2. Local InferenceHandler routes and validation.infHTTP := httptest.NewServer(mesh.caller.InferenceHandler())t.Cleanup(infHTTP.Close)@@ -483,8 +509,11 @@ func TestLocalMCPAndInferenceHandlers(t *testing.T) {if err != nil {t.Fatalf("GET /v1/models: %v", err)}- modelsBody, _ := io.ReadAll(modelsResp.Body)+ modelsBody, err := io.ReadAll(modelsResp.Body)_ = modelsResp.Body.Close()+ if err != nil {+ t.Fatalf("io.ReadAll(/v1/models): %v", err)+ }if modelsResp.StatusCode != http.StatusOK || !strings.Contains(string(modelsBody), `"object":"list"`) {t.Fatalf("GET /v1/models = %d: %s", modelsResp.StatusCode, modelsBody)}@@ -526,6 +555,91 @@ func TestLocalMCPAndInferenceHandlers(t *testing.T) {}}+func TestExternalIngressCanonicalizesActorNodePeerID(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()++ env := newStartedTestServer(t, ctx)+ s := env.server++ ep, err := s.ListenA2A(ctx, A2AOptions{+ Name: "coder",+ Public: true,+ IngressAuth: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,+ NoAnnounce: true,+ })+ if err != nil {+ t.Fatalf("ListenA2A: %v", err)+ }+ t.Cleanup(func() { _ = ep.Close() })++ var gotPeerID string+ var mu sync.Mutex+ pubSrv := &http.Server{+ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if info, ok := s.WhoIs(r.RemoteAddr); ok && info != nil {+ mu.Lock()+ gotPeerID = info.PeerID+ mu.Unlock()+ }+ w.WriteHeader(http.StatusOK)+ }),+ }+ go func() { _ = pubSrv.Serve(ep.PublicListener) }()+ t.Cleanup(func() { _ = pubSrv.Close() })++ actorHost, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = actorHost.Close() })+ cidv1Actor := peer.ToCid(actorHost.ID()).String()+ if cidv1Actor == actorHost.ID().String() {+ t.Fatalf("peer.ToCid(%s) produced identical string", actorHost.ID())+ }++ routerBiscuit := mintTestBiscuit(t, env.cpPriv, env.routerHost.ID().String(), api.RoleRouter, time.Now().Add(time.Hour))++ b := biscuit.NewBuilder(env.cpPriv)+ for _, f := range []biscuit.Fact{+ {Predicate: biscuit.Predicate{Name: api.FactActorNode, IDs: []biscuit.Term{biscuit.String(cidv1Actor)}}},+ {Predicate: biscuit.Predicate{Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleNode)}}},+ {Predicate: biscuit.Predicate{Name: api.FactEmail, IDs: []biscuit.Term{biscuit.String("[email protected]")}}},+ {Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(time.Now().Add(time.Hour))}}},+ api.MarkerFact(api.FactTargetUnrestricted),+ } {+ if err := b.AddAuthorityFact(f); err != nil {+ t.Fatalf("AddAuthorityFact: %v", err)+ }+ }+ built, err := b.Build()+ if err != nil {+ t.Fatalf("Build: %v", err)+ }+ callerBytes, err := built.Serialize()+ if err != nil {+ t.Fatalf("Serialize: %v", err)+ }++ req := httptest.NewRequest(http.MethodPost, "http://mesh/a2a/coder/invoke", strings.NewReader(`{}`))+ req.RemoteAddr = env.routerHost.ID().String()+ req.Header.Set(api.HeaderMeshBiscuit, base64.RawURLEncoding.EncodeToString(routerBiscuit))+ req.Header.Set(api.HeaderMeshIngress, api.IngressAuthModeStringEdge)+ req.Header.Set(api.HeaderMeshIngressCallerBiscuit, base64.RawURLEncoding.EncodeToString(callerBytes))++ rec := httptest.NewRecorder()+ s.externalIngressHandler().ServeHTTP(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("externalIngressHandler status = %d (%s), want 200", rec.Code, rec.Body.String())+ }++ mu.Lock()+ defer mu.Unlock()+ if gotPeerID != actorHost.ID().String() {+ t.Fatalf("WhoIs PeerID = %q, want canonical %q (from CIDv1 %q)", gotPeerID, actorHost.ID().String(), cidv1Actor)+ }+}+type inProcessMeshPair struct {provider *Servercaller *Serverdiff --git a/sdk/meshnet/routers.go b/sdk/meshnet/routers.goindex fd0f257c..311d14ba 100644--- a/sdk/meshnet/routers.go+++ b/sdk/meshnet/routers.go@@ -78,7 +78,7 @@ func (c routerCandidate) loadRatio() float64 {return float64(c.Connections) / float64(c.ConnectionLimit)}-func candidatesFromInfo(ctx context.Context, info *api.ControlPlaneInfoResponse) []routerCandidate {+func (s *Server) candidatesFromInfo(ctx context.Context, info *api.ControlPlaneInfoResponse) []routerCandidate {if len(info.GetRouters()) == 0 {return candidatesFromAddrs(ctx, parseMultiaddrs(info.GetRouterAddresses()))}@@ -86,7 +86,11 @@ func candidatesFromInfo(ctx context.Context, info *api.ControlPlaneInfoResponse)seen := map[peer.ID]bool{}for _, r := range info.GetRouters() {id, err := peer.Decode(r.GetPeerId())- if err != nil || seen[id] {+ if err != nil {+ s.log().Warn("skipping router entry with invalid peer ID", "peer_id", r.GetPeerId(), "error", err)+ continue+ }+ if seen[id] {continue}for _, pi := range routerPeers(ctx, parseMultiaddrs(r.GetAddresses())) {@@ -411,7 +415,9 @@ func (s *Server) admitByRouters(ctx context.Context) error {delay := routerRedialDelayfor attempt := 1; ; attempt++ {if attempt > 1 {- _ = s.syncMeshInfo(ctx)+ if err := s.syncMeshInfo(ctx); err != nil {+ s.log().Warn("failed refreshing router catalog during admission retry", "attempt", attempt, "error", err)+ }}targets := s.pickRouters(s.wantRouters())var fatal error@@ -673,6 +679,7 @@ func (s *Server) redialUntilUp(ctx context.Context, router peer.ID) bool {}addrs := s.host.Peerstore().Addrs(router)if len(addrs) == 0 {+ s.log().Warn("detaching router during redial: no addresses in peerstore", "router_peer_id", router.String())s.detach(router)return false}@@ -682,12 +689,21 @@ func (s *Server) redialUntilUp(ctx context.Context, router peer.ID) bool {return true}if errors.Is(err, errFatalAuth) {+ s.log().Warn("fatal auth failure during router redial; detaching and shunning router",+ "router_peer_id", router.String(),+ "shun_duration", defaultShunDuration,+ "error", err,+ )s.detach(router)s.shun(router, defaultShunDuration)return false}delay *= 2}+ s.log().Warn("redial attempts exhausted; detaching and shunning router",+ "router_peer_id", router.String(),+ "shun_duration", defaultShunDuration,+ )s.detach(router)s.shun(router, defaultShunDuration)return false@@ -909,7 +925,9 @@ func (s *Server) syncTrustedKeys(ctx context.Context) error {s.keysMu.Lock()s.trustedKeys = mergeds.keysMu.Unlock()- _ = s.persistState()+ if err := s.persistState(); err != nil {+ return fmt.Errorf("persist state: %w", err)+ }return nil}@@ -967,9 +985,11 @@ func (s *Server) syncMeshInfo(ctx context.Context) error {s.credMu.Lock()s.storedRouterAddrs = slices.Clone(info.GetRouterAddresses())s.credMu.Unlock()- _ = s.persistState()+ if err := s.persistState(); err != nil {+ return fmt.Errorf("persist state: %w", err)+ }}- s.setRouterCatalog(candidatesFromInfo(ctx, info))+ s.setRouterCatalog(s.candidatesFromInfo(ctx, info))}settings := api.DirectorySettingsFrom(info.GetDirectory())s.mu.Lock()@@ -1070,6 +1090,7 @@ func (s *Server) reconcileBannedPeers(peerIDs []string, fetchedAt time.Time) {for _, id := range peerIDs {p, err := peer.Decode(id)if err != nil {+ s.log().Warn("ignoring invalid peer ID in banned list", "peer_id", id, "error", err)continue}banned[p.String()] = p@@ -1205,6 +1226,7 @@ func (s *Server) listenForControlPlaneEvents(ctx context.Context) {case api.MeshEvent_BANNED:p, err := peer.Decode(evt.GetPeerId())if err != nil {+ s.log().Warn("ignoring BANNED gossip event with invalid peer ID", "peer_id", evt.GetPeerId(), "error", err)continue}canonical := p.String()diff --git a/sdk/meshnet/server.go b/sdk/meshnet/server.goindex 7891025a..93502f3e 100644--- a/sdk/meshnet/server.go+++ b/sdk/meshnet/server.go@@ -549,15 +549,21 @@ func (s *Server) Close() error {}hasAnnouncedA2A = trueif nameKey, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, e.name); err == nil {- _ = s.dir.withdraw(wCtx, nameKey)+ if wErr := s.dir.withdraw(wCtx, nameKey); wErr != nil && !errors.Is(wErr, errNoDirectoryRouter) {+ s.log().Debug("failed withdrawing A2A service key on close", "service", e.name, "error", wErr)+ }}}if hasAnnouncedA2A {if typeKey, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, ""); err == nil {- _ = s.dir.withdraw(wCtx, typeKey)+ if wErr := s.dir.withdraw(wCtx, typeKey); wErr != nil && !errors.Is(wErr, errNoDirectoryRouter) {+ s.log().Debug("failed withdrawing A2A service type key on close", "error", wErr)+ }}}- _ = s.dir.withdraw(wCtx, api.PeerKey(s.peerID))+ if wErr := s.dir.withdraw(wCtx, api.PeerKey(s.peerID)); wErr != nil && !errors.Is(wErr, errNoDirectoryRouter) {+ s.log().Debug("failed withdrawing peer key on close", "error", wErr)+ }cancel()}diff --git a/sdk/meshnet/statedir.go b/sdk/meshnet/statedir.goindex a170e01b..d5b4b80d 100644--- a/sdk/meshnet/statedir.go+++ b/sdk/meshnet/statedir.go@@ -258,10 +258,17 @@ func (s *Server) ensureCredential(ctx context.Context) error {}// Try OIDC refresh_token recovery if stored in credential.json.- if jwtStr, oidcErr := s.renewFromOIDCSession(ctx); oidcErr == nil && jwtStr != "" {- if regErr := s.enrollJWT(ctx, jwtStr); regErr == nil {- s.log().Info("re-enrolled via saved OIDC session", "peer_id", s.peerID.String())- return nil+ if s.hasOIDCSession() {+ jwtStr, oidcErr := s.renewFromOIDCSession(ctx)+ if oidcErr != nil {+ s.log().Warn("saved OIDC session refresh failed on startup", "peer_id", s.peerID.String(), "error", oidcErr)+ } else if jwtStr != "" {+ if regErr := s.enrollJWT(ctx, jwtStr); regErr == nil {+ s.log().Info("re-enrolled via saved OIDC session", "peer_id", s.peerID.String())+ return nil+ } else {+ s.log().Warn("re-enrollment via saved OIDC session failed on startup", "peer_id", s.peerID.String(), "error", regErr)+ }}}@@ -713,7 +720,10 @@ func (s *Server) Refresh(ctx context.Context) error {freshJWT = strings.TrimSpace(tok)}} else if s.JWTPath != "" {- if raw, err := os.ReadFile(s.JWTPath); err == nil {+ raw, err := os.ReadFile(s.JWTPath)+ if err != nil {+ s.log().Warn("failed reading JWTPath during refresh; attempting session-backed refresh", "path", s.JWTPath, "error", err)+ } else {freshJWT = strings.TrimSpace(string(raw))}}@@ -788,6 +798,12 @@ func (s *Server) Refresh(ctx context.Context) error {return nil}+func (s *Server) hasOIDCSession() bool {+ s.credMu.RLock()+ defer s.credMu.RUnlock()+ return s.oidcSession != nil && s.oidcSession.GetIssuer() != "" && s.oidcSession.GetClientId() != "" && s.oidcSession.GetRefreshToken() != ""+}+func (s *Server) renewFromOIDCSession(ctx context.Context) (string, error) {s.credMu.RLock()sess := s.oidcSession@@ -852,6 +868,9 @@ func (s *Server) renewFromOIDCSession(ctx context.Context) (string, error) {s.oidcSession.RefreshToken = tokOut.RefreshToken}s.credMu.Unlock()+ if err := s.persistState(); err != nil {+ return "", fmt.Errorf("persist state: %w", err)+ }}if tokOut.IDToken != "" {return tokOut.IDToken, nil@@ -893,19 +912,28 @@ func (s *Server) startRenewalLoop(ctx context.Context) {s.log().Warn("proactive biscuit refresh failed; attempting token re-enrollment", "error", err)}- if jwtStr, err := s.renewFromOIDCSession(ctx); err == nil && jwtStr != "" {- if regErr := s.enrollJWT(ctx, jwtStr); regErr == nil {- s.log().Info("renewed mesh credential via OIDC session", "peer_id", s.peerID.String())- continue+ if s.hasOIDCSession() {+ jwtStr, err := s.renewFromOIDCSession(ctx)+ if err != nil {+ s.log().Warn("OIDC background token refresh failed", "peer_id", s.peerID.String(), "error", err)+ } else if jwtStr != "" {+ if regErr := s.enrollJWT(ctx, jwtStr); regErr == nil {+ s.log().Info("renewed mesh credential via OIDC session", "peer_id", s.peerID.String())+ continue+ } else {+ s.log().Warn("OIDC background renewal failed", "peer_id", s.peerID.String(), "error", regErr)+ }}}kind, tok, err := s.resolveJoinSecret(ctx)- if err == nil && kind == joinSecretJWT {+ if err != nil {+ s.log().Warn("failed resolving join secret during renewal", "peer_id", s.peerID.String(), "error", err)+ } else if kind == joinSecretJWT {if regErr := s.enrollJWT(ctx, tok); regErr == nil {s.log().Info("renewed mesh credential via JWT source", "peer_id", s.peerID.String())continue} else {- s.log().Error("JWT re-enrollment failed", "error", regErr)+ s.log().Error("JWT re-enrollment failed", "peer_id", s.peerID.String(), "error", regErr)}}}diff --git a/sdk/meshnet/statedir_test.go b/sdk/meshnet/statedir_test.goindex d7a0c075..d4126bde 100644--- a/sdk/meshnet/statedir_test.go+++ b/sdk/meshnet/statedir_test.go@@ -394,7 +394,7 @@ func newFakeControlPlaneHTTPWithKeys(t *testing.T, pub ed25519.PublicKey, priv ewriteProto(w, &api.ControlPlaneInfoResponse{RouterAddresses: addrs})})mux.HandleFunc("/policies", func(w http.ResponseWriter, _ *http.Request) {- compiled, _ := api.BuildPolicyRules([]*api.PolicyRole{+ compiled, warnings := api.BuildPolicyRules([]*api.PolicyRole{{Name: api.RoleNode,AllowedTargets: []string{"*"},@@ -402,6 +402,10 @@ func newFakeControlPlaneHTTPWithKeys(t *testing.T, pub ed25519.PublicKey, priv eAllowedPublish: []string{"*"},},}, nil)+ if len(warnings) > 0 {+ http.Error(w, strings.Join(warnings, "; "), http.StatusInternalServerError)+ return+ }texts := make([]string, 0, len(compiled))for _, r := range compiled {texts = append(texts, r.Text)@@ -428,12 +432,17 @@ func newFakeControlPlaneHTTPWithKeys(t *testing.T, pub ed25519.PublicKey, priv e})return}+ pid, err := peer.Decode(req.GetPeerId())+ if err != nil {+ http.Error(w, "invalid peer_id", http.StatusBadRequest)+ return+ }pubKey, privKey := f.currentKeys()f.mu.Lock()addrs := append([]string(nil), f.routerAddrs...)f.mu.Unlock()exp := time.Now().Add(time.Hour)- tok := mintTestBiscuit(t, privKey, req.GetPeerId(), api.RoleNode, exp)+ tok := mintTestBiscuit(t, privKey, pid.String(), api.RoleNode, exp)writeProto(w, &api.BootstrapEnrollResponse{Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,BiscuitToken: tok,@@ -443,9 +452,10 @@ func newFakeControlPlaneHTTPWithKeys(t *testing.T, pub ed25519.PublicKey, priv e})})mux.HandleFunc("/enroll/status", func(w http.ResponseWriter, r *http.Request) {- peerID := r.URL.Query().Get("peer_id")- if peerID == "" {- http.Error(w, "missing peer_id", http.StatusBadRequest)+ rawPeerID := r.URL.Query().Get("peer_id")+ pid, err := peer.Decode(rawPeerID)+ if err != nil {+ http.Error(w, "invalid peer_id", http.StatusBadRequest)return}if f.pendingBootstrapPolls.Add(-1) >= 1 {@@ -460,7 +470,7 @@ func newFakeControlPlaneHTTPWithKeys(t *testing.T, pub ed25519.PublicKey, priv eaddrs := append([]string(nil), f.routerAddrs...)f.mu.Unlock()exp := time.Now().Add(time.Hour)- tok := mintTestBiscuit(t, privKey, peerID, api.RoleNode, exp)+ tok := mintTestBiscuit(t, privKey, pid.String(), api.RoleNode, exp)writeProto(w, &api.BootstrapEnrollResponse{Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,BiscuitToken: tok,@@ -474,12 +484,17 @@ func newFakeControlPlaneHTTPWithKeys(t *testing.T, pub ed25519.PublicKey, priv eif !readProto(w, r, &req) {return}+ pid, err := peer.Decode(req.GetPeerId())+ if err != nil {+ http.Error(w, "invalid peer_id", http.StatusBadRequest)+ return+ }pubKey, privKey := f.currentKeys()f.mu.Lock()addrs := append([]string(nil), f.routerAddrs...)f.mu.Unlock()exp := time.Now().Add(time.Hour)- tok := mintTestBiscuit(t, privKey, req.GetPeerId(), api.RoleNode, exp)+ tok := mintTestBiscuit(t, privKey, pid.String(), api.RoleNode, exp)writeProto(w, &api.EnrollResponse{BiscuitToken: tok,ControlPlanePublicKey: pubKey,@@ -497,6 +512,11 @@ func newFakeControlPlaneHTTPWithKeys(t *testing.T, pub ed25519.PublicKey, priv eif !readProto(w, r, &req) {return}+ pid, err := peer.Decode(req.GetPeerId())+ if err != nil {+ http.Error(w, "invalid peer_id", http.StatusBadRequest)+ return+ }rawAuth := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")biscuitBytes, err := base64.StdEncoding.DecodeString(rawAuth)if err != nil {@@ -514,7 +534,7 @@ func newFakeControlPlaneHTTPWithKeys(t *testing.T, pub ed25519.PublicKey, priv ereturn}exp := time.Now().Add(2 * time.Hour)- tok := mintTestBiscuit(t, privKey, req.GetPeerId(), api.RoleNode, exp)+ tok := mintTestBiscuit(t, privKey, pid.String(), api.RoleNode, exp)writeProto(w, &api.TokenRefreshResponse{BiscuitToken: tok,ExpireTime: timestamppb.New(exp),diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.mdindex ff6a7af8..dc2ee538 100644--- a/site/content/docs/contributing/security-architecture.md+++ b/site/content/docs/contributing/security-architecture.md@@ -290,8 +290,8 @@ least one `TaskRule` in every appended block.Every enforcement point builds its Datalog authorizer through`identity.AuthorizeMeshRequest(authorizer, MeshRequest, MeshPolicy)`: the-node's in-mesh verifier (`/libp2p-http`, `/mesh/mcp`, the local sidecar), the-node's external ingress handler (`/mesh/ingress/1.0.0`), the router's edge+node's and `sdk/meshnet`'s in-mesh verifiers (`/libp2p-http`, `/mesh/mcp`, the local sidecar), the+node's and `sdk/meshnet`'s external ingress handlers (`/mesh/ingress/1.0.0`), the router's edgecheck on `/ingress/*`, and the control plane's `/sts/token`. `MeshRequest`says what the request is (`service()`, `method()`/`path()` when it is HTTP,`host()`/`port()` when it is egress, the connection peer when there is adiff --git a/site/content/docs/guides/connecting-agents.md b/site/content/docs/guides/connecting-agents.mdindex 9312124a..8e4d093d 100644--- a/site/content/docs/guides/connecting-agents.md+++ b/site/content/docs/guides/connecting-agents.md@@ -226,9 +226,9 @@ version of this example. For inference, point any OpenAI SDK at`http://127.0.0.1:8080/v1` with the token as `api_key`, or at the socket withno key.-Native SDKs that join the mesh from inside the agent process, without a-`agentmesh-node` sidecar, are being built under `sdk/` in the repository; see-`sdk/README.md` for their status.+To join the mesh directly from inside an agent process without an+`agentmesh-node` sidecar, see the [Embedded Go SDK (`sdk/meshnet`)](../go-sdk/)+and the [Native SDKs for JavaScript and Python](../native-sdks/).## Without a node: the MCP registry serverdiff --git a/site/content/docs/guides/external-ingress.md b/site/content/docs/guides/external-ingress.mdindex efd08920..86ad9b2f 100644--- a/site/content/docs/guides/external-ingress.md+++ b/site/content/docs/guides/external-ingress.md@@ -155,6 +155,25 @@ auth mode, `agentmesh-node` logs an error, increments`agentmesh_node_service_provide_failures_total{scope="ingress"}`, and falls backto announcing the service internally so mesh peers can still reach it.+### From Go (`sdk/meshnet`)++A single-binary Go agent using the [Embedded Go SDK](../go-sdk/) opts into the+same router ingress without `agentmesh-node`:++```go+ep, err := srv.ListenA2A(ctx, meshnet.A2AOptions{+ Name: "coder",+ Description: "Repository coding agent",+ Public: true,+ IngressAuth: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,+ IngressAllow: []string{"email:[email protected]", "group:teammates"},+})+```++`ep.PublicListener` delivers verified external requests in-process (`ep.PublicURL`+holds `<router_ingress_url>/<peer_id>/a2a/coder`), while `ep.PrivateListener`+serves internal mesh peers over `/libp2p-http`.+## How `edge` and `passthrough` behave### `auth_mode: edge` (default)diff --git a/site/content/docs/guides/go-sdk.md b/site/content/docs/guides/go-sdk.mdnew file mode 100644index 00000000..3d784582--- /dev/null+++ b/site/content/docs/guides/go-sdk.md@@ -0,0 +1,466 @@+---+title: "Embedded Go SDK (meshnet)"+linkTitle: "Embedded Go SDK"+weight: 6+---++Package [`github.com/google/agentmesh/sdk/meshnet`](https://github.com/google/agentmesh/tree/main/sdk/meshnet)+embeds an Agent Mesh member directly inside a Go binary—modeled on+[`tailscale.com/tsnet`](https://pkg.go.dev/tailscale.com/tsnet)—with no external+`agentmesh-node` sidecar process and no loopback bearer token.++Use `sdk/meshnet` when you are shipping a single Go binary (an A2A agent, a CLI+such as `a2a-serve`, or an orchestrator) that should enroll, serve A2A over+private P2P and optional external HTTPS ingress, inspect verified callers, call+peer services, delegate attenuated task tokens, or hand local subprocesses a+Unix socket for progressive-discovery MCP and zero-secret `/v1` inference.++| Integration | Best fit | Directory announcement |+| :--- | :--- | :--- |+| **`sdk/meshnet` (Go)** | Single-binary Go agents, CLIs, and orchestrators | Announces `a2a://<name>` (plus optional external HTTP ingress) to the router directory unless `NoAnnounce: true`, and answers `system://mesh.catalog` |+| **[Native SDKs](../native-sdks/) (`sdk/js`, `sdk/python`)** | Node.js, browser, and Python agents | Answers `a2a://<name>` by Peer ID without publishing directory records |+| **`agentmesh-node` sidecar** | Language-agnostic sidecar/gateway wrapping unmodified servers (`mcp://`, `inference://`, `a2a://`), `egress://` `CloudTokenExchanger`, and Envoy / `agentgateway` PEPs | Publishes configured services from `agentmesh-node.yaml` |++Both runnable programs on this page live in+[`sdk/meshnet/examples`](https://github.com/google/agentmesh/tree/main/sdk/meshnet/examples)+and are compiled and linted in CI.++## 1. Start or join a mesh++For local development, run `agentmesh-one` in one terminal:++```bash+agentmesh-one --data-dir ~/agentmesh-one+```++Point your shell at its control plane URL and join-token file (never pass a+secret on a command-line flag where it would appear in `ps` output):++```bash+export AGENTMESH_CONTROL_PLANE_URL=http://127.0.0.1:33775 # API URL printed in the banner+export AGENTMESH_BOOTSTRAP_TOKEN_PATH=~/agentmesh-one/join-token+export AGENTMESH_INSECURE_CONTROL_PLANE=1 # loopback http:// only; omit for https:// hubs+```++On a shared or production mesh (`https://...`), omit+`AGENTMESH_INSECURE_CONTROL_PLANE` and supply either `BootstrapTokenPath` or a+platform workload JWT via `JWTPath` / `TokenSource` (see+[Headless enrollment](../headless-enrollment/)).++## 2. Serve an A2A agent (Private P2P + Public HTTPS Ingress)++`Server.ListenA2A` registers an A2A service in-process, announces `a2a://<name>`+to the held mesh routers, and returns in-memory `net.Listener`s that work with+any `net/http` handler—including the unmodified official `a2a-go` server+(`github.com/a2aproject/a2a-go/v2/a2asrv`):++<!-- embed: sdk/meshnet/examples/agent/main.go -->+```go+// 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.++// Command agent embeds an Agent Mesh member in-process with sdk/meshnet and+// serves an A2A agent over private P2P (/libp2p-http) and router external HTTP+// ingress (/mesh/ingress/1.0.0), optionally exposing the local MCP and /v1+// inference handlers on a Unix domain socket.+package main++import (+ "cmp"+ "context"+ "errors"+ "fmt"+ "iter"+ "log"+ "net"+ "net/http"+ "os"+ "os/signal"+ "syscall"+ "time"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2asrv"+ "github.com/google/agentmesh/api"+ "github.com/google/agentmesh/sdk/meshnet"+)++func main() {+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ srv := &meshnet.Server{+ StateDir: cmp.Or(os.Getenv("AGENTMESH_STATE_DIR"), "./state-agent"),+ ControlPlaneURL: os.Getenv("AGENTMESH_CONTROL_PLANE_URL"),+ BootstrapTokenPath: os.Getenv("AGENTMESH_BOOTSTRAP_TOKEN_PATH"),+ JWTPath: os.Getenv("AGENTMESH_JWT_PATH"),+ AllowInsecure: os.Getenv("AGENTMESH_INSECURE_CONTROL_PLANE") == "1",+ }+ status, err := srv.Up(ctx)+ if err != nil {+ log.Fatalf("meshnet.Up: %v", err)+ }+ defer func() {+ if err := srv.Close(); err != nil {+ log.Printf("meshnet.Close: %v", err)+ }+ }()++ agentName := cmp.Or(os.Getenv("AGENTMESH_AGENT_NAME"), "coder")+ ep, err := srv.ListenA2A(ctx, meshnet.A2AOptions{+ Name: agentName,+ Description: "Echo coding agent embedded via sdk/meshnet",+ Public: true,+ IngressAuth: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,+ })+ if err != nil {+ log.Fatalf("ListenA2A: %v", err)+ }+ defer func() {+ if err := ep.Close(); err != nil {+ log.Printf("Endpoints.Close: %v", err)+ }+ }()++ exec := a2asrv.AgentExecutorFunc(func(_ context.Context, ec *a2asrv.ExecutorContext) iter.Seq2[a2a.Event, error] {+ return func(yield func(a2a.Event, error) bool) {+ var prompt string+ if ec.Message != nil && len(ec.Message.Parts) > 0 {+ prompt = ec.Message.Parts[0].Text()+ }+ yield(a2a.NewMessageForTask(a2a.MessageRoleAgent, ec, a2a.NewTextPart("echo: "+prompt)), nil)+ }+ })+ card := &a2a.AgentCard{+ Name: agentName,+ Description: "Echo coding agent embedded via sdk/meshnet",+ Version: "1.0.0",+ SupportedInterfaces: []*a2a.AgentInterface{+ {+ URL: ep.PrivateURL.String() + "/invoke",+ ProtocolBinding: a2a.TransportProtocolJSONRPC,+ ProtocolVersion: "1.0",+ },+ },+ }++ rpcHandler := a2asrv.NewJSONRPCHandler(a2asrv.NewHandler(exec))+ mux := http.NewServeMux()+ mux.Handle(a2asrv.WellKnownAgentCardPath, a2asrv.NewStaticAgentCardHandler(card))+ mux.Handle("/invoke", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if caller, ok := srv.WhoIs(r.RemoteAddr); ok && caller != nil {+ log.Printf("verified caller principal=%s peer=%s task=%s", caller.Principal, caller.PeerID, caller.Task)+ }+ rpcHandler.ServeHTTP(w, r)+ }))++ privHTTP := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = privHTTP.Close() }()+ go func() {+ if err := privHTTP.Serve(ep.PrivateListener); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("private listener: %v", err)+ }+ }()++ if ep.PublicListener != nil {+ pubHTTP := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = pubHTTP.Close() }()+ go func() {+ if err := pubHTTP.Serve(ep.PublicListener); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("public listener: %v", err)+ }+ }()+ }++ if sockPath := os.Getenv("AGENTMESH_SOCKET_PATH"); sockPath != "" {+ _ = os.Remove(sockPath)+ var lc net.ListenConfig+ unixLn, err := lc.Listen(ctx, "unix", sockPath)+ if err != nil {+ log.Fatalf("listen unix %s: %v", sockPath, err)+ }+ defer func() {+ _ = unixLn.Close()+ _ = os.Remove(sockPath)+ }()+ localMux := http.NewServeMux()+ localMux.Handle("/mcp", srv.MCPHandler())+ localMux.Handle("/v1/", srv.InferenceHandler())+ localHTTP := &http.Server{Handler: localMux, ReadHeaderTimeout: 10 * time.Second}+ defer func() { _ = localHTTP.Close() }()+ go func() {+ if err := localHTTP.Serve(unixLn); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {+ log.Printf("unix socket listener: %v", err)+ }+ }()+ fmt.Printf("Local Socket: %s (/mcp, /v1/)\n", sockPath)+ }++ fmt.Printf("Peer ID: %s\n", status.PeerID)+ fmt.Printf("Private A2A: %s\n", ep.PrivateURL)+ if ep.PublicURL != nil {+ fmt.Printf("Public A2A: %s\n", ep.PublicURL)+ }+ <-ctx.Done()+}+```+<!-- /embed -->++Run the agent:++```bash+go run ./sdk/meshnet/examples/agent+```++```text+Peer ID: 12D3KooW...+Private A2A: http://agentmesh.local/mesh/12D3KooW.../a2a/coder+Public A2A: http://127.0.0.1:33776/ingress/12D3KooW.../a2a/coder+```++### How `ListenA2A` handles private and public traffic++- **Two listeners, one `http.Handler`:** `ep.PrivateListener` serves+ authenticated mesh peers over `/libp2p-http`. When `Public: true`,+ `ep.PublicListener` serves external HTTPS requests forwarded by enrolled+ routers over `/mesh/ingress/1.0.0`.+- **Automatic `AgentCard` URL rewriting:** `meshnet` relativizes interface URLs+ on `GET /.well-known/agent-card.json` and rewrites `supportedInterfaces` to+ match how each caller reached the agent (`http://agentmesh.local/mesh/<peer_id>/a2a/<name>`+ for mesh peers, `<public-ingress>/<peer_id>/a2a/<name>` for external HTTPS+ callers).+- **Unspoofable caller identity (`Server.WhoIs`):** Inside your HTTP handler,+ `srv.WhoIs(r.RemoteAddr)` returns the cryptographically verified `*CallerInfo`+ (`PeerID`, `Principal`, `Roles`, `Labels`, `Task`) bound to that in-memory+ connection—never trusting spoofable HTTP headers.+- **`EDGE` vs. `PASSTHROUGH` ingress:** `INGRESS_AUTH_MODE_EDGE` (the default)+ verifies Delegated Session Biscuits at both the router and the `meshnet`+ server (`identity.AuthorizeMeshRequest` + `IngressAllow`), while still serving+ `GET /.well-known/agent-card.json` anonymously for A2A discovery.+ `INGRESS_AUTH_MODE_PASSTHROUGH` strips spoofable `X-Mesh-*` headers and+ forwards `Authorization` untouched to your handler when your mesh role+ explicitly grants `PASSTHROUGH` in `PolicyRole.allowed_ingress`; see+ [External ingress](../external-ingress/).+- **Graceful policy-ceiling fallback:** If `Public: true` is requested on a hub+ whose `PolicyRole.allowed_ingress` denies public exposure for that service or+ auth mode, `ListenA2A` logs a warning, falls back to announcing the service+ privately inside the mesh, and sets `ep.PublicURL` to `nil` rather than+ failing startup.++## 3. Discover and call mesh agents with stock `a2a-go`++`Server.Discover` queries the router directory for healthy providers of a+service, and `Server.HTTPClient` returns an `*http.Client` that routes+`http://agentmesh.local/mesh/<peer_id>/<type>/<name>[/<path>]` directly over+authenticated `/libp2p-http` streams:++<!-- embed: sdk/meshnet/examples/call/main.go -->+```go+// 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.++// Command call joins an Agent Mesh in-process with sdk/meshnet, discovers an+// A2A service by name (or dials an explicit mesh URL), and sends a message+// using the unmodified official a2a-go client over srv.HTTPClient().+package main++import (+ "cmp"+ "context"+ "fmt"+ "log"+ "os"+ "os/signal"+ "strings"+ "syscall"+ "time"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"+ "github.com/google/agentmesh/api"+ "github.com/google/agentmesh/sdk/meshnet"+)++func main() {+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ target := "coder"+ prompt := "hello from meshnet"+ if len(os.Args) > 1 {+ target = os.Args[1]+ }+ if len(os.Args) > 2 {+ prompt = strings.Join(os.Args[2:], " ")+ }++ srv := &meshnet.Server{+ StateDir: cmp.Or(os.Getenv("AGENTMESH_STATE_DIR"), "./state-caller"),+ ControlPlaneURL: os.Getenv("AGENTMESH_CONTROL_PLANE_URL"),+ BootstrapTokenPath: os.Getenv("AGENTMESH_BOOTSTRAP_TOKEN_PATH"),+ JWTPath: os.Getenv("AGENTMESH_JWT_PATH"),+ AllowInsecure: os.Getenv("AGENTMESH_INSECURE_CONTROL_PLANE") == "1",+ }+ if _, err := srv.Up(ctx); err != nil {+ log.Fatalf("meshnet.Up: %v", err)+ }+ defer func() {+ if err := srv.Close(); err != nil {+ log.Printf("meshnet.Close: %v", err)+ }+ }()++ baseURL := target+ if !strings.HasPrefix(target, "http://") {+ providers, err := srv.Discover(ctx, api.ServiceType_SERVICE_TYPE_A2A, target)+ if err != nil {+ log.Fatalf("Discover(%q): %v", target, err)+ }+ if len(providers) == 0 {+ log.Fatalf("no providers found in mesh directory for a2a://%s", target)+ }+ baseURL = providers[0].GetLocalProxyUrl()+ }++ callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ meshHTTP := srv.HTTPClient()+ card, err := agentcard.NewResolver(meshHTTP).Resolve(callCtx, baseURL)+ if err != nil {+ log.Fatalf("Resolve(%q): %v", baseURL, err)+ }+ client, err := a2aclient.NewFromCard(callCtx, card, a2aclient.WithJSONRPCTransport(meshHTTP))+ if err != nil {+ log.Fatalf("NewFromCard: %v", err)+ }+ res, err := client.SendMessage(callCtx, &a2a.SendMessageRequest{+ Message: a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart(prompt)),+ })+ if err != nil {+ log.Fatalf("SendMessage: %v", err)+ }++ if msg, ok := res.(*a2a.Message); ok {+ for _, part := range msg.Parts {+ if text := part.Text(); text != "" {+ fmt.Println(text)+ }+ }+ return+ }+ fmt.Printf("%+v\n", res)+}+```+<!-- /embed -->++In a second terminal pointed at the same mesh, call the `coder` agent by name:++```bash+go run ./sdk/meshnet/examples/call coder "review PR #42"+```++```text+echo: review PR #42+```++Before sending a single byte of your request body, `srv.HTTPClient()` verifies+that the remote peer's Biscuit is signed by a trusted control-plane key, has+not been revoked or banned, is authorized by mesh policy to publish+`a2a://coder`, and carries every label required by `srv.EgressRequireLabels`+(and any per-request `X-Mesh-Required-Labels` header). Because `HTTPClient()`+sets no client-wide timeout, A2A Server-Sent Events (`SendStreamingMessage`) and+streaming LLM completions run unbounded while connection and header setup remain+bounded by libp2p stream deadlines.++## 4. Delegate task-scoped credentials (`AttenuateToken`)++When an orchestrator needs to hand a narrower, short-lived credential to a+worker or external sub-agent without giving it standing mesh authority, call+`srv.AttenuateToken` to append a `tar_block` (`api.TaskAuthorizationRule`, 0+Datalog rules, 0 checks) and optionally seal the Biscuit in memory:++```go+rule := &api.TaskAuthorizationRule{+ Name: "review-pr-42",+ DisplayName: "Call a2a://coder only",+ Rules: []*api.TaskRule{+ {+ AllowedServices: []string{"a2a://coder"},+ Operation: &api.TaskOperation{AllowedMethods: []string{"POST"}},+ },+ },+}++sealedToken, exp, err := srv.AttenuateToken(rule, 5*time.Minute, true)+```++Every Agent Mesh PEP (`agentmesh-router`, `agentmesh-node`, `sdk/meshnet`,+`sdk/js`, and `sdk/python`) enforces the strict intersection of Block 0 Datalog+RBAC and every appended `TaskAuthorizationRule`. With `seal == true`, the+recipient cannot append further blocks.++## 5. Local MCP and zero-secret `/v1` inference for subprocesses++When your Go process spawns an LLM runtime or CLI subprocess (for example Claude+Code, Gemini CLI, or a sandboxed coding tool), mount `srv.MCPHandler()` and+`srv.InferenceHandler()` on a local Unix domain socket (shown via+`AGENTMESH_SOCKET_PATH` in `examples/agent/main.go`):++- **`srv.MCPServer()` / `srv.MCPHandler()`** exposes the 6 progressive-discovery+ mesh tools (`list_local_services`, `discover_remote_services`,+ `get_mesh_info`, `find_remote_tools`, `describe_remote_tool`,+ `call_remote_tool`) so an agent discovers and invokes remote `mcp://*` tools+ across the mesh without loading hundreds of schemas upfront.+- **`srv.InferenceHandler()`** serves OpenAI-compatible `GET /v1/models`,+ `POST /v1/chat/completions`, and `POST /v1/completions` routed over mesh+ `inference://*` providers with automatic Biscuit injection, streaming SSE+ pass-through, and failover—requiring zero API keys in the subprocess+ environment.++## 6. State directory interoperability (`StateDir`)++`Server.StateDir` persists `identity.key` and `credential.json` with owner-only+permissions (`0700` directory, `0600` files) using the exact protobuf/protojson+layout shared by `agentmesh-node`, `sdk/js`, and `sdk/python`.++An operator can enroll interactively once with `agentmesh-node` and pass the+exported state directory directly to a Go binary built on `sdk/meshnet` (with no+join token needed at runtime):++```bash+agentmesh-node join --hub https://bananas.sam-mesh.dev+agentmesh-node state export ~/.config/my-agent/agentmesh+AGENTMESH_STATE_DIR=~/.config/my-agent/agentmesh go run ./sdk/meshnet/examples/agent+```++Conversely, a state directory populated by `meshnet.Server` (or written with+`meshnet.WriteStateDir` and inspected with `meshnet.ReadStateDir`) can be+imported into `agentmesh-node` with `agentmesh-node state import <dir>` or+opened directly by `sdk/js` and `sdk/python`. While `srv` is running, background+renewal refreshes credentials proactively before expiry, syncs rotated+control-plane signing keys, and enforces live `/mesh/events/v1` revocations and+peer bans within a second.diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.mdindex 6035e758..157c8108 100644--- a/site/content/docs/guides/native-sdks.md+++ b/site/content/docs/guides/native-sdks.md@@ -5,7 +5,10 @@ weight: 6---An agent written in JavaScript or Python can be a member of the mesh itself,-with no `agentmesh-node` beside it. The SDK enrolls with the control plane, joins+with no `agentmesh-node` beside it. (For Go programs that want an embedded+`tsnet`-style member with directory-published `ListenA2A`, external HTTP+ingress, `WhoIs`, and local `MCPHandler()` / `InferenceHandler()`, see+[Embedded Go SDK (`meshnet`)](../go-sdk/).) The SDK enrolls with the control plane, joinsthrough a router, finds services, calls MCP tools and inference or A2Aendpoints, and answers A2A requests for the agent itself. Every caller ofthe agent is checked against the mesh policy before anything reaches yourdiff --git a/tests/integration/meshnet_test.go b/tests/integration/meshnet_test.goindex 72ceaaaf..0a768002 100644--- a/tests/integration/meshnet_test.go+++ b/tests/integration/meshnet_test.go@@ -512,8 +512,11 @@ func TestMeshnetEndToEndIntegration(t *testing.T) {if err != nil {t.Fatalf("private GET ceiling-blocked: %v", err)}- privBlockedBody, _ := io.ReadAll(privBlockedResp.Body)+ privBlockedBody, err := io.ReadAll(privBlockedResp.Body)_ = privBlockedResp.Body.Close()+ if err != nil {+ t.Fatalf("io.ReadAll(ceiling-blocked): %v", err)+ }if privBlockedResp.StatusCode != http.StatusOK || string(privBlockedBody) != "private-still-works" {t.Fatalf("private ceiling-blocked = %d %q, want 200 private-still-works", privBlockedResp.StatusCode, privBlockedBody)}@@ -695,8 +698,11 @@ func TestMeshnetEndToEndIntegration(t *testing.T) {if err != nil {t.Fatalf("GET /v1/models: %v", err)}- modelsBody, _ := io.ReadAll(modelsResp.Body)+ modelsBody, err := io.ReadAll(modelsResp.Body)_ = modelsResp.Body.Close()+ if err != nil {+ t.Fatalf("io.ReadAll(/v1/models): %v", err)+ }if modelsResp.StatusCode != http.StatusOK || !strings.Contains(string(modelsBody), "mesh-qwen") {t.Fatalf("GET /v1/models = %d %s, want mesh-qwen", modelsResp.StatusCode, modelsBody)}@@ -706,8 +712,11 @@ func TestMeshnetEndToEndIntegration(t *testing.T) {if err != nil {t.Fatalf("POST /v1/chat/completions: %v", err)}- chatBody, _ := io.ReadAll(chatResp.Body)+ chatBody, err := io.ReadAll(chatResp.Body)_ = chatResp.Body.Close()+ if err != nil {+ t.Fatalf("io.ReadAll(/v1/chat/completions): %v", err)+ }if chatResp.StatusCode != http.StatusOK || !strings.Contains(string(chatBody), "mesh-reply") {t.Fatalf("POST /v1/chat/completions = %d %s, want mesh-reply", chatResp.StatusCode, chatBody)}@@ -717,22 +726,31 @@ func TestMeshnetEndToEndIntegration(t *testing.T) {if err != nil {t.Fatalf("POST streaming /v1/chat/completions: %v", err)}- streamChatBody, _ := io.ReadAll(streamChatResp.Body)+ streamChatBody, err := io.ReadAll(streamChatResp.Body)_ = streamChatResp.Body.Close()+ if err != nil {+ t.Fatalf("io.ReadAll(streaming /v1/chat/completions): %v", err)+ }if streamChatResp.StatusCode != http.StatusOK || !strings.Contains(string(streamChatBody), "[DONE]") {t.Fatalf("POST streaming /v1/chat/completions = %d %s, want SSE [DONE]", streamChatResp.StatusCode, streamChatBody)}- badInfReq, _ := http.NewRequestWithContext(ctx, http.MethodPost, localInf.URL+"/v1/chat/completions",+ badInfReq, err := http.NewRequestWithContext(ctx, http.MethodPost, localInf.URL+"/v1/chat/completions",strings.NewReader(`{"model":"mesh-qwen","messages":[{"role":"user","content":"ping"}]}`))+ if err != nil {+ t.Fatalf("NewRequestWithContext(badInf): %v", err)+ }badInfReq.Header.Set("Content-Type", "application/json")badInfReq.Header.Set(api.HeaderMeshRequiredLabels, "tier=missing")badInfResp, err := extHTTP.Do(badInfReq)if err != nil {t.Fatalf("POST /v1/chat/completions with unmet label: %v", err)}- badInfBody, _ := io.ReadAll(badInfResp.Body)+ badInfBody, err := io.ReadAll(badInfResp.Body)_ = badInfResp.Body.Close()+ if err != nil {+ t.Fatalf("io.ReadAll(badInfResp): %v", err)+ }if badInfResp.StatusCode != http.StatusServiceUnavailable {t.Fatalf("unmet required label on inference = %d %s, want 503", badInfResp.StatusCode, badInfBody)}