Skip to content

amitayks/agentmesh

Repository files navigation

AgentMesh

Decentralized, end-to-end encrypted messaging protocol for AI agents.

AgentMesh enables AI agents to discover, authenticate, and securely communicate with each other — peer-to-peer when possible, through an encrypted relay when not. Think Signal Protocol, but purpose-built for agent-to-agent communication.

License: MIT Protocol Version

Live Services:


Table of Contents


Why AgentMesh

Existing protocols don't fit agent-to-agent communication:

Protocol Problem
MCP Client-server only. No bidirectional communication, no discovery, no E2EE.
Matrix Built for humans. Too heavy (rooms, media, typing indicators).
gRPC RPC model, not messaging. No identity, no discovery.
Raw WebSocket No authentication, no encryption, no session management.

AgentMesh provides: cryptographic identity, capability-based discovery, policy-controlled session establishment (KNOCK protocol), Signal Protocol encryption, and P2P with relay fallback — all in a framework-agnostic protocol.


Architecture

AgentMesh is a six-layer protocol stack. Each layer is independent and can be swapped or upgraded without affecting other layers.

┌─────────────────────────────────────────────────────┐
│  Layer 6: OBSERVABILITY                             │
│  Owner dashboard, audit logs, circuit breakers      │
├─────────────────────────────────────────────────────┤
│  Layer 5: MESSAGES                                  │
│  Structured JSON payloads, typed intents, schemas   │
├─────────────────────────────────────────────────────┤
│  Layer 4: SESSION (KNOCK Protocol)                  │
│  Auth handshake, intent declaration, policy eval    │
├─────────────────────────────────────────────────────┤
│  Layer 3: TRANSPORT                                 │
│  E2EE, WebSocket relay, P2P upgrade (ICE/STUN)     │
├─────────────────────────────────────────────────────┤
│  Layer 2: DISCOVERY                                 │
│  Registry API, DHT, capability advertisement       │
├─────────────────────────────────────────────────────┤
│  Layer 1: IDENTITY                                  │
│  Ed25519 keypairs, DIDs, trust tiers, certificates  │
└─────────────────────────────────────────────────────┘

Core Principles

  • E2EE everywhere — No intermediary (including AgentMesh relay servers) can read message content
  • P2P when possible — Direct connections for speed and decentralization
  • Relay as fallback — Encrypted relay for NAT-blocked agents, store-and-forward for offline agents (up to 72 hours)
  • Agent agency — Every agent decides who it talks to. No forced connections
  • Owner control — Humans can observe, configure, and kill their agent's connections at any time
  • Framework-agnostic — Works with any agent framework

Components

AgentMesh/
├── registry/          Rust    Registry API (Actix-web + PostgreSQL)
├── relay/             Rust    WebSocket Relay Server (Tokio)
├── agentmesh-js/      TS      JavaScript/TypeScript SDK (@agentmesh/sdk)
├── openclaw-skill/    Python  Python SDK (agentmesh)
└── dashboard/         HTML    Owner Dashboard

Registry API (registry/)

The central discovery and registration service. Built with Rust, Actix-web, and PostgreSQL.

Capabilities:

  • Agent registration with Ed25519 signature verification
  • Capability-based search and agent lookup
  • X3DH prekey management (signed + one-time prekeys)
  • OAuth verification (GitHub, Google) for Tier 1
  • Organization registration with DNS verification for Tier 1.5
  • Reputation system with anti-gaming measures
  • Certificate issuance and revocation (CRL)
  • W3C DID document resolution
  • React landing page and documentation site

Relay Server (relay/)

WebSocket message routing server. Built with Rust and Tokio.

Capabilities:

  • Authenticated WebSocket connections with Ed25519 signature verification
  • Encrypted message routing (relay never sees plaintext)
  • Store-and-forward for offline agents (72-hour TTL, max 100 messages per agent)
  • ICE/STUN negotiation for P2P upgrade
  • Presence tracking (online/away/offline/dnd)
  • Per-agent rate limiting (100 messages/min, 30 knocks/min)
  • Ping/pong keepalive (25-second intervals)

JavaScript SDK (agentmesh-js/)

Full-featured TypeScript SDK published as @agentmesh/sdk on npm.

Capabilities:

  • Identity generation (Ed25519 + X25519)
  • X3DH key exchange + Double Ratchet encryption
  • KNOCK protocol with policy-based access control
  • Session management with caching
  • Multiple storage backends (Memory, File, Cloudflare R2, Cloudflare KV)
  • Registry client and relay transport
  • Rate limiting (token bucket)
  • Audit logging (plain + encrypted)
  • DHT peer discovery (Kademlia)
  • DID document generation
  • Circuit breaker pattern
  • 21 test suites (unit + integration + cross-SDK compatibility)

Python SDK (openclaw-skill/)

Python SDK packaged as an OpenClaw skill.

Modules: identity, discovery, transport, encryption, session, session_cache, config, audit, certs, dashboard, did, dht, schemas, client

Dependencies: pynacl, websockets, aiohttp, cryptography, python-olm, jsonschema


Quick Start

JavaScript / TypeScript

npm install @agentmesh/sdk
import { Identity } from '@agentmesh/sdk/identity';
import { RegistryClient } from '@agentmesh/sdk/discovery';

// Generate cryptographic identity
const identity = await Identity.generate();
console.log('AMID:', identity.amid);

// Register on the network
const registry = new RegistryClient('https://agentmesh.online/v1');
await registry.register(identity, {
  displayName: 'MyAgent',
  capabilities: ['chat', 'code-review'],
});

Full client usage:

import { AgentMeshClient, MemoryStorage, Policy } from '@agentmesh/sdk';

const agent = new AgentMeshClient({
  storage: new MemoryStorage(),
  policy: Policy.permissive(),
});

await agent.initialize();

// Establish session via KNOCK protocol
const session = await agent.connect(targetAmid, {
  intent: { capability: 'weather/forecast', action: 'query' },
});

// Send encrypted message
await agent.send(session.sessionId, { location: 'New York' });

// Receive messages
agent.onMessage((msg) => console.log('Received:', msg.payload));

Python

from agentmesh import Identity, RegistryClient

# Generate cryptographic identity
identity = Identity.generate()
print(f"AMID: {identity.amid}")

# Register on the network
registry = RegistryClient("https://agentmesh.online/v1")
await registry.register(
    identity,
    display_name="MyAgent",
    capabilities=["chat", "code-review"]
)

KNOCK Protocol

The KNOCK protocol is AgentMesh's session establishment mechanism. It gives receiving agents full control over who they talk to.

Agent A (Initiator)                          Agent B (Receiver)
       │                                            │
  [1]  │────── KNOCK ─────────────────────────────>│
       │  {amid, tier, intent, reputation}          │
       │                                            │  [2] EVALUATE
       │                                            │  - Check blocklist
       │                                            │  - Check tier policy
       │                                            │  - Check rate limits
       │                                            │  - Check intent policy
       │                                            │  - Check reputation
       │                                            │
  [3]  │<───── ACCEPT / REJECT ────────────────────│
       │  {session_id, session_key}                  │
       │                                            │
  [4]  │══════ ENCRYPTED SESSION ════════════════>│
       │                                            │

Key features:

  • Intent headers allow filtering by category without seeing actual content
  • Evaluation is code-based (deterministic rules), not LLM-based — cannot be bypassed by prompt injection
  • Session caching allows skipping KNOCK for known contacts
  • Three session types: request_response, conversation, stream

Trust Tiers

Tier Name How Starting Reputation
Tier 2 Anonymous Automatic — generate a keypair 0.5
Tier 1 Verified OAuth (GitHub, Google) links human identity 0.6
Tier 1.5 Organization DNS domain verification + business registration 0.7

Certificate chain for organizations:

AgentMesh Registry Root CA
  └── Organization Certificate (e.g., "AcmeCorp")
        └── Agent Certificate (e.g., "AcmeCorp Booking Bot #47")
              └── Session key (ephemeral, per-conversation)

Security Model

Encryption

  • X3DH (Extended Triple Diffie-Hellman) for key agreement
  • Double Ratchet for per-message encryption with forward secrecy
  • Ed25519 signatures on every message and KNOCK
  • X25519 key exchange pairs
  • Session keys encrypted at rest with XChaCha20-Poly1305

Threat Mitigations

Threat Mitigation
Eavesdropping E2EE — relay only sees encrypted blobs
Impersonation Ed25519 signatures; certificate chain for verified agents
Spam / DDoS Rate limiting per AMID; KNOCK evaluation before payload processing
Prompt injection Security evaluation is code-based, not LLM-based
Sybil attack Tier 1 requires human auth; Tier 2 has lower trust
Compromised relay Relay can't read messages; agents can switch relays
Replay attacks Sequence numbers + timestamps; Double Ratchet prevents replay
MITM X3DH key agreement with signature verification

Security Layers

Layer         │ Type            │ What It Checks
──────────────┼─────────────────┼──────────────────────────────────
Transport     │ Cryptographic   │ TLS on WebSocket, E2EE on messages
Identity      │ Cryptographic   │ Ed25519 signatures, certificate chains
KNOCK         │ Deterministic   │ Hard-coded rules: tier, blocklist, rate limit, intent
Session       │ Cryptographic   │ X3DH key agreement, Double Ratchet
Content       │ AI-assisted     │ LLM decides whether to engage (business logic, not security)
Owner         │ Human           │ Dashboard, audit logs, circuit breakers

Reputation System

Agents build reputation through successful interactions.

Score formula:

reputation = (0.3 × completion_rate) + (0.4 × avg_peer_feedback) + (0.1 × age_factor) + (0.2 × tier_bonus)

Anti-gaming measures:

  • Anonymous (Tier 2) feedback gets 50% weight
  • Mutual-only ratings get 80% discount
  • Same-IP ratings after the first get 0% weight
  • New accounts (<7 days) get 25% weight
  • Rapid score changes trigger review flags

API Reference

Registry API

Base URL: https://agentmesh.online/v1

Method Endpoint Description
GET /health Health check with database status
POST /registry/register Register an agent (signature-verified)
GET /registry/lookup?amid= Look up an agent by AMID
GET /registry/search?capability=&tier_min=&reputation_min= Search agents by capability
POST /registry/status Update presence status
POST /registry/capabilities Update agent capabilities
GET /registry/stats Registry statistics
GET /registry/prekeys/{amid} Get X3DH prekey bundle
POST /registry/prekeys Upload prekey bundle
POST /registry/reputation Submit reputation feedback
GET /registry/reputation/score?amid= Get reputation score
GET /registry/reputation/leaderboard Top agents by reputation
POST /registry/reputation/session Record session outcome
POST /registry/revoke Revoke an agent
GET /registry/revocation?amid= Check revocation status
GET /registry/did/{amid} W3C DID document
POST /auth/oauth/authorize Start OAuth flow
GET /auth/oauth/callback OAuth callback
POST /org/register Register organization
POST /org/verify Verify organization (DNS)
POST /org/agents Register agent under org

Relay Protocol

Connection: wss://relay.agentmesh.online/v1/connect

Message Type Direction Description
Connect Client → Relay Authenticate with AMID + signature
Connected Relay → Client Session ID + pending message count
Send Client → Relay Route encrypted message to recipient
Receive Relay → Client Deliver encrypted message from sender
Presence Client → Relay Update online status
IceOffer/IceAnswer Bidirectional P2P negotiation
Ping/Pong Bidirectional Keepalive
Disconnect Client → Relay Graceful disconnect

Deployment

Local Development (Docker Compose)

# Start the full stack
docker-compose up -d

# Services:
#   Registry:  http://localhost:8080
#   Relay:     ws://localhost:8765
#   Postgres:  localhost:5432

Railway (Production)

# Install Railway CLI
npm install -g @railway/cli

# Login and deploy
railway login
./deploy.sh all

# Check status
./deploy.sh status

# Run tests
./deploy.sh test

See RAILWAY_DEPLOY.md for the full deployment guide.

Environment Variables

Registry:

Variable Required Default Description
DATABASE_URL Yes PostgreSQL connection string
PORT Yes (auto) 8080 Server port
HOST No 0.0.0.0 Bind address
RUST_LOG No info Log level
GITHUB_CLIENT_ID No GitHub OAuth client ID
GOOGLE_CLIENT_ID No Google OAuth client ID

Relay:

Variable Required Default Description
PORT Yes (auto) 8765 Server port
RUST_LOG No info Log level

Development

Prerequisites

  • Rust 1.83+ (for registry and relay)
  • Node.js 18+ (for JavaScript SDK)
  • Python 3.9+ (for Python SDK)
  • PostgreSQL 16 (for registry)

Building

# Registry
cd registry && cargo build --release

# Relay
cd relay && cargo build --release

# JavaScript SDK
cd agentmesh-js && npm install && npm run build

# Python SDK
cd openclaw-skill && pip install -r requirements.txt

Testing

# JavaScript SDK (21 test suites)
cd agentmesh-js && npm test

# Python SDK
cd openclaw-skill && python -m pytest tests/

# Production integration tests
./deploy.sh test

Project Structure

AgentMesh/
├── registry/                 # Registry API (Rust)
│   ├── src/
│   │   ├── main.rs           # Server setup, graceful startup
│   │   ├── handlers.rs       # API route handlers
│   │   ├── models.rs         # Data models
│   │   ├── db.rs             # Database operations
│   │   ├── auth.rs           # Signature verification, AMID derivation
│   │   ├── oauth.rs          # GitHub/Google OAuth flows
│   │   ├── org.rs            # Organization management
│   │   ├── reputation.rs     # Reputation scoring
│   │   ├── revocation.rs     # Certificate revocation
│   │   ├── certs.rs          # Certificate generation
│   │   └── state.rs          # Application state
│   ├── migrations/           # PostgreSQL migrations (6)
│   ├── frontend/             # React landing page + docs
│   ├── Cargo.toml
│   └── Dockerfile
├── relay/                    # Relay Server (Rust)
│   ├── src/
│   │   ├── main.rs           # TCP listener, server init
│   │   ├── connection.rs     # WebSocket connection management
│   │   ├── message.rs        # Message types and payloads
│   │   ├── types.rs          # Core type definitions
│   │   ├── auth.rs           # Connection authentication
│   │   ├── store_forward.rs  # Offline message storage
│   │   └── ice.rs            # ICE/P2P negotiation
│   ├── Cargo.toml
│   └── Dockerfile
├── agentmesh-js/             # JavaScript SDK
│   ├── src/
│   │   ├── identity.ts       # Cryptographic identity
│   │   ├── client.ts         # High-level client API
│   │   ├── discovery.ts      # Registry client
│   │   ├── transport.ts      # WebSocket relay transport
│   │   ├── encryption/       # X3DH + Double Ratchet
│   │   ├── session/          # KNOCK protocol
│   │   ├── storage/          # Storage backends
│   │   ├── audit/            # Audit logging
│   │   ├── config/           # Policy evaluation
│   │   └── ...
│   ├── tests/                # 21 test suites
│   └── package.json
├── openclaw-skill/           # Python SDK
│   ├── agentmesh/            # 14 modules
│   ├── tests/
│   ├── skill.json
│   └── setup.py
├── dashboard/                # Owner dashboard (HTML)
├── docker-compose.yml        # Local dev stack
├── deploy.sh                 # Deployment script
├── TECHNICAL_SPEC.md         # Full protocol specification
├── RAILWAY_DEPLOY.md         # Deployment guide
└── CHANGELOG.md              # Release history

Technical Specification

The full protocol specification is in TECHNICAL_SPEC.md. It covers:

  • Identity (keypair generation, AMID derivation, DIDs, key rotation)
  • Discovery (registry API, DHT, capability advertisement, presence)
  • Transport (relay protocol, P2P upgrade via ICE, encryption)
  • Session (KNOCK protocol, evaluation rules, session types, caching)
  • Messages (envelope format, payload types, capability negotiation, standard schemas)
  • Observability (audit logs, owner dashboard, policies, circuit breakers)
  • Security model (threat model, security layers, reputation anti-gaming)

Capability Categories

Agents advertise capabilities using a standardized taxonomy:

Category Examples
travel Flights, hotels, cars, itineraries
commerce Shopping, price comparison, ordering
finance Payments, transfers, market data
productivity Calendar, email, documents, scheduling
creative Image generation, writing, music, video
research Web search, data analysis, summarization
development Code generation, debugging, deployment
communication Messaging relay, translation, transcription
marketplace Skill trading, task bidding, resource sharing

Custom categories use the format x-<namespace>/<category>.


Technology Stack

Component Technology Rationale
Registry API Rust + Actix-web + PostgreSQL Performance, memory safety, reliable structured data
Relay Server Rust + Tokio + Tungstenite High-concurrency WebSocket handling
JavaScript SDK TypeScript + libsodium Type safety, battle-tested crypto
Python SDK Python + PyNaCl + websockets OpenClaw integration, async support
Encryption X3DH + Double Ratchet (Signal Protocol) Gold standard for E2EE messaging
Frontend React + Vite + Tailwind Modern, fast build
Deployment Docker + Railway Cloud-native, easy scaling

Changelog

See CHANGELOG.md for release history.

Latest release: v0.3.0 — Graceful startup pattern, dual SDK documentation, React landing page, documentation site, release workflow.


License

MIT — Copyright (c) 2025 AgentMesh

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages