# 7h3 Protocol

> Per-message signing + replay protection for MCP and A2A traffic. TypeScript / Python / Rust. Wire version aip/0.1.

- **Type:** MCP server
- **Install:** `agentstack add mcp-icemastert-7h3-protocol`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [IceMasterT](https://agentstack.voostack.com/s/icemastert)
- **Installs:** 0
- **Category:** [Integrations](https://agentstack.voostack.com/c/integrations)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [IceMasterT](https://github.com/IceMasterT)
- **Source:** https://github.com/IceMasterT/7h3-protocol
- **Website:** https://www.npmjs.com/package/@7h3/protocol

## Install

```sh
agentstack add mcp-icemastert-7h3-protocol
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

[](https://www.npmjs.com/package/@7h3/protocol)
  [](https://www.npmjs.com/package/@7h3/protocol-pq)
  [](https://www.npmjs.com/package/@7h3/protocol-threshold)
  [](https://pypi.org/project/7h3-protocol/)
  [](https://crates.io/crates/protocol-7h3)
  [](https://github.com/IceMasterT/7h3-protocol/tree/main/src)
  [](./package.json)
  [](./docs/VERSIONING_POLICY.md)
  [](./LICENSE)

  

  **Cryptographic signing, replay protection, and E2E encryption for AI agent messages.**
  **One envelope. Every transport. Quantum-ready.**

  

---

## Table of Contents

- [The Problem](#the-problem)
- [What 7h3 Protocol Does](#what-7h3-protocol-does)
- [How It Works](#how-it-works)
- [Security Guarantees](#security-guarantees)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core API](#core-api)
- [Transports](#transports)
- [Gateway](#gateway)
- [Cloudflare Workers](#cloudflare-workers)
- [AI Coding Agents](#ai-coding-agents)
- [MCP (Claude Tool Calls)](#mcp-claude-tool-calls)
- [End-to-End Encryption](#end-to-end-encryption)
- [Capability Tokens and Delegation](#capability-tokens-and-delegation)
- [Streaming Message Signing](#streaming-message-signing)
- [Distributed Replay Cache (Redis)](#distributed-replay-cache-redis)
- [Binary Wire Format (CBOR)](#binary-wire-format-cbor)
- [Observability (Prometheus + OpenTelemetry)](#observability-prometheus--opentelemetry)
- [Post-Quantum Signatures (ML-DSA)](#post-quantum-signatures-ml-dsa)
- [Threshold Signatures (M-of-N BLS)](#threshold-signatures-m-of-n-bls)
- [Audit Log](#audit-log)
- [Rate Limiting](#rate-limiting)
- [Route Policies](#route-policies)
- [Key Infrastructure](#key-infrastructure)
- [Cross-SDK Conformance](#cross-sdk-conformance)
- [CLI Reference](#cli-reference)
- [Docker](#docker)
- [Uninstall](#uninstall)
- [Changelog](#changelog)

---

## The Problem

AI agent systems are moving fast, and the protocols underpinning them were not built with message-level security in mind.

**MCP (Model Context Protocol)** is plain JSON-RPC 2.0. A message in flight has no signature. Any intermediary — a rogue proxy, a compromised queue consumer, a misconfigured load balancer — can alter tool call parameters or replay a previously captured request. The MCP handler has no way to know.

**A2A (Agent-to-Agent)** signs Agent Cards — static configuration — not per-message traffic. Once an agent is "trusted," every message it sends is implicitly trusted regardless of whether that specific message was tampered with in transit or is a replay from ten minutes ago.

**HTTP APIs** default to IP-based rate limiting. IP addresses are trivially spoofed or shared. The same valid signed request can often be submitted multiple times, triggering duplicate writes, payments, or tool executions.

The gap these protocols share is identical: they authenticate *agents* at the connection or identity level, but they do not authenticate *individual messages* at the content level. 7h3 Protocol fills that gap without replacing anything.

---

## What 7h3 Protocol Does

7h3 Protocol wraps every message — regardless of transport — in a **signed envelope**. The envelope is compact, deterministic, and verifiable by any peer that holds the sender's public key.

**v0.5.0 feature set:**

| Feature | Mechanism |
|---|---|
| Message authentication | Ed25519 asymmetric signing or HMAC-SHA256 |
| Replay prevention | TTL + nonce deduplication (in-memory or Redis) |
| E2E encryption | X25519 key exchange + ChaCha20-Poly1305 AEAD |
| Capability delegation | Scoped, time-bounded, cryptographic credential chains |
| Streaming signing | Per-chunk HMAC + final Ed25519 over the full stream |
| Observability | Zero-dep Prometheus exposition + optional OpenTelemetry |
| Post-quantum | ML-DSA-65 / ML-DSA-87 (NIST FIPS 204) — `@7h3/protocol-pq` |
| Binary encoding | Deterministic CBOR (RFC 8949) — ~40% smaller than JSON |
| Threshold signing | M-of-N BLS12-381 aggregation — `@7h3/protocol-threshold` |
| Transport coverage | HTTP, WebSocket, gRPC, Queues, Webhooks |
| SDK coverage | TypeScript, Python, Rust, Go, Browser |

---

## How It Works

### Canonical Serialization

Signatures only mean something if everyone signs the same bytes. JSON object key order is unspecified by the spec, so 7h3 Protocol uses deterministic JSON canonicalization: keys are sorted alphabetically at every nesting level, optional absent fields are omitted entirely, and the result is UTF-8 encoded.

The canonical form is byte-identical across TypeScript, Python, Rust, and Go, proven by the shared conformance test vectors in `conformance/7h3_v0_1.json`.

### Envelope Structure

```json
{
  "body": {
    "capability":   "task.plan",
    "content":      "do something",
    "correlationId": "req-123",
    "intent":       "TASK"
  },
  "header": {
    "messageId":   "uuid-here",
    "nonce":       "random-bytes",
    "recipient":   "agent.beta",
    "sender":      "agent.alpha",
    "timestampMs": 1712500000000,
    "ttlMs":       60000,
    "version":     "7h3/0.1"
  },
  "signature": {
    "alg":   "ED25519",
    "keyId": "k1",
    "value": "base64url-sig-here"
  }
}
```

Optional fields (`capability`, `correlationId`, `recipient`) are omitted when absent — not `null`, not `""`. This is load-bearing for the canonical form.

### End-to-End Flow

```mermaid
sequenceDiagram
    participant S as Sender Agent
    participant C as 7h3 SDK
    participant T as Transport
    participant G as Gateway / Receiver
    participant U as Upstream

    S->>C: createEnvelope(sender, body, ttlMs)
    C->>C: Deterministic JSON canonicalization
    C->>C: Ed25519 sign(canonicalPayload, privateKey)
    C-->>S: SignedEnvelope {header, body, signature}
    S->>T: Transmit via HTTP / WS / gRPC / Queue / Webhook
    T->>G: Request with envelope
    G->>G: Check TTL not expired
    G->>G: Check nonce not replayed (memory or Redis)
    G->>G: Verify Ed25519 signature
    G->>G: Match route policy + rate limit
    G->>U: Forward + inject x-7h3-sender header
    U-->>G: Response
    G-->>S: Response (optionally signed)
```

### TTL and Nonce

Every envelope carries `timestampMs`, `ttlMs`, and a random `nonce`. A receiver rejects the envelope if `now > timestampMs + ttlMs`, then checks the nonce against a deduplication store. A replayed envelope fails even if the signature is valid.

---

## Security Guarantees

| Attack | Defense |
|---|---|
| Impersonation | Ed25519 — only the private key holder can produce a valid signature |
| Replay | Nonce deduplication + TTL expiry (in-memory or Redis) |
| Tampering | Signature covers the full canonical envelope; any modification breaks verification |
| Unauthorized access | Per-route `allowedSenders` policy — unlisted senders rejected before upstream |
| Response spoofing | Signed `x-7h3-response` header; `correlationId` binding |
| Rate abuse | `SlidingWindowRateLimiter` keyed by verified sender identity, not IP |
| Audit tampering | `InMemoryAuditLog` entries are Ed25519-signed and chained |
| Quantum computers | ML-DSA-65/87 via `@7h3/protocol-pq` (NIST FIPS 204) |
| Cross-instance replay | `RedisReplayStore` — atomic SET NX PX across all instances |
| Eavesdropping | X25519 + ChaCha20-Poly1305 E2E encryption |

---

## Installation

### TypeScript / Node.js

```bash
npm install @7h3/protocol
# or
pnpm add @7h3/protocol
# or
yarn add @7h3/protocol
```

Requires Node.js ≥ 18. Zero runtime dependencies — uses Node.js built-in `crypto` throughout.

### Python

```bash
pip install 7h3-protocol
```

Requires Python ≥ 3.9. Optional extras for advanced features:

```bash
pip install 7h3-protocol[redis]    # RedisReplayStore (pip install redis)
pip install 7h3-protocol[crypto]   # X25519 + ChaCha20 encryption (pip install cryptography)
pip install 7h3-protocol[pq]       # ML-DSA post-quantum (pip install dilithium-py)
```

### Rust

```toml
# Cargo.toml
[dependencies]
protocol-7h3 = "0.5"
```

### Go

```bash
go get github.com/IceMasterT/7h3-protocol/sdk/go
```

### Browser

```bash
npm install @7h3/protocol-browser
```

Pure Web Crypto API — no Node.js dependency. Works in Chrome 100+, Firefox 100+, Safari 16+, Edge 100+.

### Post-Quantum Extension

```bash
npm install @7h3/protocol-pq
```

Adds ML-DSA-65 and ML-DSA-87 (NIST FIPS 204 / Dilithium). Separate package to keep `@7h3/protocol` at zero runtime dependencies.

### Threshold Signatures Extension

```bash
npm install @7h3/protocol-threshold
```

Adds M-of-N BLS12-381 threshold signatures and Shamir Secret Sharing.

---

## Quick Start

```ts
import {
  generateEd25519KeypairBase64Url,
  createEnvelope,
  signEnvelopeEd25519,
  verifyEnvelopeEd25519,
} from '@7h3/protocol'

// 1. Generate keypairs
const sender   = await generateEd25519KeypairBase64Url()
const receiver = await generateEd25519KeypairBase64Url()

// 2. Create and sign a message
const envelope = createEnvelope('agent.alpha', {
  intent:  'TASK',
  content: 'summarize https://example.com',
}, { ttlMs: 60_000 })

const signed = await signEnvelopeEd25519(envelope, sender.privateKey, 'key-1')

// 3. Transmit `signed` via any transport (HTTP header, WS frame, queue, etc.)

// 4. Verify on the receiving end
const result = await verifyEnvelopeEd25519(signed, sender.publicKey)
if (!result.ok) throw new Error(result.error)

console.log('Verified sender:', signed.header.sender)  // 'agent.alpha'
```

---

## Core API

### Key Generation

**TypeScript:**

```ts
import { generateEd25519KeypairBase64Url } from '@7h3/protocol'

const { publicKey, privateKey } = await generateEd25519KeypairBase64Url()
// publicKey:  SPKI format, base64url, ~44 chars
// privateKey: PKCS8 format, base64url, ~88 chars
```

**Python:**

```python
from protocol_7h3 import generate_keypair

public_key, private_key = generate_keypair()
```

**Rust:**

```rust
use protocol_7h3::generate_keypair;

let (public_key, private_key) = generate_keypair().unwrap();
```

**Go:**

```go
import go7h3 "github.com/IceMasterT/7h3-protocol/sdk/go"

publicKey, privateKey, err := go7h3.GenerateKeypair()
```

**Browser:**

```ts
import { generateKeypair } from '@7h3/protocol-browser'

const { publicKey, privateKey } = await generateKeypair()
```

### Creating Envelopes

```ts
import { createEnvelope } from '@7h3/protocol'

const envelope = createEnvelope(
  'agent.alpha',              // sender ID
  {
    intent:        'TASK',
    content:       'do something',
    capability:    'task.plan',     // optional
    correlationId: 'req-123',       // optional
  },
  {
    ttlMs:     60_000,              // 1 minute (default: 60000)
    recipient: 'agent.beta',        // optional
    messageId: 'custom-uuid',       // optional — auto-generated if omitted
  }
)
```

### Signing

**Ed25519 (asymmetric — recommended):**

```ts
import { signEnvelopeEd25519 } from '@7h3/protocol'

const signed = await signEnvelopeEd25519(envelope, privateKey, 'key-id')
// signed.signature.alg === 'ED25519'
```

**HMAC-SHA256 (shared secret):**

```ts
import { signEnvelopeHmac } from '@7h3/protocol'

const signed = await signEnvelopeHmac(envelope, sharedSecret, 'key-id')
// signed.signature.alg === 'HS256'
```

**Python:**

```python
from protocol_7h3 import sign_envelope_ed25519, sign_envelope_hmac

signed = sign_envelope_ed25519(envelope, private_key, 'k1')
signed = sign_envelope_hmac(envelope, shared_secret, 'k1')
```

**Rust:**

```rust
use protocol_7h3::{sign_envelope_ed25519, sign_envelope_hmac};

let signed = sign_envelope_ed25519(&envelope, &private_key, "k1")?;
let signed = sign_envelope_hmac(&envelope, &shared_secret, "k1")?;
```

**Go:**

```go
signed, err := go7h3.SignEnvelopeEd25519(env, privateKey, "k1")
signed, err := go7h3.SignEnvelopeHmac(env, sharedSecret, "k1")
```

### Verifying

**TypeScript:**

```ts
import { verifyEnvelopeEd25519, verifyEnvelopeHmac } from '@7h3/protocol'

const result = await verifyEnvelopeEd25519(signed, publicKey)
// { ok: true }  or  { ok: false, error: 'TTL expired' | 'signature verification failed' | ... }

const result2 = await verifyEnvelopeHmac(signed, sharedSecret)
```

**Python:**

```python
from protocol_7h3 import verify_envelope_ed25519

result = verify_envelope_ed25519(signed, public_key)
if not result['ok']:
    raise ValueError(result['error'])
```

**Rust:**

```rust
use protocol_7h3::verify_envelope_ed25519;

let result = verify_envelope_ed25519(&signed, &public_key)?;
```

**Go:**

```go
ok, err := go7h3.VerifyEnvelopeEd25519(signed, publicKey)
```

---

## Transports

The same signed envelope is carried differently per transport. Verification logic is identical.

### HTTP / REST

The signed envelope travels as a JSON value in the `x-7h3-envelope` header.

**Signing outbound requests:**

```ts
import { signHttpRequest } from '@7h3/protocol'

const headers = await signHttpRequest({
  method:     'POST',
  url:        'https://api.example.com/action',
  body:       JSON.stringify(payload),
  sender:     'agent.alpha',
  privateKey: myPrivateKey,
  keyId:      'k1',
  intent:     'TASK',
})

await fetch('https://api.example.com/action', {
  method:  'POST',
  headers: { ...headers, 'Content-Type': 'application/json' },
  body:    JSON.stringify(payload),
})
```

**Verifying inbound requests (Express middleware):**

```ts
import { verifyHttpEnvelope } from '@7h3/protocol'

app.use(async (req, res, next) => {
  const result = await verifyHttpEnvelope(req.headers, {
    getPublicKey: async (senderId) => keyStore[senderId],
  })
  if (!result.ok) return res.status(401).json({ error: result.reason })
  req.sender = result.sender
  next()
})
```

**Python:**

```python
from protocol_7h3 import verify_http_envelope, sign_http_request

# Signing
headers = sign_http_request(
    method='POST', url='https://api.example.com/action',
    body=json.dumps(payload), sender='agent.alpha',
    private_key=my_private_key, key_id='k1', intent='TASK'
)

# Verifying (FastAPI/Flask middleware)
result = verify_http_envelope(request.headers, key_registry=key_store)
```

**Go:**

```go
// Middleware
func Middleware(keyRegistry go7h3.KeyRegistry) func(http.Handler) http.Handler {
    return go7h3.Middleware(keyRegistry)
}
```

**CBOR encoding (smaller payloads):**

```ts
const headers = await signHttpRequest({ ...opts, format: 'cbor' })
// Content-Type: application/7h3-cbor
// Payload ~40% smaller
```

### WebSocket

Every frame is individually signed. Sequence numbers prevent reordering attacks.

```ts
import { createWsBinding } from '@7h3/protocol'

const ws = new WebSocket('wss://api.example.com')

// Sender
const binding = createWsBinding(ws, {
  sender:     'agent.alpha',
  privateKey: myPrivateKey,
  keyId:      'k1',
})
binding.send({ intent: 'TASK', content: 'do something' })

// Receiver
const serverBinding = createWsBinding(ws, {
  getPublicKey: async (senderId) => keyStore[senderId],
})
serverBinding.onMessage((envelope) => {
  console.log('Verified from:', envelope.header.sender)
})
```

### gRPC

Envelope in `7h3-envelope-bin` gRPC metadata (binary base64).

```ts
import { grpcSigningInterceptor, grpcVerifyingInterceptor } from '@7h3/protocol'

// Client interceptor
const client = new MyServiceClient(address, credentials, {
  interceptors: [grpcSigningInterceptor({ sender: 'agent.alpha', privateKey, keyId: 'k1' })],
})

// Server interceptor
const server = new grpc.Server()
server.addService(MyService, grpcVerifyingInterceptor({
  implementation: myHandler,
  getPublicKey: async (senderId) => keyStore[senderId],
}))
```

### Message Queues

Envelope wraps payload as `{ envelope, payload }`. Works with SQS, RabbitMQ, Kafka, Pub/Sub.

```ts
import { signQueueMessage, verifyQueueMessage } from '@7h3/protocol'

// Producer
const message = await signQueueMessage(
  { taskId: '123', action: 'process' },
  { sender: 'agent.alpha', privateKey, keyId: 'k1', intent: 'TASK' }
)
await queue.send(JSON.stringify(message))

// Consumer
const result = await verifyQueueMessage(JSON.parse(rawMessage), {
  getPublicKey: async (senderId) => keyStore[senderId]

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [IceMasterT](https://github.com/IceMasterT)
- **Source:** [IceMasterT/7h3-protocol](https://github.com/IceMasterT/7h3-protocol)
- **License:** MIT
- **Homepage:** https://www.npmjs.com/package/@7h3/protocol

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-icemastert-7h3-protocol
- Seller: https://agentstack.voostack.com/s/icemastert
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
