kontext.middleware() method returns an Express router that handles OAuth metadata, bearer auth, and MCP transport. Mount it at the app root.
Factory function pattern
Pass a factory function() => McpServer instead of a single instance. Each MCP session requires its own McpServer — the MCP spec mandates a 1:1 relationship between server instances and connections. Sharing a single instance across concurrent sessions will throw.
Options
| Option | Type | Default | Description |
|---|---|---|---|
mcpPath | string | "/mcp" | Path for the MCP transport endpoint |
resourceServerUrl | string | Auto-detected | Public URL of your application. Required when behind a reverse proxy. |
dangerouslyOmitAuth | boolean | false | Skip OAuth metadata and bearer auth. For local development only. |
verifier | OAuthTokenVerifier | Built-in JWKS verifier | Custom token verification function |
metadataTransform | (metadata) => metadata | Identity | Transform OAuth metadata before serving |
onSessionInitialized | (sessionId, authInfo?, transport?) => void | — | Called when a new MCP session starts |
onSessionClosed | (sessionId) => void | — | Called when a session ends |
bodyLimit | string | number | "1mb" | Max request body size, passed to express.json() |
Registered routes
The middleware registers three route groups:| Route | Method | Purpose |
|---|---|---|
/.well-known/oauth-authorization-server | GET | OAuth authorization server metadata (RFC 8414) |
/.well-known/oauth-protected-resource{mcpPath} | GET | Protected resource metadata (RFC 9728). Default: /.well-known/oauth-protected-resource/mcp |
/mcp (or custom mcpPath) | POST, GET, DELETE | Streamable HTTP MCP transport |
.well-known routes must be accessible at the root of your domain. This means you should mount the middleware at the app root, not under a sub-path.
Session lifecycle hooks
Track session creation and teardown with theonSessionInitialized and onSessionClosed callbacks.
authInfo object contains the verified token claims, including token, clientId, scopes, expiresAt, and an extra bag with sub and email.
Custom token verifier
Replace the built-in JWKS verifier with your own. This is useful when your application sits behind a gateway that handles token verification.Metadata transform
When your application runs behind a reverse proxy, the OAuth metadata URLs may point to internal addresses. UsemetadataTransform to rewrite them before they reach the client.
Next steps
- Credentials — Exchange user tokens for integration credentials inside tool handlers.
- Production — Deployment checklist for running in production.
- Server Types — Full type reference for
MiddlewareOptionsandOAuthTokenVerifier.