Skip to main content
Glama
telepathy-TUP

TUP MCP Server

README.md
# TUP MCP Server

> **Telepathy Universal Protocol — Model Context Protocol Bridge**
>
> Secure, token-authenticated AI-to-AI collaboration across organizations.

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-green.svg)](https://www.python.org/)
[![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-purple.svg)](https://modelcontextprotocol.io/)

---

## 🌐 What is TUP MCP Server?

**tup-mcp-server** is an open-source [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that enables AI agents from different organizations to collaborate securely — without sharing system prompts, private data, model weights, or internal memory.

It implements the **Telepathy Universal Protocol (TUP)**, a governed AI-to-AI communication standard built on the principle of **Zero-Shared-State**.

Agents exchange structured **Intents** (operation type + encoded vector + cryptographic signature) instead of raw prompts. The open-source Reference Encoder provides basic encoding; [TUP Core Enterprise](https://www.telepathy-tup.com/contact) provides advanced semantic compression.

### Key Features

- 🔒 **Zero-Shared-State**: Agents exchange structured Intents, never raw data or prompts.
- 🔑 **Token-Authenticated Relay**: Session tokens protect against unauthorized access.
- ⚡ **Streamable HTTP Relay**: Stateless relay server using chunked HTTP streaming — no WebSocket overhead.
- 🧮 **4-Fold Mathematical Validation**: Condition number, round-trip, orthogonality, and eigenvalue stability checks.
- 📝 **Reference Intent Encoder**: Built-in deterministic text-to-vector encoder for open-source usage.
- 🔁 **Open Core Architecture**: Works out-of-the-box with a pure-Python fallback; drops in the high-performance `telepathy-tup` engine for enterprise speed.
- 🛡️ **DNS Rebinding Protection**: Origin and Host header validation on every request.

---

## 🏗️ Architecture

### Multi-Agent Deployment

Each agent runs its **own instance** of `mcp_server.py`. The relay routes intents between independent instances.

```
Agent A's environment:              Agent B's environment:
┌──────────────────────┐            ┌──────────────────────┐
│ Claude / GPT / etc.  │            │ Claude / GPT / etc.  │
│   ↕ MCP (stdio)      │            │   ↕ MCP (stdio)      │
│ mcp_server.py        │            │ mcp_server.py        │
└──────────┬───────────┘            └──────────┬───────────┘
           │          ┌──────────┐             │
           └──────────┤ relay.py ├─────────────┘
                      └──────────┘
                   (shared, stateless)
```

### Components

| Component | License | Description |
|---|---|---|
| `mcp_server.py` | MIT | MCP server exposing TUP tools to Claude and other agents |
| `relay.py` | MIT | Token-authenticated Streamable HTTP relay routing intents |
| `tup_core_fallback.py` | MIT | Pure-Python reference TUP engine (ActionSpec, Intent, Channel) |
| `intent_encoder.py` | MIT | Reference text-to-vector encoder using SHA-256 expansion |
| `telepathy-tup` | Proprietary | Optional high-performance Cython core ([contact us](https://www.telepathy-tup.com/contact)) |

---

## 🚀 Quick Start

### Prerequisites

- Python 3.10+
- pip

### Installation

```bash
# Clone the repository
git clone https://github.com/telepathy-TUP/tup-mcp-server.git
cd tup-mcp-server

# Install dependencies
pip install -e ".[dev]"
```

### Step 1: Run the Relay Server

```bash
python relay.py
# Relay starts at http://localhost:8001
```

### Step 2: Run the MCP Server

```bash
python mcp_server.py
```

### Step 3: Configure Claude Desktop

Add the following to your Claude Desktop MCP configuration:

```json
{
  "mcpServers": {
    "tup-mcp-server": {
      "command": "python",
      "args": ["path/to/mcp_server.py"],
      "env": {
        "TUP_RELAY_URL": "http://localhost:8001"
      }
    }
  }
}
```

---

## 🔧 MCP Tools

| Tool | Mode | Description |
|---|---|---|
| `tup_connect` | — | Registers with relay (token auth), starts stream listener |
| `tup_encode_and_send` | Recommended | Encodes text → vector → sends intent (Reference Encoder) |
| `tup_send_intent` | Advanced | Sends a pre-built vector as intent (for custom embeddings or TUP Core) |
| `tup_get_pending_intents` | — | Retrieves and clears received intents |
| `tup_decode_intent` | — | Retrieves latest intent with similarity interpretation |
| `tup_get_session_status` | — | Returns channel state, hash chain length, fallback indicator |
| `tup_transition_state` | — | Transitions the channel state machine |

### Example Usage

```
1. tup_connect(relay_url="http://localhost:8001", session_id="collab-01", role="agent_a", partner_role="agent_b")
2. tup_encode_and_send(session_id="collab-01", intent_text="Review the authentication module", operation="REVIEW")
3. tup_get_pending_intents(session_id="collab-01")
4. tup_decode_intent(session_id="collab-01")
5. tup_get_session_status(session_id="collab-01")
```

---

## 📝 How Intent Encoding Works

The open-source version includes a **Reference Intent Encoder** that converts natural-language text into fixed-dimension vectors using deterministic SHA-256 hash expansion.

### Encoding Pipeline

```
Text intent ("Review the auth module")
    ↓
SHA-256 hash expansion (iteration 0, 1, 2, ...)
    ↓
Convert 4-byte chunks to floats in [-1, 1]
    ↓
L2-normalize to unit vector
    ↓
vector=[0.123, -0.456, 0.789, ...] (N dimensions)
```

### What the Reference Encoder IS and IS NOT

| | Reference Encoder (MIT) | TUP Core (Enterprise) |
|---|---|---|
| **Method** | Deterministic hashing (SHA-256) | Proprietary semantic compression |
| **Output** | Consistent fingerprints | Meaning-preserving representations |
| **Codebook** | Uses existing ActionSpec operations | Adaptive, context-aware |
| **Best for** | Coordination, routing, intent classification | Full semantic transfer between agents |
| **Speed** | Standard Python | Optimized Cython |

> **Important**: The Reference Encoder produces deterministic fingerprints, not semantic embeddings. The same input always produces the same vector, but similar meanings do NOT produce similar vectors. For production-grade semantic compression, visit [telepathy-tup.com](https://www.telepathy-tup.com/contact).

### The ActionSpec System

TUP uses `ActionSpec` to classify intents with four parameters:

- `operation`: Intent type (any string — e.g., "ALIGN", "REVIEW", "SUMMARIZE")
- `direction`: Flow direction ("FORWARD" or "BACKWARD")
- `cardinality`: Input dimensions
- `output_dimensions`: Output dimensions

Each ActionSpec is canonicalized and hashed with Blake2b for tamper-proof identification.

---

## ⚖️ Limitations & Token Impact

### When TUP reduces token consumption (30–80% reduction)

- Multi-agent coordination where agents only need to exchange intentions
- Workflows where agents already have context and just need to synchronize
- High-frequency intent exchanges (the per-intent cost is a small HTTP payload)

### When TUP does NOT reduce token consumption

- Tasks where the full document/content must be shared between agents
- Single-agent workflows with no inter-agent communication
- Scenarios where the receiving agent needs the complete original text

### MCP Schema Overhead

The 7 MCP tools add a fixed overhead per turn to the LLM context window. This is negligible in multi-turn agent collaboration but measurable in short single-turn interactions.

### Zero-Shared-State ≠ Token Savings

Zero-Shared-State is a **privacy and security** property (no persistent memory between agents), not an efficiency metric. Token savings come from replacing full-text prompt exchange with compact intent vectors, which depends on the use case.

---

## 🔐 Security

### Token Authentication

The relay requires **session tokens** for all send/receive operations:

1. Agent registers role via `POST /session/{id}/register?role=agent_a`
2. Relay returns a unique `session_token`
3. All subsequent `/send` and `/stream` calls must include this token
4. Unregistered roles cannot create queues or inject messages

### DNS Rebinding Protection

All requests are validated against trusted Host and Origin headers. Requests from untrusted domains are rejected with `403 Forbidden`.

### Hash Chain Integrity

Every intent is appended to an immutable Blake2b hash chain, providing chronological audit tracking of all communications.

---

## 🧮 Mathematical Validation

The TUP engine implements rigorous **4-fold validation** on transformation matrices:

1. **Condition Number**: `numpy.linalg.cond(A) ≤ 10¹⁰`
2. **Round-Trip Check**: `A × A⁻¹ ≈ I` with tolerance `1e-8`
3. **Orthogonality Check**: `A × Aᵀ ≈ I` (norm-preserving optimization)
4. **Eigenvalue Stability**: `|λ| ≤ 1` for all eigenvalues (prevents divergence)

---

## 🧪 Running Tests

```bash
python -m pytest -v
```

Tests cover:
- `test_fallback_compatibility.py` — Core math, state machine, hash integrity
- `test_mcp_tools.py` — MCP tool execution, matrix rejection, encode & decode
- `test_relay_flow.py` — Token auth, DNS rebinding, unauthorized access rejection
- `test_intent_encoder.py` — Determinism, normalization, similarity, edge cases

---

## 📂 Project Structure

```
tup-mcp-server/
├── pyproject.toml              # Package configuration & dependencies
├── mcp_config.json             # Example Claude Desktop config
├── mcp_server.py               # MCP server (FastMCP + dynamic fallback)
├── relay.py                    # Token-authenticated Streamable HTTP relay
├── tup_core_fallback.py        # Pure-Python TUP engine (MIT)
├── intent_encoder.py           # Reference text-to-vector encoder (MIT)
├── README.md                   # This file
└── tests/
    ├── test_fallback_compatibility.py
    ├── test_mcp_tools.py
    ├── test_relay_flow.py
    └── test_intent_encoder.py
```

---

## 🏢 Enterprise

For production-grade deployments with advanced semantic compression, adaptive codebooks, and Cython-optimized performance:

- 🌐 **Website**: [telepathy-tup.com](https://www.telepathy-tup.com)
- 📧 **Contact**: [Enterprise inquiries](https://www.telepathy-tup.com/contact)
- 📦 **TUP Core**: Drop-in replacement for `tup_core_fallback.py` — no code changes needed

---

## 📜 License

This project is licensed under the **MIT License**. See [LICENSE](LICENSE) for details.

The optional high-performance engine `telepathy-tup` is proprietary and commercially licensed by the Telepathy team.

---

---

# TUP MCP Server (Español)

> **Telepathy Universal Protocol — Puente de Protocolo de Contexto de Modelo**
>
> Colaboración segura entre agentes de IA con autenticación por token.

---

## 🌐 ¿Qué es TUP MCP Server?

**tup-mcp-server** es un servidor de código abierto compatible con [MCP](https://modelcontextprotocol.io/) que permite a agentes de IA de distintas organizaciones colaborar de forma segura — sin compartir prompts, datos privados ni memoria interna.

Los agentes intercambian **Intents** estructurados (tipo de operación + vector codificado + firma criptográfica) en lugar de prompts de texto completo. El Reference Encoder de código abierto proporciona codificación básica; [TUP Core Enterprise](https://www.telepathy-tup.com/contact) proporciona compresión semántica avanzada.

### Características Principales

- 🔒 **Cero Estado Compartido**: Los agentes intercambian Intents estructurados, nunca datos crudos.
- 🔑 **Relay con Autenticación por Token**: Tokens de sesión protegen contra acceso no autorizado.
- 📝 **Reference Intent Encoder**: Codificador texto-a-vector incluido para uso open source.
- 🧮 **Validación Matemática de 4 Niveles**: Número de condición, round-trip, ortogonalidad y eigenvalores.
- 🔁 **Arquitectura Open Core**: Funciona inmediatamente con Python puro; acepta `telepathy-tup` como reemplazo para velocidad enterprise.

---

## 🚀 Inicio Rápido

```bash
git clone https://github.com/telepathy-TUP/tup-mcp-server.git
cd tup-mcp-server
pip install -e ".[dev]"

# Terminal 1: Relay
python relay.py

# Terminal 2: MCP Server
python mcp_server.py
```

---

## ⚖️ Limitaciones y Transparencia

### Cuándo TUP reduce tokens (30–80%)
- Coordinación multi-agente donde solo se intercambian intenciones
- Flujos donde los agentes ya tienen contexto y solo necesitan sincronizarse

### Cuándo TUP NO reduce tokens
- Tareas donde el contenido completo debe compartirse entre agentes
- Flujos de un solo agente sin comunicación inter-agente

### Reference Encoder vs. TUP Core

El Reference Encoder genera **fingerprints deterministas**, no embeddings semánticos. Para compresión semántica de nivel producción, visite [telepathy-tup.com](https://www.telepathy-tup.com/contact).

---

## 🏢 Enterprise

Para despliegues de producción con compresión semántica avanzada:

- 🌐 [telepathy-tup.com](https://www.telepathy-tup.com)
- 📧 [Consultas enterprise](https://www.telepathy-tup.com/contact)

---

## 📜 Licencia

Licenciado bajo **MIT**. Ver [LICENSE](LICENSE). El motor `telepathy-tup` es propietario.