@payloadcms/plugin-mcp 4.0.0-internal.016994f → 4.0.0-internal.0731f09

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 (186) hide show
  1. package/bin.js +0 -7
  2. package/dist/endpoint/access.d.ts.map +1 -1
  3. package/dist/endpoint/access.js +17 -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 +46 -4
  7. package/dist/endpoint/index.js.map +1 -1
  8. package/dist/endpoint/oauth.d.ts +39 -0
  9. package/dist/endpoint/oauth.d.ts.map +1 -0
  10. package/dist/endpoint/oauth.js +92 -0
  11. package/dist/endpoint/oauth.js.map +1 -0
  12. package/dist/endpoint/oauthServer.d.ts +11 -0
  13. package/dist/endpoint/oauthServer.d.ts.map +1 -0
  14. package/dist/endpoint/oauthServer.js +351 -0
  15. package/dist/endpoint/oauthServer.js.map +1 -0
  16. package/dist/index.d.ts +10 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +15 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/mcp/buildMcpServer.d.ts +2 -2
  21. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  22. package/dist/mcp/buildMcpServer.js +36 -24
  23. package/dist/mcp/buildMcpServer.js.map +1 -1
  24. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  25. package/dist/mcp/builtin/collections/authTools.js +80 -56
  26. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  27. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  28. package/dist/mcp/builtin/collections/countTool.js +9 -14
  29. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  30. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  31. package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
  32. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  33. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  34. package/dist/mcp/builtin/collections/createTool.js +48 -49
  35. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  36. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  37. package/dist/mcp/builtin/collections/deleteTool.js +44 -43
  38. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  39. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  40. package/dist/mcp/builtin/collections/duplicateTool.js +31 -37
  41. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  42. package/dist/mcp/builtin/collections/fileInput.d.ts +21 -21
  43. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  44. package/dist/mcp/builtin/collections/fileInput.js +34 -70
  45. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  46. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  47. package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
  48. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  49. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  50. package/dist/mcp/builtin/collections/findTool.js +28 -46
  51. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  52. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  53. package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
  54. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  55. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  56. package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
  57. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  58. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  59. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +30 -14
  60. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  61. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  62. package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
  63. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  64. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  65. package/dist/mcp/builtin/collections/updateTool.js +55 -87
  66. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  67. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +11 -11
  68. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
  69. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  70. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  71. package/dist/mcp/builtin/formatEntityError.js +55 -0
  72. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  73. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  74. package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
  75. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  76. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  77. package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
  78. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  79. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  80. package/dist/mcp/builtin/globals/findTool.js +10 -16
  81. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  82. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  83. package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
  84. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  85. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  86. package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
  87. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  88. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  89. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +29 -13
  90. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  91. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  92. package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
  93. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  94. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  95. package/dist/mcp/builtin/globals/updateTool.js +27 -36
  96. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  97. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  98. package/dist/mcp/sanitizeMCPConfig.js +3 -0
  99. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  100. package/dist/stdio.js +4 -3
  101. package/dist/stdio.js.map +1 -1
  102. package/dist/types.d.ts +79 -7
  103. package/dist/types.d.ts.map +1 -1
  104. package/dist/types.js.map +1 -1
  105. package/dist/utils/toStandardSchema.js.map +1 -1
  106. package/package.json +23 -28
  107. package/src/endpoint/access.ts +14 -6
  108. package/src/endpoint/index.ts +41 -3
  109. package/src/endpoint/oauth.ts +91 -0
  110. package/src/endpoint/oauthServer.ts +386 -0
  111. package/src/index.ts +38 -5
  112. package/src/mcp/buildMcpServer.ts +40 -30
  113. package/src/mcp/builtin/collections/authTools.ts +82 -71
  114. package/src/mcp/builtin/collections/countTool.ts +9 -21
  115. package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
  116. package/src/mcp/builtin/collections/createTool.ts +71 -96
  117. package/src/mcp/builtin/collections/deleteTool.ts +37 -65
  118. package/src/mcp/builtin/collections/duplicateTool.ts +36 -86
  119. package/src/mcp/builtin/collections/fileInput.spec.ts +2 -2
  120. package/src/mcp/builtin/collections/fileInput.ts +44 -81
  121. package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
  122. package/src/mcp/builtin/collections/findTool.ts +24 -106
  123. package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
  124. package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
  125. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +23 -12
  126. package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -57
  127. package/src/mcp/builtin/collections/updateTool.ts +55 -109
  128. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +12 -12
  129. package/src/mcp/builtin/formatEntityError.ts +77 -0
  130. package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
  131. package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
  132. package/src/mcp/builtin/globals/findTool.ts +13 -52
  133. package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
  134. package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
  135. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +21 -11
  136. package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
  137. package/src/mcp/builtin/globals/updateTool.ts +38 -61
  138. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  139. package/src/stdio.ts +2 -2
  140. package/src/types.ts +79 -7
  141. package/src/utils/toStandardSchema.ts +1 -1
  142. package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
  143. package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
  144. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  145. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  146. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  147. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  148. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  149. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  150. package/dist/mcp/builtin/validateEntityData.js +0 -82
  151. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  152. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  153. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  154. package/dist/utils/getVirtualFieldNames.js +0 -35
  155. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  156. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
  157. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
  158. package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
  159. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
  160. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
  161. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  162. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
  163. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  164. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
  165. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  166. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
  167. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  168. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
  169. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  170. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  171. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  172. package/dist/utils/transformPointDataToPayload.js +0 -28
  173. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  174. package/dist/utils/whereSchema.d.ts +0 -9
  175. package/dist/utils/whereSchema.d.ts.map +0 -1
  176. package/dist/utils/whereSchema.js +0 -13
  177. package/dist/utils/whereSchema.js.map +0 -1
  178. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  179. package/src/mcp/builtin/validateEntityData.ts +0 -132
  180. package/src/utils/getVirtualFieldNames.ts +0 -53
  181. package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
  182. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
  183. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
  184. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
  185. package/src/utils/transformPointDataToPayload.ts +0 -40
  186. package/src/utils/whereSchema.ts +0 -24
@@ -0,0 +1,386 @@
1
+ import type {
2
+ OAuthClientInformationFull,
3
+ OAuthTokens,
4
+ OpenIdProviderDiscoveryMetadata,
5
+ } from '@modelcontextprotocol/server'
6
+ import type { Endpoint, PayloadHandler, PayloadRequest } from 'payload'
7
+
8
+ import { OAuthErrorCode } from '@modelcontextprotocol/server'
9
+ import { createHash } from 'crypto'
10
+ import { APIError, createAuthToken } from 'payload'
11
+ import { formatAdminURL } from 'payload/shared'
12
+
13
+ import type { MCPBuiltinOAuthConfig } from '../types.js'
14
+
15
+ import { getPluginConfig } from '../utils/getPluginConfig.js'
16
+ import { getMCPURL } from './oauth.js'
17
+
18
+ type Client = { name: string; redirectURIs: string[] }
19
+
20
+ type Consent = {
21
+ clientID: string
22
+ codeChallenge: string
23
+ collection: string
24
+ redirectURI: string
25
+ state: null | string
26
+ userID: number | string
27
+ }
28
+
29
+ type Code = {
30
+ accessToken: string
31
+ clientID: string
32
+ codeChallenge: string
33
+ expiresIn?: number
34
+ redirectURI: string
35
+ }
36
+
37
+ /**
38
+ * Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is
39
+ * `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and
40
+ * the client receives the access token `issueToken` creates.
41
+ *
42
+ * Clients, consent forms, and authorization codes are encrypted and handed to the client instead
43
+ * of being stored, so nothing is written to the database.
44
+ */
45
+ export const oauthServerEndpoints: Endpoint[] = [
46
+ {
47
+ disableAuth: true,
48
+ handler: (req) => withIssuer(req, (issuer) => metadataResponse(issuer)),
49
+ method: 'get',
50
+ // OpenID discovery is the only metadata location MCP clients check below the issuer's path,
51
+ // which lets this work under /api without a route at the site root
52
+ path: '/mcp/oauth/.well-known/openid-configuration',
53
+ },
54
+ {
55
+ disableAuth: true,
56
+ handler: (req) => withIssuer(req, () => Response.json({ keys: [] })),
57
+ method: 'get',
58
+ path: '/mcp/oauth/jwks',
59
+ },
60
+ {
61
+ disableAuth: true,
62
+ handler: (req) => withIssuer(req, () => register(req)),
63
+ method: 'post',
64
+ path: '/mcp/oauth/register',
65
+ },
66
+ {
67
+ handler: (req) => withIssuer(req, () => authorize(req)),
68
+ method: 'get',
69
+ path: '/mcp/oauth/authorize',
70
+ },
71
+ {
72
+ handler: (req) => withIssuer(req, () => approve(req)),
73
+ method: 'post',
74
+ path: '/mcp/oauth/authorize',
75
+ },
76
+ {
77
+ disableAuth: true,
78
+ handler: (req) => withIssuer(req, () => token(req)),
79
+ method: 'post',
80
+ path: '/mcp/oauth/token',
81
+ },
82
+ ]
83
+
84
+ /** The authorization server URL, or `undefined` when Payload isn't the authorization server. */
85
+ const getIssuer = (req: PayloadRequest): string | undefined =>
86
+ getPluginConfig({ config: req.payload.config }).oauth?.type === 'builtin'
87
+ ? `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth`
88
+ : undefined
89
+
90
+ const withIssuer = (
91
+ req: PayloadRequest,
92
+ handler: (issuer: string) => Promise<Response> | Response,
93
+ ): Promise<Response> | Response => {
94
+ const issuer = getIssuer(req)
95
+ return issuer ? handler(issuer) : new Response(null, { status: 404 })
96
+ }
97
+
98
+ const metadataResponse = (issuer: string): Response =>
99
+ Response.json(
100
+ {
101
+ authorization_endpoint: `${issuer}/authorize`,
102
+ code_challenge_methods_supported: ['S256'],
103
+ grant_types_supported: ['authorization_code'],
104
+ // Required by OpenID discovery. No ID tokens are issued.
105
+ id_token_signing_alg_values_supported: ['RS256'],
106
+ issuer,
107
+ jwks_uri: `${issuer}/jwks`,
108
+ registration_endpoint: `${issuer}/register`,
109
+ response_types_supported: ['code'],
110
+ subject_types_supported: ['public'],
111
+ token_endpoint: `${issuer}/token`,
112
+ token_endpoint_auth_methods_supported: ['none'],
113
+ } satisfies OpenIdProviderDiscoveryMetadata,
114
+ { headers: { 'Access-Control-Allow-Origin': '*' } },
115
+ )
116
+
117
+ const register: PayloadHandler = async (req) => {
118
+ const { client_name, redirect_uris } = await req.json!().catch(() => ({}))
119
+
120
+ if (
121
+ !Array.isArray(redirect_uris) ||
122
+ !redirect_uris.length ||
123
+ !redirect_uris.every(
124
+ (uri) => typeof uri === 'string' && URL.canParse(uri) && !uri.includes('#'),
125
+ )
126
+ ) {
127
+ return Response.json({ error: OAuthErrorCode.InvalidRedirectUri }, { status: 400 })
128
+ }
129
+
130
+ const client: Client = {
131
+ name: typeof client_name === 'string' ? client_name : 'An MCP client',
132
+ redirectURIs: redirect_uris,
133
+ }
134
+
135
+ return Response.json(
136
+ {
137
+ client_id: seal({ type: 'client', data: client, req }),
138
+ client_name: client.name,
139
+ grant_types: ['authorization_code'],
140
+ redirect_uris: client.redirectURIs,
141
+ response_types: ['code'],
142
+ token_endpoint_auth_method: 'none',
143
+ } satisfies OAuthClientInformationFull,
144
+ { status: 201 },
145
+ )
146
+ }
147
+
148
+ const authorize: PayloadHandler = (req) => {
149
+ const url = new URL(req.url!)
150
+ const params = url.searchParams
151
+ const clientID = params.get('client_id')
152
+ const client = unseal<Client>({ type: 'client', req, value: clientID })
153
+ const redirectURI = params.get('redirect_uri')
154
+
155
+ // Never redirect to an address the client didn't register
156
+ if (!client || !redirectURI || !client.redirectURIs.includes(redirectURI)) {
157
+ return page({
158
+ content: '<p>Start the sign-in again from your MCP client.</p>',
159
+ status: 400,
160
+ title: 'This sign-in link is invalid',
161
+ })
162
+ }
163
+
164
+ const state = params.get('state')
165
+ const codeChallenge = params.get('code_challenge')
166
+
167
+ if (
168
+ params.get('response_type') !== 'code' ||
169
+ params.get('code_challenge_method') !== 'S256' ||
170
+ !codeChallenge
171
+ ) {
172
+ return redirect({ params: { error: OAuthErrorCode.InvalidRequest, state }, redirectURI })
173
+ }
174
+
175
+ if (!req.user) {
176
+ const loginURL = formatAdminURL({ adminRoute: req.payload.config.routes.admin, path: '/login' })
177
+
178
+ return new Response(null, {
179
+ headers: {
180
+ Location: `${loginURL}?redirect=${encodeURIComponent(url.pathname + url.search)}`,
181
+ },
182
+ status: 302,
183
+ })
184
+ }
185
+
186
+ const consent: Consent = {
187
+ clientID: clientID!,
188
+ codeChallenge,
189
+ collection: req.user.collection,
190
+ redirectURI,
191
+ state,
192
+ userID: req.user.id,
193
+ }
194
+
195
+ return page({
196
+ content: `<p>It will be able to use this app's MCP tools as ${escapeHTML(String(req.user.email ?? req.user.id))}, and you will return to ${escapeHTML(new URL(redirectURI).host || redirectURI)}.</p>
197
+ <form method="post">
198
+ <input name="consent" type="hidden" value="${seal({ type: 'consent', data: consent, expiresIn: 20 * 60 * 60, req })}">
199
+ <button name="decision" type="submit" value="allow">Allow</button>
200
+ <button name="decision" type="submit" value="deny">Deny</button>
201
+ </form>`,
202
+ status: 200,
203
+ title: `Allow ${client.name} to use your account?`,
204
+ })
205
+ }
206
+
207
+ const approve: PayloadHandler = async (req) => {
208
+ const form = new URLSearchParams(await req.text!())
209
+ const consent = unseal<Consent>({ type: 'consent', req, value: form.get('consent') })
210
+
211
+ // The form is only valid for the user it was shown to
212
+ if (!consent || req.user?.id !== consent.userID || req.user.collection !== consent.collection) {
213
+ return page({
214
+ content: '<p>Start the sign-in again from your MCP client.</p>',
215
+ status: 400,
216
+ title: 'This sign-in request expired',
217
+ })
218
+ }
219
+
220
+ const { clientID, codeChallenge, redirectURI, state } = consent
221
+
222
+ if (form.get('decision') !== 'allow') {
223
+ return redirect({ params: { error: OAuthErrorCode.AccessDenied, state }, redirectURI })
224
+ }
225
+
226
+ const { issueToken = issueLoginToken } = getPluginConfig({ config: req.payload.config })
227
+ .oauth as MCPBuiltinOAuthConfig
228
+ const { accessToken, expiresIn } = await issueToken({ req })
229
+
230
+ const code: Code = { accessToken, clientID, codeChallenge, expiresIn, redirectURI }
231
+
232
+ return redirect({
233
+ params: { code: seal({ type: 'code', data: code, expiresIn: 60, req }), state },
234
+ redirectURI,
235
+ })
236
+ }
237
+
238
+ const token: PayloadHandler = async (req) => {
239
+ const form = new URLSearchParams(await req.text!())
240
+ const code = unseal<Code>({ type: 'code', req, value: form.get('code') })
241
+
242
+ if (
243
+ form.get('grant_type') !== 'authorization_code' ||
244
+ !code ||
245
+ code.clientID !== form.get('client_id') ||
246
+ code.redirectURI !== form.get('redirect_uri') ||
247
+ // PKCE: only the client that started the sign-in knows the verifier
248
+ createHash('sha256')
249
+ .update(form.get('code_verifier') ?? '')
250
+ .digest('base64url') !== code.codeChallenge
251
+ ) {
252
+ return Response.json({ error: OAuthErrorCode.InvalidGrant }, { status: 400 })
253
+ }
254
+
255
+ return Response.json(
256
+ {
257
+ access_token: code.accessToken,
258
+ expires_in: code.expiresIn,
259
+ token_type: 'Bearer',
260
+ } satisfies OAuthTokens,
261
+ { headers: { 'Cache-Control': 'no-store' } },
262
+ )
263
+ }
264
+
265
+ /** The default `issueToken`: a Payload login token, which Payload's JWT strategy accepts. */
266
+ const issueLoginToken: NonNullable<MCPBuiltinOAuthConfig['issueToken']> = async ({ req }) => {
267
+ const collection = req.payload.collections[req.user!.collection]!
268
+
269
+ if (collection.config.auth.disableLocalStrategy) {
270
+ throw new APIError(
271
+ `The "${collection.config.slug}" collection has its local strategy disabled, so MCP clients can't get Payload login tokens for it. Pass oauth.issueToken to the MCP plugin.`,
272
+ )
273
+ }
274
+
275
+ // The full document, like the one a password login starts the session on
276
+ const user = (await req.payload.db.findOne<NonNullable<PayloadRequest['user']>>({
277
+ collection: collection.config.slug,
278
+ req,
279
+ where: { id: { equals: req.user!.id } },
280
+ }))!
281
+
282
+ const { token } = await createAuthToken({
283
+ collectionConfig: collection.config,
284
+ email: user.email!,
285
+ req,
286
+ user,
287
+ })
288
+
289
+ return { accessToken: token, expiresIn: collection.config.auth.tokenExpiration }
290
+ }
291
+
292
+ /**
293
+ * Encrypts data for the client to hold, so it doesn't need to be stored. `type` keeps one kind
294
+ * from being used as another, e.g. a client ID as an authorization code.
295
+ */
296
+ const seal = ({
297
+ type,
298
+ data,
299
+ expiresIn,
300
+ req,
301
+ }: {
302
+ data: object
303
+ /** Seconds */
304
+ expiresIn?: number
305
+ req: PayloadRequest
306
+ type: string
307
+ }): string =>
308
+ req.payload.encrypt(
309
+ JSON.stringify({ ...data, type, exp: expiresIn && Date.now() + expiresIn * 1000 }),
310
+ )
311
+
312
+ const unseal = <T>({
313
+ type,
314
+ req,
315
+ value,
316
+ }: {
317
+ req: PayloadRequest
318
+ type: string
319
+ value: null | string
320
+ }): T | undefined => {
321
+ // Only the v1 format is authenticated. Older formats decrypt anything without an error.
322
+ if (!value?.startsWith('v1:')) {
323
+ return undefined
324
+ }
325
+
326
+ try {
327
+ const data = JSON.parse(req.payload.decrypt(value))
328
+ return data.type === type && (!data.exp || data.exp > Date.now()) ? data : undefined
329
+ } catch {
330
+ return undefined
331
+ }
332
+ }
333
+
334
+ const redirect = ({
335
+ params,
336
+ redirectURI,
337
+ }: {
338
+ params: Record<string, null | string>
339
+ redirectURI: string
340
+ }): Response => {
341
+ const location = new URL(redirectURI)
342
+
343
+ for (const [key, value] of Object.entries(params)) {
344
+ if (value) {
345
+ location.searchParams.set(key, value)
346
+ }
347
+ }
348
+
349
+ return new Response(null, { headers: { Location: location.href }, status: 302 })
350
+ }
351
+
352
+ const page = ({
353
+ content,
354
+ status,
355
+ title,
356
+ }: {
357
+ content: string
358
+ status: number
359
+ title: string
360
+ }): Response =>
361
+ new Response(
362
+ `<!doctype html>
363
+ <html lang="en">
364
+ <head>
365
+ <meta charset="utf-8">
366
+ <meta name="viewport" content="width=device-width, initial-scale=1">
367
+ <title>${escapeHTML(title)}</title>
368
+ <style>
369
+ body { font-family: system-ui, sans-serif; margin: 4rem auto; max-width: 32rem; overflow-wrap: anywhere; padding: 0 1rem }
370
+ button { font: inherit; margin-inline-end: 0.5rem; padding: 0.5rem 1rem }
371
+ </style>
372
+ </head>
373
+ <body><h1>${escapeHTML(title)}</h1>${content}</body>
374
+ </html>`,
375
+ {
376
+ headers: {
377
+ // Stop other sites from framing the page to trick users into clicking Allow
378
+ 'Content-Security-Policy': "frame-ancestors 'none'",
379
+ 'Content-Type': 'text/html; charset=utf-8',
380
+ },
381
+ status,
382
+ },
383
+ )
384
+
385
+ const escapeHTML = (value: string): string =>
386
+ value.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`)
package/src/index.ts CHANGED
@@ -1,8 +1,17 @@
1
1
  import { definePlugin } from 'payload'
2
2
 
3
- import type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'
3
+ import type {
4
+ AuthorizedMCP,
5
+ MCPBuiltinOAuthConfig,
6
+ MCPExternalOAuthConfig,
7
+ MCPOAuthConfig,
8
+ MCPPluginConfig,
9
+ SanitizedMCPPluginConfig,
10
+ } from './types.js'
4
11
 
5
12
  import { mcpEndpoint } from './endpoint/index.js'
13
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'
14
+ import { oauthServerEndpoints } from './endpoint/oauthServer.js'
6
15
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
7
16
 
8
17
  declare module 'payload' {
@@ -13,11 +22,26 @@ declare module 'payload' {
13
22
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
14
23
  '@payloadcms/plugin-mcp': MCPPluginConfig
15
24
  }
25
+ export interface RequestContext {
26
+ /** Set on MCP requests before they're authenticated. */
27
+ mcp?: {
28
+ /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */
29
+ resource: string
30
+ }
31
+ }
16
32
  }
17
33
 
18
- export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }
34
+ export type {
35
+ AuthorizedMCP,
36
+ MCPBuiltinOAuthConfig,
37
+ MCPExternalOAuthConfig,
38
+ MCPOAuthConfig,
39
+ MCPPluginConfig,
40
+ SanitizedMCPPluginConfig,
41
+ }
19
42
 
20
43
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'
44
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js'
21
45
 
22
46
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
23
47
  slug: '@payloadcms/plugin-mcp',
@@ -29,7 +53,7 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
29
53
  const registered = plugins['@payloadcms/plugin-mcp']
30
54
  if (registered) {
31
55
  // @ts-expect-error
32
- registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options
56
+ registered.sanitizedOptions = pluginConfig
33
57
  }
34
58
 
35
59
  if (pluginConfig.disabled) {
@@ -40,15 +64,24 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
40
64
  ...config,
41
65
  endpoints: [
42
66
  ...(config.endpoints ?? []),
43
- // Payload prefixes /api, so the full path is /api/mcp.
44
- { handler: mcpEndpoint, method: 'post', path: '/mcp' },
67
+ // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the
68
+ // request with dev auto-login turned off, so Payload doesn't authenticate it first.
69
+ { disableAuth: true, handler: mcpEndpoint, method: 'post', path: '/mcp' },
45
70
  // Streamable HTTP's optional server=>client GET stream. We don't offer
46
71
  // one, so answer 405 per spec-— clients then skip it cleanly
47
72
  {
73
+ disableAuth: true,
48
74
  handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),
49
75
  method: 'get',
50
76
  path: '/mcp',
51
77
  },
78
+ {
79
+ disableAuth: true,
80
+ handler: oauthProtectedResourceEndpoint,
81
+ method: 'get',
82
+ path: '/mcp/oauth-protected-resource',
83
+ },
84
+ ...oauthServerEndpoints,
52
85
  ],
53
86
  }
54
87
  },
@@ -1,6 +1,7 @@
1
+ import type { PayloadRequest } from 'payload'
2
+
1
3
  import { McpServer, type ServerContext } from '@modelcontextprotocol/server'
2
- import { APIError, type PayloadRequest } from 'payload'
3
- import { z } from 'zod'
4
+ import { APIError, strictObject, z } from 'payload'
4
5
 
5
6
  import type {
6
7
  AuthorizedMCP,
@@ -24,7 +25,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js'
24
25
  *
25
26
  * `req` is the request context handlers see. For HTTP it's the live
26
27
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
27
- * synthesized one built via `createLocalReq`.
28
+ * synthesized one built via `createPayloadRequest`.
28
29
  */
29
30
  export const buildMcpServer = ({
30
31
  authorizedMCP,
@@ -35,6 +36,8 @@ export const buildMcpServer = ({
35
36
  pluginConfig: SanitizedMCPPluginConfig
36
37
  req: PayloadRequest
37
38
  }): McpServer => {
39
+ z.config(z.locales.en())
40
+
38
41
  const serverOptions = pluginConfig.mcp?.serverOptions || {}
39
42
  const server = new McpServer(
40
43
  { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },
@@ -68,7 +71,7 @@ export const buildMcpServer = ({
68
71
 
69
72
  /**
70
73
  * Runs a collection/global tool call:
71
- * - reads `collectionSlug` / `globalSlug` from the input
74
+ * - reads `slug` from the input
72
75
  * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug
73
76
  * - runs the tool handler and finalizes its response
74
77
  */
@@ -82,16 +85,15 @@ export const buildMcpServer = ({
82
85
  serverContext: ServerContext
83
86
  }): Promise<MCPToolResponse> => {
84
87
  const entity = item.type === 'collectionTool' ? 'collection' : 'global'
85
- const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'
86
88
  const toolInput = (input ?? {}) as Record<string, unknown>
87
- const slug = toolInput[slugKey] as string | undefined
89
+ const slug = toolInput.slug as string | undefined
88
90
 
89
91
  if (!slug) {
90
92
  return {
91
93
  content: [
92
94
  {
93
95
  type: 'text',
94
- text: `Error: "${item.mcpName}" requires ${slugKey}. Use getConfigInfo to inspect ${entity} slugs.`,
96
+ text: `Error: "${item.mcpName}" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,
95
97
  },
96
98
  ],
97
99
  isError: true,
@@ -126,8 +128,8 @@ export const buildMcpServer = ({
126
128
  serverContext,
127
129
  }
128
130
  const response = await (match.type === 'collectionTool'
129
- ? match.tool.handler({ ...handlerArgs, collectionSlug: slug })
130
- : match.tool.handler({ ...handlerArgs, globalSlug: slug }))
131
+ ? match.tool.handler({ ...handlerArgs, slug })
132
+ : match.tool.handler({ ...handlerArgs, slug }))
131
133
 
132
134
  return finalizeToolResponse({
133
135
  input: toolInput,
@@ -149,10 +151,7 @@ export const buildMcpServer = ({
149
151
  }
150
152
  registeredEntityTools.add(item.mcpName)
151
153
 
152
- const inputSchema = withSlugInput({
153
- name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',
154
- input: item.tool.input,
155
- })
154
+ const inputSchema = withSlugInput({ input: item.tool.input })
156
155
 
157
156
  server.registerTool(
158
157
  item.mcpName,
@@ -246,39 +245,50 @@ export const buildMcpServer = ({
246
245
  return server
247
246
  }
248
247
 
249
- const withSlugInput = ({
250
- name,
251
- input,
252
- }: {
253
- input?: ToolInputSchema
254
- name: 'collectionSlug' | 'globalSlug'
255
- }): ToolInputSchema => {
256
- const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'
257
- const slugSchema = z.string().describe(description)
248
+ const withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {
249
+ const description = 'The target slug.'
250
+ const slugSchema = z.string().check(z.describe(description))
258
251
 
259
252
  if (!input) {
260
- return z.object({ [name]: slugSchema })
253
+ return strictObject({ slug: slugSchema })
261
254
  }
262
255
 
263
- if (input instanceof z.ZodObject) {
264
- return input.extend({ [name]: slugSchema })
256
+ if (typeof input === 'object' && input !== null && '~standard' in input) {
257
+ const schema = input['~standard'].jsonSchema.input({ target: 'draft-2020-12' })
258
+ const properties = schema.properties as Record<string, unknown> | undefined
259
+
260
+ if (properties?.slug) {
261
+ return input
262
+ }
263
+
264
+ return addSlugToJSONSchema({ description, schema })
265
265
  }
266
266
 
267
- const schema = input as {
267
+ return addSlugToJSONSchema({ description, schema: input })
268
+ }
269
+
270
+ const addSlugToJSONSchema = ({
271
+ description,
272
+ schema,
273
+ }: {
274
+ description: string
275
+ schema: JsonSchemaType
276
+ }): JsonSchemaType => {
277
+ const objectSchema = schema as {
268
278
  properties?: Record<string, JsonSchemaType>
269
279
  required?: string[]
270
280
  } & JsonSchemaType
271
281
 
272
282
  return {
273
- ...schema,
283
+ ...objectSchema,
274
284
  type: 'object',
275
285
  properties: {
276
- ...schema.properties,
277
- [name]: {
286
+ ...objectSchema.properties,
287
+ slug: {
278
288
  type: 'string',
279
289
  description,
280
290
  },
281
291
  },
282
- required: Array.from(new Set([name, ...(schema.required ?? [])])),
292
+ required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),
283
293
  }
284
294
  }