@payloadcms/plugin-mcp 4.0.0-internal.a1317b2 → 4.0.0-internal.a2d053c

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 (97) hide show
  1. package/bin.js +0 -7
  2. package/dist/endpoint/access.d.ts.map +1 -1
  3. package/dist/endpoint/access.js +23 -3
  4. package/dist/endpoint/access.js.map +1 -1
  5. package/dist/endpoint/index.d.ts.map +1 -1
  6. package/dist/endpoint/index.js +46 -4
  7. package/dist/endpoint/index.js.map +1 -1
  8. package/dist/endpoint/oauth.d.ts +39 -0
  9. package/dist/endpoint/oauth.d.ts.map +1 -0
  10. package/dist/endpoint/oauth.js +94 -0
  11. package/dist/endpoint/oauth.js.map +1 -0
  12. package/dist/endpoint/oauthLoginToken.d.ts +21 -0
  13. package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
  14. package/dist/endpoint/oauthLoginToken.js +79 -0
  15. package/dist/endpoint/oauthLoginToken.js.map +1 -0
  16. package/dist/endpoint/oauthServer.d.ts +12 -0
  17. package/dist/endpoint/oauthServer.d.ts.map +1 -0
  18. package/dist/endpoint/oauthServer.js +362 -0
  19. package/dist/endpoint/oauthServer.js.map +1 -0
  20. package/dist/index.d.ts +10 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +15 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/mcp/buildMcpServer.d.ts +1 -1
  25. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  26. package/dist/mcp/buildMcpServer.js +3 -3
  27. package/dist/mcp/buildMcpServer.js.map +1 -1
  28. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  29. package/dist/mcp/builtin/collections/authTools.js +4 -3
  30. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  31. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  32. package/dist/mcp/builtin/collections/createTool.js +8 -5
  33. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  34. package/dist/mcp/builtin/collections/deleteTool.js +6 -2
  35. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  36. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  37. package/dist/mcp/builtin/collections/duplicateTool.js +6 -2
  38. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  39. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  40. package/dist/mcp/builtin/collections/fileInput.js +19 -54
  41. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  42. package/dist/mcp/builtin/collections/findTool.js +8 -4
  43. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  44. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +19 -3
  46. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  47. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  48. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  49. package/dist/mcp/builtin/collections/updateTool.js +21 -8
  50. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  51. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
  52. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  53. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  54. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +19 -3
  55. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  56. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  57. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  58. package/dist/mcp/sanitizeMCPConfig.js +3 -0
  59. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  60. package/dist/stdio.js +4 -3
  61. package/dist/stdio.js.map +1 -1
  62. package/dist/types.d.ts +92 -3
  63. package/dist/types.d.ts.map +1 -1
  64. package/dist/types.js.map +1 -1
  65. package/dist/utils/seal.d.ts +18 -0
  66. package/dist/utils/seal.d.ts.map +1 -0
  67. package/dist/utils/seal.js +27 -0
  68. package/dist/utils/seal.js.map +1 -0
  69. package/dist/utils/toStandardSchema.js.map +1 -1
  70. package/package.json +23 -26
  71. package/src/endpoint/access.ts +22 -3
  72. package/src/endpoint/index.ts +41 -3
  73. package/src/endpoint/oauth.ts +92 -0
  74. package/src/endpoint/oauthLoginToken.ts +91 -0
  75. package/src/endpoint/oauthServer.ts +396 -0
  76. package/src/index.ts +40 -5
  77. package/src/mcp/buildMcpServer.ts +5 -5
  78. package/src/mcp/builtin/collections/authTools.ts +7 -4
  79. package/src/mcp/builtin/collections/createTool.ts +16 -5
  80. package/src/mcp/builtin/collections/deleteTool.ts +3 -3
  81. package/src/mcp/builtin/collections/duplicateTool.ts +3 -2
  82. package/src/mcp/builtin/collections/fileInput.ts +17 -59
  83. package/src/mcp/builtin/collections/findTool.ts +4 -4
  84. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +12 -1
  85. package/src/mcp/builtin/collections/restoreVersionTool.ts +1 -1
  86. package/src/mcp/builtin/collections/updateTool.ts +10 -6
  87. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +1 -1
  88. package/src/mcp/builtin/globals/findTool.ts +1 -1
  89. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +11 -1
  90. package/src/mcp/builtin/globals/updateTool.ts +1 -1
  91. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  92. package/src/stdio.ts +2 -2
  93. package/src/types.ts +94 -3
  94. package/src/utils/seal.ts +46 -0
  95. package/src/utils/toStandardSchema.ts +1 -1
  96. package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
  97. package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
@@ -0,0 +1,362 @@
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 { seal, unseal } from '../utils/seal.js';
6
+ import { getMCPURL } from './oauth.js';
7
+ import { issueLoginToken, refreshLoginToken } from './oauthLoginToken.js';
8
+ /**
9
+ * Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is
10
+ * `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and
11
+ * the client receives the tokens `issueToken` creates.
12
+ *
13
+ * Clients, consent forms, authorization codes, and refresh tokens are encrypted and handed to the
14
+ * client instead of being stored. Only the default tokens write to the database, to the user's
15
+ * login sessions.
16
+ */ export const oauthServerEndpoints = [
17
+ {
18
+ disableAuth: true,
19
+ handler: (req)=>withIssuer(req, (issuer)=>metadataResponse(issuer)),
20
+ method: 'get',
21
+ // OpenID discovery is the only metadata location MCP clients check below the issuer's path,
22
+ // which lets this work under /api without a route at the site root
23
+ path: '/mcp/oauth/.well-known/openid-configuration'
24
+ },
25
+ {
26
+ disableAuth: true,
27
+ handler: (req)=>withIssuer(req, ()=>Response.json({
28
+ keys: []
29
+ })),
30
+ method: 'get',
31
+ path: '/mcp/oauth/jwks'
32
+ },
33
+ {
34
+ disableAuth: true,
35
+ handler: (req)=>withIssuer(req, ()=>register(req)),
36
+ method: 'post',
37
+ path: '/mcp/oauth/register'
38
+ },
39
+ {
40
+ handler: (req)=>withIssuer(req, ()=>authorize(req)),
41
+ method: 'get',
42
+ path: '/mcp/oauth/authorize'
43
+ },
44
+ {
45
+ handler: (req)=>withIssuer(req, ()=>approve(req)),
46
+ method: 'post',
47
+ path: '/mcp/oauth/authorize'
48
+ },
49
+ {
50
+ disableAuth: true,
51
+ handler: (req)=>withIssuer(req, ()=>token(req)),
52
+ method: 'post',
53
+ path: '/mcp/oauth/token'
54
+ }
55
+ ];
56
+ /** The authorization server URL, or `undefined` when Payload isn't the authorization server. */ const getIssuer = (req)=>getPluginConfig({
57
+ config: req.payload.config
58
+ }).oauth?.type === 'builtin' ? `${getMCPURL({
59
+ config: req.payload.config,
60
+ url: req.url
61
+ })}/oauth` : undefined;
62
+ const withIssuer = (req, handler)=>{
63
+ const issuer = getIssuer(req);
64
+ return issuer ? handler(issuer) : new Response(null, {
65
+ status: 404
66
+ });
67
+ };
68
+ /**
69
+ * The user logged in to this browser, who can allow MCP clients. Tokens and API keys in the
70
+ * `Authorization` header can't, or an MCP client could use its access token to approve itself a
71
+ * new, separate login.
72
+ */ const getBrowserUser = (req)=>req.headers.has('Authorization') ? null : req.user;
73
+ const metadataResponse = (issuer)=>Response.json({
74
+ authorization_endpoint: `${issuer}/authorize`,
75
+ code_challenge_methods_supported: [
76
+ 'S256'
77
+ ],
78
+ grant_types_supported: [
79
+ 'authorization_code',
80
+ 'refresh_token'
81
+ ],
82
+ // Required by OpenID discovery. No ID tokens are issued.
83
+ id_token_signing_alg_values_supported: [
84
+ 'RS256'
85
+ ],
86
+ issuer,
87
+ jwks_uri: `${issuer}/jwks`,
88
+ registration_endpoint: `${issuer}/register`,
89
+ response_types_supported: [
90
+ 'code'
91
+ ],
92
+ subject_types_supported: [
93
+ 'public'
94
+ ],
95
+ token_endpoint: `${issuer}/token`,
96
+ token_endpoint_auth_methods_supported: [
97
+ 'none'
98
+ ]
99
+ }, // Not cached, since without `serverURL` its URLs come from the request
100
+ {
101
+ headers: {
102
+ 'Access-Control-Allow-Origin': '*',
103
+ 'Cache-Control': 'no-store'
104
+ }
105
+ });
106
+ const register = async (req)=>{
107
+ const { client_name, redirect_uris } = await req.json().catch(()=>({}));
108
+ if (!Array.isArray(redirect_uris) || !redirect_uris.length || !redirect_uris.every((uri)=>typeof uri === 'string' && URL.canParse(uri) && !uri.includes('#'))) {
109
+ return Response.json({
110
+ error: OAuthErrorCode.InvalidRedirectUri
111
+ }, {
112
+ status: 400
113
+ });
114
+ }
115
+ const client = {
116
+ name: typeof client_name === 'string' ? client_name : 'An MCP client',
117
+ redirectURIs: redirect_uris
118
+ };
119
+ return Response.json({
120
+ client_id: seal({
121
+ type: 'client',
122
+ data: client,
123
+ req
124
+ }),
125
+ client_name: client.name,
126
+ grant_types: [
127
+ 'authorization_code',
128
+ 'refresh_token'
129
+ ],
130
+ redirect_uris: client.redirectURIs,
131
+ response_types: [
132
+ 'code'
133
+ ],
134
+ token_endpoint_auth_method: 'none'
135
+ }, {
136
+ status: 201
137
+ });
138
+ };
139
+ const authorize = (req)=>{
140
+ const url = new URL(req.url);
141
+ const params = url.searchParams;
142
+ const clientID = params.get('client_id');
143
+ const client = unseal({
144
+ type: 'client',
145
+ req,
146
+ value: clientID
147
+ });
148
+ const redirectURI = params.get('redirect_uri');
149
+ // Never redirect to an address the client didn't register
150
+ if (!client || !redirectURI || !client.redirectURIs.includes(redirectURI)) {
151
+ return page({
152
+ content: '<p>Start the sign-in again from your MCP client.</p>',
153
+ status: 400,
154
+ title: 'This sign-in link is invalid'
155
+ });
156
+ }
157
+ const state = params.get('state');
158
+ const codeChallenge = params.get('code_challenge');
159
+ if (params.get('response_type') !== 'code' || params.get('code_challenge_method') !== 'S256' || !codeChallenge) {
160
+ return redirect({
161
+ params: {
162
+ error: OAuthErrorCode.InvalidRequest,
163
+ state
164
+ },
165
+ redirectURI
166
+ });
167
+ }
168
+ const user = getBrowserUser(req);
169
+ if (!user) {
170
+ const loginURL = formatAdminURL({
171
+ adminRoute: req.payload.config.routes.admin,
172
+ path: '/login'
173
+ });
174
+ return new Response(null, {
175
+ headers: {
176
+ Location: `${loginURL}?redirect=${encodeURIComponent(url.pathname + url.search)}`
177
+ },
178
+ status: 302
179
+ });
180
+ }
181
+ const consent = {
182
+ clientID: clientID,
183
+ codeChallenge,
184
+ collection: user.collection,
185
+ redirectURI,
186
+ state,
187
+ userID: user.id
188
+ };
189
+ return page({
190
+ 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>
191
+ <form method="post">
192
+ <input name="consent" type="hidden" value="${seal({
193
+ type: 'consent',
194
+ data: consent,
195
+ expiresIn: 20 * 60 * 60,
196
+ req
197
+ })}">
198
+ <button name="decision" type="submit" value="allow">Allow</button>
199
+ <button name="decision" type="submit" value="deny">Deny</button>
200
+ </form>`,
201
+ status: 200,
202
+ title: `Allow ${client.name} to use your account?`
203
+ });
204
+ };
205
+ const approve = async (req)=>{
206
+ const form = new URLSearchParams(await req.text());
207
+ const consent = unseal({
208
+ type: 'consent',
209
+ req,
210
+ value: form.get('consent')
211
+ });
212
+ const user = getBrowserUser(req);
213
+ // The form is only valid for the user it was shown to
214
+ if (!consent || user?.id !== consent.userID || user.collection !== consent.collection) {
215
+ return page({
216
+ content: '<p>Start the sign-in again from your MCP client.</p>',
217
+ status: 400,
218
+ title: 'This sign-in request expired'
219
+ });
220
+ }
221
+ const { clientID, codeChallenge, redirectURI, state } = consent;
222
+ if (form.get('decision') !== 'allow') {
223
+ return redirect({
224
+ params: {
225
+ error: OAuthErrorCode.AccessDenied,
226
+ state
227
+ },
228
+ redirectURI
229
+ });
230
+ }
231
+ const code = {
232
+ clientID,
233
+ codeChallenge,
234
+ redirectURI,
235
+ tokens: await getTokenHooks(req).issueToken({
236
+ req
237
+ })
238
+ };
239
+ return redirect({
240
+ params: {
241
+ code: seal({
242
+ type: 'code',
243
+ data: code,
244
+ expiresIn: 60,
245
+ req
246
+ }),
247
+ state
248
+ },
249
+ redirectURI
250
+ });
251
+ };
252
+ const token = async (req)=>{
253
+ const form = new URLSearchParams(await req.text());
254
+ const clientID = form.get('client_id');
255
+ const tokens = clientID && (form.get('grant_type') === 'refresh_token' ? await refresh({
256
+ clientID,
257
+ form,
258
+ req
259
+ }) : redeemCode({
260
+ clientID,
261
+ form,
262
+ req
263
+ }));
264
+ if (!clientID || !tokens) {
265
+ return Response.json({
266
+ error: OAuthErrorCode.InvalidGrant
267
+ }, {
268
+ status: 400
269
+ });
270
+ }
271
+ return Response.json({
272
+ access_token: tokens.accessToken,
273
+ expires_in: tokens.expiresIn,
274
+ refresh_token: tokens.refreshToken && seal({
275
+ type: 'refresh',
276
+ data: {
277
+ clientID,
278
+ refreshToken: tokens.refreshToken
279
+ },
280
+ req
281
+ }),
282
+ token_type: 'Bearer'
283
+ }, {
284
+ headers: {
285
+ 'Cache-Control': 'no-store'
286
+ }
287
+ });
288
+ };
289
+ const redeemCode = ({ clientID, form, req })=>{
290
+ const code = unseal({
291
+ type: 'code',
292
+ req,
293
+ value: form.get('code')
294
+ });
295
+ 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
296
+ createHash('sha256').update(form.get('code_verifier') ?? '').digest('base64url') === code.codeChallenge) {
297
+ return code.tokens;
298
+ }
299
+ };
300
+ const refresh = async ({ clientID, form, req })=>{
301
+ const refreshToken = unseal({
302
+ type: 'refresh',
303
+ req,
304
+ value: form.get('refresh_token')
305
+ });
306
+ // Only the client a refresh token was issued to can use it
307
+ if (refreshToken?.clientID === clientID) {
308
+ return await getTokenHooks(req).refreshToken?.({
309
+ refreshToken: refreshToken.refreshToken,
310
+ req
311
+ });
312
+ }
313
+ };
314
+ /** `issueToken` and `refreshToken`, or the defaults for Payload login tokens. */ const getTokenHooks = (req)=>{
315
+ const oauth = getPluginConfig({
316
+ config: req.payload.config
317
+ }).oauth;
318
+ return oauth.issueToken ? {
319
+ issueToken: oauth.issueToken,
320
+ refreshToken: oauth.refreshToken
321
+ } : {
322
+ issueToken: issueLoginToken,
323
+ refreshToken: refreshLoginToken
324
+ };
325
+ };
326
+ const redirect = ({ params, redirectURI })=>{
327
+ const location = new URL(redirectURI);
328
+ for (const [key, value] of Object.entries(params)){
329
+ if (value) {
330
+ location.searchParams.set(key, value);
331
+ }
332
+ }
333
+ return new Response(null, {
334
+ headers: {
335
+ Location: location.href
336
+ },
337
+ status: 302
338
+ });
339
+ };
340
+ const page = ({ content, status, title })=>new Response(`<!doctype html>
341
+ <html lang="en">
342
+ <head>
343
+ <meta charset="utf-8">
344
+ <meta name="viewport" content="width=device-width, initial-scale=1">
345
+ <title>${escapeHTML(title)}</title>
346
+ <style>
347
+ body { font-family: system-ui, sans-serif; margin: 4rem auto; max-width: 32rem; overflow-wrap: anywhere; padding: 0 1rem }
348
+ button { font: inherit; margin-inline-end: 0.5rem; padding: 0.5rem 1rem }
349
+ </style>
350
+ </head>
351
+ <body><h1>${escapeHTML(title)}</h1>${content}</body>
352
+ </html>`, {
353
+ headers: {
354
+ // Stop other sites from framing the page to trick users into clicking Allow
355
+ 'Content-Security-Policy': "frame-ancestors 'none'",
356
+ 'Content-Type': 'text/html; charset=utf-8'
357
+ },
358
+ status
359
+ });
360
+ const escapeHTML = (value)=>value.replace(/[&<>"']/g, (character)=>`&#${character.charCodeAt(0)};`);
361
+
362
+ //# 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 { seal, unseal } from '../utils/seal.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\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","seal","unseal","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","data","grant_types","response_types","token_endpoint_auth_method","params","searchParams","clientID","get","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","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,IAAI,EAAEC,MAAM,QAAQ,mBAAkB;AAC/C,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,MACjBT,gBAAgB;QAAEuB,QAAQd,IAAI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OC,OAAO,CAACpD,QAAS;QACjD,IAAII,OAAO;YACT6C,SAAShD,YAAY,CAACoD,GAAG,CAACH,KAAK9C;QACjC;IACF;IAEA,OAAO,IAAItD,SAAS,MAAM;QAAEgB,SAAS;YAAEmD,UAAUgC,SAASK,IAAI;QAAC;QAAG1F,QAAQ;IAAI;AAChF;AAEA,MAAM0C,OAAO,CAAC,EACZC,OAAO,EACP3C,MAAM,EACN4C,KAAK,EAKN,GACC,IAAI1D,SACF,CAAC;;;;;OAKE,EAAE2E,WAAWjB,OAAO;;;;;;UAMjB,EAAEiB,WAAWjB,OAAO,KAAK,EAAED,QAAQ;OACtC,CAAC,EACJ;QACEzC,SAAS;YACP,4EAA4E;YAC5E,2BAA2B;YAC3B,gBAAgB;QAClB;QACAF;IACF;AAGJ,MAAM6D,aAAa,CAACrB,QAClBA,MAAMmD,OAAO,CAAC,YAAY,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"}
@@ -9,7 +9,7 @@ import type { AuthorizedMCP, SanitizedMCPPluginConfig } from '../types.js';
9
9
  *
10
10
  * `req` is the request context handlers see. For HTTP it's the live
11
11
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
12
- * synthesized one built via `createLocalReq`.
12
+ * synthesized one built via `createPayloadRequest`.
13
13
  */
14
14
  export declare const buildMcpServer: ({ authorizedMCP, pluginConfig, req, }: {
15
15
  authorizedMCP: AuthorizedMCP;
@@ -1 +1 @@
1
- {"version":3,"file":"buildMcpServer.d.ts","sourceRoot":"","sources":["../../src/mcp/buildMcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,EAAE,SAAS,EAAsB,MAAM,8BAA8B,CAAA;AAG5E,OAAO,KAAK,EACV,aAAa,EAMb,wBAAwB,EAEzB,MAAM,aAAa,CAAA;AAOpB;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,0CAIxB;IACD,aAAa,EAAE,aAAa,CAAA;IAC5B,YAAY,EAAE,wBAAwB,CAAA;IACtC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,SA8MH,CAAA"}
1
+ {"version":3,"file":"buildMcpServer.d.ts","sourceRoot":"","sources":["../../src/mcp/buildMcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,EAAE,SAAS,EAAsB,MAAM,8BAA8B,CAAA;AAG5E,OAAO,KAAK,EACV,aAAa,EAMb,wBAAwB,EAEzB,MAAM,aAAa,CAAA;AAKpB;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,0CAIxB;IACD,aAAa,EAAE,aAAa,CAAA;IAC5B,YAAY,EAAE,wBAAwB,CAAA;IACtC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,SAgNH,CAAA"}
@@ -2,7 +2,6 @@ import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { APIError, strictObject, z } from 'payload';
3
3
  import { getLogger } from '../utils/getLogger.js';
4
4
  import { toStandardSchema } from '../utils/toStandardSchema.js';
5
- z.config(z.locales.en());
6
5
  /**
7
6
  * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh
8
7
  * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh
@@ -11,8 +10,9 @@ z.config(z.locales.en());
11
10
  *
12
11
  * `req` is the request context handlers see. For HTTP it's the live
13
12
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
14
- * synthesized one built via `createLocalReq`.
13
+ * synthesized one built via `createPayloadRequest`.
15
14
  */ export const buildMcpServer = ({ authorizedMCP, pluginConfig, req })=>{
15
+ z.config(z.locales.en());
16
16
  const serverOptions = pluginConfig.mcp?.serverOptions || {};
17
17
  const server = new McpServer({
18
18
  name: 'Payload MCP Server',
@@ -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\nz.config(z.locales.en())\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 `createLocalReq`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\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","config","locales","en","buildMcpServer","authorizedMCP","pluginConfig","req","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/DF,EAAEG,MAAM,CAACH,EAAEI,OAAO,CAACC,EAAE;AAErB;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACC,MAAMC,gBAAgBF,aAAaG,GAAG,EAAED,iBAAiB,CAAC;IAC1D,MAAME,SAAS,IAAIf,UACjB;QAAEgB,MAAM;QAAsBC,SAAS;QAAS,G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AoB;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,KAAKI,IAAI,EAAE,GAAGC,MAAM,GAAGN;QAC/B,OAAOM;IACT;IAEA;;;;;GAKC,GACD,MAAMC,iBAAiB,OAAO,EAC5BX,KAAK,EACLY,IAAI,EACJC,aAAa,EAKd;QACC,MAAMC,SAASF,KAAKG,IA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F,eAAO,MAAM,oBAAoB,4CAmC/B,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAiC/B,CAAA"}
1
+ {"version":3,"file":"authTools.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"names":[],"mappings":"AAkCA,eAAO,MAAM,kBAAkB,4CA0D7B,CAAA;AAEF,eAAO,MAAM,4BAA4B,4CAmCvC,CAAA;AAEF,eAAO,MAAM,mBAAmB,4CAuC9B,CAAA;AAEF,eAAO,MAAM,2BAA2B,4CAmCtC,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAmC/B,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAiC/B,CAAA"}