@payloadcms/plugin-mcp 4.0.0-internal.f715c6e → 4.0.0-internal.f980c7c

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 (219) hide show
  1. package/bin.js +0 -7
  2. package/dist/endpoint/access.d.ts +5 -0
  3. package/dist/endpoint/access.d.ts.map +1 -1
  4. package/dist/endpoint/access.js +44 -7
  5. package/dist/endpoint/access.js.map +1 -1
  6. package/dist/endpoint/index.d.ts.map +1 -1
  7. package/dist/endpoint/index.js +58 -4
  8. package/dist/endpoint/index.js.map +1 -1
  9. package/dist/endpoint/oauth.d.ts +37 -0
  10. package/dist/endpoint/oauth.d.ts.map +1 -0
  11. package/dist/endpoint/oauth.js +105 -0
  12. package/dist/endpoint/oauth.js.map +1 -0
  13. package/dist/endpoint/oauthLoginToken.d.ts +23 -0
  14. package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
  15. package/dist/endpoint/oauthLoginToken.js +80 -0
  16. package/dist/endpoint/oauthLoginToken.js.map +1 -0
  17. package/dist/endpoint/oauthServer.d.ts +28 -0
  18. package/dist/endpoint/oauthServer.d.ts.map +1 -0
  19. package/dist/endpoint/oauthServer.js +423 -0
  20. package/dist/endpoint/oauthServer.js.map +1 -0
  21. package/dist/exports/client.d.ts +1 -1
  22. package/dist/exports/client.d.ts.map +1 -1
  23. package/dist/exports/client.js +1 -1
  24. package/dist/exports/client.js.map +1 -1
  25. package/dist/exports/rsc.d.ts +2 -0
  26. package/dist/exports/rsc.d.ts.map +1 -0
  27. package/dist/exports/rsc.js +3 -0
  28. package/dist/exports/rsc.js.map +1 -0
  29. package/dist/index.d.ts +10 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +34 -10
  32. package/dist/index.js.map +1 -1
  33. package/dist/mcp/buildMcpServer.d.ts +2 -2
  34. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  35. package/dist/mcp/buildMcpServer.js +36 -24
  36. package/dist/mcp/buildMcpServer.js.map +1 -1
  37. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  38. package/dist/mcp/builtin/collections/authTools.js +80 -56
  39. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  40. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  41. package/dist/mcp/builtin/collections/countTool.js +9 -14
  42. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  43. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  44. package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
  45. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  46. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  47. package/dist/mcp/builtin/collections/createTool.js +48 -49
  48. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  49. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  50. package/dist/mcp/builtin/collections/deleteTool.js +44 -43
  51. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  52. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  53. package/dist/mcp/builtin/collections/duplicateTool.js +31 -37
  54. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  55. package/dist/mcp/builtin/collections/fileInput.d.ts +21 -21
  56. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  57. package/dist/mcp/builtin/collections/fileInput.js +34 -70
  58. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  59. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  60. package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
  61. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  62. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  63. package/dist/mcp/builtin/collections/findTool.js +28 -46
  64. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  65. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  66. package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
  67. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  68. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  69. package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
  70. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  71. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  72. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +30 -14
  73. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  74. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  75. package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
  76. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  77. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  78. package/dist/mcp/builtin/collections/updateTool.js +55 -87
  79. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  80. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +11 -11
  81. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
  82. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  83. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  84. package/dist/mcp/builtin/formatEntityError.js +55 -0
  85. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  86. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  87. package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
  88. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  89. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  90. package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
  91. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  92. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  93. package/dist/mcp/builtin/globals/findTool.js +10 -16
  94. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  95. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  96. package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
  97. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  98. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  99. package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
  100. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  101. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  102. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +29 -13
  103. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  104. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  105. package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
  106. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  107. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  108. package/dist/mcp/builtin/globals/updateTool.js +27 -36
  109. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  110. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  111. package/dist/mcp/sanitizeMCPConfig.js +3 -0
  112. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  113. package/dist/stdio.js +4 -3
  114. package/dist/stdio.js.map +1 -1
  115. package/dist/types.d.ts +109 -7
  116. package/dist/types.d.ts.map +1 -1
  117. package/dist/types.js.map +1 -1
  118. package/dist/utils/seal.d.ts +17 -0
  119. package/dist/utils/seal.d.ts.map +1 -0
  120. package/dist/utils/seal.js +24 -0
  121. package/dist/utils/seal.js.map +1 -0
  122. package/dist/utils/toStandardSchema.js.map +1 -1
  123. package/dist/views/Authorize/AllowButtons/index.d.ts +18 -0
  124. package/dist/views/Authorize/AllowButtons/index.d.ts.map +1 -0
  125. package/dist/views/Authorize/AllowButtons/index.js +88 -0
  126. package/dist/views/Authorize/AllowButtons/index.js.map +1 -0
  127. package/dist/views/Authorize/index.css +19 -0
  128. package/dist/views/Authorize/index.d.ts +9 -0
  129. package/dist/views/Authorize/index.d.ts.map +1 -0
  130. package/dist/views/Authorize/index.js +86 -0
  131. package/dist/views/Authorize/index.js.map +1 -0
  132. package/package.json +30 -28
  133. package/src/endpoint/access.ts +47 -6
  134. package/src/endpoint/index.ts +50 -4
  135. package/src/endpoint/oauth.ts +108 -0
  136. package/src/endpoint/oauthLoginToken.ts +94 -0
  137. package/src/endpoint/oauthServer.ts +452 -0
  138. package/src/exports/client.ts +1 -1
  139. package/src/exports/rsc.ts +1 -0
  140. package/src/index.ts +53 -9
  141. package/src/mcp/buildMcpServer.ts +40 -30
  142. package/src/mcp/builtin/collections/authTools.ts +82 -71
  143. package/src/mcp/builtin/collections/countTool.ts +9 -21
  144. package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
  145. package/src/mcp/builtin/collections/createTool.ts +71 -96
  146. package/src/mcp/builtin/collections/deleteTool.ts +37 -65
  147. package/src/mcp/builtin/collections/duplicateTool.ts +36 -86
  148. package/src/mcp/builtin/collections/fileInput.spec.ts +2 -2
  149. package/src/mcp/builtin/collections/fileInput.ts +44 -81
  150. package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
  151. package/src/mcp/builtin/collections/findTool.ts +24 -106
  152. package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
  153. package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
  154. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +23 -12
  155. package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -57
  156. package/src/mcp/builtin/collections/updateTool.ts +55 -109
  157. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +12 -12
  158. package/src/mcp/builtin/formatEntityError.ts +77 -0
  159. package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
  160. package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
  161. package/src/mcp/builtin/globals/findTool.ts +13 -52
  162. package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
  163. package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
  164. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +21 -11
  165. package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
  166. package/src/mcp/builtin/globals/updateTool.ts +38 -61
  167. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  168. package/src/stdio.ts +2 -2
  169. package/src/types.ts +109 -7
  170. package/src/utils/seal.ts +46 -0
  171. package/src/utils/toStandardSchema.ts +1 -1
  172. package/src/views/Authorize/AllowButtons/index.tsx +97 -0
  173. package/src/views/Authorize/index.css +19 -0
  174. package/src/views/Authorize/index.tsx +93 -0
  175. package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
  176. package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
  177. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  178. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  179. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  180. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  181. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  182. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  183. package/dist/mcp/builtin/validateEntityData.js +0 -82
  184. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  185. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  186. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  187. package/dist/utils/getVirtualFieldNames.js +0 -35
  188. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  189. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
  190. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
  191. package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
  192. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
  193. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
  194. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  195. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
  196. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  197. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
  198. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  199. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
  200. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  201. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
  202. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  203. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  204. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  205. package/dist/utils/transformPointDataToPayload.js +0 -28
  206. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  207. package/dist/utils/whereSchema.d.ts +0 -9
  208. package/dist/utils/whereSchema.d.ts.map +0 -1
  209. package/dist/utils/whereSchema.js +0 -13
  210. package/dist/utils/whereSchema.js.map +0 -1
  211. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  212. package/src/mcp/builtin/validateEntityData.ts +0 -132
  213. package/src/utils/getVirtualFieldNames.ts +0 -53
  214. package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
  215. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
  216. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
  217. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
  218. package/src/utils/transformPointDataToPayload.ts +0 -40
  219. package/src/utils/whereSchema.ts +0 -24
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauthServer.d.ts","sourceRoot":"","sources":["../../src/endpoint/oauthServer.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,QAAQ,EAAkC,MAAM,SAAS,CAAA;AAavE,MAAM,MAAM,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,EAAE,CAAA;CAAE,CAAA;AAE7D,MAAM,MAAM,OAAO,GAAG;IACpB,QAAQ,EAAE,MAAM,CAAA;IAChB,aAAa,EAAE,MAAM,CAAA;IACrB,UAAU,EAAE,MAAM,CAAA;IAClB,WAAW,EAAE,MAAM,CAAA;IACnB,KAAK,EAAE,IAAI,GAAG,MAAM,CAAA;IACpB,MAAM,EAAE,MAAM,GAAG,MAAM,CAAA;CACxB,CAAA;AASD,wDAAwD;AACxD,MAAM,MAAM,kBAAkB,GAAG,SAAS,GAAG,cAAc,CAAA;AAE3D,wEAAwE;AACxE,eAAO,MAAM,iBAAiB,mBAAmB,CAAA;AAOjD;;;;;;;;GAQG;AACH,eAAO,MAAM,oBAAoB,EAAE,QAAQ,EAqC1C,CAAA"}
@@ -0,0 +1,423 @@
1
+ import { OAuthErrorCode } from '@modelcontextprotocol/server';
2
+ import { createHash } from 'crypto';
3
+ import { formatAdminURL } from 'payload/shared';
4
+ import { getPluginConfig } from '../utils/getPluginConfig.js';
5
+ import { seal, unseal } from '../utils/seal.js';
6
+ import { getMCPResource } from './oauth.js';
7
+ import { issueLoginToken, refreshLoginToken } from './oauthLoginToken.js';
8
+ /** The admin page where users allow MCP clients, `MCPAuthorizeView`. */ export const authorizeViewPath = '/mcp/authorize';
9
+ /**
10
+ * Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is
11
+ * `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and
12
+ * the client receives the tokens `issueToken` creates.
13
+ *
14
+ * Clients, consent forms, authorization codes, and refresh tokens are encrypted and handed to the
15
+ * client instead of being stored. Only the default tokens write to the database, to the user's
16
+ * login sessions.
17
+ */ export const oauthServerEndpoints = [
18
+ {
19
+ disableAuth: true,
20
+ handler: (req)=>withIssuer(req, (issuer)=>metadataResponse(issuer)),
21
+ method: 'get',
22
+ // OpenID discovery is the only metadata location MCP clients check below the issuer's path,
23
+ // which lets this work under /api without a route at the site root
24
+ path: '/mcp/oauth/.well-known/openid-configuration'
25
+ },
26
+ {
27
+ disableAuth: true,
28
+ handler: (req)=>withIssuer(req, ()=>Response.json({
29
+ keys: []
30
+ })),
31
+ method: 'get',
32
+ path: '/mcp/oauth/jwks'
33
+ },
34
+ {
35
+ disableAuth: true,
36
+ handler: (req)=>withIssuer(req, ()=>register(req)),
37
+ method: 'post',
38
+ path: '/mcp/oauth/register'
39
+ },
40
+ {
41
+ handler: (req)=>withIssuer(req, ()=>authorize(req)),
42
+ method: 'get',
43
+ path: '/mcp/oauth/authorize'
44
+ },
45
+ {
46
+ handler: (req)=>withIssuer(req, (issuer)=>approve({
47
+ issuer,
48
+ req
49
+ })),
50
+ method: 'post',
51
+ path: '/mcp/oauth/authorize'
52
+ },
53
+ {
54
+ disableAuth: true,
55
+ handler: (req)=>withIssuer(req, ()=>token(req)),
56
+ method: 'post',
57
+ path: '/mcp/oauth/token'
58
+ }
59
+ ];
60
+ /** The authorization server URL, or `undefined` when Payload isn't the authorization server. */ const getIssuer = (req)=>getPluginConfig({
61
+ config: req.payload.config
62
+ }).oauth?.type === 'builtin' ? `${getMCPResource({
63
+ req
64
+ })}/oauth` : undefined;
65
+ const withIssuer = (req, handler)=>{
66
+ const issuer = getIssuer(req);
67
+ return issuer ? handler(issuer) : new Response(null, {
68
+ status: 404
69
+ });
70
+ };
71
+ /**
72
+ * The user logged in to this browser, who can allow MCP clients. Tokens and API keys in the
73
+ * `Authorization` header can't, or an MCP client could use its access token to approve itself a
74
+ * new, separate login.
75
+ */ const getBrowserUser = (req)=>req.headers.has('Authorization') ? null : req.user;
76
+ const metadataResponse = (issuer)=>Response.json({
77
+ authorization_endpoint: `${issuer}/authorize`,
78
+ authorization_response_iss_parameter_supported: true,
79
+ code_challenge_methods_supported: [
80
+ 'S256'
81
+ ],
82
+ grant_types_supported: [
83
+ 'authorization_code',
84
+ 'refresh_token'
85
+ ],
86
+ // Required by OpenID discovery. No ID tokens are issued.
87
+ id_token_signing_alg_values_supported: [
88
+ 'RS256'
89
+ ],
90
+ issuer,
91
+ jwks_uri: `${issuer}/jwks`,
92
+ registration_endpoint: `${issuer}/register`,
93
+ response_types_supported: [
94
+ 'code'
95
+ ],
96
+ subject_types_supported: [
97
+ 'public'
98
+ ],
99
+ token_endpoint: `${issuer}/token`,
100
+ token_endpoint_auth_methods_supported: [
101
+ 'none'
102
+ ]
103
+ }, // Not cached, since without `serverURL` its URLs come from the request
104
+ {
105
+ headers: {
106
+ 'Access-Control-Allow-Origin': '*',
107
+ 'Cache-Control': 'no-store'
108
+ }
109
+ });
110
+ const register = async (req)=>{
111
+ const { client_name, redirect_uris } = await req.json().catch(()=>({}));
112
+ if (!Array.isArray(redirect_uris) || !redirect_uris.length || !redirect_uris.every(isValidRedirectURI)) {
113
+ return Response.json({
114
+ error: OAuthErrorCode.InvalidRedirectUri
115
+ }, {
116
+ status: 400
117
+ });
118
+ }
119
+ const client = {
120
+ name: typeof client_name === 'string' ? client_name : 'An MCP client',
121
+ redirectURIs: redirect_uris
122
+ };
123
+ return Response.json({
124
+ client_id: seal({
125
+ type: 'client',
126
+ data: client,
127
+ req
128
+ }),
129
+ client_name: client.name,
130
+ grant_types: [
131
+ 'authorization_code',
132
+ 'refresh_token'
133
+ ],
134
+ redirect_uris: client.redirectURIs,
135
+ response_types: [
136
+ 'code'
137
+ ],
138
+ token_endpoint_auth_method: 'none'
139
+ }, {
140
+ status: 201
141
+ });
142
+ };
143
+ const authorize = (req)=>{
144
+ const url = new URL(req.url);
145
+ const params = url.searchParams;
146
+ const clientID = params.get('client_id');
147
+ const client = unseal({
148
+ type: 'client',
149
+ req,
150
+ value: clientID
151
+ });
152
+ // Optional when the client registered only one
153
+ const redirectURI = params.get('redirect_uri') ?? (client?.redirectURIs.length === 1 ? client.redirectURIs[0] : null);
154
+ // Never redirect to an address the client didn't register
155
+ if (!client || !redirectURI || !client.redirectURIs.includes(redirectURI)) {
156
+ return redirectToAuthorizeView({
157
+ params: {
158
+ error: 'invalid-link'
159
+ },
160
+ req
161
+ });
162
+ }
163
+ const state = params.get('state');
164
+ const codeChallenge = params.get('code_challenge');
165
+ // Not sent to the client's address: anyone can register a client, so that would let a link to
166
+ // this site send users to any site without them doing anything
167
+ if (params.get('response_type') !== 'code' || params.get('code_challenge_method') !== 'S256' || !codeChallenge) {
168
+ return redirectToAuthorizeView({
169
+ params: {
170
+ error: 'invalid-link'
171
+ },
172
+ req
173
+ });
174
+ }
175
+ const user = getBrowserUser(req);
176
+ if (!user) {
177
+ const loginURL = formatAdminURL({
178
+ adminRoute: req.payload.config.routes.admin,
179
+ path: req.payload.config.admin.routes.login
180
+ });
181
+ return new Response(null, {
182
+ headers: {
183
+ Location: `${loginURL}?redirect=${encodeURIComponent(url.pathname + url.search)}`
184
+ },
185
+ status: 302
186
+ });
187
+ }
188
+ const consent = {
189
+ clientID: clientID,
190
+ codeChallenge,
191
+ collection: user.collection,
192
+ redirectURI,
193
+ state,
194
+ userID: user.id
195
+ };
196
+ return redirectToAuthorizeView({
197
+ params: {
198
+ consent: seal({
199
+ type: 'consent',
200
+ data: consent,
201
+ expiresInSeconds: 20 * 60,
202
+ req
203
+ })
204
+ },
205
+ req
206
+ });
207
+ };
208
+ const approve = async ({ issuer, req })=>{
209
+ // The Allow page is part of the admin panel, which other sites may be able to frame. Only
210
+ // accepting clicks from a top-level page stops them from tricking users into clicking Allow.
211
+ // Browsers too old to send the header get through here, but the page hides its buttons in frames.
212
+ const fetchDestination = req.headers.get('Sec-Fetch-Dest');
213
+ // Only the Allow page itself may submit the form, not a copy of it on another site
214
+ const fetchSite = req.headers.get('Sec-Fetch-Site');
215
+ if (fetchDestination && fetchDestination !== 'document' || fetchSite && fetchSite !== 'same-origin') {
216
+ return new Response(null, {
217
+ status: 403
218
+ });
219
+ }
220
+ const form = new URLSearchParams(await req.text());
221
+ const consent = unseal({
222
+ type: 'consent',
223
+ req,
224
+ value: form.get('consent')
225
+ });
226
+ const user = getBrowserUser(req);
227
+ // The form is only valid for the user it was shown to
228
+ if (!consent || user?.id !== consent.userID || user.collection !== consent.collection) {
229
+ return redirectToAuthorizeView({
230
+ params: {
231
+ error: 'expired'
232
+ },
233
+ req
234
+ });
235
+ }
236
+ const { clientID, codeChallenge, redirectURI, state } = consent;
237
+ // Responses to the client name this server in `iss`, so clients that use several authorization
238
+ // servers can tell which one answered
239
+ if (form.get('decision') !== 'allow') {
240
+ return redirect({
241
+ params: {
242
+ error: OAuthErrorCode.AccessDenied,
243
+ iss: issuer,
244
+ state
245
+ },
246
+ redirectURI
247
+ });
248
+ }
249
+ const code = {
250
+ clientID,
251
+ codeChallenge,
252
+ redirectURI,
253
+ tokens: await getTokenHooks(req).issueToken({
254
+ req
255
+ })
256
+ };
257
+ return redirect({
258
+ params: {
259
+ code: seal({
260
+ type: 'code',
261
+ data: code,
262
+ expiresInSeconds: 60,
263
+ req
264
+ }),
265
+ iss: issuer,
266
+ state
267
+ },
268
+ redirectURI
269
+ });
270
+ };
271
+ const token = async (req)=>{
272
+ const form = new URLSearchParams(await req.text());
273
+ const clientID = form.get('client_id');
274
+ const grantType = form.get('grant_type');
275
+ if (grantType !== 'authorization_code' && grantType !== 'refresh_token') {
276
+ return Response.json({
277
+ error: grantType ? OAuthErrorCode.UnsupportedGrantType : OAuthErrorCode.InvalidRequest
278
+ }, {
279
+ status: 400
280
+ });
281
+ }
282
+ const requiredParams = grantType === 'refresh_token' ? [
283
+ 'refresh_token'
284
+ ] : [
285
+ 'code',
286
+ 'code_verifier'
287
+ ];
288
+ if (!clientID || requiredParams.some((param)=>!form.get(param))) {
289
+ return Response.json({
290
+ error: OAuthErrorCode.InvalidRequest
291
+ }, {
292
+ status: 400
293
+ });
294
+ }
295
+ const tokens = grantType === 'refresh_token' ? await refresh({
296
+ clientID,
297
+ form,
298
+ req
299
+ }) : await redeemCode({
300
+ clientID,
301
+ form,
302
+ req
303
+ });
304
+ if (!tokens) {
305
+ return Response.json({
306
+ error: OAuthErrorCode.InvalidGrant
307
+ }, {
308
+ status: 400
309
+ });
310
+ }
311
+ return Response.json({
312
+ access_token: tokens.accessToken,
313
+ expires_in: tokens.expiresIn,
314
+ refresh_token: tokens.refreshToken && seal({
315
+ type: 'refresh',
316
+ data: {
317
+ clientID,
318
+ refreshToken: tokens.refreshToken
319
+ },
320
+ req
321
+ }),
322
+ token_type: 'Bearer'
323
+ }, {
324
+ headers: {
325
+ 'Cache-Control': 'no-store'
326
+ }
327
+ });
328
+ };
329
+ const redeemCode = async ({ clientID, form, req })=>{
330
+ const code = unseal({
331
+ type: 'code',
332
+ req,
333
+ value: form.get('code')
334
+ });
335
+ if (code?.clientID === clientID && // OAuth 2.1 clients leave it out, since PKCE does its job. OAuth 2.0 clients send it, and it must
336
+ // match then.
337
+ (!form.has('redirect_uri') || form.get('redirect_uri') === code.redirectURI) && // PKCE: only the client that started the sign-in knows the verifier
338
+ createHash('sha256').update(form.get('code_verifier') ?? '').digest('base64url') === code.codeChallenge) {
339
+ // A code must only work once. Trading it also trades its refresh token, with no leeway, so
340
+ // using the code again counts as a copied refresh token: it's refused, and the tokens revoked.
341
+ const hooks = getTokenHooks(req);
342
+ if (hooks.refreshToken && code.tokens.refreshToken) {
343
+ return await hooks.refreshToken({
344
+ refreshToken: code.tokens.refreshToken,
345
+ req,
346
+ reuseInterval: 0
347
+ });
348
+ }
349
+ return code.tokens;
350
+ }
351
+ };
352
+ const refresh = async ({ clientID, form, req })=>{
353
+ const refreshToken = unseal({
354
+ type: 'refresh',
355
+ req,
356
+ value: form.get('refresh_token')
357
+ });
358
+ // Only the client a refresh token was issued to can use it
359
+ if (refreshToken?.clientID === clientID) {
360
+ return await getTokenHooks(req).refreshToken?.({
361
+ refreshToken: refreshToken.refreshToken,
362
+ req
363
+ });
364
+ }
365
+ };
366
+ /** `issueToken` and `refreshToken`, or the defaults for Payload login tokens. */ const getTokenHooks = (req)=>{
367
+ const oauth = getPluginConfig({
368
+ config: req.payload.config
369
+ }).oauth;
370
+ return oauth.issueToken ? {
371
+ issueToken: oauth.issueToken,
372
+ refreshToken: oauth.refreshToken
373
+ } : {
374
+ issueToken: issueLoginToken,
375
+ refreshToken: refreshLoginToken
376
+ };
377
+ };
378
+ const redirect = ({ params, redirectURI })=>{
379
+ const location = new URL(redirectURI);
380
+ for (const [key, value] of Object.entries(params)){
381
+ if (value) {
382
+ location.searchParams.set(key, value);
383
+ }
384
+ }
385
+ return new Response(null, {
386
+ headers: {
387
+ Location: location.href
388
+ },
389
+ status: 302
390
+ });
391
+ };
392
+ /**
393
+ * Accepts https, http to the user's own computer only, since the code would otherwise travel
394
+ * unencrypted, and app schemes like `cursor://` that desktop apps register to receive the code.
395
+ */ const isValidRedirectURI = (uri)=>{
396
+ if (typeof uri !== 'string' || !URL.canParse(uri) || uri.includes('#')) {
397
+ return false;
398
+ }
399
+ const { hostname, protocol } = new URL(uri);
400
+ if (protocol === 'http:') {
401
+ return [
402
+ '[::1]',
403
+ '127.0.0.1',
404
+ 'localhost'
405
+ ].includes(hostname);
406
+ }
407
+ // Browser schemes that run or show content instead of sending the code to an app
408
+ return protocol !== 'javascript:' && protocol !== 'data:';
409
+ };
410
+ /** Sends the browser to `MCPAuthorizeView`, with the Allow form or the reason it can't show it. */ const redirectToAuthorizeView = ({ params, req })=>{
411
+ const viewURL = formatAdminURL({
412
+ adminRoute: req.payload.config.routes.admin,
413
+ path: authorizeViewPath
414
+ });
415
+ return new Response(null, {
416
+ headers: {
417
+ Location: `${viewURL}?${new URLSearchParams(params)}`
418
+ },
419
+ status: 302
420
+ });
421
+ };
422
+
423
+ //# sourceMappingURL=oauthServer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/endpoint/oauthServer.ts"],"sourcesContent":["import type {\n OAuthClientInformationFull,\n OAuthTokens,\n OpenIdProviderDiscoveryMetadata,\n} from '@modelcontextprotocol/server'\nimport type { Endpoint, PayloadHandler, PayloadRequest } from 'payload'\n\nimport { OAuthErrorCode } from '@modelcontextprotocol/server'\nimport { createHash } from 'crypto'\nimport { formatAdminURL } from 'payload/shared'\n\nimport type { MCPBuiltinOAuthConfig, MCPOAuthTokens } from '../types.js'\n\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\nimport { seal, unseal } from '../utils/seal.js'\nimport { getMCPResource } from './oauth.js'\nimport { issueLoginToken, refreshLoginToken } from './oauthLoginToken.js'\n\nexport type Client = { name: string; redirectURIs: string[] }\n\nexport type Consent = {\n clientID: string\n codeChallenge: string\n collection: string\n redirectURI: string\n state: null | string\n userID: number | string\n}\n\ntype Code = {\n clientID: string\n codeChallenge: string\n redirectURI: string\n tokens: MCPOAuthTokens\n}\n\n/** Why `MCPAuthorizeView` can't show the Allow form. */\nexport type AuthorizeViewError = 'expired' | 'invalid-link'\n\n/** The admin page where users allow MCP clients, `MCPAuthorizeView`. */\nexport const authorizeViewPath = '/mcp/authorize'\n\ntype RefreshToken = {\n clientID: string\n refreshToken: string\n}\n\n/**\n * Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is\n * `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and\n * the client receives the tokens `issueToken` creates.\n *\n * Clients, consent forms, authorization codes, and refresh tokens are encrypted and handed to the\n * client instead of being stored. Only the default tokens write to the database, to the user's\n * login sessions.\n */\nexport const oauthServerEndpoints: Endpoint[] = [\n {\n disableAuth: true,\n handler: (req) => withIssuer(req, (issuer) => metadataResponse(issuer)),\n method: 'get',\n // OpenID discovery is the only metadata location MCP clients check below the issuer's path,\n // which lets this work under /api without a route at the site root\n path: '/mcp/oauth/.well-known/openid-configuration',\n },\n {\n disableAuth: true,\n handler: (req) => withIssuer(req, () => Response.json({ keys: [] })),\n method: 'get',\n path: '/mcp/oauth/jwks',\n },\n {\n disableAuth: true,\n handler: (req) => withIssuer(req, () => register(req)),\n method: 'post',\n path: '/mcp/oauth/register',\n },\n {\n handler: (req) => withIssuer(req, () => authorize(req)),\n method: 'get',\n path: '/mcp/oauth/authorize',\n },\n {\n handler: (req) => withIssuer(req, (issuer) => approve({ issuer, req })),\n method: 'post',\n path: '/mcp/oauth/authorize',\n },\n {\n disableAuth: true,\n handler: (req) => withIssuer(req, () => token(req)),\n method: 'post',\n path: '/mcp/oauth/token',\n },\n]\n\n/** The authorization server URL, or `undefined` when Payload isn't the authorization server. */\nconst getIssuer = (req: PayloadRequest): string | undefined =>\n getPluginConfig({ config: req.payload.config }).oauth?.type === 'builtin'\n ? `${getMCPResource({ req })}/oauth`\n : undefined\n\nconst withIssuer = (\n req: PayloadRequest,\n handler: (issuer: string) => Promise<Response> | Response,\n): Promise<Response> | Response => {\n const issuer = getIssuer(req)\n return issuer ? handler(issuer) : new Response(null, { status: 404 })\n}\n\n/**\n * The user logged in to this browser, who can allow MCP clients. Tokens and API keys in the\n * `Authorization` header can't, or an MCP client could use its access token to approve itself a\n * new, separate login.\n */\nconst getBrowserUser = (req: PayloadRequest): PayloadRequest['user'] =>\n req.headers.has('Authorization') ? null : req.user\n\nconst metadataResponse = (issuer: string): Response =>\n Response.json(\n {\n authorization_endpoint: `${issuer}/authorize`,\n authorization_response_iss_parameter_supported: true,\n code_challenge_methods_supported: ['S256'],\n grant_types_supported: ['authorization_code', 'refresh_token'],\n // Required by OpenID discovery. No ID tokens are issued.\n id_token_signing_alg_values_supported: ['RS256'],\n issuer,\n jwks_uri: `${issuer}/jwks`,\n registration_endpoint: `${issuer}/register`,\n response_types_supported: ['code'],\n subject_types_supported: ['public'],\n token_endpoint: `${issuer}/token`,\n token_endpoint_auth_methods_supported: ['none'],\n } satisfies OpenIdProviderDiscoveryMetadata,\n // Not cached, since without `serverURL` its URLs come from the request\n { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },\n )\n\nconst register: PayloadHandler = async (req) => {\n const { client_name, redirect_uris } = await req.json!().catch(() => ({}))\n\n if (\n !Array.isArray(redirect_uris) ||\n !redirect_uris.length ||\n !redirect_uris.every(isValidRedirectURI)\n ) {\n return Response.json({ error: OAuthErrorCode.InvalidRedirectUri }, { status: 400 })\n }\n\n const client: Client = {\n name: typeof client_name === 'string' ? client_name : 'An MCP client',\n redirectURIs: redirect_uris,\n }\n\n return Response.json(\n {\n client_id: seal({ type: 'client', data: client, req }),\n client_name: client.name,\n grant_types: ['authorization_code', 'refresh_token'],\n redirect_uris: client.redirectURIs,\n response_types: ['code'],\n token_endpoint_auth_method: 'none',\n } satisfies OAuthClientInformationFull,\n { status: 201 },\n )\n}\n\nconst authorize: PayloadHandler = (req) => {\n const url = new URL(req.url!)\n const params = url.searchParams\n const clientID = params.get('client_id')\n const client = unseal<Client>({ type: 'client', req, value: clientID })\n // Optional when the client registered only one\n const redirectURI =\n params.get('redirect_uri') ??\n (client?.redirectURIs.length === 1 ? client.redirectURIs[0]! : null)\n\n // Never redirect to an address the client didn't register\n if (!client || !redirectURI || !client.redirectURIs.includes(redirectURI)) {\n return redirectToAuthorizeView({ params: { error: 'invalid-link' }, req })\n }\n\n const state = params.get('state')\n const codeChallenge = params.get('code_challenge')\n\n // Not sent to the client's address: anyone can register a client, so that would let a link to\n // this site send users to any site without them doing anything\n if (\n params.get('response_type') !== 'code' ||\n params.get('code_challenge_method') !== 'S256' ||\n !codeChallenge\n ) {\n return redirectToAuthorizeView({ params: { error: 'invalid-link' }, req })\n }\n\n const user = getBrowserUser(req)\n\n if (!user) {\n const loginURL = formatAdminURL({\n adminRoute: req.payload.config.routes.admin,\n path: req.payload.config.admin.routes.login,\n })\n\n return new Response(null, {\n headers: {\n Location: `${loginURL}?redirect=${encodeURIComponent(url.pathname + url.search)}`,\n },\n status: 302,\n })\n }\n\n const consent: Consent = {\n clientID: clientID!,\n codeChallenge,\n collection: user.collection,\n redirectURI,\n state,\n userID: user.id,\n }\n\n return redirectToAuthorizeView({\n params: { consent: seal({ type: 'consent', data: consent, expiresInSeconds: 20 * 60, req }) },\n req,\n })\n}\n\nconst approve = async ({\n issuer,\n req,\n}: {\n issuer: string\n req: PayloadRequest\n}): Promise<Response> => {\n // The Allow page is part of the admin panel, which other sites may be able to frame. Only\n // accepting clicks from a top-level page stops them from tricking users into clicking Allow.\n // Browsers too old to send the header get through here, but the page hides its buttons in frames.\n const fetchDestination = req.headers.get('Sec-Fetch-Dest')\n // Only the Allow page itself may submit the form, not a copy of it on another site\n const fetchSite = req.headers.get('Sec-Fetch-Site')\n if (\n (fetchDestination && fetchDestination !== 'document') ||\n (fetchSite && fetchSite !== 'same-origin')\n ) {\n return new Response(null, { status: 403 })\n }\n\n const form = new URLSearchParams(await req.text!())\n const consent = unseal<Consent>({ type: 'consent', req, value: form.get('consent') })\n const user = getBrowserUser(req)\n\n // The form is only valid for the user it was shown to\n if (!consent || user?.id !== consent.userID || user.collection !== consent.collection) {\n return redirectToAuthorizeView({ params: { error: 'expired' }, req })\n }\n\n const { clientID, codeChallenge, redirectURI, state } = consent\n\n // Responses to the client name this server in `iss`, so clients that use several authorization\n // servers can tell which one answered\n if (form.get('decision') !== 'allow') {\n return redirect({\n params: { error: OAuthErrorCode.AccessDenied, iss: issuer, state },\n redirectURI,\n })\n }\n\n const code: Code = {\n clientID,\n codeChallenge,\n redirectURI,\n tokens: await getTokenHooks(req).issueToken({ req }),\n }\n\n return redirect({\n params: {\n code: seal({ type: 'code', data: code, expiresInSeconds: 60, req }),\n iss: issuer,\n state,\n },\n redirectURI,\n })\n}\n\nconst token: PayloadHandler = async (req) => {\n const form = new URLSearchParams(await req.text!())\n const clientID = form.get('client_id')\n const grantType = form.get('grant_type')\n\n if (grantType !== 'authorization_code' && grantType !== 'refresh_token') {\n return Response.json(\n { error: grantType ? OAuthErrorCode.UnsupportedGrantType : OAuthErrorCode.InvalidRequest },\n { status: 400 },\n )\n }\n\n const requiredParams =\n grantType === 'refresh_token' ? ['refresh_token'] : ['code', 'code_verifier']\n\n if (!clientID || requiredParams.some((param) => !form.get(param))) {\n return Response.json({ error: OAuthErrorCode.InvalidRequest }, { status: 400 })\n }\n\n const tokens =\n grantType === 'refresh_token'\n ? await refresh({ clientID, form, req })\n : await redeemCode({ clientID, form, req })\n\n if (!tokens) {\n return Response.json({ error: OAuthErrorCode.InvalidGrant }, { status: 400 })\n }\n\n return Response.json(\n {\n access_token: tokens.accessToken,\n expires_in: tokens.expiresIn,\n refresh_token:\n tokens.refreshToken &&\n seal({\n type: 'refresh',\n data: { clientID, refreshToken: tokens.refreshToken } satisfies RefreshToken,\n req,\n }),\n token_type: 'Bearer',\n } satisfies OAuthTokens,\n { headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nconst redeemCode = async ({\n clientID,\n form,\n req,\n}: {\n clientID: string\n form: URLSearchParams\n req: PayloadRequest\n}): Promise<MCPOAuthTokens | null | undefined> => {\n const code = unseal<Code>({ type: 'code', req, value: form.get('code') })\n\n if (\n code?.clientID === clientID &&\n // OAuth 2.1 clients leave it out, since PKCE does its job. OAuth 2.0 clients send it, and it must\n // match then.\n (!form.has('redirect_uri') || form.get('redirect_uri') === code.redirectURI) &&\n // PKCE: only the client that started the sign-in knows the verifier\n createHash('sha256')\n .update(form.get('code_verifier') ?? '')\n .digest('base64url') === code.codeChallenge\n ) {\n // A code must only work once. Trading it also trades its refresh token, with no leeway, so\n // using the code again counts as a copied refresh token: it's refused, and the tokens revoked.\n const hooks = getTokenHooks(req)\n if (hooks.refreshToken && code.tokens.refreshToken) {\n return await hooks.refreshToken({\n refreshToken: code.tokens.refreshToken,\n req,\n reuseInterval: 0,\n })\n }\n\n return code.tokens\n }\n}\n\nconst refresh = async ({\n clientID,\n form,\n req,\n}: {\n clientID: string\n form: URLSearchParams\n req: PayloadRequest\n}): Promise<MCPOAuthTokens | null | undefined> => {\n const refreshToken = unseal<RefreshToken>({\n type: 'refresh',\n req,\n value: form.get('refresh_token'),\n })\n\n // Only the client a refresh token was issued to can use it\n if (refreshToken?.clientID === clientID) {\n return await getTokenHooks(req).refreshToken?.({\n refreshToken: refreshToken.refreshToken,\n req,\n })\n }\n}\n\n/** `issueToken` and `refreshToken`, or the defaults for Payload login tokens. */\nconst getTokenHooks = (req: PayloadRequest) => {\n const oauth = getPluginConfig({ config: req.payload.config }).oauth as MCPBuiltinOAuthConfig\n\n return oauth.issueToken\n ? { issueToken: oauth.issueToken, refreshToken: oauth.refreshToken }\n : { issueToken: issueLoginToken, refreshToken: refreshLoginToken }\n}\n\nconst redirect = ({\n params,\n redirectURI,\n}: {\n params: Record<string, null | string>\n redirectURI: string\n}): Response => {\n const location = new URL(redirectURI)\n\n for (const [key, value] of Object.entries(params)) {\n if (value) {\n location.searchParams.set(key, value)\n }\n }\n\n return new Response(null, { headers: { Location: location.href }, status: 302 })\n}\n\n/**\n * Accepts https, http to the user's own computer only, since the code would otherwise travel\n * unencrypted, and app schemes like `cursor://` that desktop apps register to receive the code.\n */\nconst isValidRedirectURI = (uri: unknown): boolean => {\n if (typeof uri !== 'string' || !URL.canParse(uri) || uri.includes('#')) {\n return false\n }\n\n const { hostname, protocol } = new URL(uri)\n\n if (protocol === 'http:') {\n return ['[::1]', '127.0.0.1', 'localhost'].includes(hostname)\n }\n\n // Browser schemes that run or show content instead of sending the code to an app\n return protocol !== 'javascript:' && protocol !== 'data:'\n}\n\n/** Sends the browser to `MCPAuthorizeView`, with the Allow form or the reason it can't show it. */\nconst redirectToAuthorizeView = ({\n params,\n req,\n}: {\n params: { consent: string } | { error: AuthorizeViewError }\n req: PayloadRequest\n}): Response => {\n const viewURL = formatAdminURL({\n adminRoute: req.payload.config.routes.admin,\n path: authorizeViewPath,\n })\n\n return new Response(null, {\n headers: { Location: `${viewURL}?${new URLSearchParams(params)}` },\n status: 302,\n })\n}\n"],"names":["OAuthErrorCode","createHash","formatAdminURL","getPluginConfig","seal","unseal","getMCPResource","issueLoginToken","refreshLoginToken","authorizeViewPath","oauthServerEndpoints","disableAuth","handler","req","withIssuer","issuer","metadataResponse","method","path","Response","json","keys","register","authorize","approve","token","getIssuer","config","payload","oauth","type","undefined","status","getBrowserUser","headers","has","user","authorization_endpoint","authorization_response_iss_parameter_supported","code_challenge_methods_supported","grant_types_supported","id_token_signing_alg_values_supported","jwks_uri","registration_endpoint","response_types_supported","subject_types_supported","token_endpoint","token_endpoint_auth_methods_supported","client_name","redirect_uris","catch","Array","isArray","length","every","isValidRedirectURI","error","InvalidRedirectUri","client","name","redirectURIs","client_id","data","grant_types","response_types","token_endpoint_auth_method","url","URL","params","searchParams","clientID","get","value","redirectURI","includes","redirectToAuthorizeView","state","codeChallenge","loginURL","adminRoute","routes","admin","login","Location","encodeURIComponent","pathname","search","consent","collection","userID","id","expiresInSeconds","fetchDestination","fetchSite","form","URLSearchParams","text","redirect","AccessDenied","iss","code","tokens","getTokenHooks","issueToken","grantType","UnsupportedGrantType","InvalidRequest","requiredParams","some","param","refresh","redeemCode","InvalidGrant","access_token","accessToken","expires_in","expiresIn","refresh_token","refreshToken","token_type","update","digest","hooks","reuseInterval","location","key","Object","entries","set","href","uri","canParse","hostname","protocol","viewURL"],"mappings":"AAOA,SAASA,cAAc,QAAQ,+BAA8B;AAC7D,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,cAAc,QAAQ,iBAAgB;AAI/C,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SAASC,IAAI,EAAEC,MAAM,QAAQ,mBAAkB;AAC/C,SAASC,cAAc,QAAQ,aAAY;AAC3C,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,uBAAsB;AAuBzE,sEAAsE,GACtE,OAAO,MAAMC,oBAAoB,iBAAgB;AAOjD;;;;;;;;CAQC,GACD,OAAO,MAAMC,uBAAmC;IAC9C;QACEC,aAAa;QACbC,SAAS,CAACC,MAAQC,WAAWD,KAAK,CAACE,SAAWC,iBAAiBD;QAC/DE,QAAQ;QACR,4FAA4F;QAC5F,mEAAmE;QACnEC,MAAM;IACR;IACA;QACEP,aAAa;QACbC,SAAS,CAACC,MAAQC,WAAWD,KAAK,IAAMM,SAASC,IAAI,CAAC;oBAAEC,MAAM,EAAE;gBAAC;QACjEJ,QAAQ;QACRC,MAAM;IACR;IACA;QACEP,aAAa;QACbC,SAAS,CAACC,MAAQC,WAAWD,KAAK,IAAMS,SAAST;Q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EAChB7B,MAAM,EACNK,WAAW,EAIZ;IACC,MAAMmD,WAAW,IAAIzD,IAAIM;IAEzB,KAAK,MAAM,CAACoD,KAAKrD,MAAM,IAAIsD,OAAOC,OAAO,CAAC3D,QAAS;QACjD,IAAII,OAAO;YACToD,SAASvD,YAAY,CAAC2D,GAAG,CAACH,KAAKrD;QACjC;IACF;IAEA,OAAO,IAAIrD,SAAS,MAAM;QAAEe,SAAS;YAAEiD,UAAUyC,SAASK,IAAI;QAAC;QAAGjG,QAAQ;IAAI;AAChF;AAEA;;;CAGC,GACD,MAAMuB,qBAAqB,CAAC2E;IAC1B,IAAI,OAAOA,QAAQ,YAAY,CAAC/D,IAAIgE,QAAQ,CAACD,QAAQA,IAAIxD,QAAQ,CAAC,MAAM;QACtE,OAAO;IACT;IAEA,MAAM,EAAE0D,QAAQ,EAAEC,QAAQ,EAAE,GAAG,IAAIlE,IAAI+D;IAEvC,IAAIG,aAAa,SAAS;QACxB,OAAO;YAAC;YAAS;YAAa;SAAY,CAAC3D,QAAQ,CAAC0D;IACtD;IAEA,iFAAiF;IACjF,OAAOC,aAAa,iBAAiBA,aAAa;AACpD;AAEA,iGAAiG,GACjG,MAAM1D,0BAA0B,CAAC,EAC/BP,MAAM,EACNvD,GAAG,EAIJ;IACC,MAAMyH,UAAUpI,eAAe;QAC7B6E,YAAYlE,IAAIe,OAAO,CAACD,MAAM,CAACqD,MAAM,CAACC,KAAK;QAC3C/D,MAAMT;IACR;IAEA,OAAO,IAAIU,SAAS,MAAM;QACxBe,SAAS;YAAEiD,UAAU,GAAGmD,QAAQ,CAAC,EAAE,IAAIvC,gBAAgB3B,SAAS;QAAC;QACjEpC,QAAQ;IACV;AACF"}
@@ -1,2 +1,2 @@
1
- export {};
1
+ export { AllowButtons } from '../views/Authorize/AllowButtons/index.js';
2
2
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/exports/client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,CAAA"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/exports/client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAA"}
@@ -1,4 +1,4 @@
1
1
  'use client';
2
- export { };
2
+ export { AllowButtons } from '../views/Authorize/AllowButtons/index.js';
3
3
 
4
4
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\n\nexport {}\n"],"names":[],"mappings":"AAAA;AAEA,WAAS"}
1
+ {"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\n\nexport { AllowButtons } from '../views/Authorize/AllowButtons/index.js'\n"],"names":["AllowButtons"],"mappings":"AAAA;AAEA,SAASA,YAAY,QAAQ,2CAA0C"}
@@ -0,0 +1,2 @@
1
+ export { MCPAuthorizeView } from '../views/Authorize/index.js';
2
+ //# sourceMappingURL=rsc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rsc.d.ts","sourceRoot":"","sources":["../../src/exports/rsc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAA"}
@@ -0,0 +1,3 @@
1
+ export { MCPAuthorizeView } from '../views/Authorize/index.js';
2
+
3
+ //# sourceMappingURL=rsc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["export { MCPAuthorizeView } from '../views/Authorize/index.js'\n"],"names":["MCPAuthorizeView"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,8BAA6B"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js';
1
+ import type { AuthorizedMCP, MCPBuiltinOAuthConfig, MCPExternalOAuthConfig, MCPOAuthConfig, MCPOAuthTokens, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js';
2
2
  declare module 'payload' {
3
3
  interface PayloadRequestAPI {
4
4
  MCP: true;
@@ -7,8 +7,16 @@ declare module 'payload' {
7
7
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
8
8
  '@payloadcms/plugin-mcp': MCPPluginConfig;
9
9
  }
10
+ interface RequestContext {
11
+ /** Set on MCP requests before they're authenticated. */
12
+ mcp?: {
13
+ /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */
14
+ resource: string;
15
+ };
16
+ }
10
17
  }
11
- export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig };
18
+ export type { AuthorizedMCP, MCPBuiltinOAuthConfig, MCPExternalOAuthConfig, MCPOAuthConfig, MCPOAuthTokens, MCPPluginConfig, SanitizedMCPPluginConfig, };
12
19
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js';
20
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js';
13
21
  export declare const mcpPlugin: (options: MCPPluginConfig) => import("payload").Plugin;
14
22
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAK1F,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,iBAAiB;QAChC,GAAG,EAAE,IAAI,CAAA;KACV;IACD,UAAU,iBAAiB;QACzB,uFAAuF;QACvF,wBAAwB,EAAE,eAAe,CAAA;KAC1C;CACF;AAED,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,CAAA;AAExE,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAElG,eAAO,MAAM,SAAS,wDAiCpB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,aAAa,EACb,qBAAqB,EACrB,sBAAsB,EACtB,cAAc,EACd,cAAc,EACd,eAAe,EACf,wBAAwB,EACzB,MAAM,YAAY,CAAA;AAOnB,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,iBAAiB;QAChC,GAAG,EAAE,IAAI,CAAA;KACV;IACD,UAAU,iBAAiB;QACzB,uFAAuF;QACvF,wBAAwB,EAAE,eAAe,CAAA;KAC1C;IACD,UAAiB,cAAc;QAC7B,wDAAwD;QACxD,GAAG,CAAC,EAAE;YACJ,oFAAoF;YACpF,QAAQ,EAAE,MAAM,CAAA;SACjB,CAAA;KACF;CACF;AAED,YAAY,EACV,aAAa,EACb,qBAAqB,EACrB,sBAAsB,EACtB,cAAc,EACd,cAAc,EACd,eAAe,EACf,wBAAwB,GACzB,CAAA;AAED,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAClG,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAA;AAEnE,eAAO,MAAM,SAAS,wDAmDpB,CAAA"}
package/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { definePlugin } from 'payload';
2
2
  import { mcpEndpoint } from './endpoint/index.js';
3
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js';
4
+ import { authorizeViewPath, oauthServerEndpoints } from './endpoint/oauthServer.js';
3
5
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js';
4
6
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js';
7
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js';
5
8
  export const mcpPlugin = definePlugin({
6
9
  slug: '@payloadcms/plugin-mcp',
7
10
  order: 10,
@@ -21,26 +24,47 @@ export const mcpPlugin = definePlugin({
21
24
  }
22
25
  return {
23
26
  ...config,
27
+ admin: {
28
+ ...config.admin,
29
+ components: {
30
+ ...config.admin?.components,
31
+ views: {
32
+ ...config.admin?.components?.views,
33
+ // Where users allow MCP clients, for the built-in OAuth server
34
+ mcpAuthorize: {
35
+ Component: '@payloadcms/plugin-mcp/rsc#MCPAuthorizeView',
36
+ exact: true,
37
+ meta: {
38
+ title: 'Allow an MCP client'
39
+ },
40
+ path: authorizeViewPath
41
+ }
42
+ }
43
+ }
44
+ },
24
45
  endpoints: [
25
46
  ...config.endpoints ?? [],
26
- // Payload prefixes /api, so the full path is /api/mcp.
47
+ // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the
48
+ // request with dev auto-login turned off, so Payload doesn't authenticate it first.
27
49
  {
50
+ disableAuth: true,
28
51
  handler: mcpEndpoint,
29
52
  method: 'post',
30
53
  path: '/mcp'
31
54
  },
32
- // Streamable HTTP's optional server=>client GET stream. We don't offer
33
- // one, so answer 405 per spec-— clients then skip it cleanly
34
55
  {
35
- handler: ()=>new Response(null, {
36
- headers: {
37
- Allow: 'POST'
38
- },
39
- status: 405
40
- }),
56
+ disableAuth: true,
57
+ handler: mcpEndpoint,
41
58
  method: 'get',
42
59
  path: '/mcp'
43
- }
60
+ },
61
+ {
62
+ disableAuth: true,
63
+ handler: oauthProtectedResourceEndpoint,
64
+ method: 'get',
65
+ path: '/mcp/oauth-protected-resource'
66
+ },
67
+ ...oauthServerEndpoints
44
68
  ]
45
69
  };
46
70
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { definePlugin } from 'payload'\n\nimport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'\n\nimport { mcpEndpoint } from './endpoint/index.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\n\ndeclare module 'payload' {\n export interface PayloadRequestAPI {\n MCP: true\n }\n interface RegisteredPlugins {\n /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */\n '@payloadcms/plugin-mcp': MCPPluginConfig\n }\n}\n\nexport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }\n\nexport { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'\n\nexport const mcpPlugin = definePlugin<MCPPluginConfig>({\n slug: '@payloadcms/plugin-mcp',\n order: 10,\n plugin: ({ config, options, plugins }) => {\n const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })\n\n // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.\n const registered = plugins['@payloadcms/plugin-mcp']\n if (registered) {\n // @ts-expect-error\n registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options\n }\n\n if (pluginConfig.disabled) {\n return config\n }\n\n return {\n ...config,\n endpoints: [\n ...(config.endpoints ?? []),\n // Payload prefixes /api, so the full path is /api/mcp.\n { handler: mcpEndpoint, method: 'post', path: '/mcp' },\n // Streamable HTTP's optional server=>client GET stream. We don't offer\n // one, so answer 405 per spec-— clients then skip it cleanly\n {\n handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),\n method: 'get',\n path: '/mcp',\n },\n ],\n }\n },\n})\n"],"names":["definePlugin","mcpEndpoint","sanitizeMCPConfig","defineCollectionTool","defineGlobalTool","definePrompt","defineTool","mcpPlugin","slug","order","plugin","config","options","plugins","pluginConfig","registered","sanitizedOptions","disabled","endpoints","handler","method","path","Response","headers","Allow","status"],"mappings":"AAAA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,WAAW,QAAQ,sBAAqB;AACjD,SAASC,iBAAiB,QAAQ,6BAA4B;AAc9D,SAASC,oBAAoB,EAAEC,gBAAgB,EAAEC,YAAY,EAAEC,UAAU,QAAQ,kBAAiB;AAElG,OAAO,MAAMC,YAAYP,aAA8B;IACrDQ,MAAM;IACNC,OAAO;IACPC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAE;QACnC,MAAMC,eAAeZ,kBAAkB;YAAES;YAAQG,cAAcF;QAAQ;QAEvE,gFAAgF;QAChF,MAAMG,aAAaF,OAAO,CAAC,yBAAyB;QACpD,IAAIE,YAAY;YACd,mBAAmB;YACnBA,WAAWC,gBAAgB,GAAGF;QAChC;QAEA,IAAIA,aAAaG,QAAQ,EAAE;YACzB,OAAON;QACT;QAEA,OAAO;YACL,GAAGA,MAAM;YACTO,WAAW;mBACLP,OAAOO,SAAS,IAAI,EAAE;gBAC1B,uDAAuD;gBACvD;oBAAEC,SAASlB;oBAAamB,QAAQ;oBAAQC,MAAM;gBAAO;gBACrD,uEAAuE;gBACvE,6DAA6D;gBAC7D;oBACEF,SAAS,IAAM,IAAIG,SAAS,MAAM;4BAAEC,SAAS;gCAAEC,OAAO;4BAAO;4BAAGC,QAAQ;wBAAI;oBAC5EL,QAAQ;oBACRC,MAAM;gBACR;aACD;QACH;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { definePlugin } from 'payload'\n\nimport type {\n AuthorizedMCP,\n MCPBuiltinOAuthConfig,\n MCPExternalOAuthConfig,\n MCPOAuthConfig,\n MCPOAuthTokens,\n MCPPluginConfig,\n SanitizedMCPPluginConfig,\n} from './types.js'\n\nimport { mcpEndpoint } from './endpoint/index.js'\nimport { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'\nimport { authorizeViewPath, oauthServerEndpoints } from './endpoint/oauthServer.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\n\ndeclare module 'payload' {\n export interface PayloadRequestAPI {\n MCP: true\n }\n interface RegisteredPlugins {\n /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */\n '@payloadcms/plugin-mcp': MCPPluginConfig\n }\n export interface RequestContext {\n /** Set on MCP requests before they're authenticated. */\n mcp?: {\n /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */\n resource: string\n }\n }\n}\n\nexport type {\n AuthorizedMCP,\n MCPBuiltinOAuthConfig,\n MCPExternalOAuthConfig,\n MCPOAuthConfig,\n MCPOAuthTokens,\n MCPPluginConfig,\n SanitizedMCPPluginConfig,\n}\n\nexport { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'\nexport { oauthProtectedResourceHandler } from './endpoint/oauth.js'\n\nexport const mcpPlugin = definePlugin<MCPPluginConfig>({\n slug: '@payloadcms/plugin-mcp',\n order: 10,\n plugin: ({ config, options, plugins }) => {\n const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })\n\n // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.\n const registered = plugins['@payloadcms/plugin-mcp']\n if (registered) {\n // @ts-expect-error\n registered.sanitizedOptions = pluginConfig\n }\n\n if (pluginConfig.disabled) {\n return config\n }\n\n return {\n ...config,\n admin: {\n ...config.admin,\n components: {\n ...config.admin?.components,\n views: {\n ...config.admin?.components?.views,\n // Where users allow MCP clients, for the built-in OAuth server\n mcpAuthorize: {\n Component: '@payloadcms/plugin-mcp/rsc#MCPAuthorizeView',\n exact: true,\n meta: { title: 'Allow an MCP client' },\n path: authorizeViewPath,\n },\n },\n },\n },\n endpoints: [\n ...(config.endpoints ?? []),\n // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the\n // request with dev auto-login turned off, so Payload doesn't authenticate it first.\n { disableAuth: true, handler: mcpEndpoint, method: 'post', path: '/mcp' },\n { disableAuth: true, handler: mcpEndpoint, method: 'get', path: '/mcp' },\n {\n disableAuth: true,\n handler: oauthProtectedResourceEndpoint,\n method: 'get',\n path: '/mcp/oauth-protected-resource',\n },\n ...oauthServerEndpoints,\n ],\n }\n },\n})\n"],"names":["definePlugin","mcpEndpoint","oauthProtectedResourceEndpoint","authorizeViewPath","oauthServerEndpoints","sanitizeMCPConfig","defineCollectionTool","defineGlobalTool","definePrompt","defineTool","oauthProtectedResourceHandler","mcpPlugin","slug","order","plugin","config","options","plugins","pluginConfig","registered","sanitizedOptions","disabled","admin","components","views","mcpAuthorize","Component","exact","meta","title","path","endpoints","disableAuth","handler","method"],"mappings":"AAAA,SAASA,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