@payloadcms/plugin-mcp 4.0.0-beta.6 → 4.0.0-beta.8

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 (69) hide show
  1. package/dist/endpoint/access.d.ts +5 -0
  2. package/dist/endpoint/access.d.ts.map +1 -1
  3. package/dist/endpoint/access.js +42 -5
  4. package/dist/endpoint/access.js.map +1 -1
  5. package/dist/endpoint/index.d.ts.map +1 -1
  6. package/dist/endpoint/index.js +25 -0
  7. package/dist/endpoint/index.js.map +1 -1
  8. package/dist/endpoint/oauth.d.ts +37 -0
  9. package/dist/endpoint/oauth.d.ts.map +1 -0
  10. package/dist/endpoint/oauth.js +105 -0
  11. package/dist/endpoint/oauth.js.map +1 -0
  12. package/dist/endpoint/oauthLoginToken.d.ts +23 -0
  13. package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
  14. package/dist/endpoint/oauthLoginToken.js +80 -0
  15. package/dist/endpoint/oauthLoginToken.js.map +1 -0
  16. package/dist/endpoint/oauthServer.d.ts +28 -0
  17. package/dist/endpoint/oauthServer.d.ts.map +1 -0
  18. package/dist/endpoint/oauthServer.js +423 -0
  19. package/dist/endpoint/oauthServer.js.map +1 -0
  20. package/dist/exports/client.d.ts +1 -1
  21. package/dist/exports/client.d.ts.map +1 -1
  22. package/dist/exports/client.js +1 -1
  23. package/dist/exports/client.js.map +1 -1
  24. package/dist/exports/rsc.d.ts +2 -0
  25. package/dist/exports/rsc.d.ts.map +1 -0
  26. package/dist/exports/rsc.js +3 -0
  27. package/dist/exports/rsc.js.map +1 -0
  28. package/dist/index.d.ts +10 -2
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +34 -10
  31. package/dist/index.js.map +1 -1
  32. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  33. package/dist/mcp/builtin/collections/deleteTool.js +3 -1
  34. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  35. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  36. package/dist/mcp/sanitizeMCPConfig.js +3 -0
  37. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  38. package/dist/types.d.ts +95 -0
  39. package/dist/types.d.ts.map +1 -1
  40. package/dist/types.js.map +1 -1
  41. package/dist/utils/seal.d.ts +17 -0
  42. package/dist/utils/seal.d.ts.map +1 -0
  43. package/dist/utils/seal.js +24 -0
  44. package/dist/utils/seal.js.map +1 -0
  45. package/dist/views/Authorize/AllowButtons/index.d.ts +18 -0
  46. package/dist/views/Authorize/AllowButtons/index.d.ts.map +1 -0
  47. package/dist/views/Authorize/AllowButtons/index.js +88 -0
  48. package/dist/views/Authorize/AllowButtons/index.js.map +1 -0
  49. package/dist/views/Authorize/index.css +19 -0
  50. package/dist/views/Authorize/index.d.ts +9 -0
  51. package/dist/views/Authorize/index.d.ts.map +1 -0
  52. package/dist/views/Authorize/index.js +86 -0
  53. package/dist/views/Authorize/index.js.map +1 -0
  54. package/package.json +10 -3
  55. package/src/endpoint/access.ts +45 -3
  56. package/src/endpoint/index.ts +17 -1
  57. package/src/endpoint/oauth.ts +108 -0
  58. package/src/endpoint/oauthLoginToken.ts +94 -0
  59. package/src/endpoint/oauthServer.ts +452 -0
  60. package/src/exports/client.ts +1 -1
  61. package/src/exports/rsc.ts +1 -0
  62. package/src/index.ts +52 -8
  63. package/src/mcp/builtin/collections/deleteTool.ts +3 -1
  64. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  65. package/src/types.ts +94 -0
  66. package/src/utils/seal.ts +46 -0
  67. package/src/views/Authorize/AllowButtons/index.tsx +97 -0
  68. package/src/views/Authorize/index.css +19 -0
  69. package/src/views/Authorize/index.tsx +93 -0
@@ -0,0 +1,86 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { FormHeader, Logo, MinimalTemplate } from '@payloadcms/ui/rsc';
3
+ import { formatAdminURL } from 'payload/shared';
4
+ import React from 'react';
5
+ // eslint-disable-next-line payload/no-imports-from-exports-dir -- Server component must reference exports dir for proper client boundary
6
+ import { AllowButtons } from '../../exports/client.js';
7
+ import { unseal } from '../../utils/seal.js';
8
+ import './index.css';
9
+ const baseClass = 'mcp-authorize';
10
+ const errorTitles = {
11
+ expired: 'This sign-in request expired',
12
+ 'invalid-link': 'This sign-in link is invalid'
13
+ };
14
+ /**
15
+ * The admin page where users allow an MCP client to use their account, for the built-in OAuth
16
+ * server. Its authorize endpoint sends users here with the consent to show, or with an error.
17
+ */ export function MCPAuthorizeView({ initPageResult, params, searchParams, server, user }) {
18
+ const { locale, permissions, req } = initPageResult;
19
+ const { i18n, payload } = req;
20
+ const sealedConsent = getSearchParam(searchParams?.consent);
21
+ const consent = unseal({
22
+ type: 'consent',
23
+ req,
24
+ value: sealedConsent
25
+ });
26
+ const client = consent && unseal({
27
+ type: 'client',
28
+ req,
29
+ value: consent.clientID
30
+ });
31
+ // The consent is only valid for the user it was made for
32
+ const isConsentValid = client && consent && req.user?.id === consent.userID && req.user.collection === consent.collection;
33
+ const error = getSearchParam(searchParams?.error) === 'invalid-link' ? 'invalid-link' : 'expired';
34
+ const account = String(user?.email ?? consent?.userID);
35
+ const returnHost = consent && (new URL(consent.redirectURI).host || consent.redirectURI);
36
+ return /*#__PURE__*/ _jsxs(MinimalTemplate, {
37
+ className: baseClass,
38
+ children: [
39
+ /*#__PURE__*/ _jsx("div", {
40
+ className: `${baseClass}__brand`,
41
+ children: /*#__PURE__*/ _jsx(Logo, {
42
+ i18n: i18n,
43
+ locale: locale,
44
+ params: params,
45
+ payload: payload,
46
+ permissions: permissions,
47
+ searchParams: searchParams,
48
+ server: server,
49
+ user: user
50
+ })
51
+ }),
52
+ /*#__PURE__*/ _jsx("div", {
53
+ lang: "en",
54
+ children: isConsentValid ? /*#__PURE__*/ _jsxs(_Fragment, {
55
+ children: [
56
+ /*#__PURE__*/ _jsx(FormHeader, {
57
+ description: `It will be able to use this app's MCP tools as ${account}, and you will return to ${returnHost}.`,
58
+ heading: `Allow ${client.name} to use your account?`
59
+ }),
60
+ /*#__PURE__*/ _jsxs("form", {
61
+ action: formatAdminURL({
62
+ apiRoute: payload.config.routes.api,
63
+ path: '/mcp/oauth/authorize'
64
+ }),
65
+ method: "post",
66
+ children: [
67
+ /*#__PURE__*/ _jsx("input", {
68
+ name: "consent",
69
+ type: "hidden",
70
+ value: sealedConsent
71
+ }),
72
+ /*#__PURE__*/ _jsx(AllowButtons, {})
73
+ ]
74
+ })
75
+ ]
76
+ }) : /*#__PURE__*/ _jsx(FormHeader, {
77
+ description: "Start the sign-in again from your MCP client.",
78
+ heading: errorTitles[error]
79
+ })
80
+ })
81
+ ]
82
+ });
83
+ }
84
+ const getSearchParam = (value)=>typeof value === 'string' ? value : null;
85
+
86
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/views/Authorize/index.tsx"],"sourcesContent":["import type { AdminViewServerProps } from 'payload'\n\nimport { FormHeader, Logo, MinimalTemplate } from '@payloadcms/ui/rsc'\nimport { formatAdminURL } from 'payload/shared'\nimport React from 'react'\n\nimport type { AuthorizeViewError, Client, Consent } from '../../endpoint/oauthServer.js'\n\n// eslint-disable-next-line payload/no-imports-from-exports-dir -- Server component must reference exports dir for proper client boundary\nimport { AllowButtons } from '../../exports/client.js'\nimport { unseal } from '../../utils/seal.js'\nimport './index.css'\n\nconst baseClass = 'mcp-authorize'\n\nconst errorTitles: Record<AuthorizeViewError, string> = {\n expired: 'This sign-in request expired',\n 'invalid-link': 'This sign-in link is invalid',\n}\n\n/**\n * The admin page where users allow an MCP client to use their account, for the built-in OAuth\n * server. Its authorize endpoint sends users here with the consent to show, or with an error.\n */\nexport function MCPAuthorizeView({\n initPageResult,\n params,\n searchParams,\n server,\n user,\n}: AdminViewServerProps) {\n const { locale, permissions, req } = initPageResult\n const { i18n, payload } = req\n const sealedConsent = getSearchParam(searchParams?.consent)\n const consent = unseal<Consent>({ type: 'consent', req, value: sealedConsent })\n const client = consent && unseal<Client>({ type: 'client', req, value: consent.clientID })\n // The consent is only valid for the user it was made for\n const isConsentValid =\n client &&\n consent &&\n req.user?.id === consent.userID &&\n req.user.collection === consent.collection\n const error: AuthorizeViewError =\n getSearchParam(searchParams?.error) === 'invalid-link' ? 'invalid-link' : 'expired'\n const account = String(user?.email ?? consent?.userID)\n const returnHost = consent && (new URL(consent.redirectURI).host || consent.redirectURI)\n\n return (\n <MinimalTemplate className={baseClass}>\n <div className={`${baseClass}__brand`}>\n <Logo\n i18n={i18n}\n locale={locale}\n params={params}\n payload={payload}\n permissions={permissions}\n searchParams={searchParams}\n server={server}\n user={user}\n />\n </div>\n {/* Not translated yet, so screen readers in other admin languages read it as English */}\n <div lang=\"en\">\n {isConsentValid ? (\n <>\n <FormHeader\n description={`It will be able to use this app's MCP tools as ${account}, and you will return to ${returnHost}.`}\n heading={`Allow ${client.name} to use your account?`}\n />\n <form\n action={formatAdminURL({\n apiRoute: payload.config.routes.api,\n path: '/mcp/oauth/authorize',\n })}\n method=\"post\"\n >\n <input name=\"consent\" type=\"hidden\" value={sealedConsent!} />\n <AllowButtons />\n </form>\n </>\n ) : (\n <FormHeader\n description=\"Start the sign-in again from your MCP client.\"\n heading={errorTitles[error]}\n />\n )}\n </div>\n </MinimalTemplate>\n )\n}\n\nconst getSearchParam = (value: string | string[] | undefined): null | string =>\n typeof value === 'string' ? value : null\n"],"names":["FormHeader","Logo","MinimalTemplate","formatAdminURL","React","AllowButtons","unseal","baseClass","errorTitles","expired","MCPAuthorizeView","initPageResult","params","searchParams","server","user","locale","permissions","req","i18n","payload","sealedConsent","getSearchParam","consent","type","value","client","clientID","isConsentValid","id","userID","collection","error","account","String","email","returnHost","URL","redirectURI","host","className","div","lang","description","heading","name","form","action","apiRoute","config","routes","api","path","method","input"],"mappings":";AAEA,SAASA,UAAU,EAAEC,IAAI,EAAEC,eAAe,QAAQ,qBAAoB;AACtE,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,OAAOC,WAAW,QAAO;AAIzB,yIAAyI;AACzI,SAASC,YAAY,QAAQ,0BAAyB;AACtD,SAASC,MAAM,QAAQ,sBAAqB;AAC5C,OAAO,cAAa;AAEpB,MAAMC,YAAY;AAElB,MAAMC,cAAkD;IACtDC,SAAS;IACT,gBAAgB;AAClB;AAEA;;;CAGC,GACD,OAAO,SAASC,iBAAiB,EAC/BC,cAAc,EACdC,MAAM,EACNC,YAAY,EACZC,MAAM,EACNC,IAAI,EACiB;IACrB,MAAM,EAAEC,MAAM,EAAEC,WAAW,EAAEC,GAAG,EAAE,GAAGP;IACrC,MAAM,EAAEQ,IAAI,EAAEC,OAAO,EAAE,GAAGF;IAC1B,MAAMG,gBAAgBC,eAAeT,cAAcU;IACnD,MAAMA,UAAUjB,OAAgB;QAAEkB,MAAM;QAAWN;QAAKO,OAAOJ;IAAc;IAC7E,MAAMK,SAASH,WAAWjB,OAAe;QAAEkB,MAAM;QAAUN;QAAKO,OAAOF,QAAQI,QAAQ;IAAC;IACxF,yDAAyD;IACzD,MAAMC,iBACJF,UACAH,WACAL,IAAIH,IAAI,EAAEc,OAAON,QAAQO,MAAM,IAC/BZ,IAAIH,IAAI,CAACgB,UAAU,KAAKR,QAAQQ,UAAU;IAC5C,MAAMC,QACJV,eAAeT,cAAcmB,WAAW,iBAAiB,iBAAiB;IAC5E,MAAMC,UAAUC,OAAOnB,MAAMoB,SAASZ,SAASO;IAC/C,MAAMM,aAAab,WAAY,CAAA,IAAIc,IAAId,QAAQe,WAAW,EAAEC,IAAI,IAAIhB,QAAQe,WAAW,AAAD;IAEtF,qBACE,MAACpC;QAAgBsC,WAAWjC;;0BAC1B,KAACkC;gBAAID,WAAW,GAAGjC,UAAU,OAAO,CAAC;0BACnC,cAAA,KAACN;oBACCkB,MAAMA;oBACNH,QAAQA;oBACRJ,QAAQA;oBACRQ,SAASA;oBACTH,aAAaA;oBACbJ,cAAcA;oBACdC,QAAQA;oBACRC,MAAMA;;;0BAIV,KAAC0B;gBAAIC,MAAK;0BACPd,+BACC;;sCACE,KAAC5B;4BACC2C,aAAa,CAAC,+CAA+C,EAAEV,QAAQ,yBAAyB,EAAEG,WAAW,CAAC,CAAC;4BAC/GQ,SAAS,CAAC,MAAM,EAAElB,OAAOmB,IAAI,CAAC,qBAAqB,CAAC;;sCAEtD,MAACC;4BACCC,QAAQ5C,eAAe;gCACrB6C,UAAU5B,QAAQ6B,MAAM,CAACC,MAAM,CAACC,GAAG;gCACnCC,MAAM;4BACR;4BACAC,QAAO;;8CAEP,KAACC;oCAAMT,MAAK;oCAAUrB,MAAK;oCAASC,OAAOJ;;8CAC3C,KAAChB;;;;mCAIL,KAACL;oBACC2C,aAAY;oBACZC,SAASpC,WAAW,CAACwB,MAAM;;;;;AAMvC;AAEA,MAAMV,iBAAiB,CAACG,QACtB,OAAOA,UAAU,WAAWA,QAAQ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "4.0.0-beta.6",
3
+ "version": "4.0.0-beta.8",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
6
  "mcp",
@@ -52,6 +52,11 @@
52
52
  "import": "./dist/exports/internal.js",
53
53
  "types": "./dist/exports/internal.d.ts",
54
54
  "default": "./dist/exports/internal.js"
55
+ },
56
+ "./rsc": {
57
+ "import": "./dist/exports/rsc.js",
58
+ "types": "./dist/exports/rsc.d.ts",
59
+ "default": "./dist/exports/rsc.js"
55
60
  }
56
61
  },
57
62
  "dependencies": {
@@ -59,10 +64,12 @@
59
64
  "tsx": "4.23.15"
60
65
  },
61
66
  "devDependencies": {
62
- "payload": "4.0.0-beta.6"
67
+ "@payloadcms/ui": "4.0.0-beta.8",
68
+ "payload": "4.0.0-beta.8"
63
69
  },
64
70
  "peerDependencies": {
65
- "payload": "4.0.0-beta.6"
71
+ "@payloadcms/ui": "4.0.0-beta.8",
72
+ "payload": "4.0.0-beta.8"
66
73
  },
67
74
  "//deps_notes": {
68
75
  "tsx": "Required by the `bin.js` stdio mcp. Keep the version pinned to whatever `payload` ships to avoid duplicate installs."
@@ -1,12 +1,19 @@
1
1
  import type { PayloadRequest, SanitizedPermissions } from 'payload'
2
2
 
3
- import { getAccessResults, UnauthorizedError } from 'payload'
3
+ import { executeAuthStrategies, getAccessResults, UnauthorizedError } from 'payload'
4
+ import { extractBearerToken } from 'payload/shared'
4
5
 
5
6
  import type { AuthorizedMCP, MCPItem } from '../types.js'
6
7
 
7
8
  import { getPluginConfig } from '../utils/getPluginConfig.js'
9
+ import { authenticateLoginToken } from './oauthLoginToken.js'
8
10
 
9
11
  export type GetAuthorizedMCPArgs = {
12
+ /**
13
+ * Whether the request came through the HTTP endpoint, whose response can carry the OAuth
14
+ * challenge and headers from auth strategies. stdio has no response to carry them.
15
+ */
16
+ isHTTP?: boolean
10
17
  overrideAccess: boolean
11
18
  req: PayloadRequest
12
19
  }
@@ -16,10 +23,12 @@ export type GetAuthorizedMCPArgs = {
16
23
  * `overrideAccess` skips Payload and MCP item access checks.
17
24
  */
18
25
  export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP> = async ({
26
+ isHTTP = false,
19
27
  overrideAccess,
20
28
  req,
21
29
  }) => {
22
30
  const pluginConfig = getPluginConfig({ config: req.payload.config })
31
+ const isChallengedWhenSignedOut = isHTTP && Boolean(pluginConfig.oauth)
23
32
 
24
33
  if (pluginConfig.overrideGetAuthorizedMCP) {
25
34
  return await pluginConfig.overrideGetAuthorizedMCP({
@@ -34,13 +43,46 @@ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<Authorize
34
43
  const hasAuthorization = headers.has('Authorization')
35
44
 
36
45
  headers.set('DisableAutologin', 'true')
37
- req.user = (await req.payload.auth({ headers, req })).user
46
+ // Not `payload.auth()`, which also computes permissions that filterMCPItems computes anyway
47
+ const { responseHeaders, user } = await executeAuthStrategies({
48
+ canSetHeaders: isHTTP,
49
+ headers,
50
+ payload: req.payload,
51
+ req,
52
+ })
53
+ req.user = user
54
+ if (responseHeaders) {
55
+ req.responseHeaders = responseHeaders
56
+ }
57
+
58
+ // Only bearer tokens that no auth strategy accepted get here, e.g. an OAuth access token.
59
+ // API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
60
+ const bearerToken = extractBearerToken({ headers })
61
+ // Sealed Payload login tokens from the built-in OAuth server
62
+ if (
63
+ !req.user &&
64
+ bearerToken &&
65
+ pluginConfig.oauth?.type === 'builtin' &&
66
+ !pluginConfig.oauth.issueToken
67
+ ) {
68
+ req.user = await authenticateLoginToken({ req, token: bearerToken })
69
+ }
70
+ if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
71
+ req.user = await pluginConfig.oauth.authenticate({ req, token: bearerToken })
72
+ }
38
73
 
39
- if (hasAuthorization && !req.user) {
74
+ // With OAuth, the endpoint answers with a challenge that starts the client's sign-in
75
+ if (hasAuthorization && !req.user && !isChallengedWhenSignedOut) {
40
76
  throw new UnauthorizedError(req.t)
41
77
  }
42
78
  }
43
79
 
80
+ // Signed-out users only get the challenge, so they can't use any MCP items. Skipping the access
81
+ // checks saves work, and access callbacks only see signed-in users.
82
+ if (isChallengedWhenSignedOut && !req.user) {
83
+ return { items: [], overrideAccess }
84
+ }
85
+
44
86
  return {
45
87
  items: await filterMCPItems({
46
88
  items: pluginConfig.items,
@@ -11,6 +11,7 @@ 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'
14
15
 
15
16
  export const mcpEndpoint: PayloadHandler = async (req) => {
16
17
  if (!req.url) {
@@ -18,6 +19,8 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
18
19
  }
19
20
 
20
21
  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({ req }) }
21
24
 
22
25
  const pluginConfig = getPluginConfig({ config: req.payload.config })
23
26
  const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')
@@ -33,7 +36,20 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
33
36
  throw new APIError('MCP overrideAccess must be "true" or "false".', 400)
34
37
  }
35
38
 
36
- const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
39
+ const authorizedMCP = await getAuthorizedMCP({ isHTTP: true, overrideAccess, req })
40
+
41
+ // Clients like Codex send a GET first to find out where to sign in, so this comes before the
42
+ // GET check
43
+ if (pluginConfig.oauth && !req.user) {
44
+ return oauthChallenge({ req })
45
+ }
46
+
47
+ // Streamable HTTP's optional server-to-client stream. We don't offer one, so answer 405 per
48
+ // spec, and clients skip it
49
+ if (req.method === 'GET') {
50
+ return new Response(null, { headers: { Allow: 'POST' }, status: 405 })
51
+ }
52
+
37
53
  const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
38
54
  // Payload augments the original web-standard Request in place.
39
55
  const mcpRequest = req as PayloadRequest & Request
@@ -0,0 +1,108 @@
1
+ import type { OAuthProtectedResourceMetadata } from '@modelcontextprotocol/server'
2
+ import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'
3
+
4
+ import {
5
+ bearerAuthChallengeResponse,
6
+ OAuthError,
7
+ OAuthErrorCode,
8
+ } from '@modelcontextprotocol/server'
9
+ import { createPayloadRequest, getPayload } from 'payload'
10
+ import { formatAdminURL, stripTrailingSlash } from 'payload/shared'
11
+
12
+ import { getPluginConfig } from '../utils/getPluginConfig.js'
13
+
14
+ /**
15
+ * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
16
+ * The OAuth challenge links here, so MCP clients find the authorization server without setup.
17
+ */
18
+ export const oauthProtectedResourceEndpoint: PayloadHandler = (req) => getMetadataResponse({ req })
19
+
20
+ /**
21
+ * Serves the same metadata for clients that ignore the challenge's link and only look at
22
+ * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
23
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
24
+ *
25
+ * ```ts
26
+ * import config from '@payload-config'
27
+ * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
28
+ *
29
+ * export const GET = oauthProtectedResourceHandler({ config })
30
+ * ```
31
+ */
32
+ export const oauthProtectedResourceHandler =
33
+ ({ config }: { config: Promise<SanitizedConfig> | SanitizedConfig }) =>
34
+ async (request: Request): Promise<Response> =>
35
+ getMetadataResponse({
36
+ req: await createPayloadRequest({ payload: await getPayload({ config }), req: request }),
37
+ })
38
+
39
+ /**
40
+ * Answers an unauthenticated MCP request with a challenge linking to the protected resource
41
+ * metadata, which starts the client's OAuth flow.
42
+ */
43
+ export const oauthChallenge = ({ req }: { req: PayloadRequest }): Response => {
44
+ const { oauth } = getPluginConfig({ config: req.payload.config })
45
+ const response = bearerAuthChallengeResponse(
46
+ new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),
47
+ {
48
+ requiredScopes: oauth?.type === 'external' ? oauth.scopes : undefined,
49
+ resourceMetadataUrl: `${getMCPResource({ req })}/oauth-protected-resource`,
50
+ },
51
+ )
52
+
53
+ // Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them
54
+ response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate')
55
+
56
+ return response
57
+ }
58
+
59
+ /**
60
+ * The MCP endpoint's address, as advertised in the metadata's `resource`. The metadata link and
61
+ * the built-in authorization server's issuer are based on it. Clients send it when they sign in,
62
+ * and authorization servers that support it put it in the access token's audience.
63
+ */
64
+ export const getMCPResource = ({ req }: { req: PayloadRequest }): string => {
65
+ const { config } = req.payload
66
+ const resource = getPluginConfig({ config }).oauth?.resource
67
+
68
+ if (typeof resource === 'function') {
69
+ return resource({ req })
70
+ }
71
+
72
+ if (resource) {
73
+ return resource
74
+ }
75
+
76
+ // Without the slash Next.js's `trailingSlash` would add, since the metadata link appends to it
77
+ const path = stripTrailingSlash(formatAdminURL({ apiRoute: config.routes.api, path: '/mcp' }))
78
+
79
+ return new URL(path, config.serverURL || req.url).href
80
+ }
81
+
82
+ const getMetadataResponse = async ({ req }: { req: PayloadRequest }): Promise<Response> => {
83
+ const { config } = req.payload
84
+ const { oauth } = getPluginConfig({ config })
85
+
86
+ if (!oauth) {
87
+ return new Response(null, { status: 404 })
88
+ }
89
+
90
+ const resource = getMCPResource({ req })
91
+
92
+ return Response.json(
93
+ {
94
+ authorization_servers:
95
+ oauth.type === 'builtin'
96
+ ? [`${resource}/oauth`]
97
+ : typeof oauth.authorizationServers === 'function'
98
+ ? await oauth.authorizationServers({ req })
99
+ : oauth.authorizationServers,
100
+ bearer_methods_supported: ['header'],
101
+ resource,
102
+ scopes_supported: oauth.type === 'external' ? oauth.scopes : undefined,
103
+ } satisfies OAuthProtectedResourceMetadata,
104
+ // Public document, readable by browser-based MCP clients on any origin. Not cached, since its
105
+ // URLs can depend on the request.
106
+ { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },
107
+ )
108
+ }
@@ -0,0 +1,94 @@
1
+ import type { PayloadRequest } from 'payload'
2
+
3
+ import { APIError, createAuthToken, executeAuthStrategies, redeemRefreshToken } from 'payload'
4
+
5
+ import type { MCPOAuthTokens } from '../types.js'
6
+
7
+ import { seal, unseal } from '../utils/seal.js'
8
+
9
+ /**
10
+ * The default `issueToken`: a Payload login token, sealed so it only works for MCP, where
11
+ * `authenticateLoginToken` unseals it. Otherwise an MCP client could use it as the user's admin
12
+ * panel login. When the collection uses sessions, the client also gets a refresh token.
13
+ */
14
+ export const issueLoginToken = async ({
15
+ req,
16
+ }: {
17
+ req: PayloadRequest
18
+ }): Promise<MCPOAuthTokens> => {
19
+ const collectionConfig = req.payload.collections[req.user!.collection]!.config
20
+
21
+ if (collectionConfig.auth.disableLocalStrategy) {
22
+ throw new APIError(
23
+ `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.`,
24
+ )
25
+ }
26
+
27
+ // The full document, like the one a password login starts its session on
28
+ const user = (await req.payload.db.findOne<NonNullable<PayloadRequest['user']>>({
29
+ collection: collectionConfig.slug,
30
+ req,
31
+ where: { id: { equals: req.user!.id } },
32
+ }))!
33
+
34
+ const { refreshToken, token } = await createAuthToken({
35
+ collectionConfig,
36
+ email: user.email!,
37
+ req,
38
+ shouldCreateRefreshToken: true,
39
+ user,
40
+ })
41
+
42
+ return {
43
+ accessToken: sealLoginToken({ req, token }),
44
+ expiresIn: collectionConfig.auth.tokenExpiration,
45
+ refreshToken,
46
+ }
47
+ }
48
+
49
+ /** The default `refreshToken`. Payload logs out the session when a refresh token is reused. */
50
+ export const refreshLoginToken = async ({
51
+ refreshToken,
52
+ req,
53
+ reuseInterval,
54
+ }: {
55
+ refreshToken: string
56
+ req: PayloadRequest
57
+ /** See `redeemRefreshToken`. */
58
+ reuseInterval?: number
59
+ }): Promise<MCPOAuthTokens | null> => {
60
+ const refreshed = await redeemRefreshToken({ refreshToken, req, reuseInterval })
61
+
62
+ return (
63
+ refreshed && {
64
+ accessToken: sealLoginToken({ req, token: refreshed.token }),
65
+ expiresIn: refreshed.collectionConfig.auth.tokenExpiration,
66
+ refreshToken: refreshed.refreshToken,
67
+ }
68
+ )
69
+ }
70
+
71
+ /** Finds the user of an MCP request's access token from `issueLoginToken`. */
72
+ export const authenticateLoginToken = async ({
73
+ req,
74
+ token,
75
+ }: {
76
+ req: PayloadRequest
77
+ token: string
78
+ }): Promise<PayloadRequest['user']> => {
79
+ const loginToken = unseal<{ token: string }>({ type: 'access', req, value: token })
80
+
81
+ if (!loginToken) {
82
+ return null
83
+ }
84
+
85
+ const headers = new Headers({
86
+ Authorization: `JWT ${loginToken.token}`,
87
+ DisableAutologin: 'true',
88
+ })
89
+
90
+ return (await executeAuthStrategies({ headers, payload: req.payload, req })).user
91
+ }
92
+
93
+ const sealLoginToken = ({ req, token }: { req: PayloadRequest; token: string }): string =>
94
+ seal({ type: 'access', data: { token }, req })