Skip to main content

Drop-in billing proxy for self-hosted AI agent meshes with Stripe integration and usage tracking

Project description

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

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

# Or via Docker
docker compose up

Configuration

Create a .env file:

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

# 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

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

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

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

Response:

{
  "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

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

Production

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mesh_revenue_gateway-0.1.0.tar.gz (13.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mesh_revenue_gateway-0.1.0-py3-none-any.whl (18.2 kB view details)

Uploaded Python 3

File details

Details for the file mesh_revenue_gateway-0.1.0.tar.gz.

File metadata

  • Download URL: mesh_revenue_gateway-0.1.0.tar.gz
  • Upload date:
  • Size: 13.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for mesh_revenue_gateway-0.1.0.tar.gz
Algorithm Hash digest
SHA256 87aa91210e499b3b6afff042bce512ce7eaa83505673f42c44dc1397f115b48a
MD5 2977f50e365273f73fdfc009397ea009
BLAKE2b-256 786dd01eb999b61f2c37c42992d3f793c129f01d76ed5ff89eb6b093657e3044

See more details on using hashes here.

File details

Details for the file mesh_revenue_gateway-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for mesh_revenue_gateway-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 cbcceefe2bfc7a1379b90709eb5ee0b64482b4b09dff5c6330e36b5fb6be33b8
MD5 cc510364329495f42a8c5abe55fde90e
BLAKE2b-256 1a42738e859732363647a8d4b7fa4adb71906785f7eea0daa85813c264be8363

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page