01Concepts
Tenant: id, name, slug, status, settings, createdAt and updatedAt.TenantManagerchecks forTenantStatus.ACTIVEwhen it verifies a key.TenantSettings: limits and preferences per tenant, such asmaxAgents,maxConversationsandrateLimit. Defaults come fromdefaultSettingsin theTenantManagerconfig.TenantContext: the tenant, with an optionaluserIdandmetadata.
02Set up TenantManager
TenantManager needs a storage object. MemoryTenantStorage keeps everything in process memory, so tenants and keys are lost when the process restarts. The guide recommends a database-backed TenantStorage in production.
import { MemoryTenantStorage, TenantManager } from '@lov3kaizen/agentsea-core';
const tenantManager = new TenantManager({
storage: new MemoryTenantStorage(),
defaultSettings: { maxAgents: 10, maxConversations: 100, rateLimit: 100 },
});
const tenant = await tenantManager.createTenant({ name: 'Acme Corporation', slug: 'acme' });
const { plainKey } = await tenantManager.createApiKey(tenant.id, {
name: 'Production API Key',
scopes: ['agents:execute'],
});
const verified = await tenantManager.verifyApiKey(plainKey);03API keys
createApiKey(tenantId, { name, scopes?, expiresAt? })returns{ apiKey, plainKey }. The storedapiKeyrecord holds the hashed key. GiveplainKeyto the tenant once.verifyApiKey(plainKey)returns the tenant, ornullwhen the key is unknown or the tenant is not active.revokeApiKey(apiKeyId)revokes a key.
04Quotas
checkQuota(tenantId, resource, amount = 1) returns { allowed, remaining }. incrementQuota(tenantId, resource, amount) records usage. Quota checks use an hourly period. The resource name is any string; requests, tokens, agents, conversations and storage are common choices.
const { allowed, remaining } = await tenantManager.checkQuota(tenant.id, 'requests');
if (!allowed) {
throw new Error('Quota exceeded');
}
await tenantManager.incrementQuota(tenant.id, 'requests', 1);
console.log(remaining);05Memory by tenant
TenantBufferMemory stores messages per conversation ID and per tenant. The same conversation ID under two tenants holds two separate histories.
- Other methods:
clear(conversationId, tenantId),clearAll(),getConversationIds(tenantId),getTenantIds()andsize(tenantId).
import { TenantBufferMemory } from '@lov3kaizen/agentsea-core';
const memory = new TenantBufferMemory();
const messagesA = [{ role: 'user', content: 'Hello from tenant A' }];
const messagesB = [{ role: 'user', content: 'Hello from tenant B' }];
memory.save('conv-1', messagesA, 'tenant_a');
memory.save('conv-1', messagesB, 'tenant_b');
console.log(memory.load('conv-1', 'tenant_a'));
memory.clearTenant('tenant_b');
console.log(memory.getTenantStats());06Conversation ID prefixes
Prefixing conversation IDs with the tenant ID, such as tenantId:support-userId, adds a check on reads. TenantBufferMemory already separates data by the tenantId argument, so the prefix is optional.
Warning
deleteTenant removes the tenant record from storage only. Memory held in TenantBufferMemory is not cleared. Call clearTenant(tenantId) as well.07NestJS guard
TenantGuard reads the API key from the x-api-key header and the tenant ID from x-tenant-id by default. The options are apiKeyHeader, tenantIdHeader and useSubdomain. The guard takes one options object, which includes tenantManager. Nest cannot inject that object by class, so create the guard with new TenantGuard(...) and pass the instance to @UseGuards.
import { Controller, Get, UseGuards } from '@nestjs/common';
import { TenantGuard, TenantId } from '@lov3kaizen/agentsea-nestjs';
// tenantManager: the TenantManager from section 02.
@Controller('agents')
@UseGuards(new TenantGuard({ tenantManager }))
export class TenantAgentsController {
@Get()
list(@TenantId() tenantId: string) {
return { tenantId };
}
}08Management routes
TenantController serves these routes under /tenants. It injects a TenantManager, and AgenticModule does not register it, so add it to your module yourself.
POST /tenants,GET /tenants,GET /tenants/:id,PUT /tenants/:id,DELETE /tenants/:idPOST /tenants/:id/suspend,POST /tenants/:id/activatePOST /tenants/:id/api-keys,GET /tenants/:id/quota/:resource
Warning