Synapse: Synapse Implementation Skill
Synapse is a "phone network for AI agents" — a protocol that lets any agent discover, talk to, and collaborate with any other agent through NATS messaging. Built on 6 primitives: register, discover, request, respond, emit, subscribe.
This skill provides complete, runnable implementations for all architectures — from one-liner CLI agents to production TypeScript/Python/Go SDK-based systems spanning multiple organizations.
When to Use This Skill
- Build a multi-agent system where agents need to find and call each other dynamically
- Replace N×M custom integrations with one protocol (all agents speak Synapse)
- Need real-time event streaming between agents (emit/subscribe with wildcards)
- Build cross-org agent coordination without exposing internal infrastructure
- Create lightweight "infrastructure agents" using only the NATS CLI
- Want persistent, reliable messaging (JetStream) with distributed tracing built-in
- Need peer-to-peer agent communication (not manager→worker hierarchies)
- Require cryptographic identity verification (reject unauthorized callers with signed envelopes)
- Send documents (PDF, DOCX, images, CSV) to agents for analysis over the mesh
The 6 Primitives (Quick Reference)
| Primitive |
Purpose |
Direction |
NATS Subject |
| register |
Announce agent + capabilities |
Agent→Registry |
mesh.registry.register |
| discover |
Find agents by capability |
Agent→Registry |
mesh.registry.discover |
| request |
Ask agent to do work (creates task) |
Agent→Agent |
mesh.agent.{id}.inbox |
| respond |
Return result or error |
Agent→Agent |
reply subject (auto) |
| emit |
Broadcast event to subscribers |
Agent→Listeners |
mesh.event.{type} |
| subscribe |
Listen for events with wildcards |
Listener→Agent |
mesh.event.{pattern} |
Skill File Index
Infrastructure & Setup
- setup.md — NATS installation, Docker, Synadia Cloud, multi-tenant accounts, leaf nodes
Protocol Implementation Guides
- cli-guide.md — Pure CLI agents using only the
nats binary (no code)
- typescript.md — Complete TypeScript/Node.js SDK + full code samples
- python.md — Python SDK with async handlers and full examples
- go.md — Go SDK with goroutines and production patterns
Architecture & Patterns
- patterns.md — Real-world patterns: routing, delegation, fan-out, streaming, heartbeat
- file-transfer.md — Chunked file transfer protocol: send PDFs, images, CSVs to agents via NATS, auto-dispatched to target inbox
- security.md — NKeys, JWT auth, Ed25519, multi-tenant permissions, signed envelopes
- acl.md — Cryptographic ACL: Ed25519 identity, trust store, key rotation, revocation
- cross-org.md — Leaf node topology, firewall traversal, Acme↔Globex scenario
Reliability
- observability.md — OpenTelemetry tracing, metrics, Grafana dashboards, W3C interop
- schema.md — JSON Schema validation for envelopes, manifests, and task updates (TypeScript/Python/Go)
- registry.md — JetStream-backed registry service for deterministic discovery
- tasks.md — JetStream-backed task store: state machine persistence, conversation linking, querying
- http-bridge.md — Bidirectional HTTP↔Synapse bridge: wrap any REST/Flask/FastAPI agent as a Synapse participant
- reputation.md — Per-agent, per-skill reliability scoring and ranked discovery. Detects lying agents that claim capabilities they don't have.
- governance.md — Runtime policy, identity, and enforcement: AGT trust root + Actra in-mesh gate + EnforceCore tool-boundary enforcement. Closes the default-open gap with verifiable identity, enforceable authorization, PII redaction, and tamper-proof audit.
- identity-rollout.md — Staged path to a hardened mesh: Stage 1 (DIDs + key fingerprints), Stage 2 (NKey auth + per-agent subject permissions), Stage 3 (Ed25519 envelope signing with verify-if-signed transitional mode). Includes permission gotchas and worked examples.
Production Deployment
- deployment.md — Hard-won production patterns: multi-tenant NATS isolation, boot persistence (launchd/systemd), bridge-level TaskStore integration, control-plane CLI, known gotchas, real-world task case studies. Read this before going live.
Reference
- envelope.md — Complete message envelope format, trace fields, error codes
- states.md — Task state machine and state transition rules
- subjects.md — Full subject namespace with wildcards and permissions
- comparison.md — How Synapse compares to A2A, MCP, ANP, RepoWire
Runnable Examples
- examples/identity/ — Identity rollout:
envelope_signing.py (Python Ed25519 sign/verify module), nats.conf.hardened (per-agent NKey permissions template with gotcha annotations)
- examples/governance/ — Governance integration:
enforcecore-bridge.py (Python tool-boundary enforcement + redaction + Merkle audit), mesh-policy.example.json (Actra/AGT-compatible policy)
- examples/cli/ — Bash scripts: static agents, monitors, log watchers
- examples/acl/ — Cryptographic ACL demo: signed envelopes, trust store, key rotation
- examples/reputation/ — Reputation system demo: good/flaky/lying agents, auto-ranking, lying detection
- examples/typescript/ — Full TypeScript projects (2-agent chat, event pipeline, routing)
- examples/python/ — Full Python projects (LLM agents, delegation chains)
- examples/go/ — Full Go projects (high-throughput mesh, JetStream persistence)
- examples/docker/ — Multi-container setups (local dev, Synadia, leaf nodes)
- examples/docker/e2e-bridge/ — End-to-end HTTP bridge demo (Flask ↔ Synapse ↔ Bob)
- examples/cross-org/ — Complete Acme+Globex multi-company setup with credentials
Install
# npm package (TypeScript/JavaScript)
npm install synapse-nats-sdk
# Install as a Claude Code skill
npx skills add https://github.com/drolu/synapse-skill --skill synapse
Published on npm (synapse-nats-sdk) and skills.sh.
Quick Start (30 seconds)
Option 1: Pure CLI Agent (no code)
# Terminal 1: Start NATS
nats-server &
# Terminal 2: Agent Bob (replies to requests)
nats pub mesh.registry.register '{"id":"bob-001","name":"Bob","capabilities":["chat"]}' -s nats://localhost:4222
nats reply mesh.agent.bob-001.inbox '{"text":"Hi from Bob!"}' -s nats://localhost:4222
# Terminal 3: Agent Jeff (sends request)
nats request mesh.agent.bob-001.inbox '{"text":"Hello Bob"}' -s nats://localhost:4222
# → {"text":"Hi from Bob!"}
Option 2: TypeScript SDK
cd examples/typescript/agent-sdk
npm install
node src/bob-agent.js # start Bob
node src/jeff-agent.js # Jeff discovers + requests Bob
See typescript.md for the full SDK.
Option 3: Python LLM Agent
cd examples/python/llm-agent
pip install -r requirements.txt
python research_agent.py
python summarizer_agent.py
See python.md for full code.
Option 4: HTTP Bridge (existing REST agent)
// Wrap any Flask/FastAPI/Express agent into Synapse — zero NATS code on their side
import Synapse from "synapse-nats-sdk";
import { HTTPBridge } from "./http-bridge.js";
const mesh = await Synapse.connect("nats://localhost:4222");
const bridge = new HTTPBridge(mesh, 4100);
await bridge.registerAgent({
id: "flask-chat-001", name: "Flask Chat Agent",
baseUrl: "http://localhost:5000",
capabilities: ["chat"],
skills: [{ id: "chat", name: "Chat", description: "Chat" }],
});
await bridge.startWebhook();
// Flask agent is now discoverable and callable from any Synapse agent
See http-bridge.md for full bridge documentation.
Architecture Overview
┌─────────────────────────────────────────────────────┐
│ Synapse Protocol │
│ (6 primitives, envelope format, state machine) │
└────────────────────────┬────────────────────────────┘
│
│ speaks
▼
┌─────────────────────────────────────────────────────┐
│ NATS Messaging │
├─────────────────────────────────────────────────────┤
│ • Request/reply (inbox model) │
│ • Pub/sub (wildcards) │
│ • JetStream persistence │
│ • Leaf nodes (cross-firewall) │
│ • Accounts (multi-tenant isolation) │
│ • WebSockets (browser/home agents) │
└────────────────────────┬────────────────────────────┘
│
┌────────────────┼────────────────┐
│ │ │
┌────▼────┐ ┌───▼────┐ ┌────▼────┐
│ Agent A │ │Agent B │ │ Agent C │
│(TypeSC) │ │(Python)│ │ (CLI) │
└─────────┘ └────────┘ └─────────┘
│
│ HTTP Bridge
▼
┌────────────┐
│ HTTP Agent │ (Flask/FastAPI/Express — zero NATS code)
└────────────┘
│
│ Browser SDK (WebSocket)
▼
┌────────────┐
│ Browser │ (React/Vue/Svelte — wsconnect to NATS:8443)
└────────────┘
All agents speak Synapse: servers via TCP, browsers via WebSocket, HTTP services via the bridge.
Decision Matrix
| Scenario |
Recommended Approach |
| Static data agents (uptime, config) |
CLI Guide — 5 lines of bash |
| Edge/IoT agents (sensors, cron jobs) |
CLI + JetStream |
| LLM-powered agent (needs reasoning) |
TypeScript or Python SDK |
| High-throughput data pipeline |
Go SDK |
| Cross-org coordination (firewalls) |
Cross-Org Guide |
| Need guaranteed delivery |
JetStream (Go SDK) |
| Need streaming responses (LLM tokens) |
Streaming Primitives — streamRequest() / onStreamRequest() |
| Agent takes >30s to respond (API calls, multi-step reasoning) |
Long-Running Requests — increase timeoutMs, use streamRequest(), or stable reply subject for CLI |
| Need conversation history / task persistence |
Task Store — JetStream-backed task lifecycle + multi-turn linking |
| Want observability/debugging |
Observability Guide — OTel tracing, metrics, Grafana |
| Need message validation |
Schema Guide — JSON Schema for all message types |
| Comparing with A2A/MCP |
Comparison Guide |
| Need to rank agents by reliability |
Reputation Guide — Per-skill scoring, lying detection, discoverRanked |
| Detect agents claiming skills they dont have |
Lying Detection — 3001 SKILL_NOT_FOUND tracking |
| Send documents to agents for analysis |
File Transfer — Chunked transfer over NATS (init→chunks→done→dispatch) |
| Deploy a mesh for production (boot persistence, multi-tenant NATS, known gotchas) |
Deployment Guide — launchd/systemd services, 3-account isolation, bridge integration, operational CLI |
Comparison with Other Protocols
See comparison.md for detailed comparison with:
- A2A (Google's Agent-to-Agent) — more ceremony, enterprise focus
- MCP (Anthropic's Model Context) — agent-to-tool only
- ANP (Agent Network Protocol) — decentralized DID-based
- RepoWire — local-first for coding agents only
RTerm / neuralOS Integration (synapse-bridge, v3.1.4+)
RTerm (the ops platform) is a first-class Synapse citizen via the synapse-bridge plugin — it speaks the Synapse protocol (v0.3.0) over the same NATS server, using the v3.1.2 auth/request-reply/JetStream transport. RTerm and Synapse agents share the same road (NATS) in different lanes: RTerm's own trigger mesh uses rterm.* subjects; the Synapse mesh uses mesh.* subjects.
What the plugin does:
- Discover live Synapse agents —
synapse_discover queries mesh.registry.discover (capability/skill/availability filters) and returns agents + their skills.
- Dispatch tasks to a Synapse agent —
synapse_dispatch sends a request envelope to mesh.agent.{id}.inbox and awaits the durable response (tracked in the mesh's JetStream task store).
- Register RTerm as a mesh agent —
synapse_register publishes RTerm's manifest to mesh.registry.register so other Synapse agents can discover and dispatch to it (bidirectional federation).
- Plus
synapse_health, synapse_agents_summary, the synapse_mesh_event trigger (cross-mesh remediation), and the synapse-mesh-agents dashboard panel.
Config (settings.synapse, persisted across save/load): url/servers (default nats://localhost:4222), prefix (default mesh), agentId (default rterm-001), and auth (token / user-pass / NKey / JWT / creds / TLS — inline or vault secretRef).
Example (agent prompt): "Use synapse_discover to list live mesh agents, then synapse_dispatch a status check to agentspan-001." Verified live: 4 agents discovered (grip-cli-001, grip-001, omp-cli-001, agentspan-001), dispatch → {stream: AGENT_INBOXES, seq: N}.
Also: the standalone rterm-synapse-bridge.mjs CLI shim (a proof-of-concept the plugin supersedes) does the same from a shell: rterm-synapse discover | dispatch <agent> <skill> '<json>' | demo.
Production Checklist
Before going to production, verify:
Troubleshooting
Common issues and fixes:
Agent not responding to requests:
# Check if agent's inbox has subscribers
nats server report subs -s nats://localhost:4222 | grep mesh.agent
Discovery returns empty:
# Verify agents registered
nats sub mesh.registry.register -s nats://localhost:4222 --count 1
# (run in background, watch who registers)
JetStream API calls fail when using a leaf node:
- Almost always caused by missing account isolation (see deployment.md § 1)
- Check
curl http://localhost:8222/jsz — api.errors should be 0
- Verify
accounts {} block has a dedicated LOCAL account with jetstream: enabled and a separate REMOTE account for the leaf
- Ensure
system_account points to a SYS account with NO JetStream
Cross-firewall connection fails:
- Leaf nodes must connect OUTBOUND only
- Check firewall allows NATS port (4222 default)
- Use
nats auth info to verify JWT is valid
Request times out on long-running agents (LLM, API calls, multi-step reasoning):
- Pass explicit
timeoutMs to request(): mesh.request(id, skill, input, 180_000)
- For agents taking >3 min, use
streamRequest() / onStreamRequest() instead
- From CLI: subscribe to a stable reply subject BEFORE publishing the request (not after)
- See Long-Running Requests for full patterns
See setup.md#troubleshooting for basic troubleshooting. For production-level gotchas (NATS isolation, task store bugs, boot persistence issues, bridge integration pitfalls), see deployment.md § 5.
Further Resources
Quick Commands Reference
# Infrastructure
nats-server # start local server
nats-server -js # with JetStream
docker run -p 4222:4222 nats:latest # Docker
# CLI Primitives
nats pub <subject> '<payload>' # register, emit
nats sub <subject> # subscribe (with wildcards)
nats request <subject> '<payload>' # request (blocks for reply)
nats reply <subject> '<payload>' # respond to requests
# Discovery
nats request mesh.registry.discover '{"capabilities":["chat"]}'
# Monitoring
nats server report subs # view subject subscriptions
nats top # live connection stats
nats rtt # latency test
# File Transfer
synapse-send-file report.pdf # analyze a PDF
synapse-send-file image.png --action extract # extract text from image
synapse-send-file data.csv --target grip-cli-001 --via cloud # send via Synadia Cloud
Note: This skill contains both reference material and runnable code. All examples in examples/ are self-contained and tested. Copy freely into your projects.
1---2name: synapse3description: Complete implementation guide for Synapse protocol — build multi-agent systems on NATS using CLI or code (TypeScript, Python, Go). Covers all 6 primitives, real-world patterns, security (cryptographic ACL, NKeys, JWT), cross-org topology, and production deployment.4---56# Synapse: Synapse Implementation Skill78Synapse is a "phone network for AI agents" — a protocol that lets any agent discover, talk to, and collaborate with any other agent through NATS messaging. Built on 6 primitives: **register, discover, request, respond, emit, subscribe**.910This skill provides complete, runnable implementations for all architectures — from one-liner CLI agents to production TypeScript/Python/Go SDK-based systems spanning multiple organizations.1112## When to Use This Skill1314- Build a multi-agent system where agents need to find and call each other dynamically15- Replace N×M custom integrations with one protocol (all agents speak Synapse)16- Need real-time event streaming between agents (emit/subscribe with wildcards)17- Build cross-org agent coordination without exposing internal infrastructure18- Create lightweight "infrastructure agents" using only the NATS CLI19- Want persistent, reliable messaging (JetStream) with distributed tracing built-in20- Need peer-to-peer agent communication (not manager→worker hierarchies)21- Require cryptographic identity verification (reject unauthorized callers with signed envelopes)22- Send documents (PDF, DOCX, images, CSV) to agents for analysis over the mesh2324## The 6 Primitives (Quick Reference)2526| Primitive | Purpose | Direction | NATS Subject |27|-----------|---------|-----------|--------------|28| **register** | Announce agent + capabilities | Agent→Registry | `mesh.registry.register` |29| **discover** | Find agents by capability | Agent→Registry | `mesh.registry.discover` |30| **request** | Ask agent to do work (creates task) | Agent→Agent | `mesh.agent.{id}.inbox` |31| **respond** | Return result or error | Agent→Agent | reply subject (auto) |32| **emit** | Broadcast event to subscribers | Agent→Listeners | `mesh.event.{type}` |33| **subscribe** | Listen for events with wildcards | Listener→Agent | `mesh.event.{pattern}` |3435## Skill File Index3637### Infrastructure & Setup38- **[setup.md](./setup.md)** — NATS installation, Docker, Synadia Cloud, multi-tenant accounts, leaf nodes3940### Protocol Implementation Guides41- **[cli-guide.md](./cli-guide.md)** — Pure CLI agents using only the `nats` binary (no code)42- **[typescript.md](./typescript.md)** — Complete TypeScript/Node.js SDK + full code samples43- **[python.md](./python.md)** — Python SDK with async handlers and full examples44- **[go.md](./go.md)** — Go SDK with goroutines and production patterns4546### Architecture & Patterns47- **[patterns.md](./patterns.md)** — Real-world patterns: routing, delegation, fan-out, streaming, heartbeat48- **[file-transfer.md](./file-transfer.md)** — Chunked file transfer protocol: send PDFs, images, CSVs to agents via NATS, auto-dispatched to target inbox49- **[security.md](./security.md)** — NKeys, JWT auth, Ed25519, multi-tenant permissions, signed envelopes50- **[acl.md](./acl.md)** — Cryptographic ACL: Ed25519 identity, trust store, key rotation, revocation51- **[cross-org.md](./cross-org.md)** — Leaf node topology, firewall traversal, Acme↔Globex scenario5253### Reliability54- **[observability.md](./observability.md)** — OpenTelemetry tracing, metrics, Grafana dashboards, W3C interop55- **[schema.md](./schema.md)** — JSON Schema validation for envelopes, manifests, and task updates (TypeScript/Python/Go)56- **[registry.md](./registry.md)** — JetStream-backed registry service for deterministic discovery57- **[tasks.md](./tasks.md)** — JetStream-backed task store: state machine persistence, conversation linking, querying58- **[http-bridge.md](./http-bridge.md)** — Bidirectional HTTP↔Synapse bridge: wrap any REST/Flask/FastAPI agent as a Synapse participant59- **[reputation.md](./reputation.md)** — Per-agent, per-skill reliability scoring and ranked discovery. Detects lying agents that claim capabilities they don't have.60- **[governance.md](./governance.md)** — Runtime policy, identity, and enforcement: AGT trust root + Actra in-mesh gate + EnforceCore tool-boundary enforcement. Closes the default-open gap with verifiable identity, enforceable authorization, PII redaction, and tamper-proof audit.61- **[identity-rollout.md](./identity-rollout.md)** — Staged path to a hardened mesh: Stage 1 (DIDs + key fingerprints), Stage 2 (NKey auth + per-agent subject permissions), Stage 3 (Ed25519 envelope signing with verify-if-signed transitional mode). Includes permission gotchas and worked examples.6263### Production Deployment64- **[deployment.md](./deployment.md)** — Hard-won production patterns: multi-tenant NATS isolation, boot persistence (launchd/systemd), bridge-level TaskStore integration, control-plane CLI, known gotchas, real-world task case studies. Read this before going live.6566### Reference67- **[envelope.md](./envelope.md)** — Complete message envelope format, trace fields, error codes68- **[states.md](./states.md)** — Task state machine and state transition rules69- **[subjects.md](./subjects.md)** — Full subject namespace with wildcards and permissions70- **[comparison.md](./comparison.md)** — How Synapse compares to A2A, MCP, ANP, RepoWire7172### Runnable Examples73- **[examples/identity/](./examples/identity/)** — Identity rollout: `envelope_signing.py` (Python Ed25519 sign/verify module), `nats.conf.hardened` (per-agent NKey permissions template with gotcha annotations)74- **[examples/governance/](./examples/governance/)** — Governance integration: `enforcecore-bridge.py` (Python tool-boundary enforcement + redaction + Merkle audit), `mesh-policy.example.json` (Actra/AGT-compatible policy)75- **[examples/cli/](./examples/cli/)** — Bash scripts: static agents, monitors, log watchers76- **[examples/acl/](./examples/acl/)** — Cryptographic ACL demo: signed envelopes, trust store, key rotation77- **[examples/reputation/](./examples/reputation/)** — Reputation system demo: good/flaky/lying agents, auto-ranking, lying detection78- **[examples/typescript/](./examples/typescript/)** — Full TypeScript projects (2-agent chat, event pipeline, routing)79- **[examples/python/](./examples/python/)** — Full Python projects (LLM agents, delegation chains)80- **[examples/go/](./examples/go/)** — Full Go projects (high-throughput mesh, JetStream persistence)81- **[examples/docker/](./examples/docker/)** — Multi-container setups (local dev, Synadia, leaf nodes)82- **[examples/docker/e2e-bridge/](./examples/docker/e2e-bridge/)** — End-to-end HTTP bridge demo (Flask ↔ Synapse ↔ Bob)83- **[examples/cross-org/](./examples/cross-org/)** — Complete Acme+Globex multi-company setup with credentials8485## Install8687```bash88# npm package (TypeScript/JavaScript)89npm install synapse-nats-sdk9091# Install as a Claude Code skill92npx skills add https://github.com/drolu/synapse-skill --skill synapse93```9495Published on [npm (synapse-nats-sdk)](https://www.npmjs.com/package/synapse-nats-sdk) and [skills.sh](https://www.skills.sh/drolu/synapse-skill/synapse).9697## Quick Start (30 seconds)9899### Option 1: Pure CLI Agent (no code)100101```bash102# Terminal 1: Start NATS103nats-server &104105# Terminal 2: Agent Bob (replies to requests)106nats pub mesh.registry.register '{"id":"bob-001","name":"Bob","capabilities":["chat"]}' -s nats://localhost:4222107nats reply mesh.agent.bob-001.inbox '{"text":"Hi from Bob!"}' -s nats://localhost:4222108109# Terminal 3: Agent Jeff (sends request)110nats request mesh.agent.bob-001.inbox '{"text":"Hello Bob"}' -s nats://localhost:4222111# → {"text":"Hi from Bob!"}112```113114### Option 2: TypeScript SDK115116```bash117cd examples/typescript/agent-sdk118npm install119node src/bob-agent.js # start Bob120node src/jeff-agent.js # Jeff discovers + requests Bob121```122123See **[typescript.md](./typescript.md)** for the full SDK.124125### Option 3: Python LLM Agent126127```bash128cd examples/python/llm-agent129pip install -r requirements.txt130python research_agent.py131python summarizer_agent.py132```133134See **[python.md](./python.md)** for full code.135136### Option 4: HTTP Bridge (existing REST agent)137138```typescript139// Wrap any Flask/FastAPI/Express agent into Synapse — zero NATS code on their side140import Synapse from "synapse-nats-sdk";141import { HTTPBridge } from "./http-bridge.js";142143const mesh = await Synapse.connect("nats://localhost:4222");144const bridge = new HTTPBridge(mesh, 4100);145await bridge.registerAgent({146 id: "flask-chat-001", name: "Flask Chat Agent",147 baseUrl: "http://localhost:5000",148 capabilities: ["chat"],149 skills: [{ id: "chat", name: "Chat", description: "Chat" }],150});151await bridge.startWebhook();152// Flask agent is now discoverable and callable from any Synapse agent153```154155See **[http-bridge.md](./http-bridge.md)** for full bridge documentation.156157## Architecture Overview158159```160┌─────────────────────────────────────────────────────┐161│ Synapse Protocol │162│ (6 primitives, envelope format, state machine) │163└────────────────────────┬────────────────────────────┘164 │165 │ speaks166 ▼167┌─────────────────────────────────────────────────────┐168│ NATS Messaging │169├─────────────────────────────────────────────────────┤170│ • Request/reply (inbox model) │171│ • Pub/sub (wildcards) │172│ • JetStream persistence │173│ • Leaf nodes (cross-firewall) │174│ • Accounts (multi-tenant isolation) │175│ • WebSockets (browser/home agents) │176└────────────────────────┬────────────────────────────┘177 │178 ┌────────────────┼────────────────┐179 │ │ │180 ┌────▼────┐ ┌───▼────┐ ┌────▼────┐181 │ Agent A │ │Agent B │ │ Agent C │182 │(TypeSC) │ │(Python)│ │ (CLI) │183 └─────────┘ └────────┘ └─────────┘184 │185 │ HTTP Bridge186 ▼187 ┌────────────┐188 │ HTTP Agent │ (Flask/FastAPI/Express — zero NATS code)189 └────────────┘190 │191 │ Browser SDK (WebSocket)192 ▼193 ┌────────────┐194 │ Browser │ (React/Vue/Svelte — wsconnect to NATS:8443)195 └────────────┘196```197198All agents speak Synapse: servers via TCP, browsers via WebSocket, HTTP services via the bridge.199200## Decision Matrix201202| Scenario | Recommended Approach |203|----------|---------------------|204| Static data agents (uptime, config) | [CLI Guide](./cli-guide.md) — 5 lines of bash |205| Edge/IoT agents (sensors, cron jobs) | CLI + JetStream |206| LLM-powered agent (needs reasoning) | [TypeScript](./typescript.md) or [Python](./python.md) SDK |207| High-throughput data pipeline | [Go](./go.md) SDK |208| Cross-org coordination (firewalls) | [Cross-Org Guide](./cross-org.md) |209| Need guaranteed delivery | JetStream (Go SDK) |210| Need streaming responses (LLM tokens) | [Streaming Primitives](./typescript.md#streaming-primitives) — `streamRequest()` / `onStreamRequest()` |211| Agent takes >30s to respond (API calls, multi-step reasoning) | [Long-Running Requests](./typescript.md#long-running-requests) — increase `timeoutMs`, use `streamRequest()`, or stable reply subject for CLI |212| Need conversation history / task persistence | [Task Store](./tasks.md) — JetStream-backed task lifecycle + multi-turn linking |213| Want observability/debugging | [Observability Guide](./observability.md) — OTel tracing, metrics, Grafana |214| Need message validation | [Schema Guide](./schema.md) — JSON Schema for all message types |215| Comparing with A2A/MCP | [Comparison Guide](./comparison.md) |216| Need to rank agents by reliability | [Reputation Guide](./reputation.md) — Per-skill scoring, lying detection, discoverRanked |217| Detect agents claiming skills they dont have | [Lying Detection](./reputation.md#lying-detection) — 3001 SKILL_NOT_FOUND tracking |218| Send documents to agents for analysis | [File Transfer](./file-transfer.md) — Chunked transfer over NATS (init→chunks→done→dispatch) |219| Deploy a mesh for production (boot persistence, multi-tenant NATS, known gotchas) | [Deployment Guide](./deployment.md) — launchd/systemd services, 3-account isolation, bridge integration, operational CLI |220221## Comparison with Other Protocols222223See [comparison.md](./comparison.md) for detailed comparison with:224- **A2A** (Google's Agent-to-Agent) — more ceremony, enterprise focus225- **MCP** (Anthropic's Model Context) — agent-to-tool only226- **ANP** (Agent Network Protocol) — decentralized DID-based227- **RepoWire** — local-first for coding agents only228229## RTerm / neuralOS Integration (synapse-bridge, v3.1.4+)230231RTerm (the ops platform) is a first-class Synapse citizen via the **`synapse-bridge`** plugin — it speaks the Synapse protocol (v0.3.0) over the same NATS server, using the v3.1.2 auth/request-reply/JetStream transport. RTerm and Synapse agents share the same road (NATS) in different lanes: RTerm's own trigger mesh uses `rterm.*` subjects; the Synapse mesh uses `mesh.*` subjects.232233**What the plugin does:**234- **Discover** live Synapse agents — `synapse_discover` queries `mesh.registry.discover` (capability/skill/availability filters) and returns agents + their skills.235- **Dispatch** tasks to a Synapse agent — `synapse_dispatch` sends a `request` envelope to `mesh.agent.{id}.inbox` and awaits the durable response (tracked in the mesh's JetStream task store).236- **Register RTerm as a mesh agent** — `synapse_register` publishes RTerm's manifest to `mesh.registry.register` so other Synapse agents can discover and dispatch to it (bidirectional federation).237- Plus `synapse_health`, `synapse_agents_summary`, the `synapse_mesh_event` trigger (cross-mesh remediation), and the `synapse-mesh-agents` dashboard panel.238239**Config** (`settings.synapse`, persisted across save/load): `url`/`servers` (default `nats://localhost:4222`), `prefix` (default `mesh`), `agentId` (default `rterm-001`), and `auth` (token / user-pass / NKey / JWT / creds / TLS — inline or vault `secretRef`).240241**Example (agent prompt):** "Use synapse_discover to list live mesh agents, then synapse_dispatch a status check to agentspan-001." Verified live: 4 agents discovered (grip-cli-001, grip-001, omp-cli-001, agentspan-001), dispatch → `{stream: AGENT_INBOXES, seq: N}`.242243**Also:** the standalone `rterm-synapse-bridge.mjs` CLI shim (a proof-of-concept the plugin supersedes) does the same from a shell: `rterm-synapse discover | dispatch <agent> <skill> '<json>' | demo`.244245## Production Checklist246247Before going to production, verify:248249- [ ] NATS has JetStream enabled for persistent delivery250- [ ] All subjects are documented in your permissions model251- [ ] Each agent has unique NKey credentials (no shared auth)252- [ ] Error codes are standardized and documented (see envelope.md)253- [ ] Task timeouts are enforced (default: 30s)254- [ ] Heartbeats are running (30s interval)255- [ ] Tracing is propagated via W3C Trace Context (see [observability.md](./observability.md))256- [ ] Monitoring dashboard is set up (NATS monitoring port + Grafana, see [observability.md](./observability.md))257- [ ] Leaf node connections are TLS-encrypted for cross-org traffic258- [ ] Credential rotation plan is in place (jwt expiry, nkey rotation)259- [ ] Envelope validation is enabled on send and receive (see [schema.md](./schema.md))260- [ ] Manifest validation rejects malformed registrations (error code 2002)261- [ ] OTLP endpoint is configured for trace/metric export262- [ ] Circuit breakers protect overloaded agents (see [patterns.md](./patterns.md))263- [ ] Backpressure / flow control enabled (concurrency limits, adaptive rate limiting)264- [ ] NATS account isolation verified (see [deployment.md § 1](./deployment.md#1-nats-multi-tenant-isolation-the-1-gotcha))265- [ ] JetStream store is on a persistent path (not `/tmp` — see [deployment.md § 2](./deployment.md#2-boot-persistence--platform-services))266- [ ] Services are launchd-managed with `KeepAlive=true` and `ThrottleInterval=5`267- [ ] Bridge TaskStore operations are outside `if msg.reply:` block (see [deployment.md § 3](./deployment.md#3-bridge-level-taskstore-integration-without-rewriting-the-agent))268- [ ] Control-plane CLI supports fire-and-forget + poll (see [deployment.md § 4](./deployment.md#4-control-plane-cli-pattern))269- [ ] Heartbeats use consistent format across all SDKs (`mesh.heartbeat.{id}` with envelope containing `{ v, id, type: "heartbeat", ts, from, payload: { agent_id, timestamp } }`)270271## Troubleshooting272273Common issues and fixes:274275**Agent not responding to requests:**276```bash277# Check if agent's inbox has subscribers278nats server report subs -s nats://localhost:4222 | grep mesh.agent279```280281**Discovery returns empty:**282```bash283# Verify agents registered284nats sub mesh.registry.register -s nats://localhost:4222 --count 1285# (run in background, watch who registers)286```287288**JetStream API calls fail when using a leaf node:**289- Almost always caused by missing account isolation (see [deployment.md § 1](./deployment.md#1-nats-multi-tenant-isolation-the-1-gotcha))290- Check `curl http://localhost:8222/jsz` — `api.errors` should be 0291- Verify `accounts {}` block has a dedicated LOCAL account with `jetstream: enabled` and a separate REMOTE account for the leaf292- Ensure `system_account` points to a SYS account with NO JetStream293294**Cross-firewall connection fails:**295- Leaf nodes must connect OUTBOUND only296- Check firewall allows NATS port (4222 default)297- Use `nats auth info` to verify JWT is valid298299**Request times out on long-running agents (LLM, API calls, multi-step reasoning):**300- Pass explicit `timeoutMs` to `request()`: `mesh.request(id, skill, input, 180_000)`301- For agents taking >3 min, use `streamRequest()` / `onStreamRequest()` instead302- From CLI: subscribe to a stable reply subject BEFORE publishing the request (not after)303- See [Long-Running Requests](./typescript.md#long-running-requests) for full patterns304305See [setup.md#troubleshooting](./setup.md#troubleshooting) for basic troubleshooting. For production-level gotchas (NATS isolation, task store bugs, boot persistence issues, bridge integration pitfalls), see [deployment.md § 5](./deployment.md#5-the-known-gotchas-checklist).306307## Further Resources308309- [Synapse on npm](https://www.npmjs.com/package/synapse-nats-sdk) — `npm install synapse-nats-sdk`310- [Synapse on skills.sh](https://www.skills.sh/drolu/synapse-skill/synapse) — `npx skills add https://github.com/drolu/synapse-skill --skill synapse`311- [Synapse specification](https://synapse.ai)312- [NATS documentation](https://docs.nats.io)313- [Synadia Cloud](https://cloud.synadia.com) (free tier available)314- [Academic survey on Synapse patterns](https://arxiv.org/html/2505.02279v1)315316## Quick Commands Reference317318```bash319# Infrastructure320nats-server # start local server321nats-server -js # with JetStream322docker run -p 4222:4222 nats:latest # Docker323324# CLI Primitives325nats pub <subject> '<payload>' # register, emit326nats sub <subject> # subscribe (with wildcards)327nats request <subject> '<payload>' # request (blocks for reply)328nats reply <subject> '<payload>' # respond to requests329330# Discovery331nats request mesh.registry.discover '{"capabilities":["chat"]}'332333# Monitoring334nats server report subs # view subject subscriptions335nats top # live connection stats336nats rtt # latency test337338# File Transfer339synapse-send-file report.pdf # analyze a PDF340synapse-send-file image.png --action extract # extract text from image341synapse-send-file data.csv --target grip-cli-001 --via cloud # send via Synadia Cloud342```343344---345346**Note:** This skill contains both reference material and runnable code. All examples in `examples/` are self-contained and tested. Copy freely into your projects.