brainwires-agent-network
Agent networking layer for the Brainwires Agent Framework.
Overview
brainwires-agent-network provides the full networking stack for AI agents: an MCP server framework with composable middleware, a 5-layer protocol stack for pluggable agent communication, encrypted IPC, a remote bridge for backend connectivity, agent lifecycle management, and optional distributed mesh networking.
Design principles:
- Trait-driven —
McpHandler,Transport,Router,Discovery, and friends decouple the framework from any concrete implementation - Protocol-agnostic — agents communicate over IPC, TCP, HTTP, WebSocket, A2A, or Pub/Sub through a uniform
Transporttrait - Middleware-composable — auth, rate limiting, logging, and tool filtering stack via an onion model
- Encryption-first — IPC sockets use ChaCha20-Poly1305 authenticated encryption by default
- Feature-gated — only compile the transports and discovery mechanisms you need
┌───────────────────────────────────────────────────────────┐
│ brainwires-agent-network │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 5-Layer Protocol Stack │ │
│ │ │ │
│ │ Layer 5: Application (NetworkManager, Events) │ │
│ │ Layer 4: Discovery (Manual, Registry) │ │
│ │ Layer 3: Routing (Direct, Broadcast, Content) │ │
│ │ Layer 2: Transport (IPC, Remote, TCP, A2A, PubSub)│ │
│ │ Layer 1: Identity (AgentIdentity, AgentCard) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ MCP Server Framework │ │
│ │ McpHandler ──► MiddlewareChain ──► Transport │ │
│ │ (onion model) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────┐ ┌───────────────────────────┐ │
│ │ Agent Manager │ │ Remote Bridge │ │
│ │ Spawn / List / │ │ Supabase Realtime / │ │
│ │ Stop / Await │ │ HTTP Polling Fallback │ │
│ └──────────────────┘ └───────────────────────────┘ │
└───────────────────────────────────────────────────────────┘
Quick Start
[]
= "0.3"
Minimal MCP server:
use *;
;
async
Features
| Feature | Default | Description |
|---|---|---|
server |
Yes | MCP server framework |
client |
Yes | Client for connecting to remote agent network servers |
ipc-transport |
Yes | Unix-socket IPC transport with ChaCha20 encryption |
remote-transport |
Yes | Supabase Realtime / HTTP polling bridge transport |
tcp-transport |
No | Direct TCP peer-to-peer transport |
pubsub-transport |
No | In-process pub/sub transport with topic-based messaging |
a2a-transport |
No | A2A protocol transport (requires brainwires-a2a) |
mesh |
No | Distributed mesh networking (includes tcp-transport) |
registry-discovery |
No | HTTP-based agent registry discovery |
auth-keyring |
No | Secure API key storage via system keyring |
full |
No | All optional features enabled |
# With all transports and discovery
= { = "0.3", = ["full"] }
# Just TCP and pub/sub
= { = "0.3", = ["tcp-transport", "pubsub-transport"] }
Architecture
Protocol-Layer Stack
The networking layer is organized as a 5-layer protocol stack. Each layer has a well-defined trait, and concrete implementations are feature-gated.
Layer 1: Identity
Agent identity, capability advertisement, and cryptographic credentials.
Key types:
| Type | Description |
|---|---|
AgentIdentity |
UUID, name, and AgentCard |
AgentCard |
Capabilities, supported protocols, metadata, endpoint, compute capacity |
ProtocolId |
Protocol identifier string |
SigningKey / VerifyingKey |
ChaCha20-Poly1305 signing with SHA-256 key derivation |
use ;
let identity = new
.with_capability
.with_protocol
.with_endpoint;
Layer 2: Transport
How bytes move between agents. Every transport implements the Transport trait.
Provided transports:
| Transport | Feature flag | Wire format | Use case |
|---|---|---|---|
IpcTransport |
ipc-transport |
Length-prefixed, ChaCha20-encrypted JSON | Same-machine agents |
RemoteTransport |
remote-transport |
HTTP POST with broadcast channel | Backend connectivity |
TcpTransport |
tcp-transport |
Length-prefixed JSON over TCP (Nagle disabled) | Peer-to-peer mesh |
PubSubTransport |
pubsub-transport |
In-process tokio::broadcast channels |
Same-process topic messaging |
A2aTransport |
a2a-transport |
A2A JSON-RPC over HTTP/WebSocket | Cross-framework interop |
Addressing:
Layer 3: Routing
Where messages go. Routers decide which transport addresses to deliver to.
Provided routers:
| Router | Strategy | Description |
|---|---|---|
DirectRouter |
Direct |
Point-to-point delivery to a single peer |
BroadcastRouter |
Broadcast |
Deliver to all known peers (except sender) |
ContentRouter |
ContentBased |
Route to peers subscribed to matching topics |
PeerTable tracks known peers and their transport addresses, with optional topic subscriptions for content-based routing.
Layer 4: Discovery
How agents find each other on the network.
Provided implementations:
| Implementation | Feature flag | Description |
|---|---|---|
ManualDiscovery |
Always | In-memory peer list, configured programmatically |
RegistryDiscovery |
registry-discovery |
HTTP REST-based agent registry |
Layer 5: Application (NetworkManager)
The user-facing API that ties all layers together.
use ;
use TcpTransport;
use DirectRouter;
use ManualDiscovery;
let manager = new
.add_transport
.with_router
.add_discovery
.build
.await?;
// Send a message
manager.send.await?;
// Broadcast to all peers
manager.broadcast.await?;
// Subscribe to network events
let mut events = manager.subscribe;
while let Ok = events.recv.await
MCP Server Framework
The framework follows the Model Context Protocol specification for tool-based AI server integration.
Key types:
McpHandler— defines server identity, capabilities, and tool dispatchMcpServer<H>— wires handler, middleware chain, and transport togetherMcpToolRegistry— declarative tool registration with automatic dispatchServerTransport/StdioServerTransport— request/response I/O
Middleware
Middleware follows an onion model: requests flow forward through layers, responses flow back.
| Layer | Description |
|---|---|
AuthMiddleware |
Bearer token validation |
RateLimitMiddleware |
Token-bucket rate limiter with per-tool limits |
LoggingMiddleware |
Structured request/response logging via tracing |
ToolFilterMiddleware |
Allow-list or deny-list for tool access |
IPC (Inter-Process Communication)
Local agent-to-agent communication over Unix domain sockets with authenticated encryption.
Connection lifecycle:
IpcConnection::connect(socket_path)-- plain-text connectionHandshakeexchange -- session ID, token, model, working directoryconnection.upgrade_to_encrypted(session_token)-- ChaCha20-Poly1305 from this point
Encryption (IpcCipher): Derives a 256-bit key from the session token via SHA-256 with domain separator brainwires-ipc-v1:. All post-handshake messages use ChaCha20-Poly1305 authenticated encryption. Wire format: [nonce 12B][ciphertext + auth tag 16B].
Authentication
Session-based authentication with optional keyring storage.
AuthClient — HTTP client for authenticating against the Brainwires Studio backend.
SessionManager — Persists sessions to disk as JSON with 0600 permissions. API keys are stored separately via the KeyStore trait (system keyring preferred).
Agent Manager
Trait-based agent lifecycle for MCP server mode.
Remote Bridge
Backend connectivity with protocol negotiation, heartbeats, and priority command queuing.
Dual-mode transport: Supabase Realtime WebSocket (preferred) with HTTP polling fallback for restricted environments.
Mesh Networking (feature: mesh)
Distributed agent mesh networking for multi-node coordination. Includes topology management (star, ring, full mesh, hierarchical), message routing strategies, peer discovery protocols, and federation gateways for cross-mesh bridging.
Note: The mesh module provides trait definitions and types. The protocol-layer stack (transport, routing, discovery) provides the concrete implementations that power mesh networking.
Message Types
MessageEnvelope — the universal message container:
| Field | Type | Description |
|---|---|---|
id |
Uuid |
Unique message ID |
sender |
Uuid |
Sender agent ID |
recipient |
MessageTarget |
Direct(Uuid), Broadcast, or Topic(String) |
payload |
Payload |
Json(Value), Binary(Bytes), or Text(String) |
timestamp |
DateTime<Utc> |
When the message was created |
ttl |
Option<u32> |
Remaining hops before discard |
correlation_id |
Option<Uuid> |
Links replies to requests |
transport_type |
TransportType |
Which transport originated this message |
Usage Examples
MCP Server with Auth and Rate Limiting
use *;
use ;
let server = new
.with_transport
.with_middleware
.with_middleware // 100 req/min
.with_middleware;
server.run.await?;
TCP Transport Peer-to-Peer
use ;
use ;
let mut client = new;
client.connect.await?;
let envelope = direct;
client.send.await?;
let reply = client.receive.await?;
client.disconnect.await?;
Pub/Sub Topic Messaging
use ;
use ;
let mut transport = new;
transport.connect.await?;
// Subscribe to a topic
let mut rx = transport.subscribe_topic.await;
// Send a topic message
let envelope = topic;
transport.send.await?;
A2A Transport (Cross-Framework)
use ;
let mut transport = from_url?;
transport.connect.await?;
transport.send.await?;
Encrypted IPC Connection
use ;
let conn = connect.await?;
let = conn.upgrade_to_encrypted.split;
writer.write.await?;
let response: = reader.read.await?;
Agent Discovery
use ;
cleanup_stale_sockets.await?;
let agents = list_agent_sessions_with_metadata?;
let tree = format_agent_tree?;
println!;
Integration with Brainwires
Use via the brainwires facade crate:
[]
= { = "0.3", = ["agent-network"] }
Or use standalone — brainwires-agent-network depends only on brainwires-core and brainwires-mcp.
License
Licensed under either of Apache License, Version 2.0 or MIT License at your option.