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
- Variables
- func ReadStateDir(dir string) ([]byte, *api.MemberCredential, error)
- func WriteStateDir(dir string, privKey []byte, c *api.MemberCredential) error
- type A2AOptions
- type CallerInfo
- type Endpoints
- type Server
- func (s *Server) AttenuateToken(rule *api.TaskAuthorizationRule, ttl time.Duration, seal bool) (string, time.Time, error)
- func (s *Server) Close() error
- func (s *Server) Discover(ctx context.Context, serviceType api.ServiceType, serviceName string) ([]*api.DiscoveredProvider, error)
- func (s *Server) Done() <-chan struct{}
- func (s *Server) Err() error
- func (s *Server) HTTPClient() *http.Client
- func (s *Server) InferenceHandler() http.Handler
- func (s *Server) ListenA2A(ctx context.Context, opts A2AOptions) (*Endpoints, error)
- func (s *Server) MCPHandler() http.Handler
- func (s *Server) MCPServer() *mcp.Server
- func (s *Server) Refresh(ctx context.Context) error
- func (s *Server) Status() Status
- func (s *Server) Up(ctx context.Context) (*Status, error)
- func (s *Server) WhoIs(remoteAddr string) (*CallerInfo, bool)
- type Status
Constants ¶
const ( StateDirIdentityFile = node.StateDirIdentityFile StateDirCredentialFile = node.StateDirCredentialFile )
State directory filenames, matching sdk/js, sdk/python, and `agentmesh-node state export|import`.
Variables ¶
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
MCPHandler returns a stateless StreamableHTTP handler serving Server.MCPServer at "/", "/mcp", and "/mcp/".
func (*Server) MCPServer ¶
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 ¶
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 ¶
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 ¶
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(). |