@payloadcms/plugin-mcp 4.0.0-beta.7 → 4.0.0-beta.9
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.
- package/dist/endpoint/access.d.ts +5 -0
- package/dist/endpoint/access.d.ts.map +1 -1
- package/dist/endpoint/access.js +42 -5
- package/dist/endpoint/access.js.map +1 -1
- package/dist/endpoint/index.d.ts.map +1 -1
- package/dist/endpoint/index.js +25 -0
- package/dist/endpoint/index.js.map +1 -1
- package/dist/endpoint/oauth.d.ts +37 -0
- package/dist/endpoint/oauth.d.ts.map +1 -0
- package/dist/endpoint/oauth.js +105 -0
- package/dist/endpoint/oauth.js.map +1 -0
- package/dist/endpoint/oauthLoginToken.d.ts +27 -0
- package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
- package/dist/endpoint/oauthLoginToken.js +86 -0
- package/dist/endpoint/oauthLoginToken.js.map +1 -0
- package/dist/endpoint/oauthServer.d.ts +28 -0
- package/dist/endpoint/oauthServer.d.ts.map +1 -0
- package/dist/endpoint/oauthServer.js +432 -0
- package/dist/endpoint/oauthServer.js.map +1 -0
- package/dist/exports/client.d.ts +1 -1
- package/dist/exports/client.d.ts.map +1 -1
- package/dist/exports/client.js +1 -1
- package/dist/exports/client.js.map +1 -1
- package/dist/exports/rsc.d.ts +2 -0
- package/dist/exports/rsc.d.ts.map +1 -0
- package/dist/exports/rsc.js +3 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +34 -10
- package/dist/index.js.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.js +3 -1
- package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +3 -0
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/types.d.ts +100 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/seal.d.ts +17 -0
- package/dist/utils/seal.d.ts.map +1 -0
- package/dist/utils/seal.js +24 -0
- package/dist/utils/seal.js.map +1 -0
- package/dist/views/Authorize/AllowButtons/index.d.ts +18 -0
- package/dist/views/Authorize/AllowButtons/index.d.ts.map +1 -0
- package/dist/views/Authorize/AllowButtons/index.js +88 -0
- package/dist/views/Authorize/AllowButtons/index.js.map +1 -0
- package/dist/views/Authorize/index.css +19 -0
- package/dist/views/Authorize/index.d.ts +9 -0
- package/dist/views/Authorize/index.d.ts.map +1 -0
- package/dist/views/Authorize/index.js +86 -0
- package/dist/views/Authorize/index.js.map +1 -0
- package/package.json +10 -3
- package/src/endpoint/access.ts +45 -3
- package/src/endpoint/index.ts +17 -1
- package/src/endpoint/oauth.ts +108 -0
- package/src/endpoint/oauthLoginToken.ts +100 -0
- package/src/endpoint/oauthServer.ts +461 -0
- package/src/exports/client.ts +1 -1
- package/src/exports/rsc.ts +1 -0
- package/src/index.ts +52 -8
- package/src/mcp/builtin/collections/deleteTool.ts +3 -1
- package/src/mcp/sanitizeMCPConfig.ts +1 -0
- package/src/types.ts +98 -0
- package/src/utils/seal.ts +46 -0
- package/src/views/Authorize/AllowButtons/index.tsx +97 -0
- package/src/views/Authorize/index.css +19 -0
- package/src/views/Authorize/index.tsx +93 -0
|
@@ -0,0 +1,461 @@
|
|
|
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 client = consent && unseal<Client>({ type: 'client', req, value: consent.clientID })
|
|
250
|
+
const user = getBrowserUser(req)
|
|
251
|
+
|
|
252
|
+
// The form is only valid for the user it was shown to
|
|
253
|
+
if (
|
|
254
|
+
!consent ||
|
|
255
|
+
!client ||
|
|
256
|
+
user?.id !== consent.userID ||
|
|
257
|
+
user.collection !== consent.collection
|
|
258
|
+
) {
|
|
259
|
+
return redirectToAuthorizeView({ params: { error: 'expired' }, req })
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const { clientID, codeChallenge, redirectURI, state } = consent
|
|
263
|
+
|
|
264
|
+
// Responses to the client name this server in `iss`, so clients that use several authorization
|
|
265
|
+
// servers can tell which one answered
|
|
266
|
+
if (form.get('decision') !== 'allow') {
|
|
267
|
+
return redirect({
|
|
268
|
+
params: { error: OAuthErrorCode.AccessDenied, iss: issuer, state },
|
|
269
|
+
redirectURI,
|
|
270
|
+
})
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const code: Code = {
|
|
274
|
+
clientID,
|
|
275
|
+
codeChallenge,
|
|
276
|
+
redirectURI,
|
|
277
|
+
tokens: await getTokenHooks(req).issueToken({
|
|
278
|
+
client: { name: client.name, redirectURI },
|
|
279
|
+
req,
|
|
280
|
+
}),
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return redirect({
|
|
284
|
+
params: {
|
|
285
|
+
code: seal({ type: 'code', data: code, expiresInSeconds: 60, req }),
|
|
286
|
+
iss: issuer,
|
|
287
|
+
state,
|
|
288
|
+
},
|
|
289
|
+
redirectURI,
|
|
290
|
+
})
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const token: PayloadHandler = async (req) => {
|
|
294
|
+
const form = new URLSearchParams(await req.text!())
|
|
295
|
+
const clientID = form.get('client_id')
|
|
296
|
+
const grantType = form.get('grant_type')
|
|
297
|
+
|
|
298
|
+
if (grantType !== 'authorization_code' && grantType !== 'refresh_token') {
|
|
299
|
+
return Response.json(
|
|
300
|
+
{ error: grantType ? OAuthErrorCode.UnsupportedGrantType : OAuthErrorCode.InvalidRequest },
|
|
301
|
+
{ status: 400 },
|
|
302
|
+
)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const requiredParams =
|
|
306
|
+
grantType === 'refresh_token' ? ['refresh_token'] : ['code', 'code_verifier']
|
|
307
|
+
|
|
308
|
+
if (!clientID || requiredParams.some((param) => !form.get(param))) {
|
|
309
|
+
return Response.json({ error: OAuthErrorCode.InvalidRequest }, { status: 400 })
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const tokens =
|
|
313
|
+
grantType === 'refresh_token'
|
|
314
|
+
? await refresh({ clientID, form, req })
|
|
315
|
+
: await redeemCode({ clientID, form, req })
|
|
316
|
+
|
|
317
|
+
if (!tokens) {
|
|
318
|
+
return Response.json({ error: OAuthErrorCode.InvalidGrant }, { status: 400 })
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return Response.json(
|
|
322
|
+
{
|
|
323
|
+
access_token: tokens.accessToken,
|
|
324
|
+
expires_in: tokens.expiresIn,
|
|
325
|
+
refresh_token:
|
|
326
|
+
tokens.refreshToken &&
|
|
327
|
+
seal({
|
|
328
|
+
type: 'refresh',
|
|
329
|
+
data: { clientID, refreshToken: tokens.refreshToken } satisfies RefreshToken,
|
|
330
|
+
req,
|
|
331
|
+
}),
|
|
332
|
+
token_type: 'Bearer',
|
|
333
|
+
} satisfies OAuthTokens,
|
|
334
|
+
{ headers: { 'Cache-Control': 'no-store' } },
|
|
335
|
+
)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const redeemCode = async ({
|
|
339
|
+
clientID,
|
|
340
|
+
form,
|
|
341
|
+
req,
|
|
342
|
+
}: {
|
|
343
|
+
clientID: string
|
|
344
|
+
form: URLSearchParams
|
|
345
|
+
req: PayloadRequest
|
|
346
|
+
}): Promise<MCPOAuthTokens | null | undefined> => {
|
|
347
|
+
const code = unseal<Code>({ type: 'code', req, value: form.get('code') })
|
|
348
|
+
|
|
349
|
+
if (
|
|
350
|
+
code?.clientID === clientID &&
|
|
351
|
+
// OAuth 2.1 clients leave it out, since PKCE does its job. OAuth 2.0 clients send it, and it must
|
|
352
|
+
// match then.
|
|
353
|
+
(!form.has('redirect_uri') || form.get('redirect_uri') === code.redirectURI) &&
|
|
354
|
+
// PKCE: only the client that started the sign-in knows the verifier
|
|
355
|
+
createHash('sha256')
|
|
356
|
+
.update(form.get('code_verifier') ?? '')
|
|
357
|
+
.digest('base64url') === code.codeChallenge
|
|
358
|
+
) {
|
|
359
|
+
// A code must only work once. Trading it also trades its refresh token, with no leeway, so
|
|
360
|
+
// using the code again counts as a copied refresh token: it's refused, and the tokens revoked.
|
|
361
|
+
const hooks = getTokenHooks(req)
|
|
362
|
+
if (hooks.refreshToken && code.tokens.refreshToken) {
|
|
363
|
+
return await hooks.refreshToken({
|
|
364
|
+
refreshToken: code.tokens.refreshToken,
|
|
365
|
+
req,
|
|
366
|
+
reuseInterval: 0,
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
return code.tokens
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const refresh = async ({
|
|
375
|
+
clientID,
|
|
376
|
+
form,
|
|
377
|
+
req,
|
|
378
|
+
}: {
|
|
379
|
+
clientID: string
|
|
380
|
+
form: URLSearchParams
|
|
381
|
+
req: PayloadRequest
|
|
382
|
+
}): Promise<MCPOAuthTokens | null | undefined> => {
|
|
383
|
+
const refreshToken = unseal<RefreshToken>({
|
|
384
|
+
type: 'refresh',
|
|
385
|
+
req,
|
|
386
|
+
value: form.get('refresh_token'),
|
|
387
|
+
})
|
|
388
|
+
|
|
389
|
+
// Only the client a refresh token was issued to can use it
|
|
390
|
+
if (refreshToken?.clientID === clientID) {
|
|
391
|
+
return await getTokenHooks(req).refreshToken?.({
|
|
392
|
+
refreshToken: refreshToken.refreshToken,
|
|
393
|
+
req,
|
|
394
|
+
})
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** `issueToken` and `refreshToken`, or the defaults for Payload login tokens. */
|
|
399
|
+
const getTokenHooks = (req: PayloadRequest) => {
|
|
400
|
+
const oauth = getPluginConfig({ config: req.payload.config }).oauth as MCPBuiltinOAuthConfig
|
|
401
|
+
|
|
402
|
+
return oauth.issueToken
|
|
403
|
+
? { issueToken: oauth.issueToken, refreshToken: oauth.refreshToken }
|
|
404
|
+
: { issueToken: issueLoginToken, refreshToken: refreshLoginToken }
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const redirect = ({
|
|
408
|
+
params,
|
|
409
|
+
redirectURI,
|
|
410
|
+
}: {
|
|
411
|
+
params: Record<string, null | string>
|
|
412
|
+
redirectURI: string
|
|
413
|
+
}): Response => {
|
|
414
|
+
const location = new URL(redirectURI)
|
|
415
|
+
|
|
416
|
+
for (const [key, value] of Object.entries(params)) {
|
|
417
|
+
if (value) {
|
|
418
|
+
location.searchParams.set(key, value)
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
return new Response(null, { headers: { Location: location.href }, status: 302 })
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Accepts https, http to the user's own computer only, since the code would otherwise travel
|
|
427
|
+
* unencrypted, and app schemes like `cursor://` that desktop apps register to receive the code.
|
|
428
|
+
*/
|
|
429
|
+
const isValidRedirectURI = (uri: unknown): boolean => {
|
|
430
|
+
if (typeof uri !== 'string' || !URL.canParse(uri) || uri.includes('#')) {
|
|
431
|
+
return false
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const { hostname, protocol } = new URL(uri)
|
|
435
|
+
|
|
436
|
+
if (protocol === 'http:') {
|
|
437
|
+
return ['[::1]', '127.0.0.1', 'localhost'].includes(hostname)
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Browser schemes that run or show content instead of sending the code to an app
|
|
441
|
+
return protocol !== 'javascript:' && protocol !== 'data:'
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** Sends the browser to `MCPAuthorizeView`, with the Allow form or the reason it can't show it. */
|
|
445
|
+
const redirectToAuthorizeView = ({
|
|
446
|
+
params,
|
|
447
|
+
req,
|
|
448
|
+
}: {
|
|
449
|
+
params: { consent: string } | { error: AuthorizeViewError }
|
|
450
|
+
req: PayloadRequest
|
|
451
|
+
}): Response => {
|
|
452
|
+
const viewURL = formatAdminURL({
|
|
453
|
+
adminRoute: req.payload.config.routes.admin,
|
|
454
|
+
path: authorizeViewPath,
|
|
455
|
+
})
|
|
456
|
+
|
|
457
|
+
return new Response(null, {
|
|
458
|
+
headers: { Location: `${viewURL}?${new URLSearchParams(params)}` },
|
|
459
|
+
status: 302,
|
|
460
|
+
})
|
|
461
|
+
}
|
package/src/exports/client.ts
CHANGED
|
@@ -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 {
|
|
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 {
|
|
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',
|
|
@@ -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
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
|
|
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
|
},
|
|
@@ -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}` : ''}`,
|
|
@@ -37,6 +37,7 @@ export const deleteDocumentsTool = defineCollectionTool({
|
|
|
37
37
|
depth,
|
|
38
38
|
overrideAccess: authorizedMCP.overrideAccess,
|
|
39
39
|
req,
|
|
40
|
+
trash,
|
|
40
41
|
...(locale && { locale }),
|
|
41
42
|
...(fallbackLocale !== undefined && { fallbackLocale }),
|
|
42
43
|
})
|
|
@@ -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 }),
|
|
@@ -103,6 +103,7 @@ export const sanitizeMCPConfig = ({
|
|
|
103
103
|
hooks: pluginConfig.hooks,
|
|
104
104
|
items,
|
|
105
105
|
mcp: pluginConfig.mcp,
|
|
106
|
+
oauth: pluginConfig.oauth === false ? undefined : (pluginConfig.oauth ?? { type: 'builtin' }),
|
|
106
107
|
overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP,
|
|
107
108
|
}
|
|
108
109
|
}
|