Skip to content

Developer quickstart (TenancyEngine) ​

Add TenancyEngine to an ISV backend in the same first-pass flow developers expect from Supabase, Firebase, or Vercel docs: create an app, mint a server-side key, install the SDK, read runtime context, record usage, and verify webhooks.

Runtime keys are server-side credentials. Do not ship an organization API key in browser JavaScript, mobile apps, or public source.

1. Create an application ​

  1. Open the TenancyEngine console.
  2. Go to Applications -> Add application.
  3. Copy the application slug, for example vectralabel.
  4. Open Environments and confirm the environment you will call, usually Development locally.

Use the environment-specific authority and API base URL shown in the application runtime context. For production these are https://auth.saasruntime.com and https://api.saasruntime.com.

Your platform plan decides how many applications and environments you get. The Starter plan allows one application and Production only: adding a Development or Staging environment is refused with "Your platform plan includes production only", and a second application with "Application limit reached". Upgrade to a plan with multiple environments before following the Development examples below. Environments are created with the application, so an application registered while on Starter does not gain Development and Staging automatically after an upgrade; add them under Environments.

2. Create an organization API key ​

Open API keys and create a key for your organization. Give the key only the scopes needed by your backend:

NeedScope
Read runtime context and application stateapplications.read
Read tenant state and usagetenants.read
Create tenants or consume/release usagetenants.write
Send analytics eventsanalytics:write
Read or manage storage objectsstorage.read, storage.write
List or create webhook endpoints from your backendwebhooks.manage
List offerings or environments, or check readinessofferings.read, environments.read, readiness.read
Local MCP automationmcp.full

The scope picker on the API keys page lists every scope with a description; a name that is not in that list is rejected when you create the key. A call made without a needed scope returns 403 with This API key is missing the <scope> scope. Send the key in the X-TenancyEngine-Api-Key header (the SDKs do this for you).

Store the key in your secret manager. TenancyEngine shows the plain value once.

3. Pick a key tier, then install an SDK ​

Organization API keys come in two binding tiers, plus a reserved admin tier no app key should ever hold:

TierScopeUse it for
App-scopedBound to exactly one application; every call is checked against that bindingA single app's own backend, smaller blast radius if the key leaks. Default choice.
Org-wideWorks across every application your organization ownsA backend that manages multiple TenancyEngine apps (e.g. an agency, or a platform team)
Admin (admin/admin.*)Full org scope; app-scoped keys can never hold itPlatform/org administration only, not a normal integration credential

Full SDK list, install commands, and verified quickstarts for every language and platform (.NET, TypeScript, Go, Python, Java, PHP, Ruby, browser, and all five mobile auth SDKs): SDK reference. Short version for the two most complete SDKs:

The released .NET SDK is available on nuget.org. Package download does not require a TenancyEngine API key or private-feed credentials. Your server needs its own API key to call the platform after installation. The TypeScript SDK @tenancyengine/sdk is on npm (npm install @tenancyengine/sdk, current 0.8.0). For other languages, see the SDK reference.

TypeScript ​

@tenancyengine/sdk is on the public npm registry (npm install @tenancyengine/sdk, current 0.8.0). Every example below can also be one HTTPS request with the X-TenancyEngine-Api-Key header, for example GET https://api.saasruntime.com/api/v1/runtime/applications/{slug}/context?environment=Development.

bash
npm install @tenancyengine/sdk
ts
import { TenancyEngineClient } from '@tenancyengine/sdk';

const te = new TenancyEngineClient({
  baseUrl: process.env.TENANCYENGINE_BASE_URL ?? 'https://api.saasruntime.com',
  apiKey: process.env.TENANCYENGINE_API_KEY!,
  appId: process.env.TENANCYENGINE_APP_ID!,
});

.NET ​

powershell
dotnet add package TenancyEngine.Sdk --version 2.3.0 --source https://api.nuget.org/v3/index.json

Use TenancyEngine.Sdk 2.3.0. Minimum versions by feature: RuntimeContext.Entitlement and IsUsableAt need 2.2.0 or later, customer machine access (AddTenancyEngineMachineAccess, TenancyEngineMachineTokenClient) needs 2.1.0 or later, and overlapping webhook secret rotation needs 2.3.0. See the SDK changelog.

csharp
using TenancyEngine.Sdk;

builder.Services.AddHttpClient("TenancyEngine", client =>
{
    client.BaseAddress = new Uri(builder.Configuration["TenancyEngine:BaseUrl"]
        ?? "https://api.saasruntime.com");
});

builder.Services.AddScoped(sp =>
{
    var httpFactory = sp.GetRequiredService<IHttpClientFactory>();
    var apiKey = sp.GetRequiredService<IConfiguration>()["TenancyEngine:ApiKey"]
        ?? throw new InvalidOperationException("TenancyEngine:ApiKey is required.");

    return new TenancyEngineClient(httpFactory.CreateClient("TenancyEngine"), apiKey);
});

TenancyEngine:BaseUrl is the runtime API base URL, not the OIDC authority. In production, set it to https://api.saasruntime.com. Configure your application's OIDC handler separately with authority https://auth.saasruntime.com. For lab or staging, use the corresponding approved API and authority pair; do not mix environments. The organization API key authenticates outgoing server-to-platform calls. It does not authenticate customers calling your own API.

4. Gate a request with runtime context ​

Runtime context is the one backend call your app should make before tenant-scoped work. It returns enabled features, limits, current usage, tenant status, and OIDC settings for the selected environment. The environment query parameter is required; without it the call returns a 400.

tenantId and the tenant slug below refer to a customer (tenant) of your application, so create one first: in the console open Applications -> your application -> Tenants, or call POST /api/v1/runtime/applications/{applicationId}/tenants with a tenants.write key and body {"name":"Demo Bakery","slug":"demo-bakery","environment":"Development"} (SDK: CreateTenantAsync). That route takes the application's slug or its id (the GUID shown in the console URL and in the response of GET /api/v1/runtime/applications/{slug}). An application or tenant that your key cannot use returns 404 with "code": "application_not_found" or "code": "tenant_not_found". A new tenant has no plan until you assign one under Tenants -> the tenant -> Entitlements (Assign plan), and metered calls fail with No active entitlement grant for this metered feature until you do.

ts
const context = await te.getRuntimeContext('vectralabel', 'Development', tenantId);

if (!context.features.includes('labels.ai')) {
  throw new Response('Feature not enabled', { status: 403 });
}

const limit = context.limits['labels.monthly'];
const used = context.usage['labels.monthly'] ?? 0;

if (limit !== null && limit !== undefined && used >= limit) {
  throw new Response('Plan limit reached', { status: 402 });
}
csharp
var context = await te.GetRuntimeContextAsync("vectralabel", "Development", tenantId, ct);

if (context is null || !context.Features.Contains("labels.ai"))
{
    return Results.Forbid();
}

// Plan checks that depend on what the tenant has paid for must read the entitlement snapshot (SDK 2.2.0+),
// and treat an unusable snapshot as no entitlement. See Tenant entitlements for the full pattern.
if (context.Entitlement is null || !context.Entitlement.IsUsableAt(DateTimeOffset.UtcNow))
{
    return Results.Problem("Entitlement unavailable", statusCode: StatusCodes.Status503ServiceUnavailable);
}

var limit = context.Limits.GetValueOrDefault("labels.monthly");
var used = context.Usage.GetValueOrDefault("labels.monthly");

if (limit is not null && used >= limit)
{
    return Results.Problem("Plan limit reached", statusCode: StatusCodes.Status402PaymentRequired);
}

5. Record usage with idempotency ​

Tie the idempotency key to your own operation ID so retries do not double-count usage.

ts
const result = await te.consumeUsage(
  'vectralabel',
  'demo-bakery',
  'Development',
  'labels.monthly',
  1,
  `label:${labelId}`,
);
csharp
var result = await te.ConsumeUsageAsync(
    "vectralabel",
    "demo-bakery",
    "Development",
    "labels.monthly",
    amount: 1,
    idempotencyKey: $"label:{labelId}",
    ct);

If the downstream operation fails after usage is consumed, call releaseUsage / ReleaseUsageAsync with a separate rollback idempotency key.

Release only works on gauge meters (for example concurrent seats). On a counter meter that resets monthly, release returns 400 Release is only supported for gauge meters. Choose the meter kind when you define the feature. Check the limit with the context call from step 4 before you run the operation; a tenant with no plan assigned reports no limit in its usage meters.

6. Verify webhooks ​

Create a webhook endpoint from Application -> Webhooks. Copy the signing secret when it is shown.

TenancyEngine sends X-TE-Signature: t={unixTimestamp},v1={hexHmac}. The HMAC input is {timestamp}.{rawBody}. Always verify the exact raw body bytes before parsing JSON.

ts
import { verifyWebhookSignature } from '@tenancyengine/sdk';

const rawBody = await request.text();
const signature = request.headers.get('X-TE-Signature') ?? '';

if (!verifyWebhookSignature(rawBody, signature, process.env.TENANCYENGINE_WEBHOOK_SECRET!)) {
  throw new Response('Invalid signature', { status: 400 });
}
csharp
var rawBody = await new StreamReader(Request.Body).ReadToEndAsync();
var signature = Request.Headers["X-TE-Signature"].ToString();

if (!WebhookSignatureVerifier.Verify(rawBody, signature, webhookSecret))
{
    return Results.BadRequest("Invalid signature");
}

7. Use MCP for setup automation ​

The TenancyEngine MCP server exposes console/admin/runtime tools for AI agents and local automation.

powershell
cd tenancyengine/mcp-server
npm ci
npm run build
$env:TE_BASE_URL = "https://auth.saasruntime.com"
$env:TE_API_KEY = "<organization-api-key>"
npm start

Use TE_API_KEY for runtime tools such as get_runtime_context, consume_usage, and release_usage. Use an OIDC bearer token or local dev admin key for platform-admin tools.

TenancyEngine platform documentation