Use a factory function
Always pass a factory function tokontext.middleware(). Each MCP session needs its own McpServer instance — the MCP spec requires a 1:1 relationship between server and transport. A single shared instance will fail under concurrent connections.
Set the client secret
Token exchange withkontext.require() uses a client secret for server-side operations, session tracking, and telemetry. The secret is optional — the SDK falls back to public client mode without it — but recommended for production. Set it via environment variable:
Configure token issuers
If your OAuth server issues tokens with an issuer different from the public metadata, configuretokenIssuer so the built-in verifier accepts them.
Set resourceServerUrl behind a proxy
When your application runs behind a reverse proxy or load balancer, the SDK cannot detect the public URL from the request. Set resourceServerUrl to your public endpoint:
Session management
The SDK tracks MCP sessions automatically:- Stale cleanup: Sessions inactive for 1 hour are closed and removed.
- Cleanup interval: Runs every 5 minutes.
unref’d so it does not prevent process exit.
Graceful shutdown
The SDK registersSIGINT and SIGTERM handlers that disconnect all active sessions on shutdown. This happens automatically for every Kontext instance.
For serverless environments or cases where you create and dispose SDK instances dynamically, call destroy() to clean up:
destroy() disconnects all sessions, clears credential caches, and removes the instance from the global shutdown handler set so it can be garbage collected.
Next steps
- Middleware — Full middleware configuration, session hooks, and custom verifiers.
- Server Types — Type reference for
Kontext,KontextOptions, andMiddlewareOptions.