---
title: Multi-Tenant Agent
description: Build a SaaS where each customer runs their own commerce agent with their own providers and credentials. Sessions are scoped per tenant — isolated by design, metered per tenant for billing.
---

<MetaStrip items={[
  { label: "TIME", value: "~15 min" },
  { label: "USE CASE", value: (<><ServerChip name="SaaS" accent /><ServerChip name="Marketplaces" /><ServerChip name="Agency" /></>) },
  { label: "STACK", value: (<><ServerChip name="Next.js" /><ServerChip name="OpenAI" /></>) },
]} />

Build a SaaS where each customer runs their own commerce agent with their own providers and credentials. Sessions are scoped per tenant — isolated by design, metered per tenant for billing.

<TenantArch
  tenants={[
    {
      id: "tenant_acme",
      label: "CARDS + SHIPPING",
      tone: "brand",
      servers: ["stripe", "correios", "nuvem-fiscal"],
      credentials: [
        { key: "stripe_key", value: "sk_live_aC******" },
        { key: "correios_token", value: "crs_7h******" },
      ],
    },
    {
      id: "tenant_loja",
      label: "PIX + MELHOR ENVIO",
      tone: "violet",
      servers: ["asaas", "melhor-envio", "z-api"],
      credentials: [
        { key: "asaas_key", value: "as_live_dX******" },
        { key: "me_token", value: "me_9k******" },
      ],
    },
  ]}
  apiSub="every tool call tagged with metadata.tenant_id for per-tenant billing"
  note="one CODESPAR_API_KEY · one vault · N tenants — tenant A cannot see tenant B's providers or credentials"
/>

## Prerequisites

```bash
npm install @codespar/sdk next
```

<Callout>
You need **one** CodeSpar API key for your SaaS — not one per tenant. Tenant isolation happens inside CodeSpar via session metadata.
</Callout>

<Callout type="info" title="Sessions are not accounts">
`metadata.tenant_id` separates your tenants' sessions, tool calls and usage. It
does not give a tenant an account of its own: without customer accounts, what
your tenants collect is received by one receiver for all of them, normally your
project's own account. When each tenant needs its own account, add customer
accounts; see [Sessions or customer accounts](#sessions-or-customer-accounts-two-different-jobs).
</Callout>

## Session factory

Wrap `codespar.create()` in a helper that takes a tenant config and injects `metadata.tenant_id`:

```typescript title="lib/commerce.ts"
import { CodeSpar } from "@codespar/sdk";

const codespar = new CodeSpar({ apiKey: process.env.CODESPAR_API_KEY! });

interface TenantConfig {
  id: string;
  servers: string[];
  metadata: Record<string, string>;
}

export async function createTenantSession(tenant: TenantConfig) {
  return codespar.create(tenant.id, {
    servers: tenant.servers,
    metadata: {
      tenant_id: tenant.id,
      ...tenant.metadata,
    },
  });
}
```

## API route per tenant

Use a dynamic route segment `[tenantId]` to scope every request to a tenant. The tenant config (which servers, which metadata) comes from your database:

```typescript title="app/api/commerce/[tenantId]/route.ts"
import { createTenantSession } from "@/lib/commerce";
import { NextResponse } from "next/server";

// In production, fetch from DB
const TENANTS: Record<string, { servers: string[] }> = {
  tenant_acme: { servers: ["stripe", "correios", "nuvem-fiscal"] },
  tenant_loja: { servers: ["asaas", "melhor-envio", "z-api"] },
};

export async function POST(req: Request, { params }: { params: { tenantId: string } }) {
  const tenant = TENANTS[params.tenantId];
  if (!tenant) return NextResponse.json({ error: "Tenant not found" }, { status: 404 });

  const { message } = await req.json();

  const session = await createTenantSession({
    id: params.tenantId,
    servers: tenant.servers,
    metadata: { source: "api" },
  });

  try {
    const result = await session.send(message);
    return NextResponse.json({ reply: result.message });
  } finally {
    await session.close();
  }
}
```

## Billing per tenant

Every tool call carries the `metadata.tenant_id` you set on session creation, which is what makes a per-tenant view possible at all.

<Callout type="warn">
`/v1/usage` is **not** an endpoint your billing job can call. It sits in the
service-auth subtree, so a `csk_` key answers `401`, and the credential that
does open it is CodeSpar's platform secret — it never leaves our
infrastructure. Read the aggregate in the dashboard at
[/dashboard/billing](https://codespar.dev/dashboard/billing).
</Callout>

For your own per-tenant counters, count on the side you control. You already
know the tenant at session creation, so record the attribution there rather
than trying to reconstruct it from an endpoint you cannot reach:

```typescript title="jobs/billing.ts"
// At session creation you already hold the tenant id — stamp it on CodeSpar
// for audit AND on your own meter in the same step. `codespar` is the client
// from lib/commerce.ts above; create() takes the user id, then the config.
const session = await codespar.create(tenantId, {
  servers: ["asaas"],
  metadata: { tenant_id: tenantId },
});
await meter.increment(tenantId, { sessionId: session.id });

// Tool-call detail for one session stays on the Bearer surface, so a
// reconciliation job can walk what a tenant's session actually did:
//   GET /v1/sessions/:id/tool-calls
//   GET /v1/tool-calls?since=...   (project-scoped, newest first)
```

<Callout>
The `metadata` field you set on a session is forwarded to every tool call log, making tenant-level billing and audit trails straightforward.
</Callout>

## Security considerations

- **Session isolation.** Each session has access only to the servers listed at creation time. Tenant A cannot reach Tenant B's providers — the runtime blocks it.
- **API key scoping.** Use separate CodeSpar keys per environment (test/prod), not per tenant. Tenant isolation is enforced by session scoping, not by key fragmentation.
- **Credential vault.** Each tenant's provider credentials are stored in CodeSpar's vault, encrypted per-account. Tenants never see each other's secrets.
- **Rate limiting.** Apply per-tenant rate limits in your API route — CodeSpar won't stop tenant A from exhausting tenant B's budget unless you cap it upstream.

## Sessions or customer accounts: two different jobs

`metadata.tenant_id` and customer accounts answer different questions, and a
SaaS often needs both.

| | `metadata.tenant_id` on the session | A customer account ([Spaces](/docs/concepts/spaces)) |
|---|---|---|
| What it separates | Your tenants' sessions, tool calls, audit and usage | Your tenants' money: each one gets its own account in your project |
| Where money lands | One receiver for every tenant, normally your project's own account | In that tenant's account (today, Test only) |
| How you set it up | In code, on every `create()` | In the dashboard, one customer at a time (Test today) |
| What you pass when charging | Nothing extra | The tenant's `consumer_id` on every Collect link |

- **Session metadata only** fits when your tenants never hold money through
  CodeSpar: you bill them yourself, or their payments are yours to receive.
- **Add customer accounts** when each tenant must receive into, and see, an
  account of its own. Keep `metadata.tenant_id` on the sessions as well: it
  still organizes what each tenant's agent did.
- When you charge for a tenant, always pass its `consumer_id` (today, Test only:
  in Live a link naming a consumer other than your organization's own account is
  refused with `422 receiving_identity_missing`). Without it Collect chooses the
  receiver itself: a default receiver, when one is set, is one account for the
  whole project, whichever tenant the charge was for; without a default, a
  project with more than one eligible receiver refuses the link with
  `409 collect_receiver_unresolved`. The
  [Spaces concept](/docs/concepts/spaces#always-pass-consumer_id) has the details.

[Your first customer account in Test](/docs/cookbooks/spaces-first-customer-test)
walks through opening one in the dashboard.

## Next steps

<NextStepsGrid items={[
  { label: "COOKBOOK", title: "Webhook Listener", description: "Combine with multi-tenant — scope webhook handlers per tenant.", href: "/docs/cookbooks/webhook-listener" },
  { label: "COOKBOOK", title: "Your First Customer Account in Test", description: "Give one tenant its own account, from the dashboard.", href: "/docs/cookbooks/spaces-first-customer-test" },
  { label: "CONCEPT", title: "Spaces", description: "When a tenant needs its own account, and how it fits your project.", href: "/docs/concepts/spaces" },
  { label: "COOKBOOK", title: "All cookbooks", description: "Browse the full set of runnable recipes.", href: "/docs/cookbooks" },
  { label: "CONCEPT", title: "Sessions", description: "Session metadata, lifecycle, and per-user isolation details.", href: "/docs/concepts/sessions" },
  { label: "CONCEPT", title: "Billing & Quotas", description: "Usage API, cost monitoring, tenant-level budgets.", href: "/docs/concepts/billing" },
]} />
