# Multi-tenancy (/docs/datasets/multi-tenancy)

Dataset multi-tenancy is fail-closed. If a dataset declares a `tenantKey`, dataset queries require trusted tenant context at execution time.

`tenantKey` is the physical column on the source table. `runtime.tenant` is the trusted tenant value supplied by your server, job, MCP process, or runtime integration.

Like Serve tenant auto-injection for hand-written queries, datasets inject tenant filtering automatically. The difference is where the tenant column comes from: dataset queries use the dataset `tenantKey`, while Serve builder queries use the Serve tenant configuration.

## Declare the tenant key [#declare-the-tenant-key]

<CodeBlock>
```typescript
export const Orders = dataset('orders', {
  source: 'orders',
  tenantKey: 'tenant_id',
  dimensions: {
    tenantId: dimension.string({ column: 'tenant_id' }),
    status: dimension.string(),
    country: dimension.string(),
  },
  measures: {
    revenue: measure.sum('amount'),
  },
});
```
</CodeBlock>

The `tenantKey` uses the ClickHouse column name. The optional `tenantId` dimension gives callers a semantic field name for schema introspection, but callers should not provide tenant filters when runtime tenancy is active.

## Provide tenant context [#provide-tenant-context]

<CodeBlock>
```typescript
await analytics.execute(Orders, { measures: ['revenue'] }, {
  runtime: {
    tenant: 'tenant_123',
  },
});
```
</CodeBlock>

This automatically injects a tenant predicate equivalent to:

<CodeBlock>
```sql
WHERE tenant_id = 'tenant_123'
```
</CodeBlock>

If you omit tenant context for a tenant-scoped dataset, the query is rejected:

<CodeBlock>
```typescript
await analytics.execute(Orders, { measures: ['revenue'] });
// Error: Dataset "orders" requires runtime tenant scoping.
```
</CodeBlock>

## Tenant runtime values [#tenant-runtime-values]

`runtime.tenant` supports a single tenant, a set of tenants, or an explicit trusted cross-tenant mode.

<CodeBlock>
```typescript
// Single tenant.
{ runtime: { tenant: 'tenant_123' } }

// Single tenant, object form.
{ runtime: { tenant: { id: 'tenant_123' } } }

// Trusted multi-tenant scope.
{ runtime: { tenant: { in: ['tenant_123', 'tenant_456'] } } }

// Trusted cross-tenant scope.
{ runtime: { tenant: { scope: 'all' } } }
```
</CodeBlock>

Use `{ in: [...] }` for admin or reporting surfaces scoped to a known set of tenants. Use `{ scope: 'all' }` only in trusted contexts like internal jobs or admin dashboards. Do not use cross-tenant scope in request-facing clients or MCP servers.

## Tenant filters are rejected [#tenant-filters-are-rejected]

When runtime tenancy is active, explicit filters on the tenant field are rejected. This prevents duplicate or conflicting tenant predicates.

<CodeBlock>
```typescript
await analytics.execute(Orders, {
  measures: ['revenue'],
  filters: [eq('tenantId', 'tenant_123')],
}, {
  runtime: {
    tenant: 'tenant_123',
  },
});
// Error: Cannot filter on tenant field "tenantId" when runtime tenancy enforcement is active.
```
</CodeBlock>

Tenant identity should come from trusted runtime state, not end-user query input.

## Serve tenant context [#serve-tenant-context]

With `@hypequery/serve`, configure tenant extraction from auth or request context. Semantic dataset endpoints pass that tenant identity into `@hypequery/datasets`, and datasets auto-inject the filter from `tenantKey`.

<CodeBlock>
```typescript
const api = serve({
  datasets: { orders: Orders },
  queryBuilder: db,
  tenant: {
    extract: (auth) => auth.tenantId,
    required: true,
  },
});
```
</CodeBlock>

Serve tenant `column` configuration is useful for hand-written builder queries. Semantic dataset endpoints use the dataset `tenantKey` for tenant filtering.

For simple internal or first-party apps, the auth strategy can read a tenant header and expose it as auth context:

<CodeBlock>
```typescript
import { initServe } from '@hypequery/serve';

const { serve } = initServe({
  auth: async ({ request }) => ({
    tenantId: request.headers['x-tenant-id'],
  }),
  tenant: {
    extract: (auth) => auth.tenantId,
    required: true,
  },
});

export const api = serve({
  queryBuilder: db,
  datasets: { orders: Orders },
});
```
</CodeBlock>

Only trust tenant headers at a boundary you control, such as a server-to-server call, reverse proxy, or authenticated application route. Public clients should derive tenant identity from verified auth instead of accepting arbitrary header values.

## MCP tenant context [#mcp-tenant-context]

For MCP, run tenant-scoped servers with a trusted `tenantId`. The MCP server forwards that value as dataset runtime tenant context for `query_dataset` and `query_metric`.

If registered datasets have `tenantKey`, the MCP server requires tenant scope at startup. This keeps agent calls inside the governed tenant boundary.
