Delivered remotely for a business based in San Francisco, United States. Names withheld by agreement.
Project Overview
As specialized AI agents proliferate across legal review, procurement triage, and financial reconciliation, enterprise IT teams face a familiar governance crisis: business units adopt disconnected third-party tools on corporate cards with zero visibility into tool permissions, data residency, or per-seat versus per-token costs. Meanwhile, independent agent builders lack trusted enterprise distribution, standardized authentication, and compliant billing rails.
We engineered a multi-tenant AI agent marketplace uniting a Next.js storefront and governance console with a Python execution gateway and PostgreSQL double-entry billing ledger. Enterprises evaluate, authorize, and meter verified agents from one control plane, while publishers ship packaged workflows with predictable revenue settlement.
Marketplace Governance & Metering Challenges
Building an enterprise-ready exchange for autonomous software requires solving trust and accounting problems absent from traditional SaaS directories:
- Unbounded permission sprawl: Granting an opaque third-party agent broad CRM or email access creates severe data-exfiltration exposure without fine-grained scope mediation.
- Unpredictable hybrid pricing: Agents combine fixed platform access, per-run orchestration fees, and variable upstream LLM token consumption that flat seat licenses cannot price fairly.
- Unverified reliability claims: Buyers cannot tell from marketing copy whether an agent handles edge-case schemas cleanly or collapses under prompt-injection probes.
- Invoice disputes and race conditions: Concurrent agent invocations can overrun departmental budgets or trigger duplicate charges if metering lacks idempotent accounting.
Architectural Strategy
We structured the marketplace around a manifest-governed broker proxy paired with an immutable PostgreSQL usage ledger. Rather than redirecting enterprise buyers off-platform to unmanaged vendor URLs, published agents register versioned capability manifests and run behind a Python execution proxy.
Next.js renders the public and tenant-scoped agent catalog, interactive capability comparisons, and finance dashboards. Every runtime invocation enters Python, checks tenant RBAC entitlements and Redis spend reservations, proxies authorized tool calls into isolated agent endpoints, and commits exact token and compute usage atomically into PostgreSQL before syncing aggregated billables to Stripe.
Core Capabilities
- Capability-Scoped Agent Registry: Versioned listings declare required integrations, data classification tiers, model dependencies, and deterministic JSON input/output contracts.
- Automated Sandbox Vetting Pipeline: Every new agent release undergoes containerized schema validation, latency profiling, and adversarial prompt-safety benchmarks prior to catalog approval.
- Tenant Entitlement & Approval Workflows: Workspace admins restrict which departments can install specific agents, enforce SSO authentication, and review requested OAuth scopes before activation.
- Hybrid Usage & Seat Ledger: Supports per-invocation fees, tiered token markups, prepaid credit packs, and department-level spend ceilings with real-time burn-rate alerts.
- Publisher Portal & Split Payouts: Agent creators monitor adoption funnels, inspect anonymized error rates, publish staged updates, and receive automated Stripe Connect settlements.
Technical Architecture
Buyers browse evaluated listings and configure tenant approvals inside Next.js, backed by PostgreSQL row-level security. At runtime, client applications or workspace users invoke agents through the Python gateway, which validates OIDC claims, reserves budget in Redis, mediates external tool credentials, streams execution events, and writes finalized usage rows to the PostgreSQL ledger for Stripe synchronization.
Flow: Next.js Storefront & Admin Console → OIDC/RBAC Auth → Python Execution Proxy → Redis Budget Reservation → Scoped Agent Endpoint / Docker Sandbox → PostgreSQL Double-Entry Ledger → Stripe Billing & Publisher Payouts
Separating storefront rendering in Next.js from stateful proxy execution in Python keeps catalog navigation snappy while allowing long-running streaming agent sessions to scale independently.
Technology Stack
| Category | Technology detail |
|---|---|
| Storefront & Console | Next.js and TypeScript delivering SSR agent listings, eval scorecards, and tenant admin UI |
| Execution & Metering API | Python orchestration gateway enforcing capability scopes, quotas, and token accounting |
| Core Data & Ledger DB | PostgreSQL with row-level security storing tenant catalogs, manifests, and billing entries |
| Rate & Quota Cache | Redis tracking real-time spend caps, concurrency slots, and idempotency keys |
| Agent Vetting Sandbox | Docker runners executing automated safety, latency, and schema-compliance benchmarks |
| Payments & Payouts | Stripe Billing and Connect handling metered tenant invoices and publisher settlements |
| Identity & Governance | OIDC/SAML SSO with role-based agent entitlement policies per enterprise workspace |
| Telemetry & Audit | Immutable invocation logs capturing tool calls, token counts, and policy verdicts |
Engineering Trade-offs & Solutions
| Engineering Challenge | Solution & Trade-off |
|---|---|
| Enforcing strict department budgets during concurrent agent bursts | Implemented two-phase spend reservations in Redis backed by asynchronous PostgreSQL reconciliation; adds slight pre-flight reservation latency while preventing budget overruns. |
| Protecting enterprise OAuth tokens from malicious or buggy agents | Stored integration secrets in the platform vault and injected short-lived scoped tokens solely at the Python proxy boundary; prevents agents from calling arbitrary undocumented vendor APIs. |
| Preventing duplicate billing on client network retries | Required deterministic client idempotency keys cached in Redis and enforced unique constraints in PostgreSQL ledger tables; demands strict retry header discipline from API consumers. |
| Ensuring fair, reproducible agent quality benchmarks | Executed vetting suites inside standardized Docker networks using fixed evaluation datasets per category; increases release review time for publishers while giving buyers comparable reliability metrics. |
Security & Reliability
Multi-tenant AI marketplaces concentrate high-value credentials and proprietary prompts across competing organizations. PostgreSQL enforces row-level security (RLS) across tenant installations, audit trails, and billing ledgers so application queries cannot accidentally bleed across workspace boundaries. Every agent release is pinned by immutable digest and version manifest—publishers cannot silently expand requested permissions in a patch update without triggering fresh tenant admin re-approval.
For reliability, the Python execution gateway isolates slow upstream agents with per-listing circuit breakers and configurable timeout budgets. If a downstream publisher endpoint fails mid-stream, compensating ledger entries void uncompleted reservation holds automatically so enterprises are never billed for aborted runs.
Performance & Scale
Public directory browsing and documentation pages leverage Next.js server-side rendering and edge caching, serving rich capability filters without touching transactional billing tables. Under heavy runtime concurrency, Redis handles sub-millisecond quota checks and rate limiting while Python workers stream Server-Sent Events directly to callers.
To prevent analytics and invoice aggregation from locking live invocation paths, heavy PostgreSQL reporting queries run against read replicas, and Stripe meter synchronization batches finalized ledger slices asynchronously on deterministic schedules.
Operational Outcomes
Consolidating agent discovery, security vetting, and metered accounting into one platform changed how both buyers and creators operate:
- Accelerated enterprise procurement: Security and legal reviewers sign off on standardized capability manifests and automated benchmark reports instead of auditing bespoke vendors one by one.
- Transparent FinOps accountability: Finance teams attribute exact agent and token spend to specific departments and workflows directly from unified ledger statements.
- Safer credential boundaries: Scoped proxy mediation ensures agents receive only the minimum permissions approved by workspace administrators.
- Frictionless publisher monetization: Independent AI engineers focus on agent quality while inheriting enterprise SSO, metered billing, and automated payouts out of the box.