@payloadcms/plugin-mcp 4.0.0-beta.7 → 4.0.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +23 -0
- package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
- package/dist/endpoint/oauthLoginToken.js +80 -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 +423 -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 +95 -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 +94 -0
- package/src/endpoint/oauthServer.ts +452 -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 +94 -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,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
|
+
}
|
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
|
}
|
package/src/types.ts
CHANGED
|
@@ -290,6 +290,14 @@ export type MCPPluginConfig = {
|
|
|
290
290
|
serverOptions?: MCPServerOptions
|
|
291
291
|
verboseLogs?: boolean
|
|
292
292
|
}
|
|
293
|
+
/**
|
|
294
|
+
* How MCP clients sign in. MCP requests without an authenticated user get a `401` that points
|
|
295
|
+
* to the protected resource metadata (RFC 9728). Set to `false` to only accept API keys and
|
|
296
|
+
* anonymous requests.
|
|
297
|
+
*
|
|
298
|
+
* @default { type: 'builtin' }
|
|
299
|
+
*/
|
|
300
|
+
oauth?: false | MCPOAuthConfig
|
|
293
301
|
/**
|
|
294
302
|
* Replace the default MCP authorization resolver.
|
|
295
303
|
*
|
|
@@ -307,8 +315,94 @@ export type MCPPluginConfig = {
|
|
|
307
315
|
tools?: MCPTopLevelToolsMap
|
|
308
316
|
}
|
|
309
317
|
|
|
318
|
+
export type MCPOAuthConfig = MCPBuiltinOAuthConfig | MCPExternalOAuthConfig
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* This Payload app is the authorization server. Users sign in to the admin panel and allow the
|
|
322
|
+
* MCP client, which then gets an access token for them.
|
|
323
|
+
*/
|
|
324
|
+
export type MCPBuiltinOAuthConfig = {
|
|
325
|
+
/**
|
|
326
|
+
* Creates the tokens the MCP client gets when the user clicks Allow. `req` is the user's own
|
|
327
|
+
* browser request, so `req.user` is the user who allowed it. Pass `authenticate` too if
|
|
328
|
+
* Payload's auth strategies don't accept the access token.
|
|
329
|
+
*
|
|
330
|
+
* @default a Payload login token for that user that only works for MCP, with a refresh token when
|
|
331
|
+
* the collection uses sessions
|
|
332
|
+
*/
|
|
333
|
+
issueToken?: (args: { req: PayloadRequest }) => MaybePromise<MCPOAuthTokens>
|
|
334
|
+
/**
|
|
335
|
+
* Trades a refresh token from `issueToken`, or from an earlier refresh, for new tokens. Return
|
|
336
|
+
* `null` when it's no longer valid, and the client sends the user through sign-in again. `req`
|
|
337
|
+
* is the MCP client's request, without a user. Only used together with `issueToken`.
|
|
338
|
+
*
|
|
339
|
+
* OAuth requires noticing copied refresh tokens: return a new refresh token every time, and
|
|
340
|
+
* revoke the tokens when an already used refresh token comes back.
|
|
341
|
+
*
|
|
342
|
+
* It also runs when the client trades its authorization code, on the refresh token from
|
|
343
|
+
* `issueToken`, with `reuseInterval: 0`. OAuth requires a code to work only once, so refuse that
|
|
344
|
+
* refresh token if it was used before, even moments ago.
|
|
345
|
+
*/
|
|
346
|
+
refreshToken?: (args: {
|
|
347
|
+
refreshToken: string
|
|
348
|
+
req: PayloadRequest
|
|
349
|
+
/**
|
|
350
|
+
* How long a refresh token that was just used may still be accepted, in milliseconds, e.g. for
|
|
351
|
+
* clients that refresh twice at once. `0` means not at all. When it's missing, use your usual
|
|
352
|
+
* leeway.
|
|
353
|
+
*/
|
|
354
|
+
reuseInterval?: number
|
|
355
|
+
}) => MaybePromise<MCPOAuthTokens | null>
|
|
356
|
+
type: 'builtin'
|
|
357
|
+
} & MCPOAuthSharedConfig
|
|
358
|
+
|
|
359
|
+
export type MCPOAuthTokens = {
|
|
360
|
+
accessToken: string
|
|
361
|
+
/** Seconds until the access token expires. */
|
|
362
|
+
expiresIn?: number
|
|
363
|
+
/** Lets the client get new tokens without the user, through `refreshToken`. */
|
|
364
|
+
refreshToken?: string
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Another service, e.g. your identity provider, is the authorization server. */
|
|
368
|
+
export type MCPExternalOAuthConfig = {
|
|
369
|
+
/**
|
|
370
|
+
* The authorization servers that issue access tokens for MCP clients. Clients require each one
|
|
371
|
+
* to exactly match the `issuer` in that server's metadata, so pass a function when the exact
|
|
372
|
+
* value is only known at runtime, e.g. from the server's OpenID configuration or per host.
|
|
373
|
+
*/
|
|
374
|
+
authorizationServers: ((args: { req: PayloadRequest }) => MaybePromise<string[]>) | string[]
|
|
375
|
+
/**
|
|
376
|
+
* Scopes MCP clients should request, e.g. `['openid', 'email', 'profile']`. Without them,
|
|
377
|
+
* clients request none, which some authorization servers reject or answer with a token that
|
|
378
|
+
* doesn't identify the user.
|
|
379
|
+
*/
|
|
380
|
+
scopes?: string[]
|
|
381
|
+
type: 'external'
|
|
382
|
+
} & MCPOAuthSharedConfig
|
|
383
|
+
|
|
384
|
+
type MCPOAuthSharedConfig = {
|
|
385
|
+
/**
|
|
386
|
+
* Called on MCP requests with a bearer token that Payload's auth strategies didn't accept.
|
|
387
|
+
* Return the Payload user, including its `collection`, or `null` to answer with the OAuth challenge.
|
|
388
|
+
*/
|
|
389
|
+
authenticate?: (args: {
|
|
390
|
+
req: PayloadRequest
|
|
391
|
+
token: string
|
|
392
|
+
}) => MaybePromise<PayloadRequest['user']>
|
|
393
|
+
/**
|
|
394
|
+
* The URL clients call to reach the MCP endpoint. The metadata link and the built-in
|
|
395
|
+
* authorization server's issuer are based on it.
|
|
396
|
+
*
|
|
397
|
+
* @default the absolute URL of `/api/mcp`, based on `serverURL` or the request URL
|
|
398
|
+
*/
|
|
399
|
+
resource?: ((args: { req: PayloadRequest }) => string) | string
|
|
400
|
+
}
|
|
401
|
+
|
|
310
402
|
export type SanitizedMCPPluginConfig = {
|
|
311
403
|
items: MCPItem[]
|
|
404
|
+
/** `undefined` when OAuth is turned off. */
|
|
405
|
+
oauth?: MCPOAuthConfig
|
|
312
406
|
} & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>
|
|
313
407
|
|
|
314
408
|
export type MCPServerOptions = {
|