@payloadcms/plugin-mcp 4.0.0-internal.ea6e8f8 → 4.0.0-internal.ee5d8bd

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 (64) hide show
  1. package/dist/endpoint/access.d.ts.map +1 -1
  2. package/dist/endpoint/access.js +15 -3
  3. package/dist/endpoint/access.js.map +1 -1
  4. package/dist/endpoint/index.d.ts.map +1 -1
  5. package/dist/endpoint/index.js +13 -0
  6. package/dist/endpoint/index.js.map +1 -1
  7. package/dist/endpoint/oauth.d.ts +39 -0
  8. package/dist/endpoint/oauth.d.ts.map +1 -0
  9. package/dist/endpoint/oauth.js +94 -0
  10. package/dist/endpoint/oauth.js.map +1 -0
  11. package/dist/endpoint/oauthLoginToken.d.ts +15 -0
  12. package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
  13. package/dist/endpoint/oauthLoginToken.js +45 -0
  14. package/dist/endpoint/oauthLoginToken.js.map +1 -0
  15. package/dist/endpoint/oauthServer.d.ts +12 -0
  16. package/dist/endpoint/oauthServer.d.ts.map +1 -0
  17. package/dist/endpoint/oauthServer.js +386 -0
  18. package/dist/endpoint/oauthServer.js.map +1 -0
  19. package/dist/index.d.ts +10 -2
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +15 -2
  22. package/dist/index.js.map +1 -1
  23. package/dist/mcp/buildMcpServer.js +1 -1
  24. package/dist/mcp/buildMcpServer.js.map +1 -1
  25. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  26. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  27. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  28. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  29. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  30. package/dist/mcp/builtin/collections/findTool.js +1 -1
  31. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  32. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  33. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  34. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
  35. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  36. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  37. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  38. package/dist/mcp/sanitizeMCPConfig.js +3 -0
  39. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  40. package/dist/types.d.ts +81 -0
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/types.js.map +1 -1
  43. package/dist/utils/toStandardSchema.js.map +1 -1
  44. package/package.json +20 -23
  45. package/src/endpoint/access.ts +12 -3
  46. package/src/endpoint/index.ts +8 -0
  47. package/src/endpoint/oauth.ts +92 -0
  48. package/src/endpoint/oauthLoginToken.ts +59 -0
  49. package/src/endpoint/oauthServer.ts +440 -0
  50. package/src/index.ts +40 -5
  51. package/src/mcp/buildMcpServer.ts +2 -2
  52. package/src/mcp/builtin/collections/authTools.ts +2 -2
  53. package/src/mcp/builtin/collections/createTool.ts +1 -3
  54. package/src/mcp/builtin/collections/deleteTool.ts +1 -1
  55. package/src/mcp/builtin/collections/duplicateTool.ts +1 -1
  56. package/src/mcp/builtin/collections/findTool.ts +1 -1
  57. package/src/mcp/builtin/collections/restoreVersionTool.ts +1 -1
  58. package/src/mcp/builtin/collections/updateTool.ts +1 -1
  59. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +1 -1
  60. package/src/mcp/builtin/globals/findTool.ts +1 -1
  61. package/src/mcp/builtin/globals/updateTool.ts +1 -1
  62. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  63. package/src/types.ts +82 -0
  64. package/src/utils/toStandardSchema.ts +1 -1
@@ -0,0 +1,386 @@
1
+ import { OAuthErrorCode } from '@modelcontextprotocol/server';
2
+ import { createHash } from 'crypto';
3
+ import { formatAdminURL } from 'payload/shared';
4
+ import { getPluginConfig } from '../utils/getPluginConfig.js';
5
+ import { getMCPURL } from './oauth.js';
6
+ import { issueLoginToken, refreshLoginToken } from './oauthLoginToken.js';
7
+ /**
8
+ * Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is
9
+ * `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and
10
+ * the client receives the tokens `issueToken` creates.
11
+ *
12
+ * Clients, consent forms, authorization codes, and refresh tokens are encrypted and handed to the
13
+ * client instead of being stored. Only the default tokens write to the database, to the user's
14
+ * login sessions.
15
+ */ export const oauthServerEndpoints = [
16
+ {
17
+ disableAuth: true,
18
+ handler: (req)=>withIssuer(req, (issuer)=>metadataResponse(issuer)),
19
+ method: 'get',
20
+ // OpenID discovery is the only metadata location MCP clients check below the issuer's path,
21
+ // which lets this work under /api without a route at the site root
22
+ path: '/mcp/oauth/.well-known/openid-configuration'
23
+ },
24
+ {
25
+ disableAuth: true,
26
+ handler: (req)=>withIssuer(req, ()=>Response.json({
27
+ keys: []
28
+ })),
29
+ method: 'get',
30
+ path: '/mcp/oauth/jwks'
31
+ },
32
+ {
33
+ disableAuth: true,
34
+ handler: (req)=>withIssuer(req, ()=>register(req)),
35
+ method: 'post',
36
+ path: '/mcp/oauth/register'
37
+ },
38
+ {
39
+ handler: (req)=>withIssuer(req, ()=>authorize(req)),
40
+ method: 'get',
41
+ path: '/mcp/oauth/authorize'
42
+ },
43
+ {
44
+ handler: (req)=>withIssuer(req, ()=>approve(req)),
45
+ method: 'post',
46
+ path: '/mcp/oauth/authorize'
47
+ },
48
+ {
49
+ disableAuth: true,
50
+ handler: (req)=>withIssuer(req, ()=>token(req)),
51
+ method: 'post',
52
+ path: '/mcp/oauth/token'
53
+ }
54
+ ];
55
+ /** The authorization server URL, or `undefined` when Payload isn't the authorization server. */ const getIssuer = (req)=>getPluginConfig({
56
+ config: req.payload.config
57
+ }).oauth?.type === 'builtin' ? `${getMCPURL({
58
+ config: req.payload.config,
59
+ url: req.url
60
+ })}/oauth` : undefined;
61
+ const withIssuer = (req, handler)=>{
62
+ const issuer = getIssuer(req);
63
+ return issuer ? handler(issuer) : new Response(null, {
64
+ status: 404
65
+ });
66
+ };
67
+ /**
68
+ * The user logged in to this browser, who can allow MCP clients. Tokens and API keys in the
69
+ * `Authorization` header can't, or an MCP client could use its access token to approve itself a
70
+ * new, separate login.
71
+ */ const getBrowserUser = (req)=>req.headers.has('Authorization') ? null : req.user;
72
+ const metadataResponse = (issuer)=>Response.json({
73
+ authorization_endpoint: `${issuer}/authorize`,
74
+ code_challenge_methods_supported: [
75
+ 'S256'
76
+ ],
77
+ grant_types_supported: [
78
+ 'authorization_code',
79
+ 'refresh_token'
80
+ ],
81
+ // Required by OpenID discovery. No ID tokens are issued.
82
+ id_token_signing_alg_values_supported: [
83
+ 'RS256'
84
+ ],
85
+ issuer,
86
+ jwks_uri: `${issuer}/jwks`,
87
+ registration_endpoint: `${issuer}/register`,
88
+ response_types_supported: [
89
+ 'code'
90
+ ],
91
+ subject_types_supported: [
92
+ 'public'
93
+ ],
94
+ token_endpoint: `${issuer}/token`,
95
+ token_endpoint_auth_methods_supported: [
96
+ 'none'
97
+ ]
98
+ }, // Not cached, since without `serverURL` its URLs come from the request
99
+ {
100
+ headers: {
101
+ 'Access-Control-Allow-Origin': '*',
102
+ 'Cache-Control': 'no-store'
103
+ }
104
+ });
105
+ const register = async (req)=>{
106
+ const { client_name, redirect_uris } = await req.json().catch(()=>({}));
107
+ if (!Array.isArray(redirect_uris) || !redirect_uris.length || !redirect_uris.every((uri)=>typeof uri === 'string' && URL.canParse(uri) && !uri.includes('#'))) {
108
+ return Response.json({
109
+ error: OAuthErrorCode.InvalidRedirectUri
110
+ }, {
111
+ status: 400
112
+ });
113
+ }
114
+ const client = {
115
+ name: typeof client_name === 'string' ? client_name : 'An MCP client',
116
+ redirectURIs: redirect_uris
117
+ };
118
+ return Response.json({
119
+ client_id: seal({
120
+ type: 'client',
121
+ data: client,
122
+ req
123
+ }),
124
+ client_name: client.name,
125
+ grant_types: [
126
+ 'authorization_code',
127
+ 'refresh_token'
128
+ ],
129
+ redirect_uris: client.redirectURIs,
130
+ response_types: [
131
+ 'code'
132
+ ],
133
+ token_endpoint_auth_method: 'none'
134
+ }, {
135
+ status: 201
136
+ });
137
+ };
138
+ const authorize = (req)=>{
139
+ const url = new URL(req.url);
140
+ const params = url.searchParams;
141
+ const clientID = params.get('client_id');
142
+ const client = unseal({
143
+ type: 'client',
144
+ req,
145
+ value: clientID
146
+ });
147
+ const redirectURI = params.get('redirect_uri');
148
+ // Never redirect to an address the client didn't register
149
+ if (!client || !redirectURI || !client.redirectURIs.includes(redirectURI)) {
150
+ return page({
151
+ content: '<p>Start the sign-in again from your MCP client.</p>',
152
+ status: 400,
153
+ title: 'This sign-in link is invalid'
154
+ });
155
+ }
156
+ const state = params.get('state');
157
+ const codeChallenge = params.get('code_challenge');
158
+ if (params.get('response_type') !== 'code' || params.get('code_challenge_method') !== 'S256' || !codeChallenge) {
159
+ return redirect({
160
+ params: {
161
+ error: OAuthErrorCode.InvalidRequest,
162
+ state
163
+ },
164
+ redirectURI
165
+ });
166
+ }
167
+ const user = getBrowserUser(req);
168
+ if (!user) {
169
+ const loginURL = formatAdminURL({
170
+ adminRoute: req.payload.config.routes.admin,
171
+ path: '/login'
172
+ });
173
+ return new Response(null, {
174
+ headers: {
175
+ Location: `${loginURL}?redirect=${encodeURIComponent(url.pathname + url.search)}`
176
+ },
177
+ status: 302
178
+ });
179
+ }
180
+ const consent = {
181
+ clientID: clientID,
182
+ codeChallenge,
183
+ collection: user.collection,
184
+ redirectURI,
185
+ state,
186
+ userID: user.id
187
+ };
188
+ return page({
189
+ content: `<p>It will be able to use this app's MCP tools as ${escapeHTML(String(user.email ?? user.id))}, and you will return to ${escapeHTML(new URL(redirectURI).host || redirectURI)}.</p>
190
+ <form method="post">
191
+ <input name="consent" type="hidden" value="${seal({
192
+ type: 'consent',
193
+ data: consent,
194
+ expiresIn: 20 * 60 * 60,
195
+ req
196
+ })}">
197
+ <button name="decision" type="submit" value="allow">Allow</button>
198
+ <button name="decision" type="submit" value="deny">Deny</button>
199
+ </form>`,
200
+ status: 200,
201
+ title: `Allow ${client.name} to use your account?`
202
+ });
203
+ };
204
+ const approve = async (req)=>{
205
+ const form = new URLSearchParams(await req.text());
206
+ const consent = unseal({
207
+ type: 'consent',
208
+ req,
209
+ value: form.get('consent')
210
+ });
211
+ const user = getBrowserUser(req);
212
+ // The form is only valid for the user it was shown to
213
+ if (!consent || user?.id !== consent.userID || user.collection !== consent.collection) {
214
+ return page({
215
+ content: '<p>Start the sign-in again from your MCP client.</p>',
216
+ status: 400,
217
+ title: 'This sign-in request expired'
218
+ });
219
+ }
220
+ const { clientID, codeChallenge, redirectURI, state } = consent;
221
+ if (form.get('decision') !== 'allow') {
222
+ return redirect({
223
+ params: {
224
+ error: OAuthErrorCode.AccessDenied,
225
+ state
226
+ },
227
+ redirectURI
228
+ });
229
+ }
230
+ const code = {
231
+ clientID,
232
+ codeChallenge,
233
+ redirectURI,
234
+ tokens: await getTokenHooks(req).issueToken({
235
+ req
236
+ })
237
+ };
238
+ return redirect({
239
+ params: {
240
+ code: seal({
241
+ type: 'code',
242
+ data: code,
243
+ expiresIn: 60,
244
+ req
245
+ }),
246
+ state
247
+ },
248
+ redirectURI
249
+ });
250
+ };
251
+ const token = async (req)=>{
252
+ const form = new URLSearchParams(await req.text());
253
+ const clientID = form.get('client_id');
254
+ const tokens = clientID && (form.get('grant_type') === 'refresh_token' ? await refresh({
255
+ clientID,
256
+ form,
257
+ req
258
+ }) : redeemCode({
259
+ clientID,
260
+ form,
261
+ req
262
+ }));
263
+ if (!clientID || !tokens) {
264
+ return Response.json({
265
+ error: OAuthErrorCode.InvalidGrant
266
+ }, {
267
+ status: 400
268
+ });
269
+ }
270
+ return Response.json({
271
+ access_token: tokens.accessToken,
272
+ expires_in: tokens.expiresIn,
273
+ refresh_token: tokens.refreshToken && seal({
274
+ type: 'refresh',
275
+ data: {
276
+ clientID,
277
+ refreshToken: tokens.refreshToken
278
+ },
279
+ req
280
+ }),
281
+ token_type: 'Bearer'
282
+ }, {
283
+ headers: {
284
+ 'Cache-Control': 'no-store'
285
+ }
286
+ });
287
+ };
288
+ const redeemCode = ({ clientID, form, req })=>{
289
+ const code = unseal({
290
+ type: 'code',
291
+ req,
292
+ value: form.get('code')
293
+ });
294
+ if (form.get('grant_type') === 'authorization_code' && code?.clientID === clientID && code.redirectURI === form.get('redirect_uri') && // PKCE: only the client that started the sign-in knows the verifier
295
+ createHash('sha256').update(form.get('code_verifier') ?? '').digest('base64url') === code.codeChallenge) {
296
+ return code.tokens;
297
+ }
298
+ };
299
+ const refresh = async ({ clientID, form, req })=>{
300
+ const refreshToken = unseal({
301
+ type: 'refresh',
302
+ req,
303
+ value: form.get('refresh_token')
304
+ });
305
+ // Only the client a refresh token was issued to can use it
306
+ if (refreshToken?.clientID === clientID) {
307
+ return await getTokenHooks(req).refreshToken?.({
308
+ refreshToken: refreshToken.refreshToken,
309
+ req
310
+ });
311
+ }
312
+ };
313
+ /** `issueToken` and `refreshToken`, or the defaults for Payload login tokens. */ const getTokenHooks = (req)=>{
314
+ const oauth = getPluginConfig({
315
+ config: req.payload.config
316
+ }).oauth;
317
+ return oauth.issueToken ? {
318
+ issueToken: oauth.issueToken,
319
+ refreshToken: oauth.refreshToken
320
+ } : {
321
+ issueToken: issueLoginToken,
322
+ refreshToken: refreshLoginToken
323
+ };
324
+ };
325
+ /**
326
+ * Encrypts data for the client to hold, so it doesn't need to be stored. `type` keeps one kind
327
+ * from being used as another, e.g. a client ID as an authorization code.
328
+ */ const seal = ({ type, data, expiresIn, req })=>req.payload.encrypt(JSON.stringify({
329
+ ...data,
330
+ type,
331
+ exp: expiresIn && Date.now() + expiresIn * 1000
332
+ }));
333
+ const unseal = ({ type, req, value })=>{
334
+ // Only the v1 format is authenticated. Older formats decrypt anything without an error.
335
+ if (!value?.startsWith('v1:')) {
336
+ return undefined;
337
+ }
338
+ try {
339
+ // Previous secrets can be public, like a default secret from source code, so only client IDs
340
+ // accept them. Client IDs grant nothing, and this keeps clients registered when the secret changes.
341
+ const secret = type === 'client' ? undefined : req.payload.config.secret;
342
+ const data = JSON.parse(req.payload.decrypt(value, {
343
+ secret
344
+ }));
345
+ return data.type === type && (!data.exp || data.exp > Date.now()) ? data : undefined;
346
+ } catch {
347
+ return undefined;
348
+ }
349
+ };
350
+ const redirect = ({ params, redirectURI })=>{
351
+ const location = new URL(redirectURI);
352
+ for (const [key, value] of Object.entries(params)){
353
+ if (value) {
354
+ location.searchParams.set(key, value);
355
+ }
356
+ }
357
+ return new Response(null, {
358
+ headers: {
359
+ Location: location.href
360
+ },
361
+ status: 302
362
+ });
363
+ };
364
+ const page = ({ content, status, title })=>new Response(`<!doctype html>
365
+ <html lang="en">
366
+ <head>
367
+ <meta charset="utf-8">
368
+ <meta name="viewport" content="width=device-width, initial-scale=1">
369
+ <title>${escapeHTML(title)}</title>
370
+ <style>
371
+ body { font-family: system-ui, sans-serif; margin: 4rem auto; max-width: 32rem; overflow-wrap: anywhere; padding: 0 1rem }
372
+ button { font: inherit; margin-inline-end: 0.5rem; padding: 0.5rem 1rem }
373
+ </style>
374
+ </head>
375
+ <body><h1>${escapeHTML(title)}</h1>${content}</body>
376
+ </html>`, {
377
+ headers: {
378
+ // Stop other sites from framing the page to trick users into clicking Allow
379
+ 'Content-Security-Policy': "frame-ancestors 'none'",
380
+ 'Content-Type': 'text/html; charset=utf-8'
381
+ },
382
+ status
383
+ });
384
+ const escapeHTML = (value)=>value.replace(/[&<>"']/g, (character)=>`&#${character.charCodeAt(0)};`);
385
+
386
+ //# sourceMappingURL=oauthServer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/endpoint/oauthServer.ts"],"sourcesContent":["import type {\n OAuthClientInformationFull,\n OAuthTokens,\n OpenIdProviderDiscoveryMetadata,\n} from '@modelcontextprotocol/server'\nimport type { Endpoint, PayloadHandler, PayloadRequest } from 'payload'\n\nimport { OAuthErrorCode } from '@modelcontextprotocol/server'\nimport { createHash } from 'crypto'\nimport { formatAdminURL } from 'payload/shared'\n\nimport type { MCPBuiltinOAuthConfig, MCPOAuthTokens } from '../types.js'\n\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\nimport { getMCPURL } from './oauth.js'\nimport { issueLoginToken, refreshLoginToken } from './oauthLoginToken.js'\n\ntype Client = { name: string; redirectURIs: string[] }\n\ntype Consent = {\n clientID: string\n codeChallenge: string\n collection: string\n redirectURI: string\n state: null | string\n userID: number | string\n}\n\ntype Code = {\n clientID: string\n codeChallenge: string\n redirectURI: string\n tokens: MCPOAuthTokens\n}\n\ntype RefreshToken = {\n clientID: string\n refreshToken: string\n}\n\n/**\n * Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is\n * `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and\n * the client receives the tokens `issueToken` creates.\n *\n * Clients, consent forms, authorization codes, and refresh tokens are encrypted and handed to the\n * client instead of being stored. Only the default tokens write to the database, to the user's\n * login sessions.\n */\nexport const oauthServerEndpoints: Endpoint[] = [\n {\n disableAuth: true,\n handler: (req) => withIssuer(req, (issuer) => metadataResponse(issuer)),\n method: 'get',\n // OpenID discovery is the only metadata location MCP clients check below the issuer's path,\n // which lets this work under /api without a route at the site root\n path: '/mcp/oauth/.well-known/openid-configuration',\n },\n {\n disableAuth: true,\n handler: (req) => withIssuer(req, () => Response.json({ keys: [] })),\n method: 'get',\n path: '/mcp/oauth/jwks',\n },\n {\n disableAuth: true,\n handler: (req) => withIssuer(req, () => register(req)),\n method: 'post',\n path: '/mcp/oauth/register',\n },\n {\n handler: (req) => withIssuer(req, () => authorize(req)),\n method: 'get',\n path: '/mcp/oauth/authorize',\n },\n {\n handler: (req) => withIssuer(req, () => approve(req)),\n method: 'post',\n path: '/mcp/oauth/authorize',\n },\n {\n disableAuth: true,\n handler: (req) => withIssuer(req, () => token(req)),\n method: 'post',\n path: '/mcp/oauth/token',\n },\n]\n\n/** The authorization server URL, or `undefined` when Payload isn't the authorization server. */\nconst getIssuer = (req: PayloadRequest): string | undefined =>\n getPluginConfig({ config: req.payload.config }).oauth?.type === 'builtin'\n ? `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth`\n : undefined\n\nconst withIssuer = (\n req: PayloadRequest,\n handler: (issuer: string) => Promise<Response> | Response,\n): Promise<Response> | Response => {\n const issuer = getIssuer(req)\n return issuer ? handler(issuer) : new Response(null, { status: 404 })\n}\n\n/**\n * The user logged in to this browser, who can allow MCP clients. Tokens and API keys in the\n * `Authorization` header can't, or an MCP client could use its access token to approve itself a\n * new, separate login.\n */\nconst getBrowserUser = (req: PayloadRequest): PayloadRequest['user'] =>\n req.headers.has('Authorization') ? null : req.user\n\nconst metadataResponse = (issuer: string): Response =>\n Response.json(\n {\n authorization_endpoint: `${issuer}/authorize`,\n code_challenge_methods_supported: ['S256'],\n grant_types_supported: ['authorization_code', 'refresh_token'],\n // Required by OpenID discovery. No ID tokens are issued.\n id_token_signing_alg_values_supported: ['RS256'],\n issuer,\n jwks_uri: `${issuer}/jwks`,\n registration_endpoint: `${issuer}/register`,\n response_types_supported: ['code'],\n subject_types_supported: ['public'],\n token_endpoint: `${issuer}/token`,\n token_endpoint_auth_methods_supported: ['none'],\n } satisfies OpenIdProviderDiscoveryMetadata,\n // Not cached, since without `serverURL` its URLs come from the request\n { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },\n )\n\nconst register: PayloadHandler = async (req) => {\n const { client_name, redirect_uris } = await req.json!().catch(() => ({}))\n\n if (\n !Array.isArray(redirect_uris) ||\n !redirect_uris.length ||\n !redirect_uris.every(\n (uri) => typeof uri === 'string' && URL.canParse(uri) && !uri.includes('#'),\n )\n ) {\n return Response.json({ error: OAuthErrorCode.InvalidRedirectUri }, { status: 400 })\n }\n\n const client: Client = {\n name: typeof client_name === 'string' ? client_name : 'An MCP client',\n redirectURIs: redirect_uris,\n }\n\n return Response.json(\n {\n client_id: seal({ type: 'client', data: client, req }),\n client_name: client.name,\n grant_types: ['authorization_code', 'refresh_token'],\n redirect_uris: client.redirectURIs,\n response_types: ['code'],\n token_endpoint_auth_method: 'none',\n } satisfies OAuthClientInformationFull,\n { status: 201 },\n )\n}\n\nconst authorize: PayloadHandler = (req) => {\n const url = new URL(req.url!)\n const params = url.searchParams\n const clientID = params.get('client_id')\n const client = unseal<Client>({ type: 'client', req, value: clientID })\n const redirectURI = params.get('redirect_uri')\n\n // Never redirect to an address the client didn't register\n if (!client || !redirectURI || !client.redirectURIs.includes(redirectURI)) {\n return page({\n content: '<p>Start the sign-in again from your MCP client.</p>',\n status: 400,\n title: 'This sign-in link is invalid',\n })\n }\n\n const state = params.get('state')\n const codeChallenge = params.get('code_challenge')\n\n if (\n params.get('response_type') !== 'code' ||\n params.get('code_challenge_method') !== 'S256' ||\n !codeChallenge\n ) {\n return redirect({ params: { error: OAuthErrorCode.InvalidRequest, state }, redirectURI })\n }\n\n const user = getBrowserUser(req)\n\n if (!user) {\n const loginURL = formatAdminURL({ adminRoute: req.payload.config.routes.admin, path: '/login' })\n\n return new Response(null, {\n headers: {\n Location: `${loginURL}?redirect=${encodeURIComponent(url.pathname + url.search)}`,\n },\n status: 302,\n })\n }\n\n const consent: Consent = {\n clientID: clientID!,\n codeChallenge,\n collection: user.collection,\n redirectURI,\n state,\n userID: user.id,\n }\n\n return page({\n content: `<p>It will be able to use this app's MCP tools as ${escapeHTML(String(user.email ?? user.id))}, and you will return to ${escapeHTML(new URL(redirectURI).host || redirectURI)}.</p>\n<form method=\"post\">\n<input name=\"consent\" type=\"hidden\" value=\"${seal({ type: 'consent', data: consent, expiresIn: 20 * 60 * 60, req })}\">\n<button name=\"decision\" type=\"submit\" value=\"allow\">Allow</button>\n<button name=\"decision\" type=\"submit\" value=\"deny\">Deny</button>\n</form>`,\n status: 200,\n title: `Allow ${client.name} to use your account?`,\n })\n}\n\nconst approve: PayloadHandler = async (req) => {\n const form = new URLSearchParams(await req.text!())\n const consent = unseal<Consent>({ type: 'consent', req, value: form.get('consent') })\n const user = getBrowserUser(req)\n\n // The form is only valid for the user it was shown to\n if (!consent || user?.id !== consent.userID || user.collection !== consent.collection) {\n return page({\n content: '<p>Start the sign-in again from your MCP client.</p>',\n status: 400,\n title: 'This sign-in request expired',\n })\n }\n\n const { clientID, codeChallenge, redirectURI, state } = consent\n\n if (form.get('decision') !== 'allow') {\n return redirect({ params: { error: OAuthErrorCode.AccessDenied, state }, redirectURI })\n }\n\n const code: Code = {\n clientID,\n codeChallenge,\n redirectURI,\n tokens: await getTokenHooks(req).issueToken({ req }),\n }\n\n return redirect({\n params: { code: seal({ type: 'code', data: code, expiresIn: 60, req }), state },\n redirectURI,\n })\n}\n\nconst token: PayloadHandler = async (req) => {\n const form = new URLSearchParams(await req.text!())\n const clientID = form.get('client_id')\n const tokens =\n clientID &&\n (form.get('grant_type') === 'refresh_token'\n ? await refresh({ clientID, form, req })\n : redeemCode({ clientID, form, req }))\n\n if (!clientID || !tokens) {\n return Response.json({ error: OAuthErrorCode.InvalidGrant }, { status: 400 })\n }\n\n return Response.json(\n {\n access_token: tokens.accessToken,\n expires_in: tokens.expiresIn,\n refresh_token:\n tokens.refreshToken &&\n seal({\n type: 'refresh',\n data: { clientID, refreshToken: tokens.refreshToken } satisfies RefreshToken,\n req,\n }),\n token_type: 'Bearer',\n } satisfies OAuthTokens,\n { headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nconst redeemCode = ({\n clientID,\n form,\n req,\n}: {\n clientID: string\n form: URLSearchParams\n req: PayloadRequest\n}): MCPOAuthTokens | undefined => {\n const code = unseal<Code>({ type: 'code', req, value: form.get('code') })\n\n if (\n form.get('grant_type') === 'authorization_code' &&\n code?.clientID === clientID &&\n code.redirectURI === form.get('redirect_uri') &&\n // PKCE: only the client that started the sign-in knows the verifier\n createHash('sha256')\n .update(form.get('code_verifier') ?? '')\n .digest('base64url') === code.codeChallenge\n ) {\n return code.tokens\n }\n}\n\nconst refresh = async ({\n clientID,\n form,\n req,\n}: {\n clientID: string\n form: URLSearchParams\n req: PayloadRequest\n}): Promise<MCPOAuthTokens | null | undefined> => {\n const refreshToken = unseal<RefreshToken>({\n type: 'refresh',\n req,\n value: form.get('refresh_token'),\n })\n\n // Only the client a refresh token was issued to can use it\n if (refreshToken?.clientID === clientID) {\n return await getTokenHooks(req).refreshToken?.({\n refreshToken: refreshToken.refreshToken,\n req,\n })\n }\n}\n\n/** `issueToken` and `refreshToken`, or the defaults for Payload login tokens. */\nconst getTokenHooks = (req: PayloadRequest) => {\n const oauth = getPluginConfig({ config: req.payload.config }).oauth as MCPBuiltinOAuthConfig\n\n return oauth.issueToken\n ? { issueToken: oauth.issueToken, refreshToken: oauth.refreshToken }\n : { issueToken: issueLoginToken, refreshToken: refreshLoginToken }\n}\n\n/**\n * Encrypts data for the client to hold, so it doesn't need to be stored. `type` keeps one kind\n * from being used as another, e.g. a client ID as an authorization code.\n */\nconst seal = ({\n type,\n data,\n expiresIn,\n req,\n}: {\n data: object\n /** Seconds */\n expiresIn?: number\n req: PayloadRequest\n type: string\n}): string =>\n req.payload.encrypt(\n JSON.stringify({ ...data, type, exp: expiresIn && Date.now() + expiresIn * 1000 }),\n )\n\nconst unseal = <T>({\n type,\n req,\n value,\n}: {\n req: PayloadRequest\n type: string\n value: null | string\n}): T | undefined => {\n // Only the v1 format is authenticated. Older formats decrypt anything without an error.\n if (!value?.startsWith('v1:')) {\n return undefined\n }\n\n try {\n // Previous secrets can be public, like a default secret from source code, so only client IDs\n // accept them. Client IDs grant nothing, and this keeps clients registered when the secret changes.\n const secret = type === 'client' ? undefined : req.payload.config.secret\n const data = JSON.parse(req.payload.decrypt(value, { secret }))\n return data.type === type && (!data.exp || data.exp > Date.now()) ? data : undefined\n } catch {\n return undefined\n }\n}\n\nconst redirect = ({\n params,\n redirectURI,\n}: {\n params: Record<string, null | string>\n redirectURI: string\n}): Response => {\n const location = new URL(redirectURI)\n\n for (const [key, value] of Object.entries(params)) {\n if (value) {\n location.searchParams.set(key, value)\n }\n }\n\n return new Response(null, { headers: { Location: location.href }, status: 302 })\n}\n\nconst page = ({\n content,\n status,\n title,\n}: {\n content: string\n status: number\n title: string\n}): Response =>\n new Response(\n `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHTML(title)}</title>\n<style>\nbody { font-family: system-ui, sans-serif; margin: 4rem auto; max-width: 32rem; overflow-wrap: anywhere; padding: 0 1rem }\nbutton { font: inherit; margin-inline-end: 0.5rem; padding: 0.5rem 1rem }\n</style>\n</head>\n<body><h1>${escapeHTML(title)}</h1>${content}</body>\n</html>`,\n {\n headers: {\n // Stop other sites from framing the page to trick users into clicking Allow\n 'Content-Security-Policy': \"frame-ancestors 'none'\",\n 'Content-Type': 'text/html; charset=utf-8',\n },\n status,\n },\n )\n\nconst escapeHTML = (value: string): string =>\n value.replace(/[&<>\"']/g, (character) => `&#${character.charCodeAt(0)};`)\n"],"names":["OAuthErrorCode","createHash","formatAdminURL","getPluginConfig","getMCPURL","issueLoginToken","refreshLoginToken","oauthServerEndpoints","disableAuth","handler","req","withIssuer","issuer","metadataResponse","method","path","Response","json","keys","register","authorize","approve","token","getIssuer","config","payload","oauth","type","url","undefined","status","getBrowserUser","headers","has","user","authorization_endpoint","code_challenge_methods_supported","grant_types_supported","id_token_signing_alg_values_supported","jwks_uri","registration_endpoint","response_types_supported","subject_types_supported","token_endpoint","token_endpoint_auth_methods_supported","client_name","redirect_uris","catch","Array","isArray","length","every","uri","URL","canParse","includes","error","InvalidRedirectUri","client","name","redirectURIs","client_id","seal","data","grant_types","response_types","token_endpoint_auth_method","params","searchParams","clientID","get","unseal","value","redirectURI","page","content","title","state","codeChallenge","redirect","InvalidRequest","loginURL","adminRoute","routes","admin","Location","encodeURIComponent","pathname","search","consent","collection","userID","id","escapeHTML","String","email","host","expiresIn","form","URLSearchParams","text","AccessDenied","code","tokens","getTokenHooks","issueToken","refresh","redeemCode","InvalidGrant","access_token","accessToken","expires_in","refresh_token","refreshToken","token_type","update","digest","encrypt","JSON","stringify","exp","Date","now","startsWith","secret","parse","decrypt","location","key","Object","entries","set","href","replace","character","charCodeAt"],"mappings":"AAOA,SAASA,cAAc,QAAQ,+BAA8B;AAC7D,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,cAAc,QAAQ,iBAAgB;AAI/C,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SAASC,SAAS,QAAQ,aAAY;AACtC,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,uBAAsB;AAyBzE;;;;;;;;CAQC,GACD,OAAO,MAAMC,uBAAmC;IAC9C;QACEC,aAAa;QACbC,SAAS,CAACC,MAAQC,WAAWD,KAAK,CAACE,SAAWC,iBAAiBD;QAC/DE,QAAQ;QACR,4FAA4F;QAC5F,mEAAmE;QACnEC,MAAM;IACR;IACA;QACEP,aAAa;QACbC,SAAS,CAACC,MAAQC,WAAWD,KAAK,IAAMM,SAASC,IAAI,CAAC;oBAAEC,MAAM,EAAE;gBAAC;QACjEJ,QAAQ;QACRC,MAAM;IACR;IACA;QACEP,aAAa;QACbC,SAAS,CAACC,MAAQC,WAAWD,KAAK,IAAMS,SAAST;QACjDI,QAAQ;QACRC,MAAM;IACR;IACA;QACEN,SAAS,CAACC,MAAQC,WAAWD,KAAK,IAAMU,UAAUV;QAClDI,QAAQ;QACRC,MAAM;IACR;IACA;QACEN,SAAS,CAACC,MAAQC,WAAWD,KAAK,IAAMW,QAAQX;QAChDI,QAAQ;QACRC,MAAM;IACR;IACA;QACEP,aAAa;QACbC,SAAS,CAACC,MAAQC,WAAWD,KAAK,IAAMY,MAAMZ;QAC9CI,QAAQ;QACRC,MAAM;IACR;CACD,CAAA;AAED,8FAA8F,GAC9F,MAAMQ,YAAY,CAACb,MACjBP,gBAAgB;QAAEqB,QAAQd,IAAIe,OAAO,CAACD,MAAM;IAAC,GAAGE,KAAK,EAAEC,SAAS,YAC5D,GAAGvB,UAAU;QAAEoB,QAAQd,IAAIe,OAAO,CAACD,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CAACC,YAAc,CAAC,EAAE,EAAEA,UAAUC,UAAU,CAAC,GAAG,CAAC,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js';
1
+ import type { AuthorizedMCP, MCPBuiltinOAuthConfig, MCPExternalOAuthConfig, MCPOAuthConfig, MCPOAuthTokens, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js';
2
2
  declare module 'payload' {
3
3
  interface PayloadRequestAPI {
4
4
  MCP: true;
@@ -7,8 +7,16 @@ declare module 'payload' {
7
7
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
8
8
  '@payloadcms/plugin-mcp': MCPPluginConfig;
9
9
  }
10
+ interface RequestContext {
11
+ /** Set on MCP requests before they're authenticated. */
12
+ mcp?: {
13
+ /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */
14
+ resource: string;
15
+ };
16
+ }
10
17
  }
11
- export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig };
18
+ export type { AuthorizedMCP, MCPBuiltinOAuthConfig, MCPExternalOAuthConfig, MCPOAuthConfig, MCPOAuthTokens, MCPPluginConfig, SanitizedMCPPluginConfig, };
12
19
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js';
20
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js';
13
21
  export declare const mcpPlugin: (options: MCPPluginConfig) => import("payload").Plugin;
14
22
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAK1F,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,iBAAiB;QAChC,GAAG,EAAE,IAAI,CAAA;KACV;IACD,UAAU,iBAAiB;QACzB,uFAAuF;QACvF,wBAAwB,EAAE,eAAe,CAAA;KAC1C;CACF;AAED,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,CAAA;AAExE,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAElG,eAAO,MAAM,SAAS,wDAiCpB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,aAAa,EACb,qBAAqB,EACrB,sBAAsB,EACtB,cAAc,EACd,cAAc,EACd,eAAe,EACf,wBAAwB,EACzB,MAAM,YAAY,CAAA;AAOnB,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,iBAAiB;QAChC,GAAG,EAAE,IAAI,CAAA;KACV;IACD,UAAU,iBAAiB;QACzB,uFAAuF;QACvF,wBAAwB,EAAE,eAAe,CAAA;KAC1C;IACD,UAAiB,cAAc;QAC7B,wDAAwD;QACxD,GAAG,CAAC,EAAE;YACJ,oFAAoF;YACpF,QAAQ,EAAE,MAAM,CAAA;SACjB,CAAA;KACF;CACF;AAED,YAAY,EACV,aAAa,EACb,qBAAqB,EACrB,sBAAsB,EACtB,cAAc,EACd,cAAc,EACd,eAAe,EACf,wBAAwB,GACzB,CAAA;AAED,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAClG,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAA;AAEnE,eAAO,MAAM,SAAS,wDA0CpB,CAAA"}
package/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { definePlugin } from 'payload';
2
2
  import { mcpEndpoint } from './endpoint/index.js';
3
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js';
4
+ import { oauthServerEndpoints } from './endpoint/oauthServer.js';
3
5
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js';
4
6
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js';
7
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js';
5
8
  export const mcpPlugin = definePlugin({
6
9
  slug: '@payloadcms/plugin-mcp',
7
10
  order: 10,
@@ -23,8 +26,10 @@ export const mcpPlugin = definePlugin({
23
26
  ...config,
24
27
  endpoints: [
25
28
  ...config.endpoints ?? [],
26
- // Payload prefixes /api, so the full path is /api/mcp.
29
+ // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the
30
+ // request with dev auto-login turned off, so Payload doesn't authenticate it first.
27
31
  {
32
+ disableAuth: true,
28
33
  handler: mcpEndpoint,
29
34
  method: 'post',
30
35
  path: '/mcp'
@@ -32,6 +37,7 @@ export const mcpPlugin = definePlugin({
32
37
  // Streamable HTTP's optional server=>client GET stream. We don't offer
33
38
  // one, so answer 405 per spec-— clients then skip it cleanly
34
39
  {
40
+ disableAuth: true,
35
41
  handler: ()=>new Response(null, {
36
42
  headers: {
37
43
  Allow: 'POST'
@@ -40,7 +46,14 @@ export const mcpPlugin = definePlugin({
40
46
  }),
41
47
  method: 'get',
42
48
  path: '/mcp'
43
- }
49
+ },
50
+ {
51
+ disableAuth: true,
52
+ handler: oauthProtectedResourceEndpoint,
53
+ method: 'get',
54
+ path: '/mcp/oauth-protected-resource'
55
+ },
56
+ ...oauthServerEndpoints
44
57
  ]
45
58
  };
46
59
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { definePlugin } from 'payload'\n\nimport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'\n\nimport { mcpEndpoint } from './endpoint/index.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\n\ndeclare module 'payload' {\n export interface PayloadRequestAPI {\n MCP: true\n }\n interface RegisteredPlugins {\n /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */\n '@payloadcms/plugin-mcp': MCPPluginConfig\n }\n}\n\nexport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }\n\nexport { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'\n\nexport const mcpPlugin = definePlugin<MCPPluginConfig>({\n slug: '@payloadcms/plugin-mcp',\n order: 10,\n plugin: ({ config, options, plugins }) => {\n const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })\n\n // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.\n const registered = plugins['@payloadcms/plugin-mcp']\n if (registered) {\n // @ts-expect-error\n registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options\n }\n\n if (pluginConfig.disabled) {\n return config\n }\n\n return {\n ...config,\n endpoints: [\n ...(config.endpoints ?? []),\n // Payload prefixes /api, so the full path is /api/mcp.\n { handler: mcpEndpoint, method: 'post', path: '/mcp' },\n // Streamable HTTP's optional server=>client GET stream. We don't offer\n // one, so answer 405 per spec-— clients then skip it cleanly\n {\n handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),\n method: 'get',\n path: '/mcp',\n },\n ],\n }\n },\n})\n"],"names":["definePlugin","mcpEndpoint","sanitizeMCPConfig","defineCollectionTool","defineGlobalTool","definePrompt","defineTool","mcpPlugin","slug","order","plugin","config","options","plugins","pluginConfig","registered","sanitizedOptions","disabled","endpoints","handler","method","path","Response","headers","Allow","status"],"mappings":"AAAA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,WAAW,QAAQ,sBAAqB;AACjD,SAASC,iBAAiB,QAAQ,6BAA4B;AAc9D,SAASC,oBAAoB,EAAEC,gBAAgB,EAAEC,YAAY,EAAEC,UAAU,QAAQ,kBAAiB;AAElG,OAAO,MAAMC,YAAYP,aAA8B;IACrDQ,MAAM;IACNC,OAAO;IACPC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAE;QACnC,MAAMC,eAAeZ,kBAAkB;YAAES;YAAQG,cAAcF;QAAQ;QAEvE,gFAAgF;QAChF,MAAMG,aAAaF,OAAO,CAAC,yBAAyB;QACpD,IAAIE,YAAY;YACd,mBAAmB;YACnBA,WAAWC,gBAAgB,GAAGF;QAChC;QAEA,IAAIA,aAAaG,QAAQ,EAAE;YACzB,OAAON;QACT;QAEA,OAAO;YACL,GAAGA,MAAM;YACTO,WAAW;mBACLP,OAAOO,SAAS,IAAI,EAAE;gBAC1B,uDAAuD;gBACvD;oBAAEC,SAASlB;oBAAamB,QAAQ;oBAAQC,MAAM;gBAAO;gBACrD,uEAAuE;gBACvE,6DAA6D;gBAC7D;oBACEF,SAAS,IAAM,IAAIG,SAAS,MAAM;4BAAEC,SAAS;gCAAEC,OAAO;4BAAO;4BAAGC,QAAQ;wBAAI;oBAC5EL,QAAQ;oBACRC,MAAM;gBACR;aACD;QACH;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { definePlugin } from 'payload'\n\nimport type {\n AuthorizedMCP,\n MCPBuiltinOAuthConfig,\n MCPExternalOAuthConfig,\n MCPOAuthConfig,\n MCPOAuthTokens,\n MCPPluginConfig,\n SanitizedMCPPluginConfig,\n} from './types.js'\n\nimport { mcpEndpoint } from './endpoint/index.js'\nimport { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'\nimport { oauthServerEndpoints } from './endpoint/oauthServer.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\n\ndeclare module 'payload' {\n export interface PayloadRequestAPI {\n MCP: true\n }\n interface RegisteredPlugins {\n /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */\n '@payloadcms/plugin-mcp': MCPPluginConfig\n }\n export interface RequestContext {\n /** Set on MCP requests before they're authenticated. */\n mcp?: {\n /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */\n resource: string\n }\n }\n}\n\nexport type {\n AuthorizedMCP,\n MCPBuiltinOAuthConfig,\n MCPExternalOAuthConfig,\n MCPOAuthConfig,\n MCPOAuthTokens,\n MCPPluginConfig,\n SanitizedMCPPluginConfig,\n}\n\nexport { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'\nexport { oauthProtectedResourceHandler } from './endpoint/oauth.js'\n\nexport const mcpPlugin = definePlugin<MCPPluginConfig>({\n slug: '@payloadcms/plugin-mcp',\n order: 10,\n plugin: ({ config, options, plugins }) => {\n const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })\n\n // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.\n const registered = plugins['@payloadcms/plugin-mcp']\n if (registered) {\n // @ts-expect-error\n registered.sanitizedOptions = pluginConfig\n }\n\n if (pluginConfig.disabled) {\n return config\n }\n\n return {\n ...config,\n endpoints: [\n ...(config.endpoints ?? []),\n // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the\n // request with dev auto-login turned off, so Payload doesn't authenticate it first.\n { disableAuth: true, handler: mcpEndpoint, method: 'post', path: '/mcp' },\n // Streamable HTTP's optional server=>client GET stream. We don't offer\n // one, so answer 405 per spec-— clients then skip it cleanly\n {\n disableAuth: true,\n handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),\n method: 'get',\n path: '/mcp',\n },\n {\n disableAuth: true,\n handler: oauthProtectedResourceEndpoint,\n method: 'get',\n path: '/mcp/oauth-protected-resource',\n },\n ...oauthServerEndpoints,\n ],\n }\n },\n})\n"],"names":["definePlugin","mcpEndpoint","oauthProtectedResourceEndpoint","oauthServerEndpoints","sanitizeMCPConfig","defineCollectionTool","defineGlobalTool","definePrompt","defineTool","oauthProtectedResourceHandler","mcpPlugin","slug","order","plugin","config","options","plugins","pluginConfig","registered","sanitizedOptions","disabled","endpoints","disableAuth","handler","method","path","Response","headers","Allow","status"],"mappings":"AAAA,SAASA,YAAY,QAAQ,UAAS;AAYtC,SAASC,WAAW,QAAQ,sBAAqB;AACjD,SAASC,8BAA8B,QAAQ,sBAAqB;AACpE,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,iBAAiB,QAAQ,6BAA4B;AA6B9D,SAASC,oBAAoB,EAAEC,gBAAgB,EAAEC,YAAY,EAAEC,UAAU,QAAQ,kBAAiB;AAClG,SAASC,6BAA6B,QAAQ,sBAAqB;AAEnE,OAAO,MAAMC,YAAYV,aAA8B;IACrDW,MAAM;IACNC,OAAO;IACPC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAE;QACnC,MAAMC,eAAeb,kBAAkB;YAAEU;YAAQG,cAAcF;QAAQ;QAEvE,gFAAgF;QAChF,MAAMG,aAAaF,OAAO,CAAC,yBAAyB;QACpD,IAAIE,YAAY;YACd,mBAAmB;YACnBA,WAAWC,gBAAgB,GAAGF;QAChC;QAEA,IAAIA,aAAaG,QAAQ,EAAE;YACzB,OAAON;QACT;QAEA,OAAO;YACL,GAAGA,MAAM;YACTO,WAAW;mBACLP,OAAOO,SAAS,IAAI,EAAE;gBAC1B,0FAA0F;gBAC1F,oFAAoF;gBACpF;oBAAEC,aAAa;oBAAMC,SAAStB;oBAAauB,QAAQ;oBAAQC,MAAM;gBAAO;gBACxE,uEAAuE;gBACvE,6DAA6D;gBAC7D;oBACEH,aAAa;oBACbC,SAAS,IAAM,IAAIG,SAAS,MAAM;4BAAEC,SAAS;gCAAEC,OAAO;4BAAO;4BAAGC,QAAQ;wBAAI;oBAC5EL,QAAQ;oBACRC,MAAM;gBACR;gBACA;oBACEH,aAAa;oBACbC,SAASrB;oBACTsB,QAAQ;oBACRC,MAAM;gBACR;mBACGtB;aACJ;QACH;IACF;AACF,GAAE"}
@@ -205,7 +205,7 @@ const withSlugInput = ({ input })=>{
205
205
  }
206
206
  return addSlugToJSONSchema({
207
207
  description,
208
- schema: schema
208
+ schema
209
209
  });
210
210
  }
211
211
  return addSlugToJSONSchema({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, strictObject, z } from 'payload'\n\nimport type {\n AuthorizedMCP,\n CollectionMCPItem,\n GlobalMCPItem,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n ToolInputSchema,\n} from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/**\n * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh\n * instances from this builder while they own the transport and protocol-era\n * decision.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createPayloadRequest`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n z.config(z.locales.en())\n\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = async ({\n input,\n overrideResponse,\n response,\n toolName,\n }: {\n input: unknown\n overrideResponse?: MCPResponseOverride\n response: MCPToolResponse\n toolName: string\n }): Promise<MCPToolResponse> => {\n let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {\n overridden = await hook({ input, req, response: overridden, toolName })\n }\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n /**\n * Runs a collection/global tool call:\n * - reads `slug` from the input\n * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug\n * - runs the tool handler and finalizes its response\n */\n const callEntityTool = async ({\n input,\n item,\n serverContext,\n }: {\n input: unknown\n item: CollectionMCPItem | GlobalMCPItem\n serverContext: ServerContext\n }): Promise<MCPToolResponse> => {\n const entity = item.type === 'collectionTool' ? 'collection' : 'global'\n const toolInput = (input ?? {}) as Record<string, unknown>\n const slug = toolInput.slug as string | undefined\n\n if (!slug) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: \"${item.mcpName}\" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,\n },\n ],\n isError: true,\n }\n }\n\n const match = authorizedMCP.items.find(\n (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>\n candidate.type === item.type &&\n candidate.mcpName === item.mcpName &&\n (candidate.type === 'collectionTool'\n ? candidate.collectionSlug === slug\n : candidate.type === 'globalTool' && candidate.globalSlug === slug),\n )\n\n if (!match) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"${item.mcpName}\" is not enabled for ${entity} \"${slug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const handlerArgs = {\n authorizedMCP,\n input: toolInput,\n req,\n serverContext,\n }\n const response = await (match.type === 'collectionTool'\n ? match.tool.handler({ ...handlerArgs, slug })\n : match.tool.handler({ ...handlerArgs, slug }))\n\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: match.tool.overrideResponse,\n response,\n toolName: match.mcpName,\n })\n }\n\n try {\n const registeredEntityTools = new Set<string>()\n\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool':\n case 'globalTool': {\n if (registeredEntityTools.has(item.mcpName)) {\n break\n }\n registeredEntityTools.add(item.mcpName)\n\n const inputSchema = withSlugInput({ input: item.tool.input })\n\n server.registerTool(\n item.mcpName,\n {\n annotations: item.tool.annotations,\n description: item.tool.description,\n inputSchema: toStandardSchema(inputSchema),\n },\n async (input: unknown, ctx: ServerContext) =>\n callEntityTool({ input, item, serverContext: ctx }),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.mcpName,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.mcpName,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.mcpName,\n {\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) => {\n const toolInput = (input ?? {}) as Record<string, unknown>\n const response = await tool.handler({\n authorizedMCP,\n input: toolInput,\n req,\n serverContext: ctx,\n })\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: tool.overrideResponse,\n response,\n toolName: item.mcpName,\n })\n },\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n\nconst withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {\n const description = 'The target slug.'\n const slugSchema = z.string().check(z.describe(description))\n\n if (!input) {\n return strictObject({ slug: slugSchema }) as unknown as ToolInputSchema\n }\n\n if (typeof input === 'object' && input !== null && '~standard' in input) {\n const schema = input['~standard'].jsonSchema.input({ target: 'draft-2020-12' })\n const properties = schema.properties as Record<string, unknown> | undefined\n\n if (properties?.slug) {\n return input\n }\n\n return addSlugToJSONSchema({ description, schema: schema as JsonSchemaType })\n }\n\n return addSlugToJSONSchema({ description, schema: input })\n}\n\nconst addSlugToJSONSchema = ({\n description,\n schema,\n}: {\n description: string\n schema: JsonSchemaType\n}): JsonSchemaType => {\n const objectSchema = schema as {\n properties?: Record<string, JsonSchemaType>\n required?: string[]\n } & JsonSchemaType\n\n return {\n ...objectSchema,\n type: 'object',\n properties: {\n ...objectSchema.properties,\n slug: {\n type: 'string',\n description,\n },\n },\n required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),\n }\n}\n"],"names":["McpServer","APIError","strictObject","z","getLogger","toStandardSchema","buildMcpServer","authorizedMCP","pluginConfig","req","config","locales","en","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","input","overrideResponse","response","toolName","overridden","doc","hook","hooks","afterToolCall","_doc","rest","callEntityTool","item","serverContext","entity","type","toolInput","slug","content","text","mcpName","isError","match","items","find","candidate","collectionSlug","globalSlug","handlerArgs","tool","handler","registeredEntityTools","Set","has","add","inputSchema","withSlugInput","registerTool","annotations","description","ctx","info","prompt","registerPrompt","argsSchema","undefined","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String","slugSchema","string","check","describe","schema","jsonSchema","target","properties","addSlugToJSONSchema","objectSchema","required","Array","from"],"mappings":"AAEA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,EAAEC,YAAY,EAAEC,CAAC,QAAQ,UAAS;AAanD,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACCN,EAAEO,M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;QAAgB;QAC7E,MAAMC,aAAaH,OAAOG,UAAU;QAEpC,IAAIA,YAAY9C,MAAM;YACpB,OAAOjB;QACT;QAEA,OAAOgE,oBAAoB;YAAEzB;YAAaqB,QAAQA;QAAyB;IAC7E;IAEA,OAAOI,oBAAoB;QAAEzB;QAAaqB,QAAQ5D;IAAM;AAC1D;AAEA,MAAMgE,sBAAsB,CAAC,EAC3BzB,WAAW,EACXqB,MAAM,EAIP;IACC,MAAMK,eAAeL;IAKrB,OAAO;QACL,GAAGK,YAAY;QACflD,MAAM;QACNgD,YAAY;YACV,GAAGE,aAAaF,UAAU;YAC1B9C,MAAM;gBACJF,MAAM;gBACNwB;YACF;QACF;QACA2B,UAAUC,MAAMC,IAAI,CAAC,IAAIpC,IAAI;YAAC;eAAYiC,aAAaC,QAAQ,IAAI,EAAE;SAAE;IACzE;AACF"}
1
+ {"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, strictObject, z } from 'payload'\n\nimport type {\n AuthorizedMCP,\n CollectionMCPItem,\n GlobalMCPItem,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n ToolInputSchema,\n} from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/**\n * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh\n * instances from this builder while they own the transport and protocol-era\n * decision.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createPayloadRequest`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n z.config(z.locales.en())\n\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = async ({\n input,\n overrideResponse,\n response,\n toolName,\n }: {\n input: unknown\n overrideResponse?: MCPResponseOverride\n response: MCPToolResponse\n toolName: string\n }): Promise<MCPToolResponse> => {\n let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {\n overridden = await hook({ input, req, response: overridden, toolName })\n }\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n /**\n * Runs a collection/global tool call:\n * - reads `slug` from the input\n * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug\n * - runs the tool handler and finalizes its response\n */\n const callEntityTool = async ({\n input,\n item,\n serverContext,\n }: {\n input: unknown\n item: CollectionMCPItem | GlobalMCPItem\n serverContext: ServerContext\n }): Promise<MCPToolResponse> => {\n const entity = item.type === 'collectionTool' ? 'collection' : 'global'\n const toolInput = (input ?? {}) as Record<string, unknown>\n const slug = toolInput.slug as string | undefined\n\n if (!slug) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: \"${item.mcpName}\" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,\n },\n ],\n isError: true,\n }\n }\n\n const match = authorizedMCP.items.find(\n (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>\n candidate.type === item.type &&\n candidate.mcpName === item.mcpName &&\n (candidate.type === 'collectionTool'\n ? candidate.collectionSlug === slug\n : candidate.type === 'globalTool' && candidate.globalSlug === slug),\n )\n\n if (!match) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"${item.mcpName}\" is not enabled for ${entity} \"${slug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const handlerArgs = {\n authorizedMCP,\n input: toolInput,\n req,\n serverContext,\n }\n const response = await (match.type === 'collectionTool'\n ? match.tool.handler({ ...handlerArgs, slug })\n : match.tool.handler({ ...handlerArgs, slug }))\n\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: match.tool.overrideResponse,\n response,\n toolName: match.mcpName,\n })\n }\n\n try {\n const registeredEntityTools = new Set<string>()\n\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool':\n case 'globalTool': {\n if (registeredEntityTools.has(item.mcpName)) {\n break\n }\n registeredEntityTools.add(item.mcpName)\n\n const inputSchema = withSlugInput({ input: item.tool.input })\n\n server.registerTool(\n item.mcpName,\n {\n annotations: item.tool.annotations,\n description: item.tool.description,\n inputSchema: toStandardSchema(inputSchema),\n },\n async (input: unknown, ctx: ServerContext) =>\n callEntityTool({ input, item, serverContext: ctx }),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.mcpName,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.mcpName,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.mcpName,\n {\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) => {\n const toolInput = (input ?? {}) as Record<string, unknown>\n const response = await tool.handler({\n authorizedMCP,\n input: toolInput,\n req,\n serverContext: ctx,\n })\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: tool.overrideResponse,\n response,\n toolName: item.mcpName,\n })\n },\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n\nconst withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {\n const description = 'The target slug.'\n const slugSchema = z.string().check(z.describe(description))\n\n if (!input) {\n return strictObject({ slug: slugSchema })\n }\n\n if (typeof input === 'object' && input !== null && '~standard' in input) {\n const schema = input['~standard'].jsonSchema.input({ target: 'draft-2020-12' })\n const properties = schema.properties as Record<string, unknown> | undefined\n\n if (properties?.slug) {\n return input\n }\n\n return addSlugToJSONSchema({ description, schema })\n }\n\n return addSlugToJSONSchema({ description, schema: input })\n}\n\nconst addSlugToJSONSchema = ({\n description,\n schema,\n}: {\n description: string\n schema: JsonSchemaType\n}): JsonSchemaType => {\n const objectSchema = schema as {\n properties?: Record<string, JsonSchemaType>\n required?: string[]\n } & JsonSchemaType\n\n return {\n ...objectSchema,\n type: 'object',\n properties: {\n ...objectSchema.properties,\n slug: {\n type: 'string',\n description,\n },\n },\n required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),\n }\n}\n"],"names":["McpServer","APIError","strictObject","z","getLogger","toStandardSchema","buildMcpServer","authorizedMCP","pluginConfig","req","config","locales","en","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","input","overrideResponse","response","toolName","overridden","doc","hook","hooks","afterToolCall","_doc","rest","callEntityTool","item","serverContext","entity","type","toolInput","slug","content","text","mcpName","isError","match","items","find","candidate","collectionSlug","globalSlug","handlerArgs","tool","handler","registeredEntityTools","Set","has","add","inputSchema","withSlugInput","registerTool","annotations","description","ctx","info","prompt","registerPrompt","argsSchema","undefined","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String","slugSchema","string","check","describe","schema","jsonSchema","target","properties","addSlugToJSONSchema","objectSchema","required","Array","from"],"mappings":"AAEA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,EAAEC,YAAY,EAAEC,CAAC,QAAQ,UAAS;AAanD,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACCN,EAAEO,MAAM,CAACP,EAAEQ,OAAO,CAACC,EAAE;IAErB,MAAMC,gBAAgBL,aAAaM,GAAG,EAAED,iBAAiB,CAAC;IAC1D,MAAME,SAAS,IAAIf,UACjB;QAAEgB,MAAM;QAAsBC,SAAS;QAAS,GAAGJ,cAAcK,UAAU;IAAC,GAC5EL,cAAcM,OAAO;IAGvB,MAAMC,SAAShB,UAAU;QAAEiB,SAASZ,IAAIY,OAAO;IAAC;IAEhD;;;GAGC,GACD,MAAMC,uBAAuB,OAAO,EAClCC,KAAK,EACLC,gBAAgB,EAChBC,QAAQ,EACRC,QAAQ,EAMT;QACC,IAAIC,aAAaH,mBAAmBC,UAAUA,SAASG,GAAG,IAAI,CAAC,GAAGnB,QAAQgB;QAC1E,KAAK,MAAMI,QAAQrB,aAAasB,KAAK,EAAEC,iBAAiB,EAAE,CAAE;YAC1DJ,aAAa,MAAME,KAAK;gBAAEN;gBAAOd;gBAAKgB,UAAUE;gBAAYD;YAAS;QACvE;QACA,MAAM,EAAEE,KAAK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