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 tenantinvoice.payment_succeeded→ Log paymentinvoice.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 middlewarerouters/proxy.py— Request proxying and response interceptionrouters/admin.py— Tenant management and usage queriesrouters/auth.py— API key validation and JWT issuancerouters/webhooks.py— Stripe webhook handlingtoken_counter.py— Model-specific token countingpricing.py— Cost calculation per modeldatabase.py— SQLAlchemy ORM for usage logs and tenantssecurity.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 LLMPOST /v1/embeddings— Proxy embeddingsPOST /v1/images/generations— Proxy image generation
Authentication
POST /auth/login— Generate JWTPOST /auth/keys— Create API keyDELETE /auth/keys/{key_id}— Revoke key
Admin (protected by X-Admin-Key)
GET /admin/tenants— List all tenantsPOST /admin/tenants— Create tenantGET /admin/tenants/{id}/usage— Tenant metricsPUT /admin/tenants/{id}— Update spend capGET /admin/revenue— Platform-wide revenue
Webhooks
POST /webhooks/stripe— Stripe events
License
MIT
Release files for mesh-revenue-gateway 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| mesh_revenue_gateway-0.1.0.tar.gz | 13.3 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| mesh_revenue_gateway-0.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 31.5 kB
Release files / mesh_revenue_gateway-0.1.0.tar.gz
| Download URL | mesh_revenue_gateway-0.1.0.tar.gz |
|---|---|
| Size | 13.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
87aa91210e499b3b6afff042bce512ce7eaa83505673f42c44dc1397f115b48a
|
|
BLAKE2b-256 checksum How to use checksums |
786dd01eb999b61f2c37c42992d3f793c129f01d76ed5ff89eb6b093657e3044
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.25
|
Release files / mesh_revenue_gateway-0.1.0-py3-none-any.whl
| Download URL | mesh_revenue_gateway-0.1.0-py3-none-any.whl |
|---|---|
| Size | 18.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cbcceefe2bfc7a1379b90709eb5ee0b64482b4b09dff5c6330e36b5fb6be33b8
|
|
BLAKE2b-256 checksum How to use checksums |
1a42738e859732363647a8d4b7fa4adb71906785f7eea0daa85813c264be8363
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.25
|