# TrustMesh 🔗

**Decentralized trust & reputation protocol for AI agents.**

[![npm version](https://img.shields.io/npm/v/trustmesh-ai.svg)](https://www.npmjs.com/package/trustmesh-ai)
[![test](https://github.com/geerdwedda-create/trustmesh/actions/workflows/ci.yml/badge.svg)](https://github.com/geerdwedda-create/trustmesh)
[![license](https://img.shields.io/npm/l/trustmesh-ai.svg)](https://github.com/geerdwedda-create/trustmesh/blob/main/LICENSE)

When autonomous agents transact, they need to know: *can I trust this counterparty?* TrustMesh provides peer-to-peer reputation scoring — no central authority, no single point of failure.

## Why TrustMesh?

- **AI agents are trading** — APIs, compute, data, services — but they have no credit system
- **Existing solutions** focus on identity attestation (is this agent real?) not transaction trust (will this agent deliver?)
- **Zero-budget deploy** — runs on any Node.js server, SQLite for persistence, Docker-ready

## How It Works

```
Agent A ─── interacts ───→ Agent B
   │                          │
   └── rates interaction ─────┘
         (score + claim + evidence)
                │
                ▼
         ┌─────────────┐
         │  TrustMesh  │
         │   Network   │
         └─────────────┘
                │
                ▼
   Any agent can query: "How trustworthy is Agent B?"
   → Aggregated score from direct + transitive trust graph
```

### Trust Model

1. **Direct Trust** — Based on your own interactions with an agent. You always trust your own data most.
2. **Transitive Trust** — If A trusts B, and B trusts C, A gets a weighted signal about C. Decays with distance.
3. **Evidence-Based** — Scores aren't just numbers. Every rating includes a claim type, evidence hash, and expiration. Verifiable, disputable.
4. **Sybil-Resistant** — New identities start at neutral. Trust weight grows with unique interaction partners (diversity signal), not volume.
5. **Dispute Resolution** — Bad ratings get challenged. Dispute workflow handles false claims and rehabilitation of honest mistakes.

### Score Calculation

```
trust(agent) = α × direct_score(agent)
            + β × Σ [ w(dist) × referrer_trust × referrer_rating(agent) ]
            + γ × base_reputation(agent)
```

Where:
- `α` = weight for direct experience (default: 0.6)
- `β` = weight for transitive signals (default: 0.3)
- `γ` = base reputation from network tenure (default: 0.1)
- `w(dist)` = decay factor by graph distance (default: 0.5^dist)

## Quick Start

```bash
npm install trustmesh-ai
```

```typescript
import { TrustMesh } from 'trustmesh-ai';

const mesh = new TrustMesh({
  nodeId: 'agent-alice-001',
  storage: 'sqlite', // or 'memory' for testing
  dbPath: './trust.db'
});

await mesh.start();

// Rate an interaction
await mesh.rate({
  target: 'agent-bob-042',
  score: 0.85,
  claim: 'delivered-api-data',
  evidence: 'sha256:abc123...',
  expiresAt: Date.now() + 90 * 24 * 60 * 60 * 1000 // 90 days
});

// Query trust score
const score = await mesh.getTrustScore('agent-bob-042');
console.log(score);
// { overall: 0.82, direct: 0.85, transitive: 0.78, sampleSize: 12, confidence: 0.71 }
```

## CLI

```bash
# Start the trust API server
npx trustmesh serve

# With SQLite persistence and API key auth
TRUSTMESH_STORAGE=sqlite TRUSTMESH_API_KEY=secret123 npx trustmesh serve

# Rate an interaction
npx trustmesh rate --target agent-bob --score 0.85 --claim delivered-data

# Query a trust score
npx trustmesh score --target agent-bob

# Get trust graph
npx trustmesh graph --target agent-bob

# File a dispute
npx trustmesh dispute --rating <id> --reason "false claim"

# List peers
npx trustmesh peers
```

## API Server

Run TrustMesh as a standalone trust oracle:

```bash
npx trustmesh serve --port 3456
```

### Cloud Mode (with Stripe billing)

```bash
# Start with per-account billing
STRIPE_SECRET_KEY=sk_test_... TRUSTMESH_API_KEY=admin trustmesh serve

# Or use the hosted Cloud API
# API: https://trustmesh-production-27d1.up.railway.app

# Create an account
curl -X POST https://trustmesh-production-27d1.up.railway.app/billing/signup \
  -H "Content-Type: application/json" \
  -d '{"email": "you@example.com", "tier": "free"}'

# Get your usage stats
curl https://trustmesh-production-27d1.up.railway.app/billing/usage \
  -H "Authorization: Bearer YOUR_API_KEY"

# Upgrade to Pro
curl -X POST https://trustmesh-production-27d1.up.railway.app/billing/upgrade \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"tier": "pro"}'
```

### Endpoints

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/health` | Health check (version, uptime) |
| `POST` | `/rate` | Submit a trust rating |
| `GET` | `/rate/:id` | Get a rating by ID |
| `DELETE` | `/rate/:id` | Delete a rating |
| `GET` | `/score/:agentId` | Get trust score for an agent |
| `POST` | `/score` | Batch trust scores (up to 100) |
| `GET` | `/graph/:agentId` | Trust graph neighborhood |
| `POST` | `/dispute` | File a dispute against a rating |
| `GET` | `/disputes` | List open disputes |
| `POST` | `/dispute/:id/resolve` | Resolve a dispute |
| `GET` | `/peers` | List known peers |
| `POST` | `/billing/signup` | Create account (free tier) |
| `GET` | `/billing/account` | Get account info |
| `GET` | `/billing/usage` | Get usage stats |
| `GET` | `/billing/tiers` | List pricing tiers |
| `POST` | `/billing/upgrade` | Upgrade tier (Stripe checkout) |
| `POST` | `/billing/portal` | Stripe customer portal |
| `POST` | `/billing/webhook` | Stripe webhook |
| `GET` | `/openapi.json` | OpenAPI spec |

### Authentication

Set `TRUSTMESH_API_KEY` to enable API key auth. Then pass the key via:
- `Authorization: Bearer <key>` header
- `X-API-Key: <key>` header
- `?apiKey=<key>` query parameter

## Docker

```bash
docker compose up -d
```

With API key:
```bash
TRUSTMESH_API_KEY=your-secret docker compose up -d
```

## Architecture

```
┌─────────────────────────────────┐
│           SDK Layer             │
│  (TypeScript/JS, Python soon)   │
├─────────────────────────────────┤
│         Trust Engine            │
│  Score calc, graph walk, decay  │
├─────────────────────────────────┤
│       Protocol Layer            │
│  Peer discovery, sync, dispute  │
├─────────────────────────────────┤
│       Storage Layer             │
│  SQLite (default) | Memory      │
└─────────────────────────────────┘
```

## Claim Types

Standard claim types for ratings:

| Claim | Use Case |
|-------|----------|
| `general` | Default / unspecified |
| `delivered-api-data` | API response was correct |
| `payment-received` | Payment was received |
| `payment-sent` | Payment was sent |
| `task-completed` | Task was finished |
| `task-failed` | Task was not finished |
| `data-verified` | Data integrity confirmed |
| `response-time` | Response time acceptable |
| `uptime-confirmed` | Service was available |
| `contract-fulfilled` | Contract completed |
| `contract-breached` | Contract violated |

## Monetization (Freemium)

| Tier | Price | Limits |
|------|-------|--------|
| Open Source | Free | Self-hosted, unlimited local queries |
| Cloud Free | $0 | 1K API calls/day, 100 agents |
| Cloud Pro | $29/mo | 50K API calls/day, 10K agents |
| Cloud Scale | $199/mo | 500K API calls/day, unlimited agents |
| Enterprise | Custom | SLA, dedicated infra, custom models |

## Roadmap

- [x] Core trust scoring engine
- [x] SQLite + memory storage
- [x] REST API server (Fastify)
- [x] CLI with rate/score/graph/dispute/peers commands
- [x] API key authentication
- [x] CORS support
- [x] Batch score endpoint
- [x] Dispute resolution workflow
- [x] OpenAPI spec
- [x] Docker support
- [ ] Peer-to-peer gossip protocol
- [ ] Python SDK
- [ ] Cloud API (trustmesh.ai)
- [x] MCP server integration (`trustmesh-mcp`)
- [x] LangChain tool (`trustmesh-langchain`)
- [ ] On-chain anchoring (optional, for high-value disputes)

## Integrations

### MCP Server

Use TrustMesh with Claude Desktop, Cursor, Windsurf, and any MCP-compatible agent:

```bash
npm install trustmesh-mcp
```

```json
// claude_desktop_config.json
{
  "mcpServers": {
    "trustmesh": {
      "command": "npx",
      "args": ["trustmesh-mcp"]
    }
  }
}
```

→ [trustmesh-mcp on npm](https://www.npmjs.com/package/trustmesh-mcp) · [packages/mcp](./packages/mcp/)

### LangChain

Drop-in tools for LangChain agents:

```bash
npm install trustmesh-langchain
```

```typescript
import { getTrustMeshTools } from 'trustmesh-langchain';
const tools = getTrustMeshTools();
// [TrustScoreTool, TrustRateTool, TrustCheckTool, TrustGraphTool, TrustDisputeTool]
```

→ [trustmesh-langchain on npm](https://www.npmjs.com/package/trustmesh-langchain) · [packages/langchain](./packages/langchain/)

## Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md). PRs welcome.

## Changelog

See [CHANGELOG.md](./CHANGELOG.md).

## License

MIT — use it, build on it, ship it.

---

Built by agents, for agents. ⚡