Skip to content

Run your own MCP server with TenancyEngine sign-in ​

You can run an MCP server (or any API) for your product and let people connect an AI assistant such as Claude to it. TenancyEngine is the authorization server: it signs people in, asks them to approve what the assistant may do, and issues tokens. Your server only has to say where to sign in and to check the token.

How the connection works ​

  1. The assistant calls your MCP server with no token and gets 401 with a WWW-Authenticate header that points at your resource metadata.
  2. It reads your resource metadata, which names TenancyEngine as the authorization server.
  3. It reads TenancyEngine's authorization server metadata, then sends the person through sign-in (PKCE with S256 only; there is no open client registration endpoint).
  4. The token that comes back is issued for your server only. Your server checks that and serves the call.

Register your server ​

Your server's identifier is the API base URL of the environment you register it in (Applications, your application, Environments). It must be an https URL with no fragment. Add the scopes your server understands under the application's resource scopes. Give every scope a short name and a plain-language description, because the description is what people read when they approve access.

Resource identifier and scope naming ​

  • The identifier is a logical name, not an address. It must be an https URL with no fragment and it must equal, exactly (ordinal, no trailing-slash or case tolerance), the API base URL of one active environment of your application. The platform never stamps an http or loopback audience, and verifyAccessToken refuses a non-https resource. Your server may listen anywhere (for a local proof, http://127.0.0.1:4318/mcp); the token's aud is the registered https identifier, and you pass that same string as resource.
  • One identifier per server. A token has one audience; ask for one resource per sign-in.
  • Name scopes <product>.<noun>.<verb> or <product>.<verb>, lowercase, and give each the least power that does the job. For an assistant that works on a Company Studio project, register companystudio.state.read, companystudio.report.write and companystudio.questions.answer, and require the narrowest one per tool (requiredScope). Do not register a scope for a human decision (accepting a proposal, publishing) or for anything TenancyEngine administers (applications, keys, billing): those stay with a signed-in person and are never something an approved assistant can hold. A resource-bound token can only carry openid, offline_access and the scopes you registered; the platform api scope is never available to it.
  • Describe each scope for the person who approves it ("Read the status of your project", not the internal permission name).

Two documents ​

WhatWhereServed by
Authorization server metadata (RFC 8414)/.well-known/oauth-authorization-server on the TenancyEngine sign-in hostTenancyEngine
Protected resource metadata (RFC 9728)/.well-known/oauth-protected-resource/{application-slug}/{environment} on the TenancyEngine sign-in hostTenancyEngine, or generate your own with the SDK and serve it from your host

If your server must publish its metadata on its own host (the MCP convention), generate it with the SDK helper below and serve it at /.well-known/oauth-protected-resource.

ASP.NET ​

csharp
// Program.cs
builder.Services.AddAuthentication()
    .AddTenancyEngineMcpResource(
        resource: "https://api.example.com/mcp",
        issuer: "https://auth.saasruntime.com/",
        resourceMetadataUrl: "https://api.example.com/.well-known/oauth-protected-resource");

app.MapGet("/.well-known/oauth-protected-resource", () => Results.Content(
    TenancyEngineMcpResource.BuildProtectedResourceMetadataJson(
        "https://api.example.com/mcp", "https://auth.saasruntime.com/", ["example.read"], "Example"),
    "application/json"));

app.MapPost("/mcp", handler).RequireAuthorization(
    new AuthorizeAttribute { AuthenticationSchemes = "TenancyEngineMcp" });

A token minted for any other audience is rejected, including a sibling path or the same URL with a trailing slash.

Node ​

verifyAccessToken does the whole check in one call: it fetches and caches the platform signing keys (https only, cached for ten minutes, no network call per request while cached, rotated keys picked up automatically), verifies the signature, the issuer, the exact audience, expiry and not-before (30 seconds of clock skew by default), and the scope you require. Signature verification runs on the maintained jose library, the package's one runtime dependency (exact version, MIT, no dependencies of its own). It never throws for a bad token; if the signing keys cannot be fetched it fails closed.

ts
import { buildProtectedResourceMetadata, verifyAccessToken, wwwAuthenticateChallenge } from '@tenancyengine/sdk';

const resource = 'https://api.example.com/mcp';
const issuer = 'https://auth.saasruntime.com/';
const metadataUrl = 'https://api.example.com/.well-known/oauth-protected-resource';

app.get('/.well-known/oauth-protected-resource', (_req, res) =>
  res.json(buildProtectedResourceMetadata({ resource, issuer, scopes: ['example.read'] })));

app.post('/mcp', async (req, res) => {
  const token = req.headers.authorization?.replace(/^Bearer /i, '');
  if (!token) return res.status(401).set('WWW-Authenticate', wwwAuthenticateChallenge(metadataUrl)).end();

  const result = await verifyAccessToken(token, { issuer, resource, requiredScope: 'example.read' });
  if (!result.ok) {
    if (result.error === 'jwks_unavailable') return res.status(503).end(); // our side, not the caller's fault
    return res
      .status(result.error === 'insufficient_scope' ? 403 : 401)
      .set('WWW-Authenticate', wwwAuthenticateChallenge(metadataUrl, result.error))
      .end();
  }
  // result.claims is verified: result.claims.sub is the person who approved the connection
});

Only RS256 is accepted by default, which is what TenancyEngine publishes; alg: none, HMAC algorithms and anything else are rejected before any key is looked up. Keys come only from the issuer's JWKS (a jku, x5u, jwk or x5c header in the token is never used), a token larger than 16 KiB is refused, and the JWKS is fetched without following redirects and must be on the issuer's origin. Access tokens must carry typ: at+jwt (RFC 9068), so an ID token cannot be replayed as one. If you already verify signatures with your own library, checkAccessTokenClaims still checks the claims alone.

Node: restrict clients and check current authority ​

Needs @tenancyengine/sdk 0.8.0. Not on npm until the owner's release flow publishes it.

allowedClientIds (verifyAccessToken). Accept only tokens issued to your own SPA or mobile client. The check is skipped only when the option is absent. [], a blank entry or a non-string entry throws (configuration error); it never means allow-all or deny-all. With a list, a token whose client_id and azp are both missing (or not strings) is denied, so is one where they differ (even if one matches), and otherwise the present value must equal an entry exactly (case-sensitive, no trimming, no prefix). The denial is { ok: false, error: 'invalid_token', reason: 'client_not_allowed' }; the reason never echoes the client id or your list. Leave the option out where metadata-document (CIMD) assistants are welcome. A token issued before the per-application resource rule (PR 1150) can carry a foreign aud and stays valid by signature until it expires; the current-authority check below denies it.

Current authority. verifyAccessToken is a signature check and never calls the platform, so a revoked connection, a removed member or a suspended workspace stays valid until the token expires. To close that, ask the platform per request (POST /api/v1/runtime/oauth/introspect, see docs/platform/agent-connections.md) with an application-level API key that holds only the oauth.introspect scope:

ts
import { createCurrentAuthorityChecker, verifyAccessToken } from '@tenancyengine/sdk';

const checker = createCurrentAuthorityChecker({
  resource,                                   // the same exact string you pass to verifyAccessToken
  credential: () => process.env.TE_INTROSPECT_KEY!, // application-bound key with only oauth.introspect
  // cache: { ttlSeconds: 5 }  (default 5, 0 turns it off, more than 15 throws)   timeoutMs: 3000 (default, at most 10000)
});

const local = await verifyAccessToken(token, { resource, allowedClientIds: ['my-spa'] });
if (!local.ok) return deny(local);              // 401 / 403 / 503 as before
const live = await checker.check(token, { verified: local.claims, requiredScope: 'example.read' });
if (!live.ok) {
  // inactive | binding_mismatch -> 401 invalid_token
  // insufficient_scope           -> 403
  // authority_unavailable | rate_limited -> 503, do not serve the read
  // caller_unauthorized          -> 503 and alert: your own key is wrong or lacks oauth.introspect
  return deny(live);
}
live.authority; // { sub, clientId, tenantId, scopes, roles, expiresAt, checkedAt, fromCache }

verifyAccessTokenWithAuthority(token, verifyOptions, checker, checkOptions) does both steps and never calls the platform for a token that failed local verification. checkCurrentAuthority(token, { ...checkerOptions, check: { verified, ... } }) is the one-shot form with a process-wide cache (cache.ttlSeconds is a checker option; the cache: false bypass goes under check).

  • Fail closed. A network error, timeout, TLS error, redirect (never followed), non-JSON or oversized (over 16 KiB) body, a missing or non-boolean active, an active: true answer with a missing or ill-typed member, or any 5xx is authority_unavailable; there is no fallback to the signature-only result. 401/403 is caller_unauthorized; 429 is rate_limited with retryAfterSeconds. One retry, for a network error only, inside the timeoutMs budget. Unknown extra members of the answer are ignored and never returned.
  • Binding. The platform's sub, client_id, aud and tenant_id must equal your verified claims, aud must equal resource, its exp may not exceed the token's, and its scopes must be a subset of the token's; any difference is binding_mismatch.
  • Cache. Only active: true answers are cached, in memory, for at most ttlSeconds (never past exp), at most 1000 entries, keyed by a SHA-256 of the token. Inactive and error answers are never cached. Pass cache: false for writes and irreversible actions. A revocation reaches you within the TTL (5 seconds by default).
  • Nothing sensitive in results. The token and your key never appear in a result, error text, JSON.stringify, stack or cache key, and results carry only the typed authority fields, not the verified claims or the platform's body.
  • Throws only for configuration errors: missing credential, non-https resource or issuer, ttlSeconds above 15, timeoutMs out of range, allowedClientIds: [].

Support impersonation. An operator acting as a member is reported active, with the member's sub; the platform adds impersonation and impersonation_session_id to its answer, but this checker ignores both and exposes neither, so such a request looks like the member's own. Unless the platform runs with OAuthIntrospection:RefuseImpersonationTokens=true, an app that must tell the two apart cannot do so through this checker (see docs/platform/agent-connections.md).

Your own authorization still applies. For an ordinary user token the introspected scope is the token's own scope and roles is informational (there is no scope-to-permission mapping yet). Always check, against your own data, that authority.sub may act in authority.tenantId for the thing being touched, require the scope the operation needs, and never allow something because a role name is present.

Node sign-in ​

A Node server can sign people in to your own web app with TenancyEngine using createOidcLogin (authorization code with PKCE S256, state and nonce). It reads the provider's /.well-known/openid-configuration, and it validates the ID token signature, issuer, audience, nonce and expiry. It never stores anything: you keep the returned transaction and the tokens in your own server-side session.

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

const login = createOidcLogin({
  issuer: 'https://auth.saasruntime.com/',
  clientId: process.env.TE_CLIENT_ID!,            // registered for your application
  redirectUri: 'https://app.example.com/auth/callback',
  // clientSecret: only for a confidential client; keep it on the server
});

app.get('/login', async (req, res) => {
  const { url, transaction } = await login.begin({ returnTo: '/dashboard' });
  await sessions.put(transaction.state, transaction); // server-side store keyed by state (or a sealed, HttpOnly, short-lived cookie)
  res.redirect(url);
});

app.get('/auth/callback', async (req, res) => {
  const transaction = await sessions.take(req.query.state as string); // one use only, see "Use the transaction once"
  try {
    const { claims, tokens, returnTo } = await login.handleCallback(req.query as Record<string, string>, transaction);
    req.session.user = { sub: claims.sub, email: claims.email };
    req.session.tokens = tokens;                    // yours to store and protect
    res.redirect(returnTo?.startsWith('/') ? returnTo : '/');
  } catch {
    res.status(400).send('Sign-in failed. Please try again.');
  }
});

Failures are thrown as OidcLoginError with a code (state_mismatch, nonce_mismatch, invalid_id_token, token_exchange_failed, transaction_expired, transaction_replayed, resource_invalid, resource_mismatch, and others) whose message is safe to log.

Get a token for your own resource (resource) ​

To have the access token issued for your MCP server or API, pass the same resource identifier you registered (RFC 8707). The SDK sends it as resource on the authorization request and again on the token request, so the platform stamps it as the access token aud:

ts
const login = createOidcLogin({
  clientId: process.env.TE_CLIENT_ID!,
  redirectUri: 'https://app.example.com/auth/callback',
  resource: 'https://mcp.example.com',   // one https identifier, no fragment; the same value you pass to verifyAccessToken
});

Exactly one resource is supported per login. The value is kept in the transaction (transaction.resource), and handleCallback refuses a transaction started for a different resource (or with none, when one is configured, and the reverse) with resource_mismatch, before any token request. A malformed value throws OidcLoginError resource_invalid when you create the login. Without resource nothing changes: no parameter is sent and you get a plain platform token. Needs 0.7.0.

Use the transaction once ​

The transaction (state, nonce, PKCE verifier) must be consumable exactly once, and it must be spent before the authorization code is exchanged, so that a replayed or raced callback cannot reach the token endpoint twice. handleCallback enforces this for you:

  • It keeps an in-process record of the states it has already accepted and refuses a second callback for the same transaction with transaction_replayed, before any token request. A forged state does not spend a real login. A failed token exchange does: start the sign-in again.
  • That record belongs to one createOidcLogin instance. With several instances, or when the transaction travels in a sealed cookie (which the server cannot delete), pass consumeTransaction and make it an atomic delete or set-if-absent in a shared store:
ts
const login = createOidcLogin({
  // ...
  // true only for the call that consumed the record; false or a thrown error refuses with transaction_replayed
  consumeTransaction: async (state) => (await redis.del(`oidc:tx:${state}`)) === 1,
});

Still delete the stored transaction yourself when the callback arrives; the SDK guard is the backstop, not the storage.

Sign in from a local app (loopback callback) ​

For a local proof (a desktop tool, a dev server, an agent) register a public client (PKCE S256) with a redirect URI that is a loopback IP literal, and use the same string in createOidcLogin:

ts
const login = createOidcLogin({
  clientId: process.env.TE_CLIENT_ID!,
  redirectUri: 'http://127.0.0.1:4318/auth/callback',   // exact value you registered
  allowNonProductionIssuer: true,                       // only for a lab or staging issuer, see the lab page
});

The rules, in one place:

AcceptedRefused
Wherea process at the local development tier (NODE_ENV=development or test, or TENANCYENGINE_DEPLOYMENT=local, as te lane exec sets)staging, production, lab and unknown tiers (redirect_uri_loopback_refused); there is no option that overrides this
Hostthe literals 127.0.0.1 and [::1]localhost (RFC 8252 section 8.3), any other host or alias (127.0.0.2, 2130706433, 0.0.0.0), any other http URL (redirect_uri_insecure)
Portany real port, or none (on the platform a registered port matches only that port)port 0, ports above 65535
Shapean exact URLwildcards, userinfo, fragments, whitespace, backslashes (redirect_uri_invalid)

On the platform, a registered client may register http://127.0.0.1/auth/callback (a URL with no port; or the [::1] form) once and present it with whatever port the app got that day (RFC 8252 section 7.3): scheme, host, path and query must be identical to the registered value and only the port may differ. Registered values that are not a loopback IP literal (https URLs, localhost, custom schemes) are matched exactly. A value registered with a port (such as http://127.0.0.1:4318/auth/callback) matches only that port, so register the URL without a port when the app picks a free port at runtime. For a fixed port such as 4318, register that exact URL. Staging and production clients should register https redirect URIs only.

The package @tenancyengine/sdk is on npm from 0.5.0. The loopback callback and the one-time transaction need 0.7.0.

Develop against lab or staging ​

Which lane a verifier trusts follows the same switch as the API client (TENANCYENGINE_ENVIRONMENT=lab|staging|production, production by default), and a lab or staging issuer needs a development machine and allowNonProductionIssuer: true written in your code: no environment variable (including TENANCYENGINE_ALLOW_CROSS_ENVIRONMENT) opts a verifier in. jwksUri and every endpoint in the discovery document must be on the issuer's origin. The whole recipe, the tier rules and the verifier table are on Develop against lab or staging.

Checking that a token is still good ​

verifyAccessToken is a local check of signature, issuer, audience, expiry and scope; it makes no call per request, so a revoked connection, a removed member or a narrowed role is invisible to it until the token expires. To cut those off on the next call, ask the platform with POST /api/v1/runtime/oauth/introspect (an application-level API key with the oauth.introspect scope; the answer is {"active":false} or the active token's sub, client_id, scope, aud, tenant_id, exp and current roles). Run it after the local check, treat any non-200 or non-active: true answer as "do not serve", and never fall back to the local result. Full contract: Agent connections.

Connecting Claude ​

In Claude, add a custom connector and enter your MCP server URL (https://api.example.com/mcp). Claude finds the sign-in on its own from the 401 response. The person signs in to TenancyEngine, sees what Claude is asking for, approves, and the connection is live.

What is available, and what is not yet ​

  • Audience stamping works: when the sign-in request carries resource (RFC 8707) and it equals a registered resource identifier, the access token's aud is exactly that resource (one resource per request, invalid_target otherwise), and the scopes are limited to the ones you registered. PKCE S256 only.
  • Client ID Metadata Document sign-in for assistants, and the consent screen that goes with it, are built and switched off (client_id_metadata_document_supported: false in the discovery document). An assistant that is not pre-registered cannot get a client until the owner enables it, lab first; there is no open client registration endpoint. Until then connect pre-registered clients.
  • Per-application issuers on custom domains. All tokens come from the platform sign-in host today.
  • Customer machine tokens (a different path) are described in Customer machine access.

TenancyEngine platform documentation