@entro314labs/entro-auth-mcp 0.0.0-stage → 1.8.0-beta.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2024 - present, Bereket Engida
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the “Software”), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
+ the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # @entro314labs/entro-auth-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Model Context Protocol (MCP) plugin for [Entro Auth](https://www.better-auth.com).
4
+
5
+ `mcp()` turns your Entro Auth app into an OAuth 2.1 authorization server and
6
+ protected resource for MCP clients, built on
7
+ [`@entro314labs/entro-auth-oauth-provider`](https://www.better-auth.com/docs/plugins/oauth-provider).
8
+ It serves RFC 9728 protected resource metadata and binds issued tokens to the
9
+ configured resource. Compose it with `cimd()` for the MCP 2026-07-28 Client ID
10
+ Metadata Document flow, which pins CIMD draft-00 through an explicit metadata
11
+ profile. Dynamic Client Registration is disabled unless explicitly enabled.
12
+
13
+ `@entro314labs/entro-auth-mcp` owns authorization, not MCP protocol transport. Serve MCP
14
+ 2026-07-28 requests with version 2 of the official
15
+ [`@modelcontextprotocol/server`](https://www.npmjs.com/package/@modelcontextprotocol/server)
16
+ package, configure `createMcpHandler` with `legacy: "reject"`, mount it behind
17
+ `requireMcpAuth`, and expose only the HTTP `POST` route. The modern protocol
18
+ handles each request independently and does not need a Redis-backed MCP
19
+ session store. Multi-instance `subscriptions/listen` deployments can supply a
20
+ shared SDK event bus without introducing protocol-level sessions.
21
+
22
+ ```ts
23
+ import { entroAuth } from "@entro314labs/entro-auth";
24
+ import { jwt } from "@entro314labs/entro-auth/plugins";
25
+ import { cimd } from "@entro314labs/entro-auth-cimd";
26
+ import { fetchClientMetadataResource } from "@entro314labs/entro-auth-cimd/node";
27
+ import { mcp } from "@entro314labs/entro-auth-mcp";
28
+
29
+ export const auth = entroAuth({
30
+ plugins: [
31
+ jwt(),
32
+ mcp({
33
+ loginPage: "/login",
34
+ consentPage: "/consent",
35
+ resource: "https://api.example.com/mcp",
36
+ }),
37
+ cimd({
38
+ fetchClientMetadataResource,
39
+ metadataProfile: "mcp-2026-07-28",
40
+ }),
41
+ ],
42
+ });
43
+ ```
44
+
45
+ See the [MCP plugin documentation](https://www.better-auth.com/docs/plugins/mcp).
@@ -0,0 +1,246 @@
1
+ import { DpopReplayAuthContext, DpopReplayStore, VerifyAccessTokenRequestOptions } from "@entro314labs/entro-auth/oauth2";
2
+ import { OAuthOptions, Scope, oauthProvider } from "@entro314labs/entro-auth-oauth-provider";
3
+ import { AuthContext, Awaitable } from "@entro314labs/entro-auth-core";
4
+ import { JWTPayload, JWTVerifyOptions } from "jose";
5
+ import { EntroAuthOptions } from "@entro314labs/entro-auth/types";
6
+ interface McpProtectedRequestHandlerOptions {
7
+ /** Expected authorization-server issuer for the access token. */
8
+ issuer: string;
9
+ /** Canonical MCP protected-resource URL expected in the token audience. */
10
+ audience: string;
11
+ /**
12
+ * Additional JOSE verification constraints. `issuer` and `audience` remain
13
+ * authoritative from the top-level fields.
14
+ */
15
+ jwtVerifyOptions?: Omit<JWTVerifyOptions, "issuer" | "audience">;
16
+ /** URL of the authorization server's JSON Web Key Set. */
17
+ jwksUrl?: string;
18
+ /** Remote introspection settings for opaque or remotely checked tokens. */
19
+ remoteVerify?: {
20
+ introspectUrl: string;
21
+ clientId: string;
22
+ clientSecret: string;
23
+ force?: boolean;
24
+ allowMissingAudience?: boolean;
25
+ };
26
+ /** Scopes every accepted access token must satisfy. */
27
+ requiredScopes?: readonly string[];
28
+ /**
29
+ * Scopes to advertise in unauthenticated `WWW-Authenticate` challenges.
30
+ * Defaults to `requiredScopes`.
31
+ */
32
+ challengeScopes?: readonly string[];
33
+ /** Custom required-scope matcher. Defaults to exact membership. */
34
+ isScopeSatisfied?: (requiredScope: string, grantedScopes: ReadonlySet<string>) => boolean;
35
+ /** DPoP proof validation and replay-protection settings. */
36
+ dpop?: {
37
+ proofMaxAgeSeconds?: number;
38
+ signingAlgorithms?: readonly string[];
39
+ /**
40
+ * Store that rejects a DPoP proof that was already used.
41
+ *
42
+ * Unlike `requireMcpAuth`, this handler has no auth instance to store
43
+ * proofs in, so it defaults to a process-local in-memory store. That is
44
+ * safe only for a single long-lived instance. For multiple instances or
45
+ * serverless, pass a shared store, such as
46
+ * `createDpopReplayStore(await auth.$context)` from `@entro314labs/entro-auth/oauth2`.
47
+ */
48
+ replayStore?: DpopReplayStore;
49
+ /**
50
+ * Require server-provided nonces in DPoP proofs (RFC 9449 §9). A proof
51
+ * without a current nonce gets a `401` `use_dpop_nonce` challenge with a
52
+ * fresh `DPoP-Nonce`, and successful DPoP responses carry the next one.
53
+ * Responses that carry a nonce are marked `Cache-Control: no-store`. Use
54
+ * the authorization server's secret to accept the nonces it issues, such
55
+ * as when the MCP server shares its origin.
56
+ */
57
+ nonce?: NonNullable<VerifyAccessTokenRequestOptions["dpop"]>["nonce"];
58
+ };
59
+ }
60
+ type McpRequestHandler = (request: Request, accessTokenClaims: JWTPayload) => Awaitable<Response>;
61
+ /**
62
+ * A request middleware handler that verifies an MCP access token and responds
63
+ * with an RFC 9728 `WWW-Authenticate` header for unauthenticated requests.
64
+ * When `options.requiredScopes` is set, tokens missing a required scope receive
65
+ * a 403 with an RFC 6750 `insufficient_scope` challenge naming them instead.
66
+ *
67
+ * @external
68
+ */
69
+ export declare const createMcpProtectedRequestHandler: (options: McpProtectedRequestHandlerOptions, handler: McpRequestHandler) => (request: Request) => Promise<Response>;
70
+ /**
71
+ * Options for the {@link mcp} plugin: the full OAuth provider configuration plus
72
+ * the MCP resource identifier.
73
+ */
74
+ interface McpOptions extends OAuthOptions<Scope[]> {
75
+ /**
76
+ * Seconds that a rotated refresh token can be reused to receive the same
77
+ * token response for the same effective scopes, requested resources, and
78
+ * sender constraint.
79
+ *
80
+ * OAuth Provider remains strict by default. MCP overrides that default for
81
+ * every client configured through this plugin so a retried refresh can
82
+ * recover the response produced by an earlier request. Set to `0` to disable
83
+ * the overlap window and keep strict replay handling.
84
+ *
85
+ * @default 30
86
+ */
87
+ refreshTokenReuseInterval?: NonNullable<OAuthOptions<Scope[]>["refreshTokenReuseInterval"]>;
88
+ /**
89
+ * The canonical protected resource identifier (RFC 8707 / RFC 9728) for this
90
+ * MCP server. Issued tokens are audience-bound to it, and it is published as
91
+ * `resource` in the protected resource metadata, added to `resources`, and
92
+ * used as the expected token audience.
93
+ *
94
+ * Must be an HTTPS URL with no query, fragment, or credentials. HTTP is
95
+ * accepted only on loopback hosts for local development.
96
+ */
97
+ resource: string;
98
+ }
99
+ /**
100
+ * Model Context Protocol authorization server.
101
+ *
102
+ * `mcp()` is the OAuth 2.1 / OIDC provider ({@link oauthProvider}) configured for
103
+ * MCP: it binds issued tokens to the MCP `resource`, links that resource to
104
+ * newly registered clients, and, as the resource server, serves the RFC 9728
105
+ * protected resource metadata so MCP clients discover and use it through
106
+ * standard OAuth discovery. Client registration is opt-in: compose with
107
+ * `cimd()` for Client ID Metadata Documents, or explicitly enable the OAuth
108
+ * Provider dynamic-registration options.
109
+ * It also defaults `refreshTokenReuseInterval` to 30 seconds for all MCP
110
+ * clients, allowing a retried refresh to recover a rotated response. OAuth
111
+ * Provider remains strict by default; set the MCP option to `0` to disable the
112
+ * overlap window.
113
+ * MCP 2026-07-28 pins Client ID Metadata Documents draft-00. Configure the
114
+ * CIMD plugin with `metadataProfile: "mcp-2026-07-28"` and an application-owned
115
+ * metadata-resource transport.
116
+ * Because it is the OAuth provider, it cannot be combined with a separate
117
+ * {@link oauthProvider}.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * import { entroAuth } from "@entro314labs/entro-auth";
122
+ * import { jwt } from "@entro314labs/entro-auth/plugins";
123
+ * import { cimd } from "@entro314labs/entro-auth-cimd";
124
+ * import { mcp } from "@entro314labs/entro-auth-mcp";
125
+ * import { fetchClientMetadataResource } from "./oauth-network";
126
+ *
127
+ * export const auth = entroAuth({
128
+ * plugins: [
129
+ * jwt(),
130
+ * mcp({
131
+ * loginPage: "/login",
132
+ * consentPage: "/consent",
133
+ * resource: "https://api.example.com/mcp",
134
+ * }),
135
+ * cimd({
136
+ * fetchClientMetadataResource,
137
+ * metadataProfile: "mcp-2026-07-28",
138
+ * }),
139
+ * ],
140
+ * });
141
+ * ```
142
+ */
143
+ export declare const mcp: (options: McpOptions) => ReturnType<typeof oauthProvider>;
144
+ interface RequireMcpAuthOptions {
145
+ /**
146
+ * The protected resource identifier the access token must be bound to.
147
+ * Defaults to the server's resolved base URL.
148
+ */
149
+ resource?: string;
150
+ /**
151
+ * Expected token issuer. Defaults to the OAuth provider's issuer, derived
152
+ * from `jwt.issuer` when the JWT plugin sets it and otherwise from the
153
+ * server's resolved base URL. Verification that reads this server's records
154
+ * or keys in-process also accepts that URL exactly as configured, which
155
+ * tokens issued by earlier versions carry. Verification against keys fetched
156
+ * from a URL, which is `jwksUrl` or the JWT plugin's `jwks.remoteUrl` when no
157
+ * OAuth provider runs in this process, expects the normalized issuer alone,
158
+ * since RFC 9068 §4 requires an exact match. A value set here is the only
159
+ * issuer accepted.
160
+ */
161
+ issuer?: string;
162
+ /**
163
+ * URL of the authorization server's JWKS. When set, JWT access tokens are
164
+ * verified by signature against these keys alone, which does not see
165
+ * revocation or an ended session, and opaque tokens are rejected. When
166
+ * unset and the OAuth provider runs in this process, tokens are checked
167
+ * against its records. Without that provider, JWT access tokens are verified
168
+ * by signature against the JWT plugin's keys, read in-process, or fetched from
169
+ * `jwks.remoteUrl` when the plugin publishes them there.
170
+ */
171
+ jwksUrl?: string;
172
+ /**
173
+ * Scopes to advertise in the `WWW-Authenticate` challenge (RFC 6750),
174
+ * hinting which scopes the client should request. Defaults to the enforced
175
+ * `requiredScopes` when those are set.
176
+ */
177
+ challengeScopes?: readonly string[];
178
+ /**
179
+ * Scopes the access token must include, enforced against the token's
180
+ * `scope` claim. A token missing any of them is rejected with a 403 and an
181
+ * RFC 6750 `insufficient_scope` challenge naming every missing scope, so MCP
182
+ * clients can step up their authorization in one round-trip.
183
+ */
184
+ requiredScopes?: readonly string[];
185
+ /** Custom required-scope matcher. Defaults to exact membership. */
186
+ isScopeSatisfied?: (requiredScope: string, grantedScopes: ReadonlySet<string>) => boolean;
187
+ /**
188
+ * DPoP proof validation settings. By default the replay store is backed by
189
+ * the auth instance's database adapter, so anti-replay holds across multiple
190
+ * server instances. Override `replayStore` only to point at a different store.
191
+ */
192
+ dpop?: {
193
+ proofMaxAgeSeconds?: number;
194
+ signingAlgorithms?: readonly string[];
195
+ replayStore?: DpopReplayStore;
196
+ /**
197
+ * Require server-provided nonces in DPoP proofs (RFC 9449 §9). A proof
198
+ * without a current nonce gets a `401` `use_dpop_nonce` challenge with a
199
+ * fresh `DPoP-Nonce`, and successful DPoP responses carry the next one.
200
+ *
201
+ * Nonces are derived from the auth instance's secret, the same way the
202
+ * OAuth provider's `dpop.nonce` derives them, so the MCP server accepts
203
+ * the nonces the provider issues. Pass `secret` only to keep the MCP
204
+ * server's nonces separate, such as for an MCP server on its own origin.
205
+ */
206
+ nonce?: {
207
+ required: boolean;
208
+ /**
209
+ * Seconds a nonce is accepted after it is issued. Defaults to the OAuth
210
+ * provider's `dpop.nonce.expiresIn`, then to `300`.
211
+ */
212
+ expiresIn?: number;
213
+ /** Defaults to the auth instance's secret. */
214
+ secret?: string;
215
+ };
216
+ };
217
+ }
218
+ /**
219
+ * Protects an MCP server route handler. Checks the bearer access token against
220
+ * the OAuth provider's records in-process (JWT or opaque; ended sessions,
221
+ * disabled clients, and revoked opaque tokens fail, and so do revoked JWTs
222
+ * with `revocableJwtAccessTokens`), verifies issuer, audience, and
223
+ * expiry, and forwards the token's claims to the handler. Their `sub` is the
224
+ * subject the token carries; a pairwise client's opaque token gets its
225
+ * pairwise subject.
226
+ * Unauthenticated requests receive a JSON-RPC 401 with the RFC 9728
227
+ * `WWW-Authenticate` header so MCP clients can start the authorization flow.
228
+ * Tokens missing a required scope receive a 403 with an RFC 6750
229
+ * `insufficient_scope` challenge naming the missing scopes, so clients can step
230
+ * up their authorization; a handler can raise the same challenge for scopes only
231
+ * it knows about by throwing `createInsufficientScopeError`.
232
+ *
233
+ * For a resource server that runs separately from the authorization server, or
234
+ * a server using a dynamic `baseURL`, use
235
+ * {@link createMcpProtectedRequestHandler} with explicit verification options
236
+ * instead.
237
+ *
238
+ * @external
239
+ */
240
+ export declare const requireMcpAuth: <Auth extends {
241
+ options: EntroAuthOptions;
242
+ $context: Promise<Pick<AuthContext, "baseURL" | "getPlugin"> & DpopReplayAuthContext & {
243
+ secret?: string;
244
+ }>;
245
+ }>(auth: Auth, handler: (request: Request, accessTokenClaims: JWTPayload) => Awaitable<Response>, opts?: RequireMcpAuthOptions) => (req: Request) => Promise<Response>;
246
+ export type { McpOptions, McpProtectedRequestHandlerOptions, RequireMcpAuthOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,304 @@
1
+ import { DPOP_NONCE_HEADER, DPOP_SIGNING_ALGORITHMS, createDpopNonce, createDpopReplayStore, getDpopJktFromPayload, isInsufficientScopeError, requestToResourceInput, verifyAccessTokenRequest } from "@entro314labs/entro-auth/oauth2";
2
+ import { isLoopbackHost } from "@entro314labs/entro-auth-core/utils/host";
3
+ import { createResourceServerChallenge, getIssuer, metadataResponse, oauthProvider } from "@entro314labs/entro-auth-oauth-provider";
4
+ import { getAcceptedIssuers, getLocalIntrospection, getLocalJwksSource, withExposedHeaders } from "@entro314labs/entro-auth-oauth-provider/internal";
5
+ // src/handler.ts
6
+ /**
7
+ * Validates the canonical protected-resource identifier accepted by MCP.
8
+ *
9
+ * @internal
10
+ */
11
+ function validateMcpResource(resource) {
12
+ if (typeof resource !== "string") throw new TypeError("MCP resource must be a single URL string");
13
+ let url;
14
+ try {
15
+ url = new URL(resource);
16
+ } catch {
17
+ throw new TypeError("MCP resource must be an absolute URL");
18
+ }
19
+ if (url.username || url.password) throw new TypeError("MCP resource URL must not contain credentials");
20
+ if (resource.includes("#")) throw new TypeError("MCP resource URL must not contain a fragment");
21
+ if (resource.includes("?")) throw new TypeError("MCP resource URL must not contain a query; to protect a query-carrying resource, verify tokens with verifyAccessTokenRequest and build challenges with createResourceServerChallenge");
22
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname))) throw new TypeError("MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs");
23
+ return resource;
24
+ }
25
+ /**
26
+ * Returns `response` with the next DPoP nonce (RFC 9449 §8.2). The response
27
+ * gets `Cache-Control: no-store`, overriding the handler's policy, because a
28
+ * cached copy would hand clients the nonce after it expires. The headers are copied
29
+ * because a handler's `Response` may have immutable headers.
30
+ */
31
+ async function withNextDpopNonce(response, secret) {
32
+ const headers = new Headers(response.headers);
33
+ headers.set("Cache-Control", "no-store");
34
+ headers.set(DPOP_NONCE_HEADER, await createDpopNonce({ secret }));
35
+ headers.set("Access-Control-Expose-Headers", withExposedHeaders(headers.get("access-control-expose-headers"), DPOP_NONCE_HEADER));
36
+ return new Response(response.body, {
37
+ status: response.status,
38
+ statusText: response.statusText,
39
+ headers
40
+ });
41
+ }
42
+ function toChallengeResponse(error, resource, opts) {
43
+ const challenge = createResourceServerChallenge(error, resource, opts);
44
+ if (!challenge) throw error;
45
+ const headers = new Headers(challenge.headers);
46
+ headers.set("Content-Type", "application/json");
47
+ return new Response(JSON.stringify({
48
+ jsonrpc: "2.0",
49
+ error: {
50
+ code: -32e3,
51
+ message: challenge.message
52
+ },
53
+ id: null
54
+ }), {
55
+ status: challenge.statusCode,
56
+ headers
57
+ });
58
+ }
59
+ /**
60
+ * A request middleware handler that verifies an MCP access token and responds
61
+ * with an RFC 9728 `WWW-Authenticate` header for unauthenticated requests.
62
+ * When `options.requiredScopes` is set, tokens missing a required scope receive
63
+ * a 403 with an RFC 6750 `insufficient_scope` challenge naming them instead.
64
+ *
65
+ * @external
66
+ */
67
+ const createMcpProtectedRequestHandler = (options, handler) => createProtectedRequestHandler(options, handler);
68
+ /**
69
+ * {@link createMcpProtectedRequestHandler} that can also read the
70
+ * authorization server's keys in-process.
71
+ *
72
+ * @internal
73
+ */
74
+ const createProtectedRequestHandler = (options, handler) => {
75
+ const resource = validateMcpResource(options.audience);
76
+ const resolvedChallengeOptions = {
77
+ challengeScopes: options.challengeScopes ?? options.requiredScopes,
78
+ dpopSigningAlgorithms: options.dpop?.signingAlgorithms
79
+ };
80
+ const accessTokenVerificationOptions = {
81
+ verifyOptions: {
82
+ ...options.jwtVerifyOptions,
83
+ issuer: options.issuer,
84
+ audience: options.audience
85
+ },
86
+ jwksUrl: options.jwksUrl,
87
+ jwksFetch: options.jwksFetch,
88
+ jwksCacheKey: options.jwksCacheKey,
89
+ introspect: options.introspect,
90
+ remoteVerify: options.remoteVerify,
91
+ requiredScopes: options.requiredScopes,
92
+ isScopeSatisfied: options.isScopeSatisfied,
93
+ dpop: options.dpop
94
+ };
95
+ return async (request) => {
96
+ let accessTokenClaims;
97
+ try {
98
+ accessTokenClaims = await verifyAccessTokenRequest(requestToResourceInput(request), accessTokenVerificationOptions);
99
+ } catch (error) {
100
+ return toChallengeResponse(error, resource, {
101
+ ...resolvedChallengeOptions,
102
+ request
103
+ });
104
+ }
105
+ let response;
106
+ try {
107
+ response = await handler(request, accessTokenClaims);
108
+ } catch (error) {
109
+ if (isInsufficientScopeError(error)) return toChallengeResponse(error, resource, {
110
+ ...resolvedChallengeOptions,
111
+ request
112
+ });
113
+ throw error;
114
+ }
115
+ const nonce = options.dpop?.nonce;
116
+ return nonce?.required && getDpopJktFromPayload(accessTokenClaims) ? withNextDpopNonce(response, nonce.secret) : response;
117
+ };
118
+ };
119
+ // src/plugin.ts
120
+ const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
121
+ const AUTHORIZATION_SERVER_ONLY_SCOPES = /* @__PURE__ */ new Set([
122
+ "openid",
123
+ "profile",
124
+ "email",
125
+ "phone",
126
+ "address",
127
+ "offline_access"
128
+ ]);
129
+ const resourceIdentifier = (resource) => typeof resource === "string" ? resource : resource.identifier;
130
+ const appendProtectedResource = (resources, resource) => {
131
+ const configuredResources = resources ?? [];
132
+ if (configuredResources.some((configuredResource) => resourceIdentifier(configuredResource) === resource)) return configuredResources;
133
+ return [...configuredResources, resource];
134
+ };
135
+ const appendResourceIdentifier = (resources, resource) => resources?.includes(resource) ? resources : [...resources ?? [], resource];
136
+ /**
137
+ * Build the RFC 9728 Protected Resource Metadata document. The MCP server is the
138
+ * resource server, and its authorization server is this same provider, so
139
+ * `authorization_servers` reuses the provider issuer. Resource metadata only
140
+ * advertises scopes that apply to the protected resource itself; OIDC identity
141
+ * scopes and refresh-token scopes stay authorization-server metadata.
142
+ */
143
+ const buildResourceServerMetadata = (ctx, providerOptions, resource) => {
144
+ const resourceScopes = (providerOptions.advertisedMetadata?.scopes_supported ?? providerOptions.scopes ?? []).filter((scope) => !AUTHORIZATION_SERVER_ONLY_SCOPES.has(scope));
145
+ const configuredResource = providerOptions.resources?.find((configuredResource) => resourceIdentifier(configuredResource) === resource);
146
+ const dpopBoundAccessTokensRequired = typeof configuredResource === "object" && configuredResource.dpopBoundAccessTokensRequired === true;
147
+ const metadata = {
148
+ resource,
149
+ authorization_servers: [getIssuer(ctx, providerOptions)],
150
+ bearer_methods_supported: ["header"],
151
+ dpop_signing_alg_values_supported: [...providerOptions.dpop?.signingAlgorithms ?? DPOP_SIGNING_ALGORITHMS]
152
+ };
153
+ if (dpopBoundAccessTokensRequired) metadata.dpop_bound_access_tokens_required = true;
154
+ if (resourceScopes.length) metadata.scopes_supported = [...resourceScopes];
155
+ return metadata;
156
+ };
157
+ /**
158
+ * Model Context Protocol authorization server.
159
+ *
160
+ * `mcp()` is the OAuth 2.1 / OIDC provider ({@link oauthProvider}) configured for
161
+ * MCP: it binds issued tokens to the MCP `resource`, links that resource to
162
+ * newly registered clients, and, as the resource server, serves the RFC 9728
163
+ * protected resource metadata so MCP clients discover and use it through
164
+ * standard OAuth discovery. Client registration is opt-in: compose with
165
+ * `cimd()` for Client ID Metadata Documents, or explicitly enable the OAuth
166
+ * Provider dynamic-registration options.
167
+ * It also defaults `refreshTokenReuseInterval` to 30 seconds for all MCP
168
+ * clients, allowing a retried refresh to recover a rotated response. OAuth
169
+ * Provider remains strict by default; set the MCP option to `0` to disable the
170
+ * overlap window.
171
+ * MCP 2026-07-28 pins Client ID Metadata Documents draft-00. Configure the
172
+ * CIMD plugin with `metadataProfile: "mcp-2026-07-28"` and an application-owned
173
+ * metadata-resource transport.
174
+ * Because it is the OAuth provider, it cannot be combined with a separate
175
+ * {@link oauthProvider}.
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * import { entroAuth } from "@entro314labs/entro-auth";
180
+ * import { jwt } from "@entro314labs/entro-auth/plugins";
181
+ * import { cimd } from "@entro314labs/entro-auth-cimd";
182
+ * import { mcp } from "@entro314labs/entro-auth-mcp";
183
+ * import { fetchClientMetadataResource } from "./oauth-network";
184
+ *
185
+ * export const auth = entroAuth({
186
+ * plugins: [
187
+ * jwt(),
188
+ * mcp({
189
+ * loginPage: "/login",
190
+ * consentPage: "/consent",
191
+ * resource: "https://api.example.com/mcp",
192
+ * }),
193
+ * cimd({
194
+ * fetchClientMetadataResource,
195
+ * metadataProfile: "mcp-2026-07-28",
196
+ * }),
197
+ * ],
198
+ * });
199
+ * ```
200
+ */
201
+ const mcp = (options) => {
202
+ const { resource: configuredResource, refreshTokenReuseInterval = 30, ...oauthOptions } = options;
203
+ const resource = validateMcpResource(configuredResource);
204
+ const provider = oauthProvider({
205
+ refreshTokenReuseInterval,
206
+ ...oauthOptions,
207
+ resources: appendProtectedResource(oauthOptions.resources, resource),
208
+ clientRegistrationDefaultResources: appendResourceIdentifier(oauthOptions.clientRegistrationDefaultResources, resource)
209
+ });
210
+ const serveProviderDiscovery = provider.onRequest;
211
+ return {
212
+ ...provider,
213
+ onRequest: async (request, ctx) => {
214
+ const handledByProvider = await serveProviderDiscovery?.(request, ctx);
215
+ if (handledByProvider) return handledByProvider;
216
+ const pathname = new URL(request.url).pathname;
217
+ const requestPath = ctx.options.advanced?.skipTrailingSlashes ? pathname.replace(/\/+$/, "") || "/" : pathname;
218
+ let resourcePath = "";
219
+ try {
220
+ resourcePath = new URL(resource).pathname.replace(/\/$/, "");
221
+ } catch {
222
+ resourcePath = "";
223
+ }
224
+ if (!(/* @__PURE__ */ new Set([PROTECTED_RESOURCE_METADATA_PATH, `${PROTECTED_RESOURCE_METADATA_PATH}${resourcePath}`])).has(requestPath)) return;
225
+ if (request.method !== "GET" && request.method !== "HEAD") return { response: new Response(null, {
226
+ status: 405,
227
+ headers: { Allow: "GET, HEAD" }
228
+ }) };
229
+ const response = metadataResponse(buildResourceServerMetadata({ context: ctx }, oauthOptions, resource));
230
+ if (request.method === "HEAD") return { response: new Response(null, {
231
+ status: response.status,
232
+ headers: response.headers
233
+ }) };
234
+ return { response };
235
+ }
236
+ };
237
+ };
238
+ // src/require-mcp-auth.ts
239
+ /** The OAuth provider's `dpop.nonce.expiresIn`, which `mcp()` passes through. */
240
+ function getProviderNonceExpiresIn(options) {
241
+ return (options.plugins?.find((plugin) => plugin.id === "oauth-provider"))?.options?.dpop?.nonce?.expiresIn;
242
+ }
243
+ /**
244
+ * Protects an MCP server route handler. Checks the bearer access token against
245
+ * the OAuth provider's records in-process (JWT or opaque; ended sessions,
246
+ * disabled clients, and revoked opaque tokens fail, and so do revoked JWTs
247
+ * with `revocableJwtAccessTokens`), verifies issuer, audience, and
248
+ * expiry, and forwards the token's claims to the handler. Their `sub` is the
249
+ * subject the token carries; a pairwise client's opaque token gets its
250
+ * pairwise subject.
251
+ * Unauthenticated requests receive a JSON-RPC 401 with the RFC 9728
252
+ * `WWW-Authenticate` header so MCP clients can start the authorization flow.
253
+ * Tokens missing a required scope receive a 403 with an RFC 6750
254
+ * `insufficient_scope` challenge naming the missing scopes, so clients can step
255
+ * up their authorization; a handler can raise the same challenge for scopes only
256
+ * it knows about by throwing `createInsufficientScopeError`.
257
+ *
258
+ * For a resource server that runs separately from the authorization server, or
259
+ * a server using a dynamic `baseURL`, use
260
+ * {@link createMcpProtectedRequestHandler} with explicit verification options
261
+ * instead.
262
+ *
263
+ * @external
264
+ */
265
+ const requireMcpAuth = (auth, handler, opts) => {
266
+ if (opts?.resource !== void 0) validateMcpResource(opts.resource);
267
+ return async (req) => {
268
+ const authContext = await auth.$context;
269
+ const { baseURL, secret } = authContext;
270
+ if (!baseURL) throw new Error("requireMcpAuth requires a resolvable base URL. For dynamic base URLs use `createMcpProtectedRequestHandler` with explicit verification options.");
271
+ const nonce = opts?.dpop?.nonce;
272
+ const nonceSecret = nonce?.secret ?? secret;
273
+ if (nonce?.required && !nonceSecret) throw new Error("requireMcpAuth requires dpop.nonce.secret when the auth context has no secret.");
274
+ const introspect = opts?.jwksUrl ? void 0 : getLocalIntrospection(authContext, req, { subject: "token" });
275
+ const jwtPlugin = authContext.getPlugin("jwt");
276
+ const localJwks = introspect || opts?.jwksUrl ? void 0 : getLocalJwksSource(authContext, req);
277
+ const issuerContext = authContext;
278
+ const issuer = opts?.issuer ?? (introspect || localJwks ? getAcceptedIssuers(issuerContext) : getIssuer({ context: issuerContext }));
279
+ const resource = opts?.resource ?? baseURL;
280
+ const jwksUrl = opts?.jwksUrl ?? jwtPlugin?.options?.jwks?.remoteUrl ?? `${baseURL}/jwks`;
281
+ return createProtectedRequestHandler({
282
+ ...localJwks,
283
+ introspect,
284
+ issuer,
285
+ audience: resource,
286
+ jwtVerifyOptions: { requiredClaims: ["azp"] },
287
+ requiredScopes: opts?.requiredScopes,
288
+ challengeScopes: opts?.challengeScopes,
289
+ isScopeSatisfied: opts?.isScopeSatisfied,
290
+ jwksUrl,
291
+ dpop: {
292
+ proofMaxAgeSeconds: opts?.dpop?.proofMaxAgeSeconds,
293
+ signingAlgorithms: opts?.dpop?.signingAlgorithms,
294
+ replayStore: opts?.dpop?.replayStore ?? createDpopReplayStore(authContext),
295
+ nonce: nonce && nonceSecret ? {
296
+ required: nonce.required,
297
+ expiresIn: nonce.expiresIn ?? getProviderNonceExpiresIn(auth.options),
298
+ secret: nonceSecret
299
+ } : void 0
300
+ }
301
+ }, handler)(req);
302
+ };
303
+ };
304
+ export { createMcpProtectedRequestHandler, mcp, requireMcpAuth };
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@entro314labs/entro-auth-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.8.0-beta.12",
4
+ "description": "Model Context Protocol (MCP) plugin for Entro Auth",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/entro314-labs/entro-auth#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/entro314-labs/entro-auth.git",
11
+ "directory": "packages/mcp"
12
+ },
13
+ "keywords": [
14
+ "mcp",
15
+ "model context protocol",
16
+ "auth",
17
+ "oauth",
18
+ "oidc",
19
+ "rfc9728",
20
+ "rfc8707",
21
+ "typescript",
22
+ "entro-auth"
23
+ ],
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "sideEffects": false,
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "main": "./dist/index.mjs",
32
+ "module": "./dist/index.mjs",
33
+ "types": "./dist/index.d.mts",
34
+ "exports": {
35
+ ".": {
36
+ "dev-source": "./src/index.ts",
37
+ "types": "./dist/index.d.mts",
38
+ "default": "./dist/index.mjs"
39
+ }
40
+ },
41
+ "typesVersions": {
42
+ "*": {
43
+ "*": [
44
+ "./dist/index.d.mts"
45
+ ]
46
+ }
47
+ },
48
+ "dependencies": {
49
+ "@entro314labs/entro-auth-oauth-provider": "^1.8.0-beta.12",
50
+ "jose": "^6.1.3"
51
+ },
52
+ "devDependencies": {
53
+ "@entro314labs/entro-auth-core": "1.8.0-beta.12",
54
+ "@modelcontextprotocol/client": "2.3.1",
55
+ "@modelcontextprotocol/server": "2.3.1",
56
+ "@entro314labs/entro-auth": "1.8.0-beta.12",
57
+ "better-call": "1.4.6",
58
+ "tsdown": "0.23.1"
59
+ },
60
+ "peerDependencies": {
61
+ "@entro314labs/entro-auth-core": "^1.8.0-beta.12",
62
+ "@entro314labs/entro-auth": "^1.8.0-beta.12",
63
+ "better-call": "~1.4.5"
64
+ },
65
+ "scripts": {
66
+ "build": "tsdown",
67
+ "dev": "tsdown --watch",
68
+ "lint:package": "publint run --strict --pack false",
69
+ "lint:types": "attw --profile esm-only --pack .",
70
+ "typecheck": "tsc --project tsconfig.json",
71
+ "test": "vitest",
72
+ "coverage": "vitest run --coverage --coverage.provider=istanbul"
73
+ }
6
74
  }