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
- Open the TenancyEngine console.
- Go to Applications -> Add application.
- Copy the application slug, for example
vectralabel. - Open Environments and confirm the environment you will call, usually
Developmentlocally.
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:
| Need | Scope |
|---|---|
| Read runtime context and application state | applications.read |
| Read tenant state and usage | tenants.read |
| Create tenants or consume/release usage | tenants.write |
| Send analytics events | analytics:write |
| Read or manage storage objects | storage.read, storage.write |
| List or create webhook endpoints from your backend | webhooks.manage |
| List offerings or environments, or check readiness | offerings.read, environments.read, readiness.read |
| Local MCP automation | mcp.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:
| Tier | Scope | Use it for |
|---|---|---|
| App-scoped | Bound to exactly one application; every call is checked against that binding | A single app's own backend, smaller blast radius if the key leaks. Default choice. |
| Org-wide | Works across every application your organization owns | A 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 it | Platform/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/sdkis on the public npm registry (npm install @tenancyengine/sdk, current 0.8.0). Every example below can also be one HTTPS request with theX-TenancyEngine-Api-Keyheader, for exampleGET https://api.saasruntime.com/api/v1/runtime/applications/{slug}/context?environment=Development.
npm install @tenancyengine/sdkimport { 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
dotnet add package TenancyEngine.Sdk --version 2.3.0 --source https://api.nuget.org/v3/index.jsonUse 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.
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.
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 });
}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.
const result = await te.consumeUsage(
'vectralabel',
'demo-bakery',
'Development',
'labels.monthly',
1,
`label:${labelId}`,
);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.
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 });
}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.
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 startUse 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.
Related
SDK reference - install commands and quickstarts for every language and platform
Mobile and browser apps - PKCE OIDC credential model for mobile/browser apps
Applications - register and configure your first app
API keys - create and revoke organization developer keys
Application webhooks - webhook signing and delivery logs
Application analytics - runtime analytics events
Tenant entitlements - feature and limit state
Setup wizard quick win - try a read-only API call from the console