@payloadcms/plugin-mcp 4.0.0-internal.a2d053c → 4.0.0-internal.a5acc33

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.
Files changed (42) hide show
  1. package/dist/endpoint/access.d.ts.map +1 -1
  2. package/dist/endpoint/access.js +3 -23
  3. package/dist/endpoint/access.js.map +1 -1
  4. package/dist/endpoint/index.d.ts.map +1 -1
  5. package/dist/endpoint/index.js +0 -13
  6. package/dist/endpoint/index.js.map +1 -1
  7. package/dist/index.d.ts +2 -10
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -15
  10. package/dist/index.js.map +1 -1
  11. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  12. package/dist/mcp/sanitizeMCPConfig.js +0 -3
  13. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  14. package/dist/types.d.ts +0 -82
  15. package/dist/types.d.ts.map +1 -1
  16. package/dist/types.js.map +1 -1
  17. package/package.json +3 -3
  18. package/src/endpoint/access.ts +3 -22
  19. package/src/endpoint/index.ts +0 -8
  20. package/src/index.ts +4 -39
  21. package/src/mcp/sanitizeMCPConfig.ts +0 -1
  22. package/src/types.ts +0 -83
  23. package/dist/endpoint/oauth.d.ts +0 -39
  24. package/dist/endpoint/oauth.d.ts.map +0 -1
  25. package/dist/endpoint/oauth.js +0 -94
  26. package/dist/endpoint/oauth.js.map +0 -1
  27. package/dist/endpoint/oauthLoginToken.d.ts +0 -21
  28. package/dist/endpoint/oauthLoginToken.d.ts.map +0 -1
  29. package/dist/endpoint/oauthLoginToken.js +0 -79
  30. package/dist/endpoint/oauthLoginToken.js.map +0 -1
  31. package/dist/endpoint/oauthServer.d.ts +0 -12
  32. package/dist/endpoint/oauthServer.d.ts.map +0 -1
  33. package/dist/endpoint/oauthServer.js +0 -362
  34. package/dist/endpoint/oauthServer.js.map +0 -1
  35. package/dist/utils/seal.d.ts +0 -18
  36. package/dist/utils/seal.d.ts.map +0 -1
  37. package/dist/utils/seal.js +0 -27
  38. package/dist/utils/seal.js.map +0 -1
  39. package/src/endpoint/oauth.ts +0 -92
  40. package/src/endpoint/oauthLoginToken.ts +0 -91
  41. package/src/endpoint/oauthServer.ts +0 -396
  42. package/src/utils/seal.ts +0 -46
@@ -1,11 +1,10 @@
1
1
  import type { PayloadRequest, SanitizedPermissions } from 'payload'
2
2
 
3
- import { executeAuthStrategies, getAccessResults, UnauthorizedError } from 'payload'
3
+ import { getAccessResults, UnauthorizedError } from 'payload'
4
4
 
5
5
  import type { AuthorizedMCP, MCPItem } from '../types.js'
6
6
 
7
7
  import { getPluginConfig } from '../utils/getPluginConfig.js'
8
- import { authenticateLoginToken } from './oauthLoginToken.js'
9
8
 
10
9
  export type GetAuthorizedMCPArgs = {
11
10
  overrideAccess: boolean
@@ -35,27 +34,9 @@ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<Authorize
35
34
  const hasAuthorization = headers.has('Authorization')
36
35
 
37
36
  headers.set('DisableAutologin', 'true')
38
- // Not `payload.auth()`, which also computes permissions that filterMCPItems computes anyway
39
- req.user = (await executeAuthStrategies({ headers, payload: req.payload, req })).user
40
-
41
- // Only bearer tokens that no auth strategy accepted get here, e.g. an OAuth access token.
42
- // API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
43
- const bearerToken = headers.get('Authorization')?.match(/^Bearer (.+)$/)?.[1]
44
- // Sealed Payload login tokens from the built-in OAuth server
45
- if (
46
- !req.user &&
47
- bearerToken &&
48
- pluginConfig.oauth?.type === 'builtin' &&
49
- !pluginConfig.oauth.issueToken
50
- ) {
51
- req.user = await authenticateLoginToken({ req, token: bearerToken })
52
- }
53
- if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
54
- req.user = await pluginConfig.oauth.authenticate({ req, token: bearerToken })
55
- }
37
+ req.user = (await req.payload.auth({ headers, req })).user
56
38
 
57
- // With OAuth, the endpoint answers with a challenge that starts the client's sign-in
58
- if (hasAuthorization && !req.user && !pluginConfig.oauth) {
39
+ if (hasAuthorization && !req.user) {
59
40
  throw new UnauthorizedError(req.t)
60
41
  }
61
42
  }
@@ -11,7 +11,6 @@ import { APIError } from 'payload'
11
11
  import { buildMcpServer } from '../mcp/buildMcpServer.js'
12
12
  import { getPluginConfig } from '../utils/getPluginConfig.js'
13
13
  import { getAuthorizedMCP } from './access.js'
14
- import { getMCPResource, oauthChallenge } from './oauth.js'
15
14
 
16
15
  export const mcpEndpoint: PayloadHandler = async (req) => {
17
16
  if (!req.url) {
@@ -19,8 +18,6 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
19
18
  }
20
19
 
21
20
  req.payloadAPI = 'MCP' as const
22
- // Lets auth strategies check that an OAuth access token was issued for this MCP server
23
- req.context.mcp = { resource: getMCPResource({ config: req.payload.config, url: req.url }) }
24
21
 
25
22
  const pluginConfig = getPluginConfig({ config: req.payload.config })
26
23
  const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')
@@ -37,11 +34,6 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
37
34
  }
38
35
 
39
36
  const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
40
-
41
- if (pluginConfig.oauth && !req.user) {
42
- return oauthChallenge({ req })
43
- }
44
-
45
37
  const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
46
38
  // Payload augments the original web-standard Request in place.
47
39
  const mcpRequest = req as PayloadRequest & Request
package/src/index.ts CHANGED
@@ -1,18 +1,8 @@
1
1
  import { definePlugin } from 'payload'
2
2
 
3
- import type {
4
- AuthorizedMCP,
5
- MCPBuiltinOAuthConfig,
6
- MCPExternalOAuthConfig,
7
- MCPOAuthConfig,
8
- MCPOAuthTokens,
9
- MCPPluginConfig,
10
- SanitizedMCPPluginConfig,
11
- } from './types.js'
3
+ import type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'
12
4
 
13
5
  import { mcpEndpoint } from './endpoint/index.js'
14
- import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'
15
- import { oauthServerEndpoints } from './endpoint/oauthServer.js'
16
6
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
17
7
 
18
8
  declare module 'payload' {
@@ -23,27 +13,11 @@ declare module 'payload' {
23
13
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
24
14
  '@payloadcms/plugin-mcp': MCPPluginConfig
25
15
  }
26
- export interface RequestContext {
27
- /** Set on MCP requests before they're authenticated. */
28
- mcp?: {
29
- /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */
30
- resource: string
31
- }
32
- }
33
16
  }
34
17
 
35
- export type {
36
- AuthorizedMCP,
37
- MCPBuiltinOAuthConfig,
38
- MCPExternalOAuthConfig,
39
- MCPOAuthConfig,
40
- MCPOAuthTokens,
41
- MCPPluginConfig,
42
- SanitizedMCPPluginConfig,
43
- }
18
+ export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }
44
19
 
45
20
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'
46
- export { oauthProtectedResourceHandler } from './endpoint/oauth.js'
47
21
 
48
22
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
49
23
  slug: '@payloadcms/plugin-mcp',
@@ -66,24 +40,15 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
66
40
  ...config,
67
41
  endpoints: [
68
42
  ...(config.endpoints ?? []),
69
- // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the
70
- // request with dev auto-login turned off, so Payload doesn't authenticate it first.
71
- { disableAuth: true, handler: mcpEndpoint, method: 'post', path: '/mcp' },
43
+ // Payload prefixes /api, so the full path is /api/mcp.
44
+ { handler: mcpEndpoint, method: 'post', path: '/mcp' },
72
45
  // Streamable HTTP's optional server=>client GET stream. We don't offer
73
46
  // one, so answer 405 per spec-— clients then skip it cleanly
74
47
  {
75
- disableAuth: true,
76
48
  handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),
77
49
  method: 'get',
78
50
  path: '/mcp',
79
51
  },
80
- {
81
- disableAuth: true,
82
- handler: oauthProtectedResourceEndpoint,
83
- method: 'get',
84
- path: '/mcp/oauth-protected-resource',
85
- },
86
- ...oauthServerEndpoints,
87
52
  ],
88
53
  }
89
54
  },
@@ -103,7 +103,6 @@ export const sanitizeMCPConfig = ({
103
103
  hooks: pluginConfig.hooks,
104
104
  items,
105
105
  mcp: pluginConfig.mcp,
106
- oauth: pluginConfig.oauth === false ? undefined : (pluginConfig.oauth ?? { type: 'builtin' }),
107
106
  overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP,
108
107
  }
109
108
  }
package/src/types.ts CHANGED
@@ -290,14 +290,6 @@ export type MCPPluginConfig = {
290
290
  serverOptions?: MCPServerOptions
291
291
  verboseLogs?: boolean
292
292
  }
293
- /**
294
- * How MCP clients sign in. MCP requests without an authenticated user get a `401` that points
295
- * to the protected resource metadata (RFC 9728). Set to `false` to only accept API keys and
296
- * anonymous requests.
297
- *
298
- * @default { type: 'builtin' }
299
- */
300
- oauth?: false | MCPOAuthConfig
301
293
  /**
302
294
  * Replace the default MCP authorization resolver.
303
295
  *
@@ -315,83 +307,8 @@ export type MCPPluginConfig = {
315
307
  tools?: MCPTopLevelToolsMap
316
308
  }
317
309
 
318
- export type MCPOAuthConfig = MCPBuiltinOAuthConfig | MCPExternalOAuthConfig
319
-
320
- /**
321
- * This Payload app is the authorization server. Users sign in to the admin panel and allow the
322
- * MCP client, which then gets an access token for them.
323
- */
324
- export type MCPBuiltinOAuthConfig = {
325
- /**
326
- * Creates the tokens the MCP client gets when the user clicks Allow. `req` is the user's own
327
- * browser request, so `req.user` is the user who allowed it. Pass `authenticate` too if
328
- * Payload's auth strategies don't accept the access token.
329
- *
330
- * @default a Payload login token for that user that only works for MCP, with a refresh token when
331
- * the collection uses sessions
332
- */
333
- issueToken?: (args: { req: PayloadRequest }) => MaybePromise<MCPOAuthTokens>
334
- /**
335
- * Trades a refresh token from `issueToken`, or from an earlier refresh, for new tokens. Return
336
- * `null` when it's no longer valid, and the client sends the user through sign-in again. `req`
337
- * is the MCP client's request, without a user. Only used together with `issueToken`.
338
- *
339
- * OAuth requires noticing copied refresh tokens: return a new refresh token every time, and
340
- * revoke the tokens when an already used refresh token comes back.
341
- */
342
- refreshToken?: (args: {
343
- refreshToken: string
344
- req: PayloadRequest
345
- }) => MaybePromise<MCPOAuthTokens | null>
346
- type: 'builtin'
347
- } & MCPOAuthSharedConfig
348
-
349
- export type MCPOAuthTokens = {
350
- accessToken: string
351
- /** Seconds until the access token expires. */
352
- expiresIn?: number
353
- /** Lets the client get new tokens without the user, through `refreshToken`. */
354
- refreshToken?: string
355
- }
356
-
357
- /** Another service, e.g. your identity provider, is the authorization server. */
358
- export type MCPExternalOAuthConfig = {
359
- /**
360
- * The authorization servers that issue access tokens for MCP clients. Clients require each one
361
- * to exactly match the `issuer` in that server's metadata, so pass a function when the exact
362
- * value is only known at runtime, e.g. from the server's OpenID configuration or per host.
363
- */
364
- authorizationServers: ((args: { req: PayloadRequest }) => MaybePromise<string[]>) | string[]
365
- /**
366
- * Scopes MCP clients should request, e.g. `['openid', 'email', 'profile']`. Without them,
367
- * clients request none, which some authorization servers reject or answer with a token that
368
- * doesn't identify the user.
369
- */
370
- scopes?: string[]
371
- type: 'external'
372
- } & MCPOAuthSharedConfig
373
-
374
- type MCPOAuthSharedConfig = {
375
- /**
376
- * Called on MCP requests with a bearer token that Payload's auth strategies didn't accept.
377
- * Return the Payload user, including its `collection`, or `null` to answer with the OAuth challenge.
378
- */
379
- authenticate?: (args: {
380
- req: PayloadRequest
381
- token: string
382
- }) => MaybePromise<PayloadRequest['user']>
383
- /**
384
- * The URL clients call to reach the MCP endpoint.
385
- *
386
- * @default the absolute URL of `/api/mcp`, based on `serverURL` or the request URL
387
- */
388
- resource?: string
389
- }
390
-
391
310
  export type SanitizedMCPPluginConfig = {
392
311
  items: MCPItem[]
393
- /** `undefined` when OAuth is turned off. */
394
- oauth?: MCPOAuthConfig
395
312
  } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>
396
313
 
397
314
  export type MCPServerOptions = {
@@ -1,39 +0,0 @@
1
- import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload';
2
- /**
3
- * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
4
- * The OAuth challenge links here, so MCP clients find the authorization server without setup.
5
- */
6
- export declare const oauthProtectedResourceEndpoint: PayloadHandler;
7
- /**
8
- * Serves the same metadata for clients that ignore the challenge's link and only look at
9
- * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
10
- * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
11
- *
12
- * ```ts
13
- * import config from '@payload-config'
14
- * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
15
- *
16
- * export const GET = oauthProtectedResourceHandler(config)
17
- * ```
18
- */
19
- export declare const oauthProtectedResourceHandler: (config: Promise<SanitizedConfig> | SanitizedConfig) => (request: Request) => Promise<Response>;
20
- /**
21
- * Answers an unauthenticated MCP request with a challenge linking to the protected resource
22
- * metadata, which starts the client's OAuth flow.
23
- */
24
- export declare const oauthChallenge: ({ req }: {
25
- req: PayloadRequest;
26
- }) => Response;
27
- /**
28
- * The MCP endpoint's address, as advertised in the metadata's `resource`. Clients send it when
29
- * they sign in, and authorization servers that support it put it in the access token's audience.
30
- */
31
- export declare const getMCPResource: ({ config, url }: {
32
- config: SanitizedConfig;
33
- url: string;
34
- }) => string;
35
- export declare const getMCPURL: ({ config, url }: {
36
- config: SanitizedConfig;
37
- url: string;
38
- }) => string;
39
- //# sourceMappingURL=oauth.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/endpoint/oauth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAW9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,EAAE,cAAsD,CAAA;AAEnG;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,6BAA6B,WAC/B,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,eACnC,OAAO,KAAG,OAAO,CAAC,QAAQ,CAGtC,CAAA;AAEN;;;GAGG;AACH,eAAO,MAAM,cAAc,YAAa;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,KAAG,QAcjE,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,oBAAqB;IAAE,MAAM,EAAE,eAAe,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,KAAG,MAChB,CAAA;AAE3E,eAAO,MAAM,SAAS,oBAAqB;IAAE,MAAM,EAAE,eAAe,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,KAAG,MACnB,CAAA"}
@@ -1,94 +0,0 @@
1
- import { bearerAuthChallengeResponse, OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';
2
- import { createPayloadRequest, getPayload } from 'payload';
3
- import { getPluginConfig } from '../utils/getPluginConfig.js';
4
- /**
5
- * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
6
- * The OAuth challenge links here, so MCP clients find the authorization server without setup.
7
- */ export const oauthProtectedResourceEndpoint = (req)=>getMetadataResponse({
8
- req
9
- });
10
- /**
11
- * Serves the same metadata for clients that ignore the challenge's link and only look at
12
- * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
13
- * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
14
- *
15
- * ```ts
16
- * import config from '@payload-config'
17
- * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
18
- *
19
- * export const GET = oauthProtectedResourceHandler(config)
20
- * ```
21
- */ export const oauthProtectedResourceHandler = (config)=>async (request)=>getMetadataResponse({
22
- req: await createPayloadRequest({
23
- payload: await getPayload({
24
- config
25
- }),
26
- req: request
27
- })
28
- });
29
- /**
30
- * Answers an unauthenticated MCP request with a challenge linking to the protected resource
31
- * metadata, which starts the client's OAuth flow.
32
- */ export const oauthChallenge = ({ req })=>{
33
- const { oauth } = getPluginConfig({
34
- config: req.payload.config
35
- });
36
- const response = bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')), {
37
- requiredScopes: oauth?.type === 'external' ? oauth.scopes : undefined,
38
- resourceMetadataUrl: `${getMCPURL({
39
- config: req.payload.config,
40
- url: req.url
41
- })}/oauth-protected-resource`
42
- });
43
- // Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them
44
- response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate');
45
- return response;
46
- };
47
- /**
48
- * The MCP endpoint's address, as advertised in the metadata's `resource`. Clients send it when
49
- * they sign in, and authorization servers that support it put it in the access token's audience.
50
- */ export const getMCPResource = ({ config, url })=>getPluginConfig({
51
- config
52
- }).oauth?.resource ?? getMCPURL({
53
- config,
54
- url
55
- });
56
- export const getMCPURL = ({ config, url })=>new URL(`${config.routes.api}/mcp`, config.serverURL || url).href;
57
- const getMetadataResponse = async ({ req })=>{
58
- const { config } = req.payload;
59
- const { oauth } = getPluginConfig({
60
- config
61
- });
62
- if (!oauth) {
63
- return new Response(null, {
64
- status: 404
65
- });
66
- }
67
- return Response.json({
68
- authorization_servers: oauth.type === 'builtin' ? [
69
- `${getMCPURL({
70
- config,
71
- url: req.url
72
- })}/oauth`
73
- ] : typeof oauth.authorizationServers === 'function' ? await oauth.authorizationServers({
74
- req
75
- }) : oauth.authorizationServers,
76
- bearer_methods_supported: [
77
- 'header'
78
- ],
79
- resource: getMCPResource({
80
- config,
81
- url: req.url
82
- }),
83
- scopes_supported: oauth.type === 'external' ? oauth.scopes : undefined
84
- }, // Public document, readable by browser-based MCP clients on any origin. Not cached, since
85
- // without `serverURL` its URLs come from the request.
86
- {
87
- headers: {
88
- 'Access-Control-Allow-Origin': '*',
89
- 'Cache-Control': 'no-store'
90
- }
91
- });
92
- };
93
-
94
- //# sourceMappingURL=oauth.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/endpoint/oauth.ts"],"sourcesContent":["import type { OAuthProtectedResourceMetadata } from '@modelcontextprotocol/server'\nimport type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'\n\nimport {\n bearerAuthChallengeResponse,\n OAuthError,\n OAuthErrorCode,\n} from '@modelcontextprotocol/server'\nimport { createPayloadRequest, getPayload } from 'payload'\n\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\n\n/**\n * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.\n * The OAuth challenge links here, so MCP clients find the authorization server without setup.\n */\nexport const oauthProtectedResourceEndpoint: PayloadHandler = (req) => getMetadataResponse({ req })\n\n/**\n * Serves the same metadata for clients that ignore the challenge's link and only look at\n * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at\n * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:\n *\n * ```ts\n * import config from '@payload-config'\n * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'\n *\n * export const GET = oauthProtectedResourceHandler(config)\n * ```\n */\nexport const oauthProtectedResourceHandler =\n (config: Promise<SanitizedConfig> | SanitizedConfig) =>\n async (request: Request): Promise<Response> =>\n getMetadataResponse({\n req: await createPayloadRequest({ payload: await getPayload({ config }), req: request }),\n })\n\n/**\n * Answers an unauthenticated MCP request with a challenge linking to the protected resource\n * metadata, which starts the client's OAuth flow.\n */\nexport const oauthChallenge = ({ req }: { req: PayloadRequest }): Response => {\n const { oauth } = getPluginConfig({ config: req.payload.config })\n const response = bearerAuthChallengeResponse(\n new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),\n {\n requiredScopes: oauth?.type === 'external' ? oauth.scopes : undefined,\n resourceMetadataUrl: `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth-protected-resource`,\n },\n )\n\n // Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them\n response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate')\n\n return response\n}\n\n/**\n * The MCP endpoint's address, as advertised in the metadata's `resource`. Clients send it when\n * they sign in, and authorization servers that support it put it in the access token's audience.\n */\nexport const getMCPResource = ({ config, url }: { config: SanitizedConfig; url: string }): string =>\n getPluginConfig({ config }).oauth?.resource ?? getMCPURL({ config, url })\n\nexport const getMCPURL = ({ config, url }: { config: SanitizedConfig; url: string }): string =>\n new URL(`${config.routes.api}/mcp`, config.serverURL || url).href\n\nconst getMetadataResponse = async ({ req }: { req: PayloadRequest }): Promise<Response> => {\n const { config } = req.payload\n const { oauth } = getPluginConfig({ config })\n\n if (!oauth) {\n return new Response(null, { status: 404 })\n }\n\n return Response.json(\n {\n authorization_servers:\n oauth.type === 'builtin'\n ? [`${getMCPURL({ config, url: req.url! })}/oauth`]\n : typeof oauth.authorizationServers === 'function'\n ? await oauth.authorizationServers({ req })\n : oauth.authorizationServers,\n bearer_methods_supported: ['header'],\n resource: getMCPResource({ config, url: req.url! }),\n scopes_supported: oauth.type === 'external' ? oauth.scopes : undefined,\n } satisfies OAuthProtectedResourceMetadata,\n // Public document, readable by browser-based MCP clients on any origin. Not cached, since\n // without `serverURL` its URLs come from the request.\n { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },\n )\n}\n"],"names":["bearerAuthChallengeResponse","OAuthError","OAuthErrorCode","createPayloadRequest","getPayload","getPluginConfig","oauthProtectedResourceEndpoint","req","getMetadataResponse","oauthProtectedResourceHandler","config","request","payload","oauthChallenge","oauth","response","InvalidToken","t","requiredScopes","type","scopes","undefined","resourceMetadataUrl","getMCPURL","url","headers","set","getMCPResource","resource","URL","routes","api","serverURL","href","Response","status","json","authorization_servers","authorizationServers","bearer_methods_supported","scopes_supported"],"mappings":"AAGA,SACEA,2BAA2B,EAC3BC,UAAU,EACVC,cAAc,QACT,+BAA8B;AACrC,SAASC,oBAAoB,EAAEC,UAAU,QAAQ,UAAS;AAE1D,SAASC,eAAe,QAAQ,8BAA6B;AAE7D;;;CAGC,GACD,OAAO,MAAMC,iCAAiD,CAACC,MAAQC,oBAAoB;QAAED;IAAI,GAAE;AAEnG;;;;;;;;;;;CAWC,GACD,OAAO,MAAME,gCACX,CAACC,SACD,OAAOC,UACLH,oBAAoB;YAClBD,KAAK,MAAMJ,qBAAqB;gBAAES,SAAS,MAAMR,WAAW;oBAAEM;gBAAO;gBAAIH,KAAKI;YAAQ;QACxF,GAAE;AAEN;;;CAGC,GACD,OAAO,MAAME,iBAAiB,CAAC,EAAEN,GAAG,EAA2B;IAC7D,MAAM,EAAEO,KAAK,EAAE,GAAGT,gBAAgB;QAAEK,QAAQH,IAAIK,OAAO,CAACF,MAAM;IAAC;IAC/D,MAAMK,WAAWf,4BACf,IAAIC,WAAWC,eAAec,YAAY,EAAET,IAAIU,CAAC,CAAC,wBAClD;QACEC,gBAAgBJ,OAAOK,SAAS,aAAaL,MAAMM,MAAM,GAAGC;QAC5DC,qBAAqB,GAAGC,UAAU;YAAEb,QAAQH,IAAIK,OAAO,CAACF,MAAM;YAAEc,KAAKjB,IAAIiB,GAAG;QAAE,GAAG,yBAAyB,CAAC;IAC7G;IAGF,+FAA+F;IAC/FT,SAASU,OAAO,CAACC,GAAG,CAAC,iCAAiC;IAEtD,OAAOX;AACT,EAAC;AAED;;;CAGC,GACD,OAAO,MAAMY,iBAAiB,CAAC,EAAEjB,MAAM,EAAEc,GAAG,EAA4C,GACtFnB,gBAAgB;QAAEK;IAAO,GAAGI,KAAK,EAAEc,YAAYL,UAAU;QAAEb;QAAQc;IAAI,GAAE;AAE3E,OAAO,MAAMD,YAAY,CAAC,EAAEb,MAAM,EAAEc,GAAG,EAA4C,GACjF,IAAIK,IAAI,GAAGnB,OAAOoB,MAAM,CAACC,GAAG,CAAC,IAAI,CAAC,EAAErB,OAAOsB,SAAS,IAAIR,KAAKS,IAAI,CAAA;AAEnE,MAAMzB,sBAAsB,OAAO,EAAED,GAAG,EAA2B;IACjE,MAAM,EAAEG,MAAM,EAAE,GAAGH,IAAIK,OAAO;IAC9B,MAAM,EAAEE,KAAK,EAAE,GAAGT,gBAAgB;QAAEK;IAAO;IAE3C,IAAI,CAACI,OAAO;QACV,OAAO,IAAIoB,SAAS,MAAM;YAAEC,QAAQ;QAAI;IAC1C;IAEA,OAAOD,SAASE,IAAI,CAClB;QACEC,uBACEvB,MAAMK,IAAI,KAAK,YACX;YAAC,GAAGI,UAAU;gBAAEb;gBAAQc,KAAKjB,IAAIiB,GAAG;YAAE,GAAG,MAAM,CAAC;SAAC,GACjD,OAAOV,MAAMwB,oBAAoB,KAAK,aACpC,MAAMxB,MAAMwB,oBAAoB,CAAC;YAAE/B;QAAI,KACvCO,MAAMwB,oBAAoB;QAClCC,0BAA0B;YAAC;SAAS;QACpCX,UAAUD,eAAe;YAAEjB;YAAQc,KAAKjB,IAAIiB,GAAG;QAAE;QACjDgB,kBAAkB1B,MAAMK,IAAI,KAAK,aAAaL,MAAMM,MAAM,GAAGC;IAC/D,GACA,0FAA0F;IAC1F,sDAAsD;IACtD;QAAEI,SAAS;YAAE,+BAA+B;YAAK,iBAAiB;QAAW;IAAE;AAEnF"}
@@ -1,21 +0,0 @@
1
- import type { PayloadRequest } from 'payload';
2
- import type { MCPOAuthTokens } from '../types.js';
3
- /**
4
- * The default `issueToken`: a Payload login token, sealed so it only works for MCP, where
5
- * `authenticateLoginToken` unseals it. Otherwise an MCP client could use it as the user's admin
6
- * panel login. When the collection uses sessions, the client also gets a refresh token.
7
- */
8
- export declare const issueLoginToken: ({ req, }: {
9
- req: PayloadRequest;
10
- }) => Promise<MCPOAuthTokens>;
11
- /** The default `refreshToken`. Payload logs out the session when a refresh token is reused. */
12
- export declare const refreshLoginToken: ({ refreshToken, req, }: {
13
- refreshToken: string;
14
- req: PayloadRequest;
15
- }) => Promise<MCPOAuthTokens | null>;
16
- /** Finds the user of an MCP request's access token from `issueLoginToken`. */
17
- export declare const authenticateLoginToken: ({ req, token, }: {
18
- req: PayloadRequest;
19
- token: string;
20
- }) => Promise<PayloadRequest['user']>;
21
- //# sourceMappingURL=oauthLoginToken.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"oauthLoginToken.d.ts","sourceRoot":"","sources":["../../src/endpoint/oauthLoginToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIjD;;;;GAIG;AACH,eAAO,MAAM,eAAe,aAEzB;IACD,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,cAAc,CA6BzB,CAAA;AAED,+FAA+F;AAC/F,eAAO,MAAM,iBAAiB,2BAG3B;IACD,YAAY,EAAE,MAAM,CAAA;IACpB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAUhC,CAAA;AAED,8EAA8E;AAC9E,eAAO,MAAM,sBAAsB,oBAGhC;IACD,GAAG,EAAE,cAAc,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;CACd,KAAG,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,CAajC,CAAA"}
@@ -1,79 +0,0 @@
1
- import { APIError, createAuthToken, executeAuthStrategies, redeemRefreshToken } from 'payload';
2
- import { seal, unseal } from '../utils/seal.js';
3
- /**
4
- * The default `issueToken`: a Payload login token, sealed so it only works for MCP, where
5
- * `authenticateLoginToken` unseals it. Otherwise an MCP client could use it as the user's admin
6
- * panel login. When the collection uses sessions, the client also gets a refresh token.
7
- */ export const issueLoginToken = async ({ req })=>{
8
- const collectionConfig = req.payload.collections[req.user.collection].config;
9
- if (collectionConfig.auth.disableLocalStrategy) {
10
- throw new APIError(`MCP clients can't get Payload login tokens for the "${collectionConfig.slug}" collection because its local strategy is disabled. Pass oauth.issueToken to the MCP plugin.`);
11
- }
12
- // The full document, like the one a password login starts its session on
13
- const user = await req.payload.db.findOne({
14
- collection: collectionConfig.slug,
15
- req,
16
- where: {
17
- id: {
18
- equals: req.user.id
19
- }
20
- }
21
- });
22
- const { refreshToken, token } = await createAuthToken({
23
- collectionConfig,
24
- email: user.email,
25
- req,
26
- shouldCreateRefreshToken: true,
27
- user
28
- });
29
- return {
30
- accessToken: sealLoginToken({
31
- req,
32
- token
33
- }),
34
- expiresIn: collectionConfig.auth.tokenExpiration,
35
- refreshToken
36
- };
37
- };
38
- /** The default `refreshToken`. Payload logs out the session when a refresh token is reused. */ export const refreshLoginToken = async ({ refreshToken, req })=>{
39
- const refreshed = await redeemRefreshToken({
40
- refreshToken,
41
- req
42
- });
43
- return refreshed && {
44
- accessToken: sealLoginToken({
45
- req,
46
- token: refreshed.token
47
- }),
48
- expiresIn: refreshed.collectionConfig.auth.tokenExpiration,
49
- refreshToken: refreshed.refreshToken
50
- };
51
- };
52
- /** Finds the user of an MCP request's access token from `issueLoginToken`. */ export const authenticateLoginToken = async ({ req, token })=>{
53
- const loginToken = unseal({
54
- type: 'access',
55
- req,
56
- value: token
57
- });
58
- if (!loginToken) {
59
- return null;
60
- }
61
- const headers = new Headers({
62
- Authorization: `JWT ${loginToken.token}`,
63
- DisableAutologin: 'true'
64
- });
65
- return (await executeAuthStrategies({
66
- headers,
67
- payload: req.payload,
68
- req
69
- })).user;
70
- };
71
- const sealLoginToken = ({ req, token })=>seal({
72
- type: 'access',
73
- data: {
74
- token
75
- },
76
- req
77
- });
78
-
79
- //# sourceMappingURL=oauthLoginToken.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/endpoint/oauthLoginToken.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { APIError, createAuthToken, executeAuthStrategies, redeemRefreshToken } from 'payload'\n\nimport type { MCPOAuthTokens } from '../types.js'\n\nimport { seal, unseal } from '../utils/seal.js'\n\n/**\n * The default `issueToken`: a Payload login token, sealed so it only works for MCP, where\n * `authenticateLoginToken` unseals it. Otherwise an MCP client could use it as the user's admin\n * panel login. When the collection uses sessions, the client also gets a refresh token.\n */\nexport const issueLoginToken = async ({\n req,\n}: {\n req: PayloadRequest\n}): Promise<MCPOAuthTokens> => {\n const collectionConfig = req.payload.collections[req.user!.collection]!.config\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new APIError(\n `MCP clients can't get Payload login tokens for the \"${collectionConfig.slug}\" collection because its local strategy is disabled. Pass oauth.issueToken to the MCP plugin.`,\n )\n }\n\n // The full document, like the one a password login starts its session on\n const user = (await req.payload.db.findOne<NonNullable<PayloadRequest['user']>>({\n collection: collectionConfig.slug,\n req,\n where: { id: { equals: req.user!.id } },\n }))!\n\n const { refreshToken, token } = await createAuthToken({\n collectionConfig,\n email: user.email!,\n req,\n shouldCreateRefreshToken: true,\n user,\n })\n\n return {\n accessToken: sealLoginToken({ req, token }),\n expiresIn: collectionConfig.auth.tokenExpiration,\n refreshToken,\n }\n}\n\n/** The default `refreshToken`. Payload logs out the session when a refresh token is reused. */\nexport const refreshLoginToken = async ({\n refreshToken,\n req,\n}: {\n refreshToken: string\n req: PayloadRequest\n}): Promise<MCPOAuthTokens | null> => {\n const refreshed = await redeemRefreshToken({ refreshToken, req })\n\n return (\n refreshed && {\n accessToken: sealLoginToken({ req, token: refreshed.token }),\n expiresIn: refreshed.collectionConfig.auth.tokenExpiration,\n refreshToken: refreshed.refreshToken,\n }\n )\n}\n\n/** Finds the user of an MCP request's access token from `issueLoginToken`. */\nexport const authenticateLoginToken = async ({\n req,\n token,\n}: {\n req: PayloadRequest\n token: string\n}): Promise<PayloadRequest['user']> => {\n const loginToken = unseal<{ token: string }>({ type: 'access', req, value: token })\n\n if (!loginToken) {\n return null\n }\n\n const headers = new Headers({\n Authorization: `JWT ${loginToken.token}`,\n DisableAutologin: 'true',\n })\n\n return (await executeAuthStrategies({ headers, payload: req.payload, req })).user\n}\n\nconst sealLoginToken = ({ req, token }: { req: PayloadRequest; token: string }): string =>\n seal({ type: 'access', data: { token }, req })\n"],"names":["APIError","createAuthToken","executeAuthStrategies","redeemRefreshToken","seal","unseal","issueLoginToken","req","collectionConfig","payload","collections","user","collection","config","auth","disableLocalStrategy","slug","db","findOne","where","id","equals","refreshToken","token","email","shouldCreateRefreshToken","accessToken","sealLoginToken","expiresIn","tokenExpiration","refreshLoginToken","refreshed","authenticateLoginToken","loginToken","type","value","headers","Headers","Authorization","DisableAutologin","data"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,eAAe,EAAEC,qBAAqB,EAAEC,kBAAkB,QAAQ,UAAS;AAI9F,SAASC,IAAI,EAAEC,MAAM,QAAQ,mBAAkB;AAE/C;;;;CAIC,GACD,OAAO,MAAMC,kBAAkB,OAAO,EACpCC,GAAG,EAGJ;IACC,MAAMC,mBAAmBD,IAAIE,OAAO,CAACC,WAAW,CAACH,IAAII,IAAI,CAAEC,UAAU,CAAC,CAAEC,MAAM;IAE9E,IAAIL,iBAAiBM,IAAI,CAACC,oBAAoB,EAAE;QAC9C,MAAM,IAAIf,SACR,CAAC,oDAAoD,EAAEQ,iBAAiBQ,IAAI,CAAC,6FAA6F,CAAC;IAE/K;IAEA,yEAAyE;IACzE,MAAML,OAAQ,MAAMJ,IAAIE,OAAO,CAACQ,EAAE,CAACC,OAAO,CAAsC;QAC9EN,YAAYJ,iBAAiBQ,IAAI;QACjCT;QACAY,OAAO;YAAEC,IAAI;gBAAEC,QAAQd,IAAII,IAAI,CAAES,EAAE;YAAC;QAAE;IACxC;IAEA,MAAM,EAAEE,YAAY,EAAEC,KAAK,EAAE,GAAG,MAAMtB,gBAAgB;QACpDO;QACAgB,OAAOb,KAAKa,KAAK;QACjBjB;QACAkB,0BAA0B;QAC1Bd;IACF;IAEA,OAAO;QACLe,aAAaC,eAAe;YAAEpB;YAAKgB;QAAM;QACzCK,WAAWpB,iBAAiBM,IAAI,CAACe,eAAe;QAChDP;IACF;AACF,EAAC;AAED,6FAA6F,GAC7F,OAAO,MAAMQ,oBAAoB,OAAO,EACtCR,YAAY,EACZf,GAAG,EAIJ;IACC,MAAMwB,YAAY,MAAM5B,mBAAmB;QAAEmB;QAAcf;IAAI;IAE/D,OACEwB,aAAa;QACXL,aAAaC,eAAe;YAAEpB;YAAKgB,OAAOQ,UAAUR,KAAK;QAAC;QAC1DK,WAAWG,UAAUvB,gBAAgB,CAACM,IAAI,CAACe,eAAe;QAC1DP,cAAcS,UAAUT,YAAY;IACtC;AAEJ,EAAC;AAED,4EAA4E,GAC5E,OAAO,MAAMU,yBAAyB,OAAO,EAC3CzB,GAAG,EACHgB,KAAK,EAIN;IACC,MAAMU,aAAa5B,OAA0B;QAAE6B,MAAM;QAAU3B;QAAK4B,OAAOZ;IAAM;IAEjF,IAAI,CAACU,YAAY;QACf,OAAO;IACT;IAEA,MAAMG,UAAU,IAAIC,QAAQ;QAC1BC,eAAe,CAAC,IAAI,EAAEL,WAAWV,KAAK,EAAE;QACxCgB,kBAAkB;IACpB;IAEA,OAAO,AAAC,CAAA,MAAMrC,sBAAsB;QAAEkC;QAAS3B,SAASF,IAAIE,OAAO;QAAEF;IAAI,EAAC,EAAGI,IAAI;AACnF,EAAC;AAED,MAAMgB,iBAAiB,CAAC,EAAEpB,GAAG,EAAEgB,KAAK,EAA0C,GAC5EnB,KAAK;QAAE8B,MAAM;QAAUM,MAAM;YAAEjB;QAAM;QAAGhB;IAAI"}
@@ -1,12 +0,0 @@
1
- import type { Endpoint } from 'payload';
2
- /**
3
- * Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is
4
- * `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and
5
- * the client receives the tokens `issueToken` creates.
6
- *
7
- * Clients, consent forms, authorization codes, and refresh tokens are encrypted and handed to the
8
- * client instead of being stored. Only the default tokens write to the database, to the user's
9
- * login sessions.
10
- */
11
- export declare const oauthServerEndpoints: Endpoint[];
12
- //# sourceMappingURL=oauthServer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"oauthServer.d.ts","sourceRoot":"","sources":["../../src/endpoint/oauthServer.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,QAAQ,EAAkC,MAAM,SAAS,CAAA;AAoCvE;;;;;;;;GAQG;AACH,eAAO,MAAM,oBAAoB,EAAE,QAAQ,EAqC1C,CAAA"}