@payloadcms/plugin-mcp 4.0.0-internal.293e026 → 4.0.0-internal.2a3c3bc

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 (242) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/defaultAccess.d.ts +3 -0
  3. package/dist/defaultAccess.d.ts.map +1 -0
  4. package/dist/defaultAccess.js +3 -0
  5. package/dist/defaultAccess.js.map +1 -0
  6. package/dist/defineTool.d.ts +8 -8
  7. package/dist/defineTool.d.ts.map +1 -1
  8. package/dist/endpoint/access.d.ts +12 -5
  9. package/dist/endpoint/access.d.ts.map +1 -1
  10. package/dist/endpoint/access.js +76 -88
  11. package/dist/endpoint/access.js.map +1 -1
  12. package/dist/endpoint/index.d.ts +1 -1
  13. package/dist/endpoint/index.d.ts.map +1 -1
  14. package/dist/endpoint/index.js +102 -16
  15. package/dist/endpoint/index.js.map +1 -1
  16. package/dist/endpoint/oauth.d.ts +27 -0
  17. package/dist/endpoint/oauth.d.ts.map +1 -0
  18. package/dist/endpoint/oauth.js +61 -0
  19. package/dist/endpoint/oauth.js.map +1 -0
  20. package/dist/exports/client.d.ts +1 -1
  21. package/dist/exports/client.d.ts.map +1 -1
  22. package/dist/exports/client.js +1 -1
  23. package/dist/exports/client.js.map +1 -1
  24. package/dist/exports/internal.d.ts +2 -0
  25. package/dist/exports/internal.d.ts.map +1 -0
  26. package/dist/exports/internal.js +3 -0
  27. package/dist/exports/internal.js.map +1 -0
  28. package/dist/index.d.ts +3 -2
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +22 -20
  31. package/dist/index.js.map +1 -1
  32. package/dist/mcp/buildMcpServer.d.ts +6 -6
  33. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  34. package/dist/mcp/buildMcpServer.js +146 -81
  35. package/dist/mcp/buildMcpServer.js.map +1 -1
  36. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  37. package/dist/mcp/builtin/collections/authTools.js +123 -61
  38. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  39. package/dist/mcp/builtin/collections/countTool.d.ts +2 -0
  40. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -0
  41. package/dist/mcp/builtin/collections/countTool.js +63 -0
  42. package/dist/mcp/builtin/collections/countTool.js.map +1 -0
  43. package/dist/mcp/builtin/collections/countVersionsTool.d.ts +2 -0
  44. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -0
  45. package/dist/mcp/builtin/collections/countVersionsTool.js +60 -0
  46. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -0
  47. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  48. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  49. package/dist/mcp/builtin/collections/createTool.js +114 -68
  50. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  51. package/dist/mcp/builtin/collections/deleteTool.d.ts +1 -1
  52. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  53. package/dist/mcp/builtin/collections/deleteTool.js +55 -61
  54. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  55. package/dist/mcp/builtin/collections/duplicateTool.d.ts +2 -0
  56. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -0
  57. package/dist/mcp/builtin/collections/duplicateTool.js +90 -0
  58. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -0
  59. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  60. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  61. package/dist/mcp/builtin/collections/fileInput.js +88 -0
  62. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  63. package/dist/mcp/builtin/collections/findDistinctTool.d.ts +2 -0
  64. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -0
  65. package/dist/mcp/builtin/collections/findDistinctTool.js +77 -0
  66. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -0
  67. package/dist/mcp/builtin/collections/findTool.d.ts +1 -1
  68. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  69. package/dist/mcp/builtin/collections/findTool.js +61 -74
  70. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  71. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts +2 -0
  72. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -0
  73. package/dist/mcp/builtin/collections/findVersionByIDTool.js +74 -0
  74. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -0
  75. package/dist/mcp/builtin/collections/findVersionsTool.d.ts +2 -0
  76. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -0
  77. package/dist/mcp/builtin/collections/findVersionsTool.js +84 -0
  78. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -0
  79. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts +2 -0
  80. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -0
  81. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +103 -0
  82. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -0
  83. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts +2 -0
  84. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -0
  85. package/dist/mcp/builtin/collections/restoreVersionTool.js +69 -0
  86. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -0
  87. package/dist/mcp/builtin/collections/updateTool.d.ts +1 -1
  88. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  89. package/dist/mcp/builtin/collections/updateTool.js +118 -137
  90. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  91. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  92. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  93. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  94. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  95. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  96. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  97. package/dist/mcp/builtin/formatEntityError.js +55 -0
  98. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  99. package/dist/mcp/builtin/getConfigInfoTool.d.ts +2 -0
  100. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -0
  101. package/dist/mcp/builtin/getConfigInfoTool.js +69 -0
  102. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -0
  103. package/dist/mcp/builtin/globals/countVersionsTool.d.ts +2 -0
  104. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -0
  105. package/dist/mcp/builtin/globals/countVersionsTool.js +60 -0
  106. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -0
  107. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  108. package/dist/mcp/builtin/globals/findTool.js +27 -36
  109. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  110. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts +2 -0
  111. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -0
  112. package/dist/mcp/builtin/globals/findVersionByIDTool.js +68 -0
  113. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -0
  114. package/dist/mcp/builtin/globals/findVersionsTool.d.ts +2 -0
  115. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -0
  116. package/dist/mcp/builtin/globals/findVersionsTool.js +78 -0
  117. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -0
  118. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts +2 -0
  119. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -0
  120. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +81 -0
  121. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -0
  122. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts +2 -0
  123. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -0
  124. package/dist/mcp/builtin/globals/restoreVersionTool.js +70 -0
  125. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -0
  126. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  127. package/dist/mcp/builtin/globals/updateTool.js +44 -62
  128. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  129. package/dist/mcp/builtinTools.d.ts +150 -19
  130. package/dist/mcp/builtinTools.d.ts.map +1 -1
  131. package/dist/mcp/builtinTools.js +125 -20
  132. package/dist/mcp/builtinTools.js.map +1 -1
  133. package/dist/mcp/sanitizeMCPConfig.d.ts +0 -1
  134. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  135. package/dist/mcp/sanitizeMCPConfig.js +125 -58
  136. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  137. package/dist/stdio.d.ts +3 -3
  138. package/dist/stdio.d.ts.map +1 -1
  139. package/dist/stdio.js +86 -47
  140. package/dist/stdio.js.map +1 -1
  141. package/dist/types.d.ts +138 -114
  142. package/dist/types.d.ts.map +1 -1
  143. package/dist/types.js +2 -4
  144. package/dist/types.js.map +1 -1
  145. package/dist/utils/camelCase.d.ts.map +1 -1
  146. package/dist/utils/getPluginConfig.d.ts +1 -1
  147. package/dist/utils/getPluginConfig.js +1 -1
  148. package/dist/utils/getPluginConfig.js.map +1 -1
  149. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  150. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  151. package/package.json +11 -18
  152. package/src/defaultAccess.ts +3 -0
  153. package/src/endpoint/access.ts +81 -101
  154. package/src/endpoint/index.ts +93 -15
  155. package/src/endpoint/oauth.ts +72 -0
  156. package/src/exports/client.ts +2 -1
  157. package/src/exports/internal.ts +1 -0
  158. package/src/index.ts +19 -20
  159. package/src/mcp/buildMcpServer.ts +181 -116
  160. package/src/mcp/builtin/collections/authTools.ts +122 -75
  161. package/src/mcp/builtin/collections/countTool.ts +61 -0
  162. package/src/mcp/builtin/collections/countVersionsTool.ts +60 -0
  163. package/src/mcp/builtin/collections/createTool.ts +117 -88
  164. package/src/mcp/builtin/collections/deleteTool.ts +48 -74
  165. package/src/mcp/builtin/collections/duplicateTool.ts +84 -0
  166. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  167. package/src/mcp/builtin/collections/fileInput.ts +127 -0
  168. package/src/mcp/builtin/collections/findDistinctTool.ts +67 -0
  169. package/src/mcp/builtin/collections/findTool.ts +57 -110
  170. package/src/mcp/builtin/collections/findVersionByIDTool.ts +66 -0
  171. package/src/mcp/builtin/collections/findVersionsTool.ts +83 -0
  172. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +91 -0
  173. package/src/mcp/builtin/collections/restoreVersionTool.ts +65 -0
  174. package/src/mcp/builtin/collections/updateTool.ts +106 -143
  175. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  176. package/src/mcp/builtin/formatEntityError.ts +77 -0
  177. package/src/mcp/builtin/getConfigInfoTool.ts +68 -0
  178. package/src/mcp/builtin/globals/countVersionsTool.ts +60 -0
  179. package/src/mcp/builtin/globals/findTool.ts +27 -57
  180. package/src/mcp/builtin/globals/findVersionByIDTool.ts +64 -0
  181. package/src/mcp/builtin/globals/findVersionsTool.ts +69 -0
  182. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +73 -0
  183. package/src/mcp/builtin/globals/restoreVersionTool.ts +68 -0
  184. package/src/mcp/builtin/globals/updateTool.ts +51 -79
  185. package/src/mcp/builtinTools.ts +118 -41
  186. package/src/mcp/sanitizeMCPConfig.ts +121 -78
  187. package/src/stdio.ts +80 -47
  188. package/src/types.ts +156 -120
  189. package/src/utils/getPluginConfig.ts +1 -1
  190. package/dist/@types/assets.d.js +0 -2
  191. package/dist/@types/assets.d.js.map +0 -1
  192. package/dist/collection/getAccessField.d.ts +0 -12
  193. package/dist/collection/getAccessField.d.ts.map +0 -1
  194. package/dist/collection/getAccessField.js +0 -57
  195. package/dist/collection/getAccessField.js.map +0 -1
  196. package/dist/collection/index.d.ts +0 -6
  197. package/dist/collection/index.d.ts.map +0 -1
  198. package/dist/collection/index.js +0 -60
  199. package/dist/collection/index.js.map +0 -1
  200. package/dist/components/AccessField/index.client.d.ts +0 -10
  201. package/dist/components/AccessField/index.client.d.ts.map +0 -1
  202. package/dist/components/AccessField/index.client.js +0 -305
  203. package/dist/components/AccessField/index.client.js.map +0 -1
  204. package/dist/components/AccessField/index.css +0 -93
  205. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  206. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  207. package/dist/utils/getVirtualFieldNames.js +0 -35
  208. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  209. package/dist/utils/localAPIDefaults.d.ts +0 -20
  210. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  211. package/dist/utils/localAPIDefaults.js +0 -19
  212. package/dist/utils/localAPIDefaults.js.map +0 -1
  213. package/dist/utils/schemaConversion/buildToolInput.d.ts +0 -29
  214. package/dist/utils/schemaConversion/buildToolInput.d.ts.map +0 -1
  215. package/dist/utils/schemaConversion/buildToolInput.js +0 -51
  216. package/dist/utils/schemaConversion/buildToolInput.js.map +0 -1
  217. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  218. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  219. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  220. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  221. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -15
  222. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  223. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -464
  224. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  225. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -158
  226. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  227. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  228. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  229. package/dist/utils/transformPointDataToPayload.js +0 -28
  230. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  231. package/src/@types/assets.d.ts +0 -3
  232. package/src/collection/getAccessField.ts +0 -64
  233. package/src/collection/index.ts +0 -64
  234. package/src/components/AccessField/index.client.tsx +0 -344
  235. package/src/components/AccessField/index.css +0 -93
  236. package/src/utils/getVirtualFieldNames.ts +0 -53
  237. package/src/utils/localAPIDefaults.ts +0 -22
  238. package/src/utils/schemaConversion/buildToolInput.ts +0 -68
  239. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
  240. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -103
  241. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -529
  242. package/src/utils/transformPointDataToPayload.ts +0 -40
@@ -1,132 +1,112 @@
1
- import type { DefaultDocumentIDType, PayloadRequest, TypedUser } from 'payload'
1
+ import type { PayloadRequest, SanitizedPermissions } from 'payload'
2
2
 
3
- import crypto from 'crypto'
4
- import { UnauthorizedError } from 'payload'
3
+ import { getAccessResults, UnauthorizedError } from 'payload'
5
4
 
6
- import type { AuthorizedMCP, MCPAPIKeysDoc } from '../types.js'
5
+ import type { AuthorizedMCP, MCPItem } from '../types.js'
7
6
 
8
- import { getLogger } from '../utils/getLogger.js'
9
7
  import { getPluginConfig } from '../utils/getPluginConfig.js'
10
8
 
9
+ export type GetAuthorizedMCPArgs = {
10
+ overrideAccess: boolean
11
+ req: PayloadRequest
12
+ }
13
+
11
14
  /**
12
- * Resolves the API key (or dev-mode session) and returns the items the caller
13
- * may use. Denied items are dropped from the array.
15
+ * Authenticates an MCP request and removes items the user cannot access.
16
+ * `overrideAccess` skips Payload and MCP item access checks.
14
17
  */
15
- export const getAuthorizedMCP: (args: { req: PayloadRequest }) => Promise<AuthorizedMCP> = async ({
18
+ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP> = async ({
19
+ overrideAccess,
16
20
  req,
17
21
  }) => {
18
- const logger = getLogger({ payload: req.payload })
19
22
  const pluginConfig = getPluginConfig({ config: req.payload.config })
20
23
 
21
- const authHeader = req.headers.get('Authorization')
22
- const hasBearerToken = authHeader?.startsWith('Bearer ')
23
-
24
- const buildAuthorized = (apiKeyDoc: MCPAPIKeysDoc): AuthorizedMCP => ({
25
- items: pluginConfig.items.filter((item) => {
26
- switch (item.type) {
27
- case 'collectionTool':
28
- return apiKeyDoc.access.collections?.[item.collectionSlug]?.[item.key] !== false
29
- case 'globalTool':
30
- return apiKeyDoc.access.globals?.[item.globalSlug]?.[item.key] !== false
31
- case 'prompt':
32
- return apiKeyDoc.access.prompts?.[item.key] !== false
33
- case 'resource':
34
- return apiKeyDoc.access.resources?.[item.key] !== false
35
- case 'tool':
36
- return apiKeyDoc.access.tools?.[item.key] !== false
37
- }
38
- }),
39
- overrideAccess:
40
- typeof apiKeyDoc.overrideAccess === 'boolean' ? apiKeyDoc.overrideAccess : false,
41
- user: apiKeyDoc.user,
42
- })
43
-
44
- if (pluginConfig.overrideAuth) {
45
- return await pluginConfig.overrideAuth({
46
- getAPIKeyDoc: (overrideApiKey) => getAPIKeyDoc({ logger, overrideApiKey, pluginConfig, req }),
47
- getAuthorizedMCP: ({ apiKeyDoc }) => buildAuthorized(apiKeyDoc),
24
+ if (pluginConfig.overrideGetAuthorizedMCP) {
25
+ return await pluginConfig.overrideGetAuthorizedMCP({
26
+ overrideAccess,
48
27
  pluginConfig,
49
28
  req,
50
29
  })
51
30
  }
52
31
 
53
- if (process.env.NODE_ENV === 'development' && !hasBearerToken) {
54
- logger.info('Dev mode: skipping API key check, using session user')
55
- return buildAuthorized({
56
- id: -1,
57
- access: {},
58
- overrideAccess: true,
59
- user: req.user ?? null,
60
- })
32
+ if (req.headers) {
33
+ const headers = new Headers(req.headers)
34
+ const hasAuthorization = headers.has('Authorization')
35
+
36
+ headers.set('DisableAutologin', 'true')
37
+ req.user = (await req.payload.auth({ headers, req })).user
38
+
39
+ // With OAuth, the endpoint answers with a challenge that starts the client's sign-in
40
+ if (hasAuthorization && !req.user && !pluginConfig.oauth) {
41
+ throw new UnauthorizedError(req.t)
42
+ }
61
43
  }
62
44
 
63
- return buildAuthorized(await getAPIKeyDoc({ logger, pluginConfig, req }))
45
+ return {
46
+ items: await filterMCPItems({
47
+ items: pluginConfig.items,
48
+ overrideAccess,
49
+ req,
50
+ }),
51
+ overrideAccess,
52
+ }
64
53
  }
65
54
 
66
- const getAPIKeyDoc = async ({
67
- logger,
68
- overrideApiKey,
69
- pluginConfig,
55
+ export const filterMCPItems = async ({
56
+ items,
57
+ overrideAccess,
70
58
  req,
71
59
  }: {
72
- logger: ReturnType<typeof getLogger>
73
- overrideApiKey?: string
74
- pluginConfig: ReturnType<typeof getPluginConfig>
60
+ items: MCPItem[]
61
+ overrideAccess: boolean
75
62
  req: PayloadRequest
76
- }): Promise<MCPAPIKeysDoc> => {
77
- const authHeader = req.headers.get('Authorization')
78
- const hasBearerToken = authHeader?.startsWith('Bearer ')
79
-
80
- const apiKey =
81
- overrideApiKey ?? (hasBearerToken ? authHeader?.replace('Bearer ', '').trim() || null : null)
82
-
83
- if (!apiKey) {
84
- throw new UnauthorizedError()
85
- }
86
-
87
- const sha256APIKeyIndex = crypto
88
- .createHmac('sha256', req.payload.secret)
89
- .update(apiKey)
90
- .digest('hex')
91
-
92
- const doc = await req.payload.db.findOne<MCPAPIKeysDoc>({
93
- collection: 'payload-mcp-api-keys',
94
- req,
95
- where: {
96
- apiKeyIndex: { equals: sha256APIKeyIndex },
97
- },
98
- })
99
-
100
- if (!doc || !doc.user) {
101
- throw new UnauthorizedError()
63
+ }): Promise<MCPItem[]> => {
64
+ // Match Payload core: overrideAccess bypasses access evaluation
65
+ if (overrideAccess) {
66
+ return items
102
67
  }
103
68
 
104
- logger.info('API Key is valid')
69
+ const authorizedItems: MCPItem[] = []
105
70
 
106
- const userRef = doc.user
107
- const userID =
108
- typeof userRef === 'object' && userRef !== null && 'id' in userRef
109
- ? userRef.id
110
- : (userRef as unknown as DefaultDocumentIDType)
71
+ const permissions = await getAccessResults({ req })
111
72
 
112
- const user = (await req.payload.findByID({
113
- id: userID,
114
- collection: pluginConfig.userCollection,
115
- depth: 0,
116
- disableErrors: true,
117
- req,
118
- })) as null | TypedUser
119
-
120
- if (!user) {
121
- throw new UnauthorizedError()
73
+ for (const item of items) {
74
+ if (!(await checkItemAccess({ item, permissions, req }))) {
75
+ continue
76
+ }
77
+ authorizedItems.push(item)
122
78
  }
123
79
 
124
- return {
125
- ...doc,
126
- user: {
127
- ...user,
128
- _strategy: 'mcp-api-key' as const,
129
- collection: pluginConfig.userCollection,
130
- },
80
+ return authorizedItems
81
+ }
82
+
83
+ /**
84
+ * Runs MCP item access callbacks
85
+ */
86
+ const checkItemAccess = async ({
87
+ item,
88
+ permissions,
89
+ req,
90
+ }: {
91
+ item: MCPItem
92
+ permissions?: SanitizedPermissions
93
+ req: PayloadRequest
94
+ }): Promise<boolean> => {
95
+ switch (item.type) {
96
+ case 'collectionTool':
97
+ return (
98
+ !item.tool.access ||
99
+ (await item.tool.access({ slug: item.collectionSlug, permissions, req }))
100
+ )
101
+ case 'globalTool':
102
+ return (
103
+ !item.tool.access || (await item.tool.access({ slug: item.globalSlug, permissions, req }))
104
+ )
105
+ case 'prompt':
106
+ return !item.prompt.access || (await item.prompt.access({ permissions, req }))
107
+ case 'resource':
108
+ return !item.resource.access || (await item.resource.access({ permissions, req }))
109
+ case 'tool':
110
+ return !item.tool.access || (await item.tool.access({ permissions, req }))
131
111
  }
132
112
  }
@@ -1,9 +1,17 @@
1
- import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'
2
- import { APIError, type PayloadHandler } from 'payload'
1
+ import type { PayloadHandler, PayloadRequest } from 'payload'
2
+
3
+ import {
4
+ createMcpHandler,
5
+ isLegacyRequest,
6
+ readRequestBody,
7
+ WebStandardStreamableHTTPServerTransport,
8
+ } from '@modelcontextprotocol/server'
9
+ import { APIError } from 'payload'
3
10
 
4
11
  import { buildMcpServer } from '../mcp/buildMcpServer.js'
5
12
  import { getPluginConfig } from '../utils/getPluginConfig.js'
6
13
  import { getAuthorizedMCP } from './access.js'
14
+ import { oauthChallenge } from './oauth.js'
7
15
 
8
16
  export const mcpEndpoint: PayloadHandler = async (req) => {
9
17
  if (!req.url) {
@@ -13,23 +21,93 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
13
21
  req.payloadAPI = 'MCP' as const
14
22
 
15
23
  const pluginConfig = getPluginConfig({ config: req.payload.config })
16
- const authorizedMCP = await getAuthorizedMCP({ req })
24
+ const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')
25
+
26
+ if (overrideAccessParam !== null && process.env.NODE_ENV !== 'development') {
27
+ throw new APIError('MCP overrideAccess is only available in development.', 400)
28
+ }
29
+
30
+ let overrideAccess = false
31
+ if (overrideAccessParam === 'true') {
32
+ overrideAccess = true
33
+ } else if (overrideAccessParam !== null && overrideAccessParam !== 'false') {
34
+ throw new APIError('MCP overrideAccess must be "true" or "false".', 400)
35
+ }
36
+
37
+ const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
38
+
39
+ if (pluginConfig.oauth && !req.user) {
40
+ return oauthChallenge({ req })
41
+ }
17
42
 
18
- const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
43
+ const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
44
+ // Payload augments the original web-standard Request in place.
45
+ const mcpRequest = req as PayloadRequest & Request
46
+ const parsedBody = await parseRequestBody({ maxRequestBodySize, request: mcpRequest })
19
47
 
20
- const transport = new WebStandardStreamableHTTPServerTransport({
21
- enableJsonResponse: true,
22
- sessionIdGenerator: undefined, // stateless mode
48
+ // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
49
+ if (await isLegacyRequest(mcpRequest, parsedBody, { maxRequestBodySize })) {
50
+ const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
51
+ const transport = new WebStandardStreamableHTTPServerTransport({
52
+ enableJsonResponse: true,
53
+ maxRequestBodySize,
54
+ sessionIdGenerator: undefined, // stateless mode
55
+ })
56
+ transport.onerror = (err) => {
57
+ req.payload.logger.error({ err, msg: 'Error serving legacy MCP request' })
58
+ }
59
+
60
+ try {
61
+ await server.connect(transport)
62
+ return await transport.handleRequest(mcpRequest, { parsedBody })
63
+ } finally {
64
+ await server.close().catch((err) => {
65
+ req.payload.logger.error({ err, msg: 'Error closing MCP server' })
66
+ })
67
+ }
68
+ }
69
+
70
+ const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
71
+ legacy: 'reject',
72
+ maxRequestBodySize,
73
+ // SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
74
+ maxSubscriptions: 0,
75
+ onerror: (err) => {
76
+ req.payload.logger.error({ err, msg: 'Error serving modern MCP request' })
77
+ },
78
+ responseMode: 'json',
23
79
  })
24
80
 
25
- await server.connect(transport)
81
+ try {
82
+ return await handler.fetch(mcpRequest, { parsedBody })
83
+ } finally {
84
+ await handler.close().catch((err) => {
85
+ req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })
86
+ })
87
+ }
88
+ }
26
89
 
27
- const mcpRequest = new Request(req.url, {
28
- body: req.body,
29
- duplex: 'half',
30
- headers: req.headers,
31
- method: req.method,
32
- } as { duplex: 'half' } & RequestInit)
90
+ /**
91
+ * Parses a POST body once so the era check and the SDK handler can share it. The SDK
92
+ * skips its size limit for a pre-parsed body, so this reads with the same limit. It reads
93
+ * a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,
94
+ * or not JSON), leaving the original request for the SDK to read and answer.
95
+ */
96
+ const parseRequestBody = async ({
97
+ maxRequestBodySize,
98
+ request,
99
+ }: {
100
+ maxRequestBodySize?: number
101
+ request: Request
102
+ }): Promise<unknown> => {
103
+ if (request.method.toUpperCase() !== 'POST') {
104
+ return undefined
105
+ }
33
106
 
34
- return await transport.handleRequest(mcpRequest)
107
+ try {
108
+ const body = await readRequestBody(request.clone(), maxRequestBodySize)
109
+ return body.tooLarge ? undefined : JSON.parse(body.text)
110
+ } catch {
111
+ return undefined
112
+ }
35
113
  }
@@ -0,0 +1,72 @@
1
+ import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'
2
+
3
+ import {
4
+ bearerAuthChallengeResponse,
5
+ OAuthError,
6
+ OAuthErrorCode,
7
+ } from '@modelcontextprotocol/server'
8
+
9
+ import { getPluginConfig } from '../utils/getPluginConfig.js'
10
+
11
+ /**
12
+ * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
13
+ * The OAuth challenge links here, so MCP clients find the authorization server without setup.
14
+ */
15
+ export const oauthProtectedResourceEndpoint: PayloadHandler = (req) =>
16
+ getMetadataResponse({ config: req.payload.config, url: req.url! })
17
+
18
+ /**
19
+ * Serves the same metadata for clients that ignore the challenge's link and only look at
20
+ * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
21
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
22
+ *
23
+ * ```ts
24
+ * import config from '@payload-config'
25
+ * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
26
+ *
27
+ * export const GET = oauthProtectedResourceHandler(config)
28
+ * ```
29
+ */
30
+ export const oauthProtectedResourceHandler =
31
+ (config: Promise<SanitizedConfig> | SanitizedConfig) =>
32
+ async (request: Request): Promise<Response> =>
33
+ getMetadataResponse({ config: await config, url: request.url })
34
+
35
+ /**
36
+ * Answers an unauthenticated MCP request with a challenge linking to the protected resource
37
+ * metadata, which starts the client's OAuth flow.
38
+ */
39
+ export const oauthChallenge = ({ req }: { req: PayloadRequest }): Response =>
40
+ bearerAuthChallengeResponse(
41
+ new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),
42
+ {
43
+ resourceMetadataUrl: `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth-protected-resource`,
44
+ },
45
+ )
46
+
47
+ const getMCPURL = ({ config, url }: { config: SanitizedConfig; url: string }): string =>
48
+ new URL(`${config.routes.api}/mcp`, config.serverURL || url).href
49
+
50
+ const getMetadataResponse = ({
51
+ config,
52
+ url,
53
+ }: {
54
+ config: SanitizedConfig
55
+ url: string
56
+ }): Response => {
57
+ const pluginConfig = getPluginConfig({ config })
58
+
59
+ if (!pluginConfig.oauth) {
60
+ return new Response(null, { status: 404 })
61
+ }
62
+
63
+ return Response.json(
64
+ {
65
+ authorization_servers: pluginConfig.oauth.authorizationServers,
66
+ bearer_methods_supported: ['header'],
67
+ resource: pluginConfig.oauth.resource ?? getMCPURL({ config, url }),
68
+ },
69
+ // Public document, readable by browser-based MCP clients on any origin
70
+ { headers: { 'Access-Control-Allow-Origin': '*' } },
71
+ )
72
+ }
@@ -1,2 +1,3 @@
1
1
  'use client'
2
- export { AccessField } from '../components/AccessField/index.client.js'
2
+
3
+ export {}
@@ -0,0 +1 @@
1
+ export { filterMCPItems, getAuthorizedMCP } from '../endpoint/access.js'
package/src/index.ts CHANGED
@@ -1,14 +1,14 @@
1
- import { defaultUserCollection, definePlugin } from 'payload'
1
+ import { definePlugin } from 'payload'
2
2
 
3
3
  import type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'
4
4
 
5
- import { getAPIKeysCollection } from './collection/index.js'
6
5
  import { mcpEndpoint } from './endpoint/index.js'
6
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'
7
7
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
8
8
 
9
9
  declare module 'payload' {
10
- export interface PayloadRequest {
11
- payloadAPI: 'GraphQL' | 'local' | 'MCP' | 'REST'
10
+ export interface PayloadRequestAPI {
11
+ MCP: true
12
12
  }
13
13
  interface RegisteredPlugins {
14
14
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
@@ -19,22 +19,13 @@ declare module 'payload' {
19
19
  export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }
20
20
 
21
21
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'
22
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js'
22
23
 
23
24
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
24
25
  slug: '@payloadcms/plugin-mcp',
25
26
  order: 10,
26
- plugin: ({ config, plugins, ...rawConfig }) => {
27
- // Our `payload-mcp-api-keys` is auth-enabled; if it'd be the only auth
28
- // collection, Payload's later sanitize would pick it as `admin.user`.
29
- // Pre-seed the default user collection to prevent that.
30
- if (!config.admin?.user) {
31
- const firstCollectionWithAuth = (config.collections ?? []).find(({ auth }) => Boolean(auth))
32
- if (!firstCollectionWithAuth) {
33
- ;(config.collections ??= []).push(defaultUserCollection)
34
- }
35
- }
36
-
37
- const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: rawConfig })
27
+ plugin: ({ config, options, plugins }) => {
28
+ const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })
38
29
 
39
30
  // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.
40
31
  const registered = plugins['@payloadcms/plugin-mcp']
@@ -43,10 +34,6 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
43
34
  registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options
44
35
  }
45
36
 
46
- ;(config.collections ??= []).push(getAPIKeysCollection({ pluginConfig }))
47
-
48
- // Keep the API-keys collection registered even when disabled, so DB schema
49
- // and generated types don't drift between enabled/disabled environments.
50
37
  if (pluginConfig.disabled) {
51
38
  return config
52
39
  }
@@ -57,6 +44,18 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
57
44
  ...(config.endpoints ?? []),
58
45
  // Payload prefixes /api, so the full path is /api/mcp.
59
46
  { handler: mcpEndpoint, method: 'post', path: '/mcp' },
47
+ // Streamable HTTP's optional server=>client GET stream. We don't offer
48
+ // one, so answer 405 per spec-— clients then skip it cleanly
49
+ {
50
+ handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),
51
+ method: 'get',
52
+ path: '/mcp',
53
+ },
54
+ {
55
+ handler: oauthProtectedResourceEndpoint,
56
+ method: 'get',
57
+ path: '/mcp/oauth-protected-resource',
58
+ },
60
59
  ],
61
60
  }
62
61
  },