@payloadcms/plugin-mcp 4.0.0-internal.5a4aa81 → 4.0.0-internal.5d2e3d1

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 (120) 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 +42 -5
  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 +1 -1
  34. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  35. package/dist/mcp/buildMcpServer.js +3 -3
  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 +4 -3
  39. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  40. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  41. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  42. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  43. package/dist/mcp/builtin/collections/deleteTool.js +9 -3
  44. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  45. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  46. package/dist/mcp/builtin/collections/duplicateTool.js +6 -2
  47. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  48. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  49. package/dist/mcp/builtin/collections/fileInput.js +19 -54
  50. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  51. package/dist/mcp/builtin/collections/findTool.js +8 -4
  52. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  53. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  54. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +19 -3
  55. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  56. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  57. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  58. package/dist/mcp/builtin/collections/updateTool.js +6 -2
  59. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  60. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
  61. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  62. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  63. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +19 -3
  64. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  65. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  66. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  67. package/dist/mcp/sanitizeMCPConfig.js +3 -0
  68. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  69. package/dist/stdio.js +4 -3
  70. package/dist/stdio.js.map +1 -1
  71. package/dist/types.d.ts +105 -3
  72. package/dist/types.d.ts.map +1 -1
  73. package/dist/types.js.map +1 -1
  74. package/dist/utils/seal.d.ts +17 -0
  75. package/dist/utils/seal.d.ts.map +1 -0
  76. package/dist/utils/seal.js +24 -0
  77. package/dist/utils/seal.js.map +1 -0
  78. package/dist/utils/toStandardSchema.js.map +1 -1
  79. package/dist/views/Authorize/AllowButtons/index.d.ts +18 -0
  80. package/dist/views/Authorize/AllowButtons/index.d.ts.map +1 -0
  81. package/dist/views/Authorize/AllowButtons/index.js +88 -0
  82. package/dist/views/Authorize/AllowButtons/index.js.map +1 -0
  83. package/dist/views/Authorize/index.css +19 -0
  84. package/dist/views/Authorize/index.d.ts +9 -0
  85. package/dist/views/Authorize/index.d.ts.map +1 -0
  86. package/dist/views/Authorize/index.js +86 -0
  87. package/dist/views/Authorize/index.js.map +1 -0
  88. package/package.json +30 -26
  89. package/src/endpoint/access.ts +45 -3
  90. package/src/endpoint/index.ts +50 -4
  91. package/src/endpoint/oauth.ts +108 -0
  92. package/src/endpoint/oauthLoginToken.ts +94 -0
  93. package/src/endpoint/oauthServer.ts +452 -0
  94. package/src/exports/client.ts +1 -1
  95. package/src/exports/rsc.ts +1 -0
  96. package/src/index.ts +53 -9
  97. package/src/mcp/buildMcpServer.ts +5 -5
  98. package/src/mcp/builtin/collections/authTools.ts +7 -4
  99. package/src/mcp/builtin/collections/createTool.ts +1 -3
  100. package/src/mcp/builtin/collections/deleteTool.ts +6 -4
  101. package/src/mcp/builtin/collections/duplicateTool.ts +3 -2
  102. package/src/mcp/builtin/collections/fileInput.ts +17 -59
  103. package/src/mcp/builtin/collections/findTool.ts +4 -4
  104. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +12 -1
  105. package/src/mcp/builtin/collections/restoreVersionTool.ts +1 -1
  106. package/src/mcp/builtin/collections/updateTool.ts +3 -2
  107. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +1 -1
  108. package/src/mcp/builtin/globals/findTool.ts +1 -1
  109. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +11 -1
  110. package/src/mcp/builtin/globals/updateTool.ts +1 -1
  111. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  112. package/src/stdio.ts +2 -2
  113. package/src/types.ts +105 -3
  114. package/src/utils/seal.ts +46 -0
  115. package/src/utils/toStandardSchema.ts +1 -1
  116. package/src/views/Authorize/AllowButtons/index.tsx +97 -0
  117. package/src/views/Authorize/index.css +19 -0
  118. package/src/views/Authorize/index.tsx +93 -0
  119. package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
  120. package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
@@ -0,0 +1,452 @@
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 { formatAdminURL } from 'payload/shared'
11
+
12
+ import type { MCPBuiltinOAuthConfig, MCPOAuthTokens } from '../types.js'
13
+
14
+ import { getPluginConfig } from '../utils/getPluginConfig.js'
15
+ import { seal, unseal } from '../utils/seal.js'
16
+ import { getMCPResource } from './oauth.js'
17
+ import { issueLoginToken, refreshLoginToken } from './oauthLoginToken.js'
18
+
19
+ export type Client = { name: string; redirectURIs: string[] }
20
+
21
+ export type Consent = {
22
+ clientID: string
23
+ codeChallenge: string
24
+ collection: string
25
+ redirectURI: string
26
+ state: null | string
27
+ userID: number | string
28
+ }
29
+
30
+ type Code = {
31
+ clientID: string
32
+ codeChallenge: string
33
+ redirectURI: string
34
+ tokens: MCPOAuthTokens
35
+ }
36
+
37
+ /** Why `MCPAuthorizeView` can't show the Allow form. */
38
+ export type AuthorizeViewError = 'expired' | 'invalid-link'
39
+
40
+ /** The admin page where users allow MCP clients, `MCPAuthorizeView`. */
41
+ export const authorizeViewPath = '/mcp/authorize'
42
+
43
+ type RefreshToken = {
44
+ clientID: string
45
+ refreshToken: string
46
+ }
47
+
48
+ /**
49
+ * Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is
50
+ * `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and
51
+ * the client receives the tokens `issueToken` creates.
52
+ *
53
+ * Clients, consent forms, authorization codes, and refresh tokens are encrypted and handed to the
54
+ * client instead of being stored. Only the default tokens write to the database, to the user's
55
+ * login sessions.
56
+ */
57
+ export const oauthServerEndpoints: Endpoint[] = [
58
+ {
59
+ disableAuth: true,
60
+ handler: (req) => withIssuer(req, (issuer) => metadataResponse(issuer)),
61
+ method: 'get',
62
+ // OpenID discovery is the only metadata location MCP clients check below the issuer's path,
63
+ // which lets this work under /api without a route at the site root
64
+ path: '/mcp/oauth/.well-known/openid-configuration',
65
+ },
66
+ {
67
+ disableAuth: true,
68
+ handler: (req) => withIssuer(req, () => Response.json({ keys: [] })),
69
+ method: 'get',
70
+ path: '/mcp/oauth/jwks',
71
+ },
72
+ {
73
+ disableAuth: true,
74
+ handler: (req) => withIssuer(req, () => register(req)),
75
+ method: 'post',
76
+ path: '/mcp/oauth/register',
77
+ },
78
+ {
79
+ handler: (req) => withIssuer(req, () => authorize(req)),
80
+ method: 'get',
81
+ path: '/mcp/oauth/authorize',
82
+ },
83
+ {
84
+ handler: (req) => withIssuer(req, (issuer) => approve({ issuer, req })),
85
+ method: 'post',
86
+ path: '/mcp/oauth/authorize',
87
+ },
88
+ {
89
+ disableAuth: true,
90
+ handler: (req) => withIssuer(req, () => token(req)),
91
+ method: 'post',
92
+ path: '/mcp/oauth/token',
93
+ },
94
+ ]
95
+
96
+ /** The authorization server URL, or `undefined` when Payload isn't the authorization server. */
97
+ const getIssuer = (req: PayloadRequest): string | undefined =>
98
+ getPluginConfig({ config: req.payload.config }).oauth?.type === 'builtin'
99
+ ? `${getMCPResource({ req })}/oauth`
100
+ : undefined
101
+
102
+ const withIssuer = (
103
+ req: PayloadRequest,
104
+ handler: (issuer: string) => Promise<Response> | Response,
105
+ ): Promise<Response> | Response => {
106
+ const issuer = getIssuer(req)
107
+ return issuer ? handler(issuer) : new Response(null, { status: 404 })
108
+ }
109
+
110
+ /**
111
+ * The user logged in to this browser, who can allow MCP clients. Tokens and API keys in the
112
+ * `Authorization` header can't, or an MCP client could use its access token to approve itself a
113
+ * new, separate login.
114
+ */
115
+ const getBrowserUser = (req: PayloadRequest): PayloadRequest['user'] =>
116
+ req.headers.has('Authorization') ? null : req.user
117
+
118
+ const metadataResponse = (issuer: string): Response =>
119
+ Response.json(
120
+ {
121
+ authorization_endpoint: `${issuer}/authorize`,
122
+ authorization_response_iss_parameter_supported: true,
123
+ code_challenge_methods_supported: ['S256'],
124
+ grant_types_supported: ['authorization_code', 'refresh_token'],
125
+ // Required by OpenID discovery. No ID tokens are issued.
126
+ id_token_signing_alg_values_supported: ['RS256'],
127
+ issuer,
128
+ jwks_uri: `${issuer}/jwks`,
129
+ registration_endpoint: `${issuer}/register`,
130
+ response_types_supported: ['code'],
131
+ subject_types_supported: ['public'],
132
+ token_endpoint: `${issuer}/token`,
133
+ token_endpoint_auth_methods_supported: ['none'],
134
+ } satisfies OpenIdProviderDiscoveryMetadata,
135
+ // Not cached, since without `serverURL` its URLs come from the request
136
+ { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },
137
+ )
138
+
139
+ const register: PayloadHandler = async (req) => {
140
+ const { client_name, redirect_uris } = await req.json!().catch(() => ({}))
141
+
142
+ if (
143
+ !Array.isArray(redirect_uris) ||
144
+ !redirect_uris.length ||
145
+ !redirect_uris.every(isValidRedirectURI)
146
+ ) {
147
+ return Response.json({ error: OAuthErrorCode.InvalidRedirectUri }, { status: 400 })
148
+ }
149
+
150
+ const client: Client = {
151
+ name: typeof client_name === 'string' ? client_name : 'An MCP client',
152
+ redirectURIs: redirect_uris,
153
+ }
154
+
155
+ return Response.json(
156
+ {
157
+ client_id: seal({ type: 'client', data: client, req }),
158
+ client_name: client.name,
159
+ grant_types: ['authorization_code', 'refresh_token'],
160
+ redirect_uris: client.redirectURIs,
161
+ response_types: ['code'],
162
+ token_endpoint_auth_method: 'none',
163
+ } satisfies OAuthClientInformationFull,
164
+ { status: 201 },
165
+ )
166
+ }
167
+
168
+ const authorize: PayloadHandler = (req) => {
169
+ const url = new URL(req.url!)
170
+ const params = url.searchParams
171
+ const clientID = params.get('client_id')
172
+ const client = unseal<Client>({ type: 'client', req, value: clientID })
173
+ // Optional when the client registered only one
174
+ const redirectURI =
175
+ params.get('redirect_uri') ??
176
+ (client?.redirectURIs.length === 1 ? client.redirectURIs[0]! : null)
177
+
178
+ // Never redirect to an address the client didn't register
179
+ if (!client || !redirectURI || !client.redirectURIs.includes(redirectURI)) {
180
+ return redirectToAuthorizeView({ params: { error: 'invalid-link' }, req })
181
+ }
182
+
183
+ const state = params.get('state')
184
+ const codeChallenge = params.get('code_challenge')
185
+
186
+ // Not sent to the client's address: anyone can register a client, so that would let a link to
187
+ // this site send users to any site without them doing anything
188
+ if (
189
+ params.get('response_type') !== 'code' ||
190
+ params.get('code_challenge_method') !== 'S256' ||
191
+ !codeChallenge
192
+ ) {
193
+ return redirectToAuthorizeView({ params: { error: 'invalid-link' }, req })
194
+ }
195
+
196
+ const user = getBrowserUser(req)
197
+
198
+ if (!user) {
199
+ const loginURL = formatAdminURL({
200
+ adminRoute: req.payload.config.routes.admin,
201
+ path: req.payload.config.admin.routes.login,
202
+ })
203
+
204
+ return new Response(null, {
205
+ headers: {
206
+ Location: `${loginURL}?redirect=${encodeURIComponent(url.pathname + url.search)}`,
207
+ },
208
+ status: 302,
209
+ })
210
+ }
211
+
212
+ const consent: Consent = {
213
+ clientID: clientID!,
214
+ codeChallenge,
215
+ collection: user.collection,
216
+ redirectURI,
217
+ state,
218
+ userID: user.id,
219
+ }
220
+
221
+ return redirectToAuthorizeView({
222
+ params: { consent: seal({ type: 'consent', data: consent, expiresInSeconds: 20 * 60, req }) },
223
+ req,
224
+ })
225
+ }
226
+
227
+ const approve = async ({
228
+ issuer,
229
+ req,
230
+ }: {
231
+ issuer: string
232
+ req: PayloadRequest
233
+ }): Promise<Response> => {
234
+ // The Allow page is part of the admin panel, which other sites may be able to frame. Only
235
+ // accepting clicks from a top-level page stops them from tricking users into clicking Allow.
236
+ // Browsers too old to send the header get through here, but the page hides its buttons in frames.
237
+ const fetchDestination = req.headers.get('Sec-Fetch-Dest')
238
+ // Only the Allow page itself may submit the form, not a copy of it on another site
239
+ const fetchSite = req.headers.get('Sec-Fetch-Site')
240
+ if (
241
+ (fetchDestination && fetchDestination !== 'document') ||
242
+ (fetchSite && fetchSite !== 'same-origin')
243
+ ) {
244
+ return new Response(null, { status: 403 })
245
+ }
246
+
247
+ const form = new URLSearchParams(await req.text!())
248
+ const consent = unseal<Consent>({ type: 'consent', req, value: form.get('consent') })
249
+ const user = getBrowserUser(req)
250
+
251
+ // The form is only valid for the user it was shown to
252
+ if (!consent || user?.id !== consent.userID || user.collection !== consent.collection) {
253
+ return redirectToAuthorizeView({ params: { error: 'expired' }, req })
254
+ }
255
+
256
+ const { clientID, codeChallenge, redirectURI, state } = consent
257
+
258
+ // Responses to the client name this server in `iss`, so clients that use several authorization
259
+ // servers can tell which one answered
260
+ if (form.get('decision') !== 'allow') {
261
+ return redirect({
262
+ params: { error: OAuthErrorCode.AccessDenied, iss: issuer, state },
263
+ redirectURI,
264
+ })
265
+ }
266
+
267
+ const code: Code = {
268
+ clientID,
269
+ codeChallenge,
270
+ redirectURI,
271
+ tokens: await getTokenHooks(req).issueToken({ req }),
272
+ }
273
+
274
+ return redirect({
275
+ params: {
276
+ code: seal({ type: 'code', data: code, expiresInSeconds: 60, req }),
277
+ iss: issuer,
278
+ state,
279
+ },
280
+ redirectURI,
281
+ })
282
+ }
283
+
284
+ const token: PayloadHandler = async (req) => {
285
+ const form = new URLSearchParams(await req.text!())
286
+ const clientID = form.get('client_id')
287
+ const grantType = form.get('grant_type')
288
+
289
+ if (grantType !== 'authorization_code' && grantType !== 'refresh_token') {
290
+ return Response.json(
291
+ { error: grantType ? OAuthErrorCode.UnsupportedGrantType : OAuthErrorCode.InvalidRequest },
292
+ { status: 400 },
293
+ )
294
+ }
295
+
296
+ const requiredParams =
297
+ grantType === 'refresh_token' ? ['refresh_token'] : ['code', 'code_verifier']
298
+
299
+ if (!clientID || requiredParams.some((param) => !form.get(param))) {
300
+ return Response.json({ error: OAuthErrorCode.InvalidRequest }, { status: 400 })
301
+ }
302
+
303
+ const tokens =
304
+ grantType === 'refresh_token'
305
+ ? await refresh({ clientID, form, req })
306
+ : await redeemCode({ clientID, form, req })
307
+
308
+ if (!tokens) {
309
+ return Response.json({ error: OAuthErrorCode.InvalidGrant }, { status: 400 })
310
+ }
311
+
312
+ return Response.json(
313
+ {
314
+ access_token: tokens.accessToken,
315
+ expires_in: tokens.expiresIn,
316
+ refresh_token:
317
+ tokens.refreshToken &&
318
+ seal({
319
+ type: 'refresh',
320
+ data: { clientID, refreshToken: tokens.refreshToken } satisfies RefreshToken,
321
+ req,
322
+ }),
323
+ token_type: 'Bearer',
324
+ } satisfies OAuthTokens,
325
+ { headers: { 'Cache-Control': 'no-store' } },
326
+ )
327
+ }
328
+
329
+ const redeemCode = async ({
330
+ clientID,
331
+ form,
332
+ req,
333
+ }: {
334
+ clientID: string
335
+ form: URLSearchParams
336
+ req: PayloadRequest
337
+ }): Promise<MCPOAuthTokens | null | undefined> => {
338
+ const code = unseal<Code>({ type: 'code', req, value: form.get('code') })
339
+
340
+ if (
341
+ code?.clientID === clientID &&
342
+ // OAuth 2.1 clients leave it out, since PKCE does its job. OAuth 2.0 clients send it, and it must
343
+ // match then.
344
+ (!form.has('redirect_uri') || form.get('redirect_uri') === code.redirectURI) &&
345
+ // PKCE: only the client that started the sign-in knows the verifier
346
+ createHash('sha256')
347
+ .update(form.get('code_verifier') ?? '')
348
+ .digest('base64url') === code.codeChallenge
349
+ ) {
350
+ // A code must only work once. Trading it also trades its refresh token, with no leeway, so
351
+ // using the code again counts as a copied refresh token: it's refused, and the tokens revoked.
352
+ const hooks = getTokenHooks(req)
353
+ if (hooks.refreshToken && code.tokens.refreshToken) {
354
+ return await hooks.refreshToken({
355
+ refreshToken: code.tokens.refreshToken,
356
+ req,
357
+ reuseInterval: 0,
358
+ })
359
+ }
360
+
361
+ return code.tokens
362
+ }
363
+ }
364
+
365
+ const refresh = async ({
366
+ clientID,
367
+ form,
368
+ req,
369
+ }: {
370
+ clientID: string
371
+ form: URLSearchParams
372
+ req: PayloadRequest
373
+ }): Promise<MCPOAuthTokens | null | undefined> => {
374
+ const refreshToken = unseal<RefreshToken>({
375
+ type: 'refresh',
376
+ req,
377
+ value: form.get('refresh_token'),
378
+ })
379
+
380
+ // Only the client a refresh token was issued to can use it
381
+ if (refreshToken?.clientID === clientID) {
382
+ return await getTokenHooks(req).refreshToken?.({
383
+ refreshToken: refreshToken.refreshToken,
384
+ req,
385
+ })
386
+ }
387
+ }
388
+
389
+ /** `issueToken` and `refreshToken`, or the defaults for Payload login tokens. */
390
+ const getTokenHooks = (req: PayloadRequest) => {
391
+ const oauth = getPluginConfig({ config: req.payload.config }).oauth as MCPBuiltinOAuthConfig
392
+
393
+ return oauth.issueToken
394
+ ? { issueToken: oauth.issueToken, refreshToken: oauth.refreshToken }
395
+ : { issueToken: issueLoginToken, refreshToken: refreshLoginToken }
396
+ }
397
+
398
+ const redirect = ({
399
+ params,
400
+ redirectURI,
401
+ }: {
402
+ params: Record<string, null | string>
403
+ redirectURI: string
404
+ }): Response => {
405
+ const location = new URL(redirectURI)
406
+
407
+ for (const [key, value] of Object.entries(params)) {
408
+ if (value) {
409
+ location.searchParams.set(key, value)
410
+ }
411
+ }
412
+
413
+ return new Response(null, { headers: { Location: location.href }, status: 302 })
414
+ }
415
+
416
+ /**
417
+ * Accepts https, http to the user's own computer only, since the code would otherwise travel
418
+ * unencrypted, and app schemes like `cursor://` that desktop apps register to receive the code.
419
+ */
420
+ const isValidRedirectURI = (uri: unknown): boolean => {
421
+ if (typeof uri !== 'string' || !URL.canParse(uri) || uri.includes('#')) {
422
+ return false
423
+ }
424
+
425
+ const { hostname, protocol } = new URL(uri)
426
+
427
+ if (protocol === 'http:') {
428
+ return ['[::1]', '127.0.0.1', 'localhost'].includes(hostname)
429
+ }
430
+
431
+ // Browser schemes that run or show content instead of sending the code to an app
432
+ return protocol !== 'javascript:' && protocol !== 'data:'
433
+ }
434
+
435
+ /** Sends the browser to `MCPAuthorizeView`, with the Allow form or the reason it can't show it. */
436
+ const redirectToAuthorizeView = ({
437
+ params,
438
+ req,
439
+ }: {
440
+ params: { consent: string } | { error: AuthorizeViewError }
441
+ req: PayloadRequest
442
+ }): Response => {
443
+ const viewURL = formatAdminURL({
444
+ adminRoute: req.payload.config.routes.admin,
445
+ path: authorizeViewPath,
446
+ })
447
+
448
+ return new Response(null, {
449
+ headers: { Location: `${viewURL}?${new URLSearchParams(params)}` },
450
+ status: 302,
451
+ })
452
+ }
@@ -1,3 +1,3 @@
1
1
  'use client'
2
2
 
3
- export {}
3
+ export { AllowButtons } from '../views/Authorize/AllowButtons/index.js'
@@ -0,0 +1 @@
1
+ export { MCPAuthorizeView } from '../views/Authorize/index.js'
package/src/index.ts CHANGED
@@ -1,8 +1,18 @@
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
+ MCPOAuthTokens,
9
+ MCPPluginConfig,
10
+ SanitizedMCPPluginConfig,
11
+ } from './types.js'
4
12
 
5
13
  import { mcpEndpoint } from './endpoint/index.js'
14
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'
15
+ import { authorizeViewPath, oauthServerEndpoints } from './endpoint/oauthServer.js'
6
16
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
7
17
 
8
18
  declare module 'payload' {
@@ -13,11 +23,27 @@ declare module 'payload' {
13
23
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
14
24
  '@payloadcms/plugin-mcp': MCPPluginConfig
15
25
  }
26
+ export interface RequestContext {
27
+ /** Set on MCP requests before they're authenticated. */
28
+ mcp?: {
29
+ /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */
30
+ resource: string
31
+ }
32
+ }
16
33
  }
17
34
 
18
- export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }
35
+ export type {
36
+ AuthorizedMCP,
37
+ MCPBuiltinOAuthConfig,
38
+ MCPExternalOAuthConfig,
39
+ MCPOAuthConfig,
40
+ MCPOAuthTokens,
41
+ MCPPluginConfig,
42
+ SanitizedMCPPluginConfig,
43
+ }
19
44
 
20
45
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'
46
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js'
21
47
 
22
48
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
23
49
  slug: '@payloadcms/plugin-mcp',
@@ -29,7 +55,7 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
29
55
  const registered = plugins['@payloadcms/plugin-mcp']
30
56
  if (registered) {
31
57
  // @ts-expect-error
32
- registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options
58
+ registered.sanitizedOptions = pluginConfig
33
59
  }
34
60
 
35
61
  if (pluginConfig.disabled) {
@@ -38,17 +64,35 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
38
64
 
39
65
  return {
40
66
  ...config,
67
+ admin: {
68
+ ...config.admin,
69
+ components: {
70
+ ...config.admin?.components,
71
+ views: {
72
+ ...config.admin?.components?.views,
73
+ // Where users allow MCP clients, for the built-in OAuth server
74
+ mcpAuthorize: {
75
+ Component: '@payloadcms/plugin-mcp/rsc#MCPAuthorizeView',
76
+ exact: true,
77
+ meta: { title: 'Allow an MCP client' },
78
+ path: authorizeViewPath,
79
+ },
80
+ },
81
+ },
82
+ },
41
83
  endpoints: [
42
84
  ...(config.endpoints ?? []),
43
- // Payload prefixes /api, so the full path is /api/mcp.
44
- { handler: mcpEndpoint, method: 'post', path: '/mcp' },
45
- // Streamable HTTP's optional server=>client GET stream. We don't offer
46
- // one, so answer 405 per spec-— clients then skip it cleanly
85
+ // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the
86
+ // request with dev auto-login turned off, so Payload doesn't authenticate it first.
87
+ { disableAuth: true, handler: mcpEndpoint, method: 'post', path: '/mcp' },
88
+ { disableAuth: true, handler: mcpEndpoint, method: 'get', path: '/mcp' },
47
89
  {
48
- handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),
90
+ disableAuth: true,
91
+ handler: oauthProtectedResourceEndpoint,
49
92
  method: 'get',
50
- path: '/mcp',
93
+ path: '/mcp/oauth-protected-resource',
51
94
  },
95
+ ...oauthServerEndpoints,
52
96
  ],
53
97
  }
54
98
  },
@@ -17,8 +17,6 @@ import type {
17
17
  import { getLogger } from '../utils/getLogger.js'
18
18
  import { toStandardSchema } from '../utils/toStandardSchema.js'
19
19
 
20
- z.config(z.locales.en())
21
-
22
20
  /**
23
21
  * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh
24
22
  * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh
@@ -27,7 +25,7 @@ z.config(z.locales.en())
27
25
  *
28
26
  * `req` is the request context handlers see. For HTTP it's the live
29
27
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
30
- * synthesized one built via `createLocalReq`.
28
+ * synthesized one built via `createPayloadRequest`.
31
29
  */
32
30
  export const buildMcpServer = ({
33
31
  authorizedMCP,
@@ -38,6 +36,8 @@ export const buildMcpServer = ({
38
36
  pluginConfig: SanitizedMCPPluginConfig
39
37
  req: PayloadRequest
40
38
  }): McpServer => {
39
+ z.config(z.locales.en())
40
+
41
41
  const serverOptions = pluginConfig.mcp?.serverOptions || {}
42
42
  const server = new McpServer(
43
43
  { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },
@@ -250,7 +250,7 @@ const withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema
250
250
  const slugSchema = z.string().check(z.describe(description))
251
251
 
252
252
  if (!input) {
253
- return strictObject({ slug: slugSchema }) as unknown as ToolInputSchema
253
+ return strictObject({ slug: slugSchema })
254
254
  }
255
255
 
256
256
  if (typeof input === 'object' && input !== null && '~standard' in input) {
@@ -261,7 +261,7 @@ const withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema
261
261
  return input
262
262
  }
263
263
 
264
- return addSlugToJSONSchema({ description, schema: schema as JsonSchemaType })
264
+ return addSlugToJSONSchema({ description, schema })
265
265
  }
266
266
 
267
267
  return addSlugToJSONSchema({ description, schema: input })
@@ -1,4 +1,4 @@
1
- import { createLocalReq, strictObject, z } from 'payload'
1
+ import { createPayloadRequest, strictObject, z } from 'payload'
2
2
 
3
3
  import type { MCPToolResponse } from '../../../types.js'
4
4
 
@@ -53,7 +53,10 @@ export const authCollectionTool = defineCollectionTool({
53
53
  if (input.headers) {
54
54
  authHeaders = new Headers(input.headers)
55
55
  }
56
- const authReq = await createLocalReq({ req: { headers: authHeaders } }, req.payload)
56
+ const authReq = await createPayloadRequest({
57
+ payload: req.payload,
58
+ req: { headers: authHeaders },
59
+ })
57
60
  const result = await req.payload.auth({ headers: authHeaders, req: authReq })
58
61
 
59
62
  if (result.user) {
@@ -232,7 +235,7 @@ export const unlockCollectionTool = defineCollectionTool({
232
235
  text: `# Account Unlocked\n\n**Collection:** ${slug}\n**Email:** ${input.email}\n**Result:** ${result ? 'Success' : 'Failed'}`,
233
236
  },
234
237
  ],
235
- doc: { result } as Record<string, unknown>,
238
+ doc: { result },
236
239
  }
237
240
  } catch (error) {
238
241
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
@@ -267,7 +270,7 @@ export const verifyCollectionTool = defineCollectionTool({
267
270
  text: `# Email Verification Successful\n\n**Collection:** ${slug}\n**Result:** ${result ? 'Success' : 'Failed'}`,
268
271
  },
269
272
  ],
270
- doc: { result } as Record<string, unknown>,
273
+ doc: { result },
271
274
  }
272
275
  } catch (error) {
273
276
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
@@ -83,9 +83,7 @@ export const createDocumentsTool = defineCollectionTool({
83
83
  select: returning ? select : { id: true },
84
84
  })
85
85
 
86
- docs.push(
87
- returning ? { doc: result as Record<string, unknown>, index } : { id: result.id, index },
88
- )
86
+ docs.push(returning ? { doc: result, index } : { id: result.id, index })
89
87
  } catch (error) {
90
88
  const message = error instanceof Error ? error.message : 'Unknown error'
91
89
  const formattedError = formatEntityError({
@@ -1,4 +1,4 @@
1
- import { deleteDocumentsInputSchema } from 'payload'
1
+ import { deleteDocumentsInputSchema, parseDocumentID } from 'payload'
2
2
 
3
3
  import { defaultAccess } from '../../../defaultAccess.js'
4
4
  import { defineCollectionTool } from '../../../defineTool.js'
@@ -23,7 +23,7 @@ export const deleteDocumentsTool = defineCollectionTool({
23
23
  const payload = req.payload
24
24
  const logger = getLogger({ payload })
25
25
 
26
- const { id, depth, fallbackLocale, locale, where } = input
26
+ const { id, depth, fallbackLocale, locale, trash, where } = input
27
27
 
28
28
  logger.info(
29
29
  `Deleting document from collection: ${slug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`,
@@ -32,11 +32,12 @@ export const deleteDocumentsTool = defineCollectionTool({
32
32
  try {
33
33
  if (id !== undefined) {
34
34
  const result = await payload.delete({
35
- id,
35
+ id: parseDocumentID({ id, collectionSlug: slug, payload }),
36
36
  collection: slug,
37
37
  depth,
38
38
  overrideAccess: authorizedMCP.overrideAccess,
39
39
  req,
40
+ trash,
40
41
  ...(locale && { locale }),
41
42
  ...(fallbackLocale !== undefined && { fallbackLocale }),
42
43
  })
@@ -48,7 +49,7 @@ export const deleteDocumentsTool = defineCollectionTool({
48
49
  text: `Document deleted successfully from collection "${slug}"!\nDeleted document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
49
50
  },
50
51
  ],
51
- doc: result as Record<string, unknown>,
52
+ doc: result,
52
53
  }
53
54
  }
54
55
 
@@ -63,6 +64,7 @@ export const deleteDocumentsTool = defineCollectionTool({
63
64
  depth,
64
65
  overrideAccess: authorizedMCP.overrideAccess,
65
66
  req,
67
+ trash,
66
68
  where,
67
69
  ...(locale && { locale }),
68
70
  ...(fallbackLocale !== undefined && { fallbackLocale }),