Metadata-Version: 2.4
Name: mesh-revenue-gateway
Version: 0.1.0
Summary: Drop-in billing proxy for self-hosted AI agent meshes with Stripe integration and usage tracking
Project-URL: Homepage, https://github.com/yourusername/mesh-revenue-gateway
Project-URL: Documentation, https://github.com/yourusername/mesh-revenue-gateway#readme
Project-URL: Repository, https://github.com/yourusername/mesh-revenue-gateway
Project-URL: Issues, https://github.com/yourusername/mesh-revenue-gateway/issues
Author-email: Developer <dev@example.com>
License: MIT
Keywords: agents,ai,billing,llm,proxy,revenue,stripe
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Requires-Dist: aiosqlite>=0.19.0
Requires-Dist: fastapi>=0.109.0
Requires-Dist: httpx>=0.26.0
Requires-Dist: passlib[bcrypt]>=1.7.4
Requires-Dist: pydantic-settings>=2.1.0
Requires-Dist: pydantic>=2.5.0
Requires-Dist: python-jose[cryptography]>=3.3.0
Requires-Dist: python-multipart>=0.0.6
Requires-Dist: rich>=13.7.0
Requires-Dist: sqlalchemy>=2.0.25
Requires-Dist: stripe>=7.11.0
Requires-Dist: tiktoken>=0.5.2
Requires-Dist: typer>=0.9.0
Requires-Dist: uvicorn[standard]>=0.27.0
Provides-Extra: dev
Requires-Dist: black>=23.12.0; extra == 'dev'
Requires-Dist: httpx>=0.26.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
Requires-Dist: pytest>=7.4.0; extra == 'dev'
Requires-Dist: ruff>=0.1.9; extra == 'dev'
Description-Content-Type: text/markdown

# Mesh Revenue Gateway

Drop-in FastAPI billing proxy for self-hosted AI agent meshes with real-time token tracking, Stripe integration, and multi-tenant management.

## What is this?

Mesh Revenue Gateway solves the critical monetization gap in the self-hosted agent ecosystem. It's a lightweight FastAPI proxy that wraps your existing OpenAI/Anthropic/local model endpoints, tracks token usage in real-time, integrates with Stripe for usage-based billing, and manages per-tenant API keys—all without modifying your agent code. Built for developers who want self-hosted control but need production-ready billing infrastructure.

## Features

- **Token-Level Usage Tracking** — Real-time counting for OpenAI, Anthropic, and local LLM endpoints
- **Stripe Integration** — Automatic invoice generation, usage-based billing, and subscription management
- **Multi-Tenant API Keys** — Isolated per-tenant credentials with granular access control
- **Spend Caps & Rate Limiting** — Hard limits on daily tokens, requests/minute, and monthly spend
- **Admin Dashboard** — Monitor per-tenant usage, revenue trends, and mesh health
- **One-Hour Setup** — Drop into your ZachOS architecture with zero agent code changes
- **SQLite + Optional Postgres** — Start local, scale to production without migration pain
- **Webhook Support** — Inbound Stripe events, outbound usage notifications for integrations

## Quick Start

### Installation

```bash
# Clone and install
git clone <repo>
cd mesh-revenue-gateway
pip install -e .

# Or via Docker
docker compose up
```

### Configuration

Create a `.env` file:

```env
STRIPE_API_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
DATABASE_URL=sqlite:///./revenue.db
ADMIN_API_KEY=your-secure-key
UPSTREAM_OPENAI_BASE_URL=http://localhost:8000
```

### Running the Server

```bash
# Standalone
python -m mesh_revenue_gateway.main

# Or with Docker Compose
docker compose up -d
```

The proxy listens on `http://localhost:9090` by default.

## Usage Examples

### 1. Proxy an OpenAI Request

```bash
curl -X POST http://localhost:9090/v1/chat/completions \
  -H "Authorization: Bearer tenant-key-abc123" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4",
    "messages": [{"role": "user", "content": "Hello"}]
  }'
```

**Behind the scenes:**
- Token count is extracted from the response
- Usage is logged to the database with tenant ID and timestamp
- Stripe is notified for billing aggregation
- Spend cap is checked before response

### 2. Create a Tenant and API Key

```bash
curl -X POST http://localhost:9090/admin/tenants \
  -H "X-Admin-Key: your-secure-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Acme Corp",
    "stripe_customer_id": "cus_...",
    "daily_token_limit": 1000000,
    "monthly_spend_cap": 500
  }'
```

### 3. Monitor Tenant Usage

```bash
curl http://localhost:9090/admin/tenants/tenant-uuid/usage \
  -H "X-Admin-Key: your-secure-key"
```

**Response:**
```json
{
  "tenant_id": "...",
  "tokens_used_today": 245000,
  "tokens_used_month": 2100000,
  "estimated_cost": 42.50,
  "requests_count": 1250,
  "last_request": "2026-03-30T12:45:00Z"
}
```

### 4. Handle Stripe Webhooks

Webhook endpoint: `POST /webhooks/stripe`

Automatically processes:
- `customer.subscription.deleted` → Disable tenant
- `invoice.payment_succeeded` → Log payment
- `invoice.payment_failed` → Alert admin

## Tech Stack

| Layer | Technology |
|-------|------------|
| **API Framework** | FastAPI 0.104+ |
| **Database** | SQLite (local) / Postgres (production) |
| **Billing** | Stripe API |
| **Token Counting** | tiktoken (OpenAI), anthropic SDK |
| **Authentication** | JWT + API keys |
| **Deployment** | Docker / Docker Compose |
| **Admin Dashboard** | Next.js + shadcn/ui (separate repo) |

## Architecture

```
Client Request
     ↓
Mesh Revenue Gateway (FastAPI)
     ├─ Authenticate tenant
     ├─ Check spend cap / rate limit
     ├─ Proxy to upstream (OpenAI/local model)
     ├─ Count tokens in response
     ├─ Log usage to database
     ├─ Notify Stripe
     └─ Return response to client
```

## Core Modules

- **`main.py`** — FastAPI app initialization and middleware
- **`routers/proxy.py`** — Request proxying and response interception
- **`routers/admin.py`** — Tenant management and usage queries
- **`routers/auth.py`** — API key validation and JWT issuance
- **`routers/webhooks.py`** — Stripe webhook handling
- **`token_counter.py`** — Model-specific token counting
- **`pricing.py`** — Cost calculation per model
- **`database.py`** — SQLAlchemy ORM for usage logs and tenants
- **`security.py`** — Key derivation, rate limiting, spend cap enforcement

## Environment Variables

| Variable | Required | Default | Purpose |
|----------|----------|---------|---------|
| `STRIPE_API_KEY` | Yes | — | Stripe secret key |
| `STRIPE_WEBHOOK_SECRET` | Yes | — | Webhook signature verification |
| `DATABASE_URL` | No | `sqlite:///./revenue.db` | SQLite or Postgres connection |
| `ADMIN_API_KEY` | Yes | — | Protect admin endpoints |
| `UPSTREAM_OPENAI_BASE_URL` | No | `https://api.openai.com/v1` | Target LLM endpoint |
| `JWT_SECRET` | No | Auto-generated | JWT signing key |
| `PORT` | No | `9090` | Server port |

## Deployment

### Local Development

```bash
docker compose -f docker-compose.dev.yml up
```

### Production

```bash
docker compose -f docker-compose.yml up -d
# Or Kubernetes:
kubectl apply -f k8s/
```

Includes:
- Environment-specific configs
- Postgres for multi-instance deployment
- Health check endpoints
- Structured logging

## API Endpoints

### Public Proxy
- `POST /v1/chat/completions` — Proxy to LLM
- `POST /v1/embeddings` — Proxy embeddings
- `POST /v1/images/generations` — Proxy image generation

### Authentication
- `POST /auth/login` — Generate JWT
- `POST /auth/keys` — Create API key
- `DELETE /auth/keys/{key_id}` — Revoke key

### Admin (protected by `X-Admin-Key`)
- `GET /admin/tenants` — List all tenants
- `POST /admin/tenants` — Create tenant
- `GET /admin/tenants/{id}/usage` — Tenant metrics
- `PUT /admin/tenants/{id}` — Update spend cap
- `GET /admin/revenue` — Platform-wide revenue

### Webhooks
- `POST /webhooks/stripe` — Stripe events

## License

MIT