Help us shape the future of Go! Take the 2026 Go Developer Survey

meshnet

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

README

sdk/meshnet — Embedded Go SDK for Agent Mesh

Package meshnet (github.com/google/agentmesh/sdk/meshnet) embeds an Agent Mesh member directly inside a Go binary—modeled on 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.

Capabilities

  • Lifecycle & State Compatibility (Server.Up, WriteStateDir, ReadStateDir): Built directly on internal/node.AgentMeshNode so embedded Go applications and agentmesh-node share one PEP. Holds the bbolt store lock (ErrStateDirLocked) on StateDir while running (or uses a temporary 0700 directory removed on Close when StateDir is empty), resumes cached credentials from StateDir (including public-client OIDCSession recovery that persists rotated refresh_tokens before POST /register), enrolls via BootstrapTokenPath / BootstrapToken / JWTPath / TokenSource, returns from Up as soon as the first router admits the member while remaining dials up to Routers finish in the background, refreshes credentials proactively, backs off exponentially (2s to 5m) and signals Done() / Err() / OnCredentialLapse (ErrCredentialLapsed, Status.CredentialLapsed) if a credential lapses, verifies signed /keys sets, and enforces live /mesh/events/v1 FloodSub revocations and bans.
  • In-Process A2A Serving (Server.ListenA2A): Announces a2a://<name> to the router directory (unless NoAnnounce: true) and returns in-memory net.Listeners (PrivateListener over /libp2p-http and optional PublicListener over /mesh/ingress/1.0.0 in EDGE or PASSTHROUGH mode) plus canonical PrivateURL and PublicURL endpoints (PublicURL is nil when NoAnnounce: true, when no router advertises an ingress_url, or when the hub policy ceiling withholds public exposure). Automatically relativizes and rewrites A2A AgentCard supportedInterfaces URLs per caller.
  • Per-Server Prometheus Metrics (Server.Registerer): Optionally registers peer_id-labeled state gauges and refusal/ingress counters (agentmesh_meshnet_*) so multiple Server instances can share a prometheus.Registerer without collision, unregistering all collectors on Close.
  • 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. Returns (nil, false) for unauthenticated external requests (INGRESS_AUTH_MODE_PASSTHROUGH and anonymous GET /.well-known/agent-card.json discovery), and sets PeerID to "" for verified external EDGE callers without a mesh node identity (such as OIDC users).
  • 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 (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.

Examples

1. Serve an A2A Agent (examples/agent)
// 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()
}
2. Discover & Call Remote Mesh Agents (examples/call)
// 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)
}
3. Interoperate with agentmesh-node State Directories

An operator can enroll interactively once with agentmesh-node and hand the resulting state directory directly to a Go binary embedding meshnet.Server:

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

Documentation

Overview

Package meshnet embeds an Agent Mesh member directly inside a Go program (modeled on tailscale.com/tsnet), providing in-process A2A listeners (private P2P and public external HTTP ingress), a mesh-routing *http.Client, unspoofable WhoIs caller inspection, a local progressive-discovery MCP server, and a zero-secret OpenAI-compatible /v1 inference handler without an external agentmesh-node sidecar binary.

Internally, meshnet wraps internal/node.AgentMeshNode so embedded Go applications and the standalone agentmesh-node binary share a single Policy Enforcement Point (PEP), router attachment loop, directory client, and credential lifecycle implementation.

Index

Constants

View Source
const (
	StateDirIdentityFile   = node.StateDirIdentityFile
	StateDirCredentialFile = node.StateDirCredentialFile
)

State directory filenames, matching sdk/js, sdk/python, and `agentmesh-node state export|import`.

Variables

View Source
var ErrCredentialLapsed = errors.New("meshnet: member credential expired and renewal failed")

ErrCredentialLapsed reports that the member's Biscuit credential has expired and background renewal failed. Background renewal continues retrying with exponential backoff until Close is called or renewal succeeds.

View Source
var ErrCredentialRetired = errors.New("meshnet: saved credential signing key retired; provide a join token to re-enroll")

ErrCredentialRetired indicates that the persisted credential's control-plane signing key was rotated past its grace period while this member was offline, and no join token or TokenSource was supplied to re-enroll.

View Source
var ErrStateDirLocked = errors.New("meshnet: state directory is already locked by another instance")

ErrStateDirLocked reports that another running Server or agentmesh-node instance already holds the bbolt file lock on StateDir.

Functions

func ReadStateDir

func ReadStateDir(dir string) ([]byte, *api.MemberCredential, error)

ReadStateDir loads a member's libp2p private key and MemberCredential from dir, rejecting unknown fields in credential.json.

When MemberCredential.oidc_session is populated (for example from an interactive `agentmesh-node join` export), Server uses it to recover expired credentials for public OIDC clients (no client_secret is stored in MemberCredential) and persists any rotated refresh_token immediately before calling POST /register so one-time refresh tokens survive transient failures.

func WriteStateDir

func WriteStateDir(dir string, privKey []byte, c *api.MemberCredential) error

WriteStateDir writes a member's libp2p private key and MemberCredential to dir with owner-only permissions (0700 directory, 0600 files).

Types

type A2AOptions

type A2AOptions struct {
	// Name is the service name published under a2a://<Name>. Required.
	Name string
	// Description is advertised in system://mesh.catalog discovery responses.
	Description string
	// Public exposes the service on external router HTTP ingress
	// (/ingress/<peer_id>/a2a/<Name>) in addition to private mesh P2P.
	Public bool
	// IngressAuth selects edge Biscuit verification (default) or passthrough
	// when Public is true.
	IngressAuth api.IngressAuthMode
	// IngressAllow optionally restricts which attested principals ("email:*",
	// "user:*", "group:*", "idp_role:*", "node:*") may invoke the service in
	// INGRESS_AUTH_MODE_EDGE.
	IngressAllow []string
	// NoAnnounce skips directory announcements while still serving streams from
	// peers that dial this PeerID directly. Because no router holds a directory
	// route for an unannounced service, Endpoints.PublicURL is always nil when
	// NoAnnounce is true (even if Public is also set).
	NoAnnounce bool
}

A2AOptions configures an in-process A2A service registered on a Server.

type CallerInfo

type CallerInfo struct {
	PeerID    string
	Principal string
	Roles     []string
	Labels    map[string]string
	Task      string
}

CallerInfo carries the cryptographically verified mesh identity of an inbound caller returned by Server.WhoIs.

type Endpoints

type Endpoints struct {
	// PrivateListener delivers HTTP requests from authenticated mesh peers over
	// /libp2p-http. Always non-nil.
	PrivateListener net.Listener
	// PrivateURL is http://agentmesh.local/mesh/<peer_id>/a2a/<name>.
	PrivateURL *url.URL
	// PublicListener delivers external HTTP requests forwarded by enrolled
	// routers over /mesh/ingress/1.0.0. Non-nil iff A2AOptions.Public is true.
	PublicListener net.Listener
	// PublicURL is <router_ingress_url>/<peer_id>/a2a/<name> when Public is
	// true, NoAnnounce is false, the hub's policy ceiling admitted the ingress
	// announcement, and at least one router in the catalog advertises an
	// ingress_url; nil otherwise.
	PublicURL *url.URL
	// Close unregisters the service, withdraws its directory keys, and closes
	// PrivateListener and PublicListener.
	Close func() error
}

Endpoints holds the in-memory listeners and canonical URLs for an A2A service registered via Server.ListenA2A.

type Server

type Server struct {
	// StateDir persists identity.key and credential.json (0700/0600, byte-for-byte
	// compatible with sdk/js, sdk/python, and `agentmesh-node state export|import`)
	// alongside the local bbolt store lock (agent.db), returning ErrStateDirLocked
	// if another Server or agentmesh-node instance already holds the directory.
	// When empty, Up creates an ephemeral Ed25519 identity in a temporary 0700
	// directory that is removed on Close (or if Up fails).
	StateDir string

	// ControlPlaneURL is the Agent Mesh hub URL (e.g. "https://bananas.sam-mesh.dev").
	// Optional when resuming from a populated StateDir that already records
	// control_plane_url.
	ControlPlaneURL string

	// BootstrapTokenPath reads a bootstrap enrollment token from disk when no
	// valid credential exists in StateDir. Preferred over BootstrapToken so
	// secrets stay in files rather than process arguments.
	BootstrapTokenPath string

	// BootstrapToken supplies an in-memory bootstrap enrollment token (for
	// example read from an environment variable or secret manager).
	BootstrapToken string

	// JWTPath reads a platform OIDC / Kubernetes ServiceAccount / SPIFFE JWT from
	// disk for POST /register enrollment and POST /refresh re-attestation.
	JWTPath string

	// TokenSource dynamically fetches a fresh platform JWT for POST /register
	// enrollment and proactive POST /refresh renewal.
	TokenSource func(ctx context.Context) (string, error)

	// Labels are operator-declared key=value pairs requested at enrollment time
	// (signed into Block 0 only when permitted by PolicyRole.allowed_labels).
	Labels map[string]string

	// EgressRequireLabels sets a consumer-side label floor enforced on every
	// outbound provider's Biscuit before request data leaves this Server.
	EgressRequireLabels map[string]string

	// Routers is the target number of mesh routers to stay attached to (default 2).
	Routers int

	// RouterSelector filters candidate routers to those attesting all key=value pairs.
	RouterSelector map[string]string

	// RouterPrefer ranks routers matching more key=value pairs first.
	RouterPrefer map[string]string

	// ListenAddrs overrides the libp2p listen multiaddrs. When empty, Server
	// binds ephemeral UDP QUIC and TCP ports on all interfaces so direct P2P and
	// hole-punching work alongside Circuit Relay v2 without colliding across
	// multiple in-process Servers.
	ListenAddrs []string

	// AllowInsecure opts into http:// control-plane URLs and keeps
	// loopback/private peer multiaddrs during local development and integration tests.
	AllowInsecure bool

	// Registerer, when non-nil, registers per-Server state gauges and refusal
	// counters wrapped with peer_id="<id>" so multiple Servers can share one
	// Prometheus registry without colliding. Collectors are unregistered on
	// Close. When nil, no per-Server Prometheus collectors are registered.
	Registerer prometheus.Registerer

	// OnCredentialLapse, when non-nil, is invoked whenever a background renewal
	// attempt fails after the member's credential has expired. Background
	// renewal continues retrying with exponential backoff (2s up to 5m).
	OnCredentialLapse func(err error)

	// Logger receives structured meshnet lifecycle warnings and diagnostics.
	// Defaults to slog.Default().
	Logger *slog.Logger
	// contains filtered or unexported fields
}

Server is an embedded Agent Mesh node. Configure its exported fields and call Up (and then ListenA2A, HTTPClient, MCPHandler, or InferenceHandler) to join the mesh in-process.

func (*Server) AttenuateToken

func (s *Server) AttenuateToken(rule *api.TaskAuthorizationRule, ttl time.Duration, seal bool) (string, time.Time, error)

AttenuateToken appends a validated TaskAuthorizationRule (tar_block fact, 0 Datalog rules, 0 checks) to the Server's current Biscuit in memory without a control-plane round trip, optionally sealing it so downstream holders cannot append further blocks.

func (*Server) Close

func (s *Server) Close() error

Close withdraws directory records (bounded to 5s), closes all registered A2A listeners, unregisters per-Server Prometheus collectors, stops background loops, and shuts down the libp2p host and state store.

func (*Server) Discover

func (s *Server) Discover(ctx context.Context, serviceType api.ServiceType, serviceName string) ([]*api.DiscoveredProvider, error)

Discover queries the mesh directory for providers offering serviceType (and optionally a specific serviceName; pass "" to browse all providers of that type via parallel catalog fan-out). Returned DiscoveredProvider.LocalProxyUrl values can be passed directly to Server.HTTPClient.

func (*Server) Done

func (s *Server) Done() <-chan struct{}

Done returns a channel that is closed when either the member's credential lapses (Err() wraps ErrCredentialLapsed) or Close is called (Err() is nil unless a lapse already occurred).

func (*Server) Err

func (s *Server) Err() error

Err returns nil while the Server's credential is healthy and after a clean Close, or an error wrapping ErrCredentialLapsed if the member's credential expired and background renewal failed. Check Status().CredentialLapsed to observe whether a subsequent backoff retry has recovered the credential.

func (*Server) HTTPClient

func (s *Server) HTTPClient() *http.Client

HTTPClient returns an *http.Client whose Transport routes mesh URLs of the form http://<any-host>/mesh/<peer_id>/<type>/<name>[/<path>] directly over authenticated libp2p /libp2p-http streams via the underlying AgentMeshNode egress PEP (performing provider Biscuit, label, egress-floor, and publish-grant verification before sending request bytes, and rewriting A2A AgentCard interface URLs back onto the local mesh URL).

No client-wide Timeout is set so Server-Sent Events (SSE) and streaming completions run unbounded; connection establishment and header reads are bounded by the underlying libp2p swarm and stream deadlines.

func (*Server) InferenceHandler

func (s *Server) InferenceHandler() http.Handler

InferenceHandler returns a zero-secret OpenAI-compatible HTTP handler serving GET /v1/models, POST /v1/chat/completions, and POST /v1/completions backed by inference://* providers on the mesh.

func (*Server) ListenA2A

func (s *Server) ListenA2A(ctx context.Context, opts A2AOptions) (*Endpoints, error)

ListenA2A registers an in-process A2A service on the running Server, announces it to the mesh directory (unless NoAnnounce is true), and returns the in-memory listeners and canonical URLs to pass to http.Server.Serve.

func (*Server) MCPHandler

func (s *Server) MCPHandler() http.Handler

MCPHandler returns a stateless StreamableHTTP handler serving Server.MCPServer at "/", "/mcp", and "/mcp/".

func (*Server) MCPServer

func (s *Server) MCPServer() *mcp.Server

MCPServer returns an in-process *mcp.Server exposing the 6 progressive mesh discovery and tool-invocation tools (get_mesh_info, list_local_services, discover_remote_services, find_remote_tools, describe_remote_tool, call_remote_tool). Returns nil if Up has not succeeded.

func (*Server) Refresh

func (s *Server) Refresh(ctx context.Context) error

Refresh proactively exchanges the Server's current Biscuit for a fresh one at POST /refresh (attaching a fresh platform JWT when TokenSource or JWTPath is configured), verifies the returned credential, persists it to StateDir, and re-authenticates attached router sessions.

func (*Server) Status

func (s *Server) Status() Status

Status returns a snapshot of the member's PeerID, control-plane URL, currently attached routers, public router ingress base URLs, credential expiry, and live credential-lapse state. Because Up returns on the first router admission while additional router dials finish in the background, AttachedRouters may list fewer than Server.Routers immediately after Up.

func (*Server) Up

func (s *Server) Up(ctx context.Context) (*Status, error)

Up loads or enrolls the member credential, syncs mesh trust material and policy from the control plane, starts the gated libp2p host, authenticates with mesh routers, and starts background renewal, sync, and reprovide loops.

Up returns as soon as at least one router admits the member while any remaining router dials up to Server.Routers complete in the background, so the returned Status.AttachedRouters may initially list a single router.

func (*Server) WhoIs

func (s *Server) WhoIs(remoteAddr string) (*CallerInfo, bool)

WhoIs returns the cryptographically verified mesh identity of the caller behind an active HTTP request served on PrivateListener or PublicListener, keyed by http.Request.RemoteAddr. Because connections are in-memory net.Pipe pairs tracked in Server's active table, WhoIs cannot be spoofed by HTTP headers.

WhoIs returns (nil, false) for unauthenticated external requests, such as INGRESS_AUTH_MODE_PASSTHROUGH requests and anonymous GET /.well-known/agent-card.json discovery requests. For verified external EDGE callers that carry a user Biscuit rather than a mesh node identity, CallerInfo.PeerID is empty.

type Status

type Status struct {
	PeerID           string
	ControlPlaneURL  string
	AttachedRouters  []string
	IngressURLs      []string
	ExpireTime       time.Time
	CredentialLapsed bool
}

Status describes the live mesh connectivity and credential state of a Server. Because Up returns as soon as the first router admits the member while remaining router dials finish in the background, AttachedRouters immediately after Up may list one router before reaching Server.Routers.

Directories

Path Synopsis
examples
agent command
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.
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.
call command
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().
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().

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL