Skip to Content

MCP

Turn your Entro Auth server into an OAuth provider for MCP clients

OAuth MCP

The MCP plugin lets your app act as an OAuth authorization server and protected resource for Model Context Protocol clients. It is built on the OAuth 2.1 Provider, so MCP clients discover your endpoints and obtain resource-bound access tokens through standard OAuth flows.

mcp() configures the OAuth provider with MCP resource binding and serves the RFC 9728 protected resource metadata. For the MCP 2026-07-28 profile, compose it with Client ID Metadata Documents and select the profile that pins CIMD draft-00. MCP deprecates Dynamic Client Registration (DCR), so Entro Auth never enables DCR implicitly.

Install @entro314labs/entro-auth-mcp, the recommended @entro314labs/entro-auth-cimd companion package, and version 2 of the official MCP TypeScript SDK.

Installation

Install the packages

npm install @entro314labs/entro-auth-mcp @entro314labs/entro-auth-cimd @modelcontextprotocol/server zod

Configure authorization

Add the MCP plugin to your auth configuration alongside the JWT plugin. The JWT plugin is required: it provides the stable signing key used for ID tokens and access tokens, and exposes the /jwks endpoint that resource servers use to verify them. Disable the JWT plugin's /token route and its set-auth-jwt header. Session JWTs share the access tokens' signing key, so a resource server that checks only issuer and audience could accept one; see OAuth Provider Mode.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { jwt } from "@entro314labs/entro-auth/plugins"; 
import { cimd } from "@entro314labs/entro-auth-cimd"; 
import { mcp } from "@entro314labs/entro-auth-mcp"; 
import { fetchClientMetadataResource } from "@entro314labs/entro-auth-cimd/node"; 

export const auth = entroAuth({
    disabledPaths: ["/token"], 
    plugins: [
        jwt({ disableSettingJwtHeader: true }), 
        mcp({ 
            loginPage: "/sign-in", // path to your login page
            consentPage: "/consent", // path to your consent page
            resource: "https://api.example.com/mcp" // protected resource identifier
        }), 
        cimd({ 
            fetchClientMetadataResource, 
            metadataProfile: "mcp-2026-07-28", 
        }), 
    ]
});

Node.js deployments can use the bundled transport shown above. Bun, Deno, Workers, and other runtimes must inject an equivalent transport that resolves each hostname once, rejects RFC 6890 special-use addresses, pins the approved address for the connection, and refuses redirects. The transport retrieves both the Client ID Metadata Document and discovery-owned resources such as jwks_uri. See the CIMD security boundary for the complete contract.

mcp() is the OAuth provider. Do not also register a separate oauthProvider() plugin in the same app.

Generate Schema

Run the migration or generate the schema to add the necessary tables to the database.

npx @entro314labs/entro-auth-cli migrate

The MCP plugin uses the same schema as the OAuth Provider plugin (oauthClient, oauthAccessToken, oauthRefreshToken, oauthConsent, oauthClientAssertion, oauthResource, oauthClientResource). See the OAuth Provider schema for details.

Endpoints

mcp() serves every OAuth Provider endpoint, including introspection (/oauth2/introspect), revocation (/oauth2/revoke), consent, and end-session. MCP clients use these:

EndpointPath
Authorization/oauth2/authorize
Token/oauth2/token
Dynamic registration (when explicitly enabled)/oauth2/register
UserInfo/oauth2/userinfo

Discovery follows OAuth 2.0 Authorization Server Metadata (RFC 8414) and Protected Resource Metadata (RFC 9728). The well-known URLs are derived from the issuer, so a server with a base path serves them at the issuer-inserted location rather than the bare root. Discovery advertises client_id_metadata_document_supported only when cimd() is installed, and registration_endpoint only when DCR is enabled.

Entro Auth owns OAuth discovery, client registration and discovery, PKCE authorization, resource binding, token issuance and refresh, and protected-resource challenges. The official MCP TypeScript SDK v2 owns the stateless MCP protocol and transport. Configure servers with legacy: "reject", and pin SDK client version negotiation to 2026-07-28 when adopting this profile.

Usage

Add device authorization for your own CLI

MCP clients normally discover the authorization server from protected resource metadata, then use the authorization code flow with PKCE. Keep that flow for general MCP compatibility.

If your product also ships a command-line application, the same authorization server can let the CLI authorize through a browser without opening a local callback listener. Add the OAuth Device Authorization integration:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { jwt } from "@entro314labs/entro-auth/plugins";
import { oauthDeviceAuthorization } from "@entro314labs/entro-auth-oauth-provider";
import { mcp } from "@entro314labs/entro-auth-mcp";

export const auth = entroAuth({
  disabledPaths: ["/token"],
  plugins: [
    jwt({ disableSettingJwtHeader: true }),
    mcp({
      loginPage: "/sign-in",
      consentPage: "/consent",
      resource: "https://api.example.com/mcp",
      scopes: ["openid", "profile", "offline_access", "mcp:read"],
    }),
    oauthDeviceAuthorization({ verificationUri: "/device" }),
  ],
});

mcp() is already the OAuth Provider, so this composition does not add a separate oauthProvider() plugin. MCP clients continue to use discovery and authorization code with PKCE. Your registered public CLI can request the same MCP resource through /device/code and poll /oauth2/token for an audience-bound access token.

Only use the device grant in an MCP client that explicitly implements RFC 8628. Adding oauthDeviceAuthorization() to the server does not change the standard flow chosen by existing MCP clients. See Authorize a CLI to call an API for client registration and token polling.

Protected Resource Metadata

The RFC 9728 /.well-known/oauth-protected-resource document is served by the auth handler at the well-known root and at the resource-path-inserted alias: for a resource of https://example.com/api/mcp, /.well-known/oauth-protected-resource and /.well-known/oauth-protected-resource/api/mcp. It tells MCP clients which authorization server protects the resource, which scopes it supports, which resource identifier their access tokens must be bound to, and which DPoP proof algorithms are supported.

Both paths are outside your auth base path. A framework that forwards only /api/auth/* to auth.handler never hands them over, so add a route for each that does. The same goes for the authorization server document at /.well-known/oauth-authorization-server/api/auth; see Expose the well-known metadata.

app/.well-known/oauth-protected-resource/route.ts
import { auth } from "@/lib/auth";

export const GET = (request: Request) => auth.handler(request);

To tell a person what the server is, add resourceMetadata. It takes the describing fields of the document (resource_name, resource_documentation, resource_policy_uri, resource_tos_uri); everything a client acts on still comes from the rest of the configuration.

auth.ts
mcp({
    resource: "https://example.com/api/mcp",
    resourceMetadata: {
        resource_name: "Example Notes",
        resource_documentation: "https://example.com/docs/mcp",
    },
    // ...
})

Set resource to the protected resource identifier MCP clients request and access tokens carry as aud:

auth.ts
mcp({
    loginPage: "/sign-in",
    consentPage: "/consent",
    resource: "https://api.example.com/mcp"
})

resource must be an HTTPS URL with no query, fragment, or credentials; HTTP is accepted only on loopback hosts for local development. A resource whose URL requires a query component cannot use mcp(), requireMcpAuth, or createMcpProtectedRequestHandler. Verify its tokens with verifyAccessTokenRequest from @entro314labs/entro-auth/oauth2, and build challenges with createResourceServerChallenge from @entro314labs/entro-auth-oauth-provider.

The MCP resource has no scope restriction by default. To restrict it, add { identifier: resource, allowedScopes: [...] } to resources; otherwise mcp() adds it automatically.

mcp() also registers this identifier as a default client-registration resource. A dynamically registered client is linked to the MCP resource even when its registration request omits the non-standard resources field. Any clientRegistrationDefaultResources you provide are preserved, and the MCP resource is appended once.

Optional DCR fallback

CIMD is the recommended client identity mechanism. If you deliberately support older clients that still require DCR, enable both provider controls explicitly:

mcp({
  loginPage: "/sign-in",
  consentPage: "/consent",
  resource: "https://api.example.com/mcp",
  allowDynamicClientRegistration: true,
  allowUnauthenticatedClientRegistration: true,
  clientRegistrationDefaultApplicationType: "infer",
})

allowUnauthenticatedClientRegistration: true lets anyone on the internet register a client, with a name and logo they choose. Each such client is linked to the MCP resource and to every clientRegistrationDefaultResources entry. Read dynamic client registration before you enable it, and set clientRegistrationDefaultScopes so anonymous clients get only the scopes they need.

Some MCP clients omit application_type and register custom-scheme callbacks or http callbacks on localhost, 127.0.0.1, or [::1], which the web default rejects. clientRegistrationDefaultApplicationType: "infer" registers those clients as native; see dynamic client registration.

The registration endpoint is absent from discovery unless DCR is enabled. A DCR request does not need Entro Auth's resources extension: mcp() adds its canonical resource as a server-owned default.

Protecting an MCP Route

MCP 2026-07-28 uses a stateless request and response model: every client JSON-RPC request or notification is an independent HTTP POST, and the server does not maintain a protocol-level session between requests. Use the official MCP TypeScript SDK v2 to implement that transport, then wrap its POST handler with requireMcpAuth.

The following Next.js route creates a fresh MCP server for each request and rejects traffic from the session-oriented 2025 protocol. It exports only POST, so the framework responds to GET and DELETE with 405 Method Not Allowed.

app/api/mcp/route.ts
import { auth } from "@/lib/auth";
import { requireMcpAuth } from "@entro314labs/entro-auth-mcp"; 
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server"; 
import * as z from "zod";

const resource = "https://api.example.com/mcp";

const mcpServerHandler = createMcpHandler(
    () => {
        const server = new McpServer({
            name: "example-mcp-server",
            version: "1.0.0",
        });

        server.registerTool(
            "echo",
            {
                description: "Echo a message",
                inputSchema: z.object({
                    message: z.string(),
                }),
            },
            async ({ message }) => ({
                content: [{ type: "text", text: `Tool echo: ${message}` }],
            }),
        );

        return server;
    },
    {
        legacy: "reject", // accept only the MCP 2026-07-28 protocol
    },
);

const POST = requireMcpAuth(
    auth,
    (request) => mcpServerHandler.fetch(request),
    {
        resource, // must match mcp({ resource })
    },
);

export { POST };

createMcpHandler returns JSON or request-scoped Server-Sent Events (SSE) as required by the operation; it does not require a Redis-backed MCP session store. If you implement subscriptions/listen across multiple server instances, provide the SDK with a shared event bus for that extension. OAuth clients, consent, authorization codes, refresh tokens, CIMD metadata, and DPoP replay detection still use durable state because they are authorization and security records, not MCP transport sessions.

requireMcpAuth reads the Authorization header and checks the access token against the authorization server's records, in the same process. It accepts JWT and opaque access tokens, rejects a token whose session ended or whose client is disabled, and checks the issuer, audience, and expiry. It rejects a revoked opaque token, and a revoked JWT access token only with revocableJwtAccessTokens: true. It also enforces RFC 9449 Demonstrating Proof of Possession (DPoP) when an access token is DPoP-bound. Unauthenticated requests receive a JSON-RPC 401 with the RFC 9728 WWW-Authenticate header, so MCP clients can start the authorization flow. Tokens missing a required scope receive a 403 with an RFC 6750 insufficient_scope challenge, which MCP clients use to step up their authorization. A client that sent its token with the DPoP scheme gets a DPoP challenge instead (RFC 9449 §7.1). It names the missing scopes in scope and the accepted proof algorithms in algs. Like the Bearer challenge, it carries resource_metadata.

The wrapper passes the verified access-token claims as a second callback argument, not as a database record. The example keeps authentication at the route boundary; if a tool needs token context, convert those claims to the SDK's AuthInfo and pass it through mcpServerHandler.fetch(request, { authInfo }). requireMcpAuth never exposes a refresh token. It reads the token's records from your auth instance instead of requesting its own endpoints, so it also works on runtimes that cannot send a request to their own hostname. Each request reads those records from your database. The claims' sub is the subject the token carries, as with the resource client: for a user token, the user ID, or the pairwise subject when the provider sets accessTokenSubject: "pairwise", and for a client_credentials JWT, the client ID. A pairwise client's opaque token gets its pairwise subject, so the handler never sees a user ID the token hides. DPoP replay protection uses your auth instance's database adapter by default so it works across server instances; pass dpop.replayStore only when you need a different shared store.

To require server-provided DPoP nonces, set dpop: { nonce: { required: true } } on mcp() and pass the same option to requireMcpAuth. A DPoP request without a current nonce then receives a JSON-RPC 401 with a WWW-Authenticate: DPoP error="use_dpop_nonce" challenge and a fresh DPoP-Nonce header. Successful DPoP responses carry the next nonce. Every response that carries a nonce is marked Cache-Control: no-store. requireMcpAuth derives nonces from your auth secret and accepts them for the provider's dpop.nonce.expiresIn. A nonce from a token response therefore works at any MCP server that uses the same secret and lifetime. createMcpProtectedRequestHandler has no auth instance and defaults the lifetime to 300 seconds, so pass the provider's expiresIn to it when that differs. See Server-provided nonces.

An MCP server that calls a downstream API for the user must not pass the user's token through. Exchange it for a token to that API with token exchange instead. mcp() links every dynamically registered client to the MCP resource, so read the registration default resources item in token exchange limitations before you enable it.

By default, requireMcpAuth reads the server's resolved Entro Auth URL from the auth context and uses it as the expected resource. It expects the issuer the provider signs, which follows jwt.issuer when you set it. Because it checks tokens against this server's own records or keys in-process, it also accepts that issuer as you configured it, which tokens issued before 1.8 carry. If mcp({ resource }) uses a different identifier, pass that same value to requireMcpAuth, as shown above. Pass issuer only when the tokens come from an authorization server with a different issuer. An issuer you pass is the only value accepted. Set jwksUrl to verify JWT access tokens with the keys at that URL instead, for example when the authorization server runs separately. Remote verification is exact: with jwksUrl and no issuer, the expected issuer is the normalized one that discovery publishes, and a token that carries the configured form is rejected, as RFC 9068 §4 requires. The same holds when the JWT plugin sets jwks.remoteUrl and no OAuth provider runs in this process, because the signature is then checked against keys fetched from that URL. Without jwksUrl, a provider in this process checks its records, so both forms are accepted. requireMcpAuth takes one issuer, so JWT access tokens issued before 1.8 that carry the configured form are rejected there until they expire. To accept both forms at a remote resource server, verify with the resource client and pass both values as verifyOptions.issuer. Signature checks alone do not see revocation or an ended session, and they reject opaque tokens:

requireMcpAuth(auth, handler, {
    resource: "https://api.example.com/mcp", // protected resource identifier
    issuer: "https://auth.example.com", // only for another authorization server
    jwksUrl: "https://auth.example.com/api/auth/jwks",
    challengeScopes: ["openid", "profile"] // advertised in the 401 challenge
})

Without the resource option, the audience check expects the URL of your Entro Auth server. If your MCP resource has a different URL, its token fails with invalid_token. The MCP authorization specification says an MCP server must validate that a token was issued for it as the intended audience. It also requires an MCP client to send the server's own URI as the resource parameter. Set resource to that URI when it differs from the default.

With jwksUrl, signing keys are cached for five minutes. If a refetch fails, a cached key can still verify a token for up to ten minutes after the last successful fetch. See Verify access tokens.

With in-process verification, requireMcpAuth accepts an opaque access token only when its stored audience includes the MCP resource. A token request that omits the resource parameter uses the resources bound to the authorization code, and a refresh request uses the resources stored on the refresh token. When no resource is named or bound, the token has no MCP audience and verification fails. The specification requires MCP clients to send the resource parameter in authorization and token requests, so a conforming client is not affected.

To require scopes, pass requiredScopes. A token missing any of them is rejected with a 403 and an insufficient_scope challenge naming every missing scope, so the client can re-authorize for all of them at once (step-up authorization):

requireMcpAuth(auth, handler, {
    resource: "https://api.example.com/mcp",
    requiredScopes: ["mcp:tools"], // enforced against the token's scope claim
})

When the required scopes depend on the request (one tool needs more than another), throw createInsufficientScopeError from the handler to challenge for exactly those scopes:

import { createInsufficientScopeError } from "@entro314labs/entro-auth/oauth2";

requireMcpAuth(auth, async (request, accessTokenClaims) => {
    if (isAdminTool(request) && !hasScope(accessTokenClaims, "mcp:admin")) {
        throw createInsufficientScopeError(["mcp:admin"]);
    }
    return executeMcpRequest(request, accessTokenClaims);
})

Reach for this only when re-authorizing would actually help. A denial the user cannot fix by granting scopes (they are not a member of the organization, the record belongs to someone else) should stay an ordinary 403: challenging sends them through consent to no effect. Errors your handler throws for any other reason propagate to your framework unchanged.

Configuration

mcp() extends the OAuth Provider options. All OAuth provider options are passed flat (there is no nested oidcConfig). The required MCP-specific option is resource.

For every client configured through mcp(), the plugin defaults refreshTokenReuseInterval to 30 seconds. This lets a client retry a refresh with the old token and receive the same rotated token response when another request already consumed that refresh token, including when two refresh requests arrive at the same time. A request that overlaps waits at most 5 seconds for the first one. OAuth Provider itself remains strict by default; set refreshTokenReuseInterval: 0 on mcp() to disable the overlap window.

Inside the window, reuse of a rotated refresh token is not treated as replay, so the token family is not revoked. An attacker who replays a stolen bearer refresh token within 30 seconds of the legitimate refresh gets the replacement refresh token, as long as the retry asks for the same scopes and resources. A DPoP-bound refresh token also needs a valid DPoP proof from the key it is bound to. Most MCP clients are public clients with no secret, so nothing else stops a bearer token retry. Set refreshTokenReuseInterval: 0 unless your clients lose refresh responses; see Refresh tokens.

Prop

Type

The most commonly tuned OAuth provider options are below. See the OAuth Provider Configuration for the full list.

Prop

Type

Remote MCP Server

requireMcpAuth checks tokens against the records of the auth instance you pass it. With jwksUrl, it verifies JWT signatures against that URL instead. When the resource server runs separately from the authorization server, or uses a dynamic baseURL, use createMcpProtectedRequestHandler with explicit verification options instead of requireMcpAuth.

mcp-server.ts
import { createMcpProtectedRequestHandler } from "@entro314labs/entro-auth-mcp"; 

const handler = createMcpProtectedRequestHandler( 
    {
        issuer: "https://auth.example.com/api/auth",
        audience: "https://api.example.com/mcp",
        jwksUrl: "https://auth.example.com/api/auth/jwks",
        jwtVerifyOptions: { typ: "at+jwt", requiredClaims: ["azp"] }, 
    },
    async (request, accessTokenClaims) => { 
        // accessTokenClaims holds the verified access-token claims
        return new Response(JSON.stringify({
            jsonrpc: "2.0",
            result: { sub: accessTokenClaims.sub },
            id: 1
        }))
    }
)

createMcpProtectedRequestHandler returns the same RFC 9728 WWW-Authenticate response for unauthenticated requests. Set requiredScopes in its options to require scopes; a token missing any of them receives the same 403 insufficient_scope challenge as requireMcpAuth. Set challengeScopes in the same options object to advertise a scope hint on unauthenticated challenges.

Both helpers expose WWW-Authenticate to browser clients on other origins. If your CORS layer sets Access-Control-Expose-Headers, see Resource Server for what it must include.

To stop a captured DPoP proof from being used twice, the handler records each proof it accepts for a DPoP-bound token. Unlike requireMcpAuth, createMcpProtectedRequestHandler keeps that record in memory by default. The default is safe only for a single long-lived instance. Other instances do not see the record, and a restart clears it. An attacker who captures a proof can replay it against another instance until the proof expires.

If the handler runs on several instances or on serverless, pass a shared store as dpop.replayStore:

  • If the handler runs in the same app as your Entro Auth server, use createDpopReplayStore(await auth.$context), as shown in Protect your API. It records proofs in secondary storage or the database, wherever your auth instance keeps verification values.
  • Otherwise, implement DpopReplayStore on storage that every instance shares. Its reserve method must record the proof's key until at least expiresAt in one atomic step, and return false if the key is already recorded. If reserve throws, the request fails.

On this page