@payloadcms/plugin-mcp 4.0.0-internal.a0ef1b8 → 4.0.0-internal.add4c47

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 (250) hide show
  1. package/LICENSE.md +1 -1
  2. package/bin.js +7 -0
  3. package/dist/defaultAccess.d.ts +3 -0
  4. package/dist/defaultAccess.d.ts.map +1 -0
  5. package/dist/defaultAccess.js +3 -0
  6. package/dist/defaultAccess.js.map +1 -0
  7. package/dist/defineTool.d.ts +8 -8
  8. package/dist/defineTool.d.ts.map +1 -1
  9. package/dist/endpoint/access.d.ts +12 -5
  10. package/dist/endpoint/access.d.ts.map +1 -1
  11. package/dist/endpoint/access.js +75 -88
  12. package/dist/endpoint/access.js.map +1 -1
  13. package/dist/endpoint/index.d.ts +1 -1
  14. package/dist/endpoint/index.d.ts.map +1 -1
  15. package/dist/endpoint/index.js +68 -17
  16. package/dist/endpoint/index.js.map +1 -1
  17. package/dist/exports/client.d.ts +1 -1
  18. package/dist/exports/client.d.ts.map +1 -1
  19. package/dist/exports/client.js +1 -1
  20. package/dist/exports/client.js.map +1 -1
  21. package/dist/exports/internal.d.ts +2 -0
  22. package/dist/exports/internal.d.ts.map +1 -0
  23. package/dist/exports/internal.js +3 -0
  24. package/dist/exports/internal.js.map +1 -0
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +15 -20
  28. package/dist/index.js.map +1 -1
  29. package/dist/mcp/buildMcpServer.d.ts +4 -4
  30. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  31. package/dist/mcp/buildMcpServer.js +133 -80
  32. package/dist/mcp/buildMcpServer.js.map +1 -1
  33. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  34. package/dist/mcp/builtin/collections/authTools.js +44 -6
  35. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  36. package/dist/mcp/builtin/collections/countTool.d.ts +2 -0
  37. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -0
  38. package/dist/mcp/builtin/collections/countTool.js +68 -0
  39. package/dist/mcp/builtin/collections/countTool.js.map +1 -0
  40. package/dist/mcp/builtin/collections/countVersionsTool.d.ts +2 -0
  41. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -0
  42. package/dist/mcp/builtin/collections/countVersionsTool.js +64 -0
  43. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -0
  44. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  45. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  46. package/dist/mcp/builtin/collections/createTool.js +50 -45
  47. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  48. package/dist/mcp/builtin/collections/deleteTool.d.ts +1 -1
  49. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  50. package/dist/mcp/builtin/collections/deleteTool.js +15 -22
  51. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  52. package/dist/mcp/builtin/collections/duplicateTool.d.ts +2 -0
  53. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -0
  54. package/dist/mcp/builtin/collections/duplicateTool.js +96 -0
  55. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -0
  56. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  57. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  58. package/dist/mcp/builtin/collections/fileInput.js +117 -0
  59. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  60. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  61. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  62. package/dist/mcp/builtin/collections/findDistinctTool.d.ts +2 -0
  63. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -0
  64. package/dist/mcp/builtin/collections/findDistinctTool.js +92 -0
  65. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -0
  66. package/dist/mcp/builtin/collections/findTool.d.ts +1 -1
  67. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  68. package/dist/mcp/builtin/collections/findTool.js +52 -47
  69. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  70. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts +2 -0
  71. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -0
  72. package/dist/mcp/builtin/collections/findVersionByIDTool.js +83 -0
  73. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -0
  74. package/dist/mcp/builtin/collections/findVersionsTool.d.ts +2 -0
  75. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -0
  76. package/dist/mcp/builtin/collections/findVersionsTool.js +98 -0
  77. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -0
  78. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +9 -0
  79. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -0
  80. package/dist/mcp/builtin/collections/formatCollectionError.js +60 -0
  81. package/dist/mcp/builtin/collections/formatCollectionError.js.map +1 -0
  82. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts +2 -0
  83. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -0
  84. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +87 -0
  85. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -0
  86. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts +2 -0
  87. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -0
  88. package/dist/mcp/builtin/collections/restoreVersionTool.js +81 -0
  89. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -0
  90. package/dist/mcp/builtin/collections/updateTool.d.ts +1 -1
  91. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  92. package/dist/mcp/builtin/collections/updateTool.js +106 -93
  93. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  94. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  95. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  96. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  97. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  98. package/dist/mcp/builtin/getConfigInfoTool.d.ts +2 -0
  99. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -0
  100. package/dist/mcp/builtin/getConfigInfoTool.js +68 -0
  101. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -0
  102. package/dist/mcp/builtin/globals/countVersionsTool.d.ts +2 -0
  103. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -0
  104. package/dist/mcp/builtin/globals/countVersionsTool.js +64 -0
  105. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -0
  106. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  107. package/dist/mcp/builtin/globals/findTool.js +20 -23
  108. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  109. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts +2 -0
  110. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -0
  111. package/dist/mcp/builtin/globals/findVersionByIDTool.js +79 -0
  112. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -0
  113. package/dist/mcp/builtin/globals/findVersionsTool.d.ts +2 -0
  114. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -0
  115. package/dist/mcp/builtin/globals/findVersionsTool.js +94 -0
  116. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -0
  117. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts +2 -0
  118. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -0
  119. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +65 -0
  120. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -0
  121. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts +2 -0
  122. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -0
  123. package/dist/mcp/builtin/globals/restoreVersionTool.js +77 -0
  124. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -0
  125. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  126. package/dist/mcp/builtin/globals/updateTool.js +33 -42
  127. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  128. package/dist/mcp/builtin/validateEntityData.d.ts +14 -0
  129. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -0
  130. package/dist/mcp/builtin/validateEntityData.js +82 -0
  131. package/dist/mcp/builtin/validateEntityData.js.map +1 -0
  132. package/dist/mcp/builtinTools.d.ts +150 -19
  133. package/dist/mcp/builtinTools.d.ts.map +1 -1
  134. package/dist/mcp/builtinTools.js +125 -20
  135. package/dist/mcp/builtinTools.js.map +1 -1
  136. package/dist/mcp/sanitizeMCPConfig.d.ts +0 -1
  137. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  138. package/dist/mcp/sanitizeMCPConfig.js +124 -58
  139. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  140. package/dist/stdio.d.ts +3 -3
  141. package/dist/stdio.d.ts.map +1 -1
  142. package/dist/stdio.js +84 -46
  143. package/dist/stdio.js.map +1 -1
  144. package/dist/types.d.ts +112 -110
  145. package/dist/types.d.ts.map +1 -1
  146. package/dist/types.js +2 -4
  147. package/dist/types.js.map +1 -1
  148. package/dist/utils/camelCase.d.ts.map +1 -1
  149. package/dist/utils/getPluginConfig.d.ts +1 -1
  150. package/dist/utils/getPluginConfig.js +1 -1
  151. package/dist/utils/getPluginConfig.js.map +1 -1
  152. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  153. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  154. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  155. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  156. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  157. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +13 -0
  158. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -0
  159. package/dist/utils/schemaConversion/getEntityInputSchema.js +66 -0
  160. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -0
  161. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +5 -10
  162. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  163. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +15 -95
  164. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -1
  165. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +15 -40
  166. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  167. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  168. package/dist/utils/whereSchema.d.ts +9 -0
  169. package/dist/utils/whereSchema.d.ts.map +1 -0
  170. package/dist/utils/whereSchema.js +13 -0
  171. package/dist/utils/whereSchema.js.map +1 -0
  172. package/package.json +10 -15
  173. package/src/defaultAccess.ts +3 -0
  174. package/src/endpoint/access.ts +81 -101
  175. package/src/endpoint/index.ts +58 -16
  176. package/src/exports/client.ts +2 -1
  177. package/src/exports/internal.ts +1 -0
  178. package/src/index.ts +12 -20
  179. package/src/mcp/buildMcpServer.ts +170 -115
  180. package/src/mcp/builtin/collections/authTools.ts +45 -9
  181. package/src/mcp/builtin/collections/countTool.ts +73 -0
  182. package/src/mcp/builtin/collections/countVersionsTool.ts +69 -0
  183. package/src/mcp/builtin/collections/createTool.ts +67 -62
  184. package/src/mcp/builtin/collections/deleteTool.ts +20 -18
  185. package/src/mcp/builtin/collections/duplicateTool.ts +134 -0
  186. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  187. package/src/mcp/builtin/collections/fileInput.ts +154 -0
  188. package/src/mcp/builtin/collections/findDistinctTool.ts +119 -0
  189. package/src/mcp/builtin/collections/findTool.ts +66 -37
  190. package/src/mcp/builtin/collections/findVersionByIDTool.ts +109 -0
  191. package/src/mcp/builtin/collections/findVersionsTool.ts +154 -0
  192. package/src/mcp/builtin/collections/formatCollectionError.ts +84 -0
  193. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +80 -0
  194. package/src/mcp/builtin/collections/restoreVersionTool.ts +107 -0
  195. package/src/mcp/builtin/collections/updateTool.ts +132 -115
  196. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  197. package/src/mcp/builtin/getConfigInfoTool.ts +67 -0
  198. package/src/mcp/builtin/globals/countVersionsTool.ts +68 -0
  199. package/src/mcp/builtin/globals/findTool.ts +28 -19
  200. package/src/mcp/builtin/globals/findVersionByIDTool.ts +103 -0
  201. package/src/mcp/builtin/globals/findVersionsTool.ts +147 -0
  202. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +63 -0
  203. package/src/mcp/builtin/globals/restoreVersionTool.ts +99 -0
  204. package/src/mcp/builtin/globals/updateTool.ts +52 -57
  205. package/src/mcp/builtin/validateEntityData.ts +132 -0
  206. package/src/mcp/builtinTools.ts +118 -41
  207. package/src/mcp/sanitizeMCPConfig.ts +120 -78
  208. package/src/stdio.ts +79 -46
  209. package/src/types.ts +128 -115
  210. package/src/utils/getPluginConfig.ts +1 -1
  211. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  212. package/src/utils/schemaConversion/getEntityInputSchema.ts +96 -0
  213. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +12 -19
  214. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +17 -114
  215. package/src/utils/whereSchema.ts +24 -0
  216. package/dist/@types/assets.d.js +0 -2
  217. package/dist/@types/assets.d.js.map +0 -1
  218. package/dist/collection/getAccessField.d.ts +0 -12
  219. package/dist/collection/getAccessField.d.ts.map +0 -1
  220. package/dist/collection/getAccessField.js +0 -57
  221. package/dist/collection/getAccessField.js.map +0 -1
  222. package/dist/collection/index.d.ts +0 -6
  223. package/dist/collection/index.d.ts.map +0 -1
  224. package/dist/collection/index.js +0 -60
  225. package/dist/collection/index.js.map +0 -1
  226. package/dist/components/AccessField/index.client.d.ts +0 -10
  227. package/dist/components/AccessField/index.client.d.ts.map +0 -1
  228. package/dist/components/AccessField/index.client.js +0 -305
  229. package/dist/components/AccessField/index.client.js.map +0 -1
  230. package/dist/components/AccessField/index.css +0 -93
  231. package/dist/utils/localAPIDefaults.d.ts +0 -20
  232. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  233. package/dist/utils/localAPIDefaults.js +0 -19
  234. package/dist/utils/localAPIDefaults.js.map +0 -1
  235. package/dist/utils/schemaConversion/buildToolInput.d.ts +0 -29
  236. package/dist/utils/schemaConversion/buildToolInput.d.ts.map +0 -1
  237. package/dist/utils/schemaConversion/buildToolInput.js +0 -51
  238. package/dist/utils/schemaConversion/buildToolInput.js.map +0 -1
  239. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  240. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  241. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  242. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  243. package/src/@types/assets.d.ts +0 -3
  244. package/src/collection/getAccessField.ts +0 -64
  245. package/src/collection/index.ts +0 -64
  246. package/src/components/AccessField/index.client.tsx +0 -344
  247. package/src/components/AccessField/index.css +0 -93
  248. package/src/utils/localAPIDefaults.ts +0 -22
  249. package/src/utils/schemaConversion/buildToolInput.ts +0 -68
  250. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
@@ -1,5 +1,11 @@
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
+ WebStandardStreamableHTTPServerTransport,
7
+ } from '@modelcontextprotocol/server'
8
+ import { APIError } from 'payload'
3
9
 
4
10
  import { buildMcpServer } from '../mcp/buildMcpServer.js'
5
11
  import { getPluginConfig } from '../utils/getPluginConfig.js'
@@ -13,23 +19,59 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
13
19
  req.payloadAPI = 'MCP' as const
14
20
 
15
21
  const pluginConfig = getPluginConfig({ config: req.payload.config })
16
- const authorizedMCP = await getAuthorizedMCP({ req })
22
+ const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')
17
23
 
18
- const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
24
+ if (overrideAccessParam !== null && process.env.NODE_ENV !== 'development') {
25
+ throw new APIError('MCP overrideAccess is only available in development.', 400)
26
+ }
19
27
 
20
- const transport = new WebStandardStreamableHTTPServerTransport({
21
- enableJsonResponse: true,
22
- sessionIdGenerator: undefined, // stateless mode
23
- })
28
+ let overrideAccess = false
29
+ if (overrideAccessParam === 'true') {
30
+ overrideAccess = true
31
+ } else if (overrideAccessParam !== null && overrideAccessParam !== 'false') {
32
+ throw new APIError('MCP overrideAccess must be "true" or "false".', 400)
33
+ }
24
34
 
25
- await server.connect(transport)
35
+ const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
36
+ // Payload augments the original web-standard Request in place.
37
+ const mcpRequest = req as PayloadRequest & Request
26
38
 
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)
39
+ // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
40
+ if (await isLegacyRequest(mcpRequest)) {
41
+ const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
42
+ const transport = new WebStandardStreamableHTTPServerTransport({
43
+ enableJsonResponse: true,
44
+ sessionIdGenerator: undefined, // stateless mode
45
+ })
46
+ transport.onerror = (err) => {
47
+ req.payload.logger.error({ err, msg: 'Error serving legacy MCP request' })
48
+ }
33
49
 
34
- return await transport.handleRequest(mcpRequest)
50
+ try {
51
+ await server.connect(transport)
52
+ return await transport.handleRequest(mcpRequest)
53
+ } finally {
54
+ await server.close().catch((err) => {
55
+ req.payload.logger.error({ err, msg: 'Error closing MCP server' })
56
+ })
57
+ }
58
+ }
59
+
60
+ const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
61
+ legacy: 'reject',
62
+ // SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
63
+ maxSubscriptions: 0,
64
+ onerror: (err) => {
65
+ req.payload.logger.error({ err, msg: 'Error serving modern MCP request' })
66
+ },
67
+ responseMode: 'json',
68
+ })
69
+
70
+ try {
71
+ return await handler.fetch(mcpRequest)
72
+ } finally {
73
+ await handler.close().catch((err) => {
74
+ req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })
75
+ })
76
+ }
35
77
  }
@@ -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,13 @@
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'
7
6
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
8
7
 
9
8
  declare module 'payload' {
10
- export interface PayloadRequest {
11
- payloadAPI: 'GraphQL' | 'local' | 'MCP' | 'REST'
9
+ export interface PayloadRequestAPI {
10
+ MCP: true
12
11
  }
13
12
  interface RegisteredPlugins {
14
13
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
@@ -23,18 +22,8 @@ export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from
23
22
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
24
23
  slug: '@payloadcms/plugin-mcp',
25
24
  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 })
25
+ plugin: ({ config, options, plugins }) => {
26
+ const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })
38
27
 
39
28
  // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.
40
29
  const registered = plugins['@payloadcms/plugin-mcp']
@@ -43,10 +32,6 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
43
32
  registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options
44
33
  }
45
34
 
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
35
  if (pluginConfig.disabled) {
51
36
  return config
52
37
  }
@@ -57,6 +42,13 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
57
42
  ...(config.endpoints ?? []),
58
43
  // Payload prefixes /api, so the full path is /api/mcp.
59
44
  { handler: mcpEndpoint, method: 'post', path: '/mcp' },
45
+ // Streamable HTTP's optional server=>client GET stream. We don't offer
46
+ // one, so answer 405 per spec-— clients then skip it cleanly
47
+ {
48
+ handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),
49
+ method: 'get',
50
+ path: '/mcp',
51
+ },
60
52
  ],
61
53
  }
62
54
  },
@@ -1,34 +1,26 @@
1
1
  import { McpServer, type ServerContext } from '@modelcontextprotocol/server'
2
- import { APIError, entityToStandaloneJSONSchema, type PayloadRequest } from 'payload'
2
+ import { APIError, type PayloadRequest } from 'payload'
3
+ import { z } from 'zod'
3
4
 
4
5
  import type {
5
6
  AuthorizedMCP,
7
+ CollectionMCPItem,
8
+ GlobalMCPItem,
6
9
  JsonSchemaType,
7
10
  MCPResponseOverride,
8
11
  MCPToolResponse,
9
12
  SanitizedMCPPluginConfig,
13
+ ToolInputSchema,
10
14
  } from '../types.js'
11
15
 
12
- import { toCamelCase } from '../utils/camelCase.js'
13
16
  import { getLogger } from '../utils/getLogger.js'
14
- import {
15
- getCollectionVirtualFieldNames,
16
- getGlobalVirtualFieldNames,
17
- } from '../utils/getVirtualFieldNames.js'
18
- import { removeVirtualFieldsFromSchema } from '../utils/schemaConversion/removeVirtualFieldsFromSchema.js'
19
17
  import { toStandardSchema } from '../utils/toStandardSchema.js'
20
18
 
21
- /** `findPosts`, `updateSiteSettings` — auto-prefixed wire name for collection/global tools. */
22
- const wireName = (key: string, slug: string): string => {
23
- const camel = toCamelCase(slug)
24
- return `${key}${camel.charAt(0).toUpperCase()}${camel.slice(1)}`
25
- }
26
-
27
19
  /**
28
- * Transport-agnostic core: registers every authorized MCP item onto a fresh
29
- * `McpServer` and returns it. The caller is responsible for picking a transport
30
- * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and
31
- * calling `server.connect(transport)`.
20
+ * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh
21
+ * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh
22
+ * instances from this builder while they own the transport and protocol-era
23
+ * decision.
32
24
  *
33
25
  * `req` is the request context handlers see. For HTTP it's the live
34
26
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
@@ -55,110 +47,130 @@ export const buildMcpServer = ({
55
47
  * Wrap a tool handler's response with the tool's `overrideResponse`, then
56
48
  * strip the internal `doc` field so it doesn't leak onto the wire.
57
49
  */
58
- const finalizeToolResponse = (
59
- response: MCPToolResponse,
60
- overrideResponse?: MCPResponseOverride,
61
- ): MCPToolResponse => {
62
- const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response
50
+ const finalizeToolResponse = async ({
51
+ input,
52
+ overrideResponse,
53
+ response,
54
+ toolName,
55
+ }: {
56
+ input: unknown
57
+ overrideResponse?: MCPResponseOverride
58
+ response: MCPToolResponse
59
+ toolName: string
60
+ }): Promise<MCPToolResponse> => {
61
+ let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response
62
+ for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {
63
+ overridden = await hook({ input, req, response: overridden, toolName })
64
+ }
63
65
  const { doc: _doc, ...rest } = overridden
64
66
  return rest
65
67
  }
66
68
 
69
+ /**
70
+ * Runs a collection/global tool call:
71
+ * - reads `collectionSlug` / `globalSlug` from the input
72
+ * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug
73
+ * - runs the tool handler and finalizes its response
74
+ */
75
+ const callEntityTool = async ({
76
+ input,
77
+ item,
78
+ serverContext,
79
+ }: {
80
+ input: unknown
81
+ item: CollectionMCPItem | GlobalMCPItem
82
+ serverContext: ServerContext
83
+ }): Promise<MCPToolResponse> => {
84
+ const entity = item.type === 'collectionTool' ? 'collection' : 'global'
85
+ const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'
86
+ const toolInput = (input ?? {}) as Record<string, unknown>
87
+ const slug = toolInput[slugKey] as string | undefined
88
+
89
+ if (!slug) {
90
+ return {
91
+ content: [
92
+ {
93
+ type: 'text',
94
+ text: `Error: "${item.mcpName}" requires ${slugKey}. Use getConfigInfo to inspect ${entity} slugs.`,
95
+ },
96
+ ],
97
+ isError: true,
98
+ }
99
+ }
100
+
101
+ const match = authorizedMCP.items.find(
102
+ (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>
103
+ candidate.type === item.type &&
104
+ candidate.mcpName === item.mcpName &&
105
+ (candidate.type === 'collectionTool'
106
+ ? candidate.collectionSlug === slug
107
+ : candidate.type === 'globalTool' && candidate.globalSlug === slug),
108
+ )
109
+
110
+ if (!match) {
111
+ return {
112
+ content: [
113
+ {
114
+ type: 'text',
115
+ text: `Error: MCP access to "${item.mcpName}" is not enabled for ${entity} "${slug}"`,
116
+ },
117
+ ],
118
+ isError: true,
119
+ }
120
+ }
121
+
122
+ const handlerArgs = {
123
+ authorizedMCP,
124
+ input: toolInput,
125
+ req,
126
+ serverContext,
127
+ }
128
+ const response = await (match.type === 'collectionTool'
129
+ ? match.tool.handler({ ...handlerArgs, collectionSlug: slug })
130
+ : match.tool.handler({ ...handlerArgs, globalSlug: slug }))
131
+
132
+ return finalizeToolResponse({
133
+ input: toolInput,
134
+ overrideResponse: match.tool.overrideResponse,
135
+ response,
136
+ toolName: match.mcpName,
137
+ })
138
+ }
139
+
67
140
  try {
141
+ const registeredEntityTools = new Set<string>()
142
+
68
143
  for (const item of authorizedMCP.items) {
69
144
  switch (item.type) {
70
- case 'collectionTool': {
71
- const tool = item.tool
72
- const name = wireName(item.key, item.collectionSlug)
73
- let inputSchema = tool.input
74
- if (typeof inputSchema === 'function') {
75
- const collection = req.payload.collections[item.collectionSlug]?.config
76
- if (!collection) {
77
- throw new APIError(
78
- `Collection schema not found for slug: ${item.collectionSlug}`,
79
- 500,
80
- )
81
- }
82
- const collectionSchema = removeVirtualFieldsFromSchema(
83
- entityToStandaloneJSONSchema({
84
- config: req.payload.config,
85
- defaultIDType: req.payload.db.defaultIDType,
86
- entity: collection,
87
- i18n: req.i18n,
88
- }) as unknown as JsonSchemaType,
89
- getCollectionVirtualFieldNames(req.payload.config, item.collectionSlug),
90
- )
91
- inputSchema = inputSchema({ collectionSchema })
92
- }
93
- server.registerTool(
94
- name,
95
- {
96
- description: tool.description,
97
- inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined,
98
- },
99
- async (input: unknown, ctx: ServerContext) =>
100
- finalizeToolResponse(
101
- await tool.handler({
102
- authorizedMCP,
103
- collectionSlug: item.collectionSlug,
104
- input: (input ?? {}) as Record<string, unknown>,
105
- req,
106
- serverContext: ctx,
107
- }),
108
- tool.overrideResponse,
109
- ),
110
- )
111
- logger.info(`✅ Tool: ${name} Registered.`)
112
- break
113
- }
145
+ case 'collectionTool':
114
146
  case 'globalTool': {
115
- const tool = item.tool
116
- const name = wireName(item.key, item.globalSlug)
117
- let inputSchema = tool.input
118
- if (typeof inputSchema === 'function') {
119
- const globalEntity = req.payload.config.globals.find(
120
- (globalConfig) => globalConfig.slug === item.globalSlug,
121
- )
122
- if (!globalEntity) {
123
- throw new APIError(`Global schema not found for slug: ${item.globalSlug}`, 500)
124
- }
125
- const globalSchema = removeVirtualFieldsFromSchema(
126
- entityToStandaloneJSONSchema({
127
- config: req.payload.config,
128
- defaultIDType: req.payload.db.defaultIDType,
129
- entity: globalEntity,
130
- i18n: req.i18n,
131
- }) as unknown as JsonSchemaType,
132
- getGlobalVirtualFieldNames(req.payload.config, item.globalSlug),
133
- )
134
-
135
- inputSchema = inputSchema({ globalSchema })
147
+ if (registeredEntityTools.has(item.mcpName)) {
148
+ break
136
149
  }
150
+ registeredEntityTools.add(item.mcpName)
151
+
152
+ const inputSchema = withSlugInput({
153
+ name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',
154
+ input: item.tool.input,
155
+ })
156
+
137
157
  server.registerTool(
138
- name,
158
+ item.mcpName,
139
159
  {
140
- description: tool.description,
141
- inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined,
160
+ annotations: item.tool.annotations,
161
+ description: item.tool.description,
162
+ inputSchema: toStandardSchema(inputSchema),
142
163
  },
143
164
  async (input: unknown, ctx: ServerContext) =>
144
- finalizeToolResponse(
145
- await tool.handler({
146
- authorizedMCP,
147
- globalSlug: item.globalSlug,
148
- input: (input ?? {}) as Record<string, unknown>,
149
- req,
150
- serverContext: ctx,
151
- }),
152
- tool.overrideResponse,
153
- ),
165
+ callEntityTool({ input, item, serverContext: ctx }),
154
166
  )
155
- logger.info(`✅ Tool: ${name} Registered.`)
167
+ logger.info(`✅ Tool: ${item.mcpName} Registered.`)
156
168
  break
157
169
  }
158
170
  case 'prompt': {
159
171
  const prompt = item.prompt
160
172
  server.registerPrompt(
161
- item.key,
173
+ item.mcpName,
162
174
  {
163
175
  argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,
164
176
  description: prompt.description,
@@ -177,7 +189,7 @@ export const buildMcpServer = ({
177
189
  case 'resource': {
178
190
  const resource = item.resource
179
191
  server.registerResource(
180
- item.key,
192
+ item.mcpName,
181
193
  // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)
182
194
  resource.uri,
183
195
  {
@@ -200,23 +212,29 @@ export const buildMcpServer = ({
200
212
  case 'tool': {
201
213
  const tool = item.tool
202
214
  server.registerTool(
203
- item.key,
215
+ item.mcpName,
204
216
  {
217
+ annotations: tool.annotations,
205
218
  description: tool.description,
206
219
  inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,
207
220
  },
208
- async (input: unknown, ctx: ServerContext) =>
209
- finalizeToolResponse(
210
- await tool.handler({
211
- authorizedMCP,
212
- input: (input ?? {}) as Record<string, unknown>,
213
- req,
214
- serverContext: ctx,
215
- }),
216
- tool.overrideResponse,
217
- ),
221
+ async (input: unknown, ctx: ServerContext) => {
222
+ const toolInput = (input ?? {}) as Record<string, unknown>
223
+ const response = await tool.handler({
224
+ authorizedMCP,
225
+ input: toolInput,
226
+ req,
227
+ serverContext: ctx,
228
+ })
229
+ return finalizeToolResponse({
230
+ input: toolInput,
231
+ overrideResponse: tool.overrideResponse,
232
+ response,
233
+ toolName: item.mcpName,
234
+ })
235
+ },
218
236
  )
219
- logger.info(`✅ Tool: ${item.key} Registered.`)
237
+ logger.info(`✅ Tool: ${item.mcpName} Registered.`)
220
238
  break
221
239
  }
222
240
  }
@@ -227,3 +245,40 @@ export const buildMcpServer = ({
227
245
 
228
246
  return server
229
247
  }
248
+
249
+ const withSlugInput = ({
250
+ name,
251
+ input,
252
+ }: {
253
+ input?: ToolInputSchema
254
+ name: 'collectionSlug' | 'globalSlug'
255
+ }): ToolInputSchema => {
256
+ const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'
257
+ const slugSchema = z.string().describe(description)
258
+
259
+ if (!input) {
260
+ return z.object({ [name]: slugSchema })
261
+ }
262
+
263
+ if (input instanceof z.ZodObject) {
264
+ return input.extend({ [name]: slugSchema })
265
+ }
266
+
267
+ const schema = input as {
268
+ properties?: Record<string, JsonSchemaType>
269
+ required?: string[]
270
+ } & JsonSchemaType
271
+
272
+ return {
273
+ ...schema,
274
+ type: 'object',
275
+ properties: {
276
+ ...schema.properties,
277
+ [name]: {
278
+ type: 'string',
279
+ description,
280
+ },
281
+ },
282
+ required: Array.from(new Set([name, ...(schema.required ?? [])])),
283
+ }
284
+ }
@@ -32,13 +32,18 @@ const wrapError =
32
32
  }
33
33
 
34
34
  export const authCollectionTool = defineCollectionTool({
35
+ annotations: {
36
+ destructiveHint: false,
37
+ idempotentHint: true,
38
+ openWorldHint: false,
39
+ readOnlyHint: true,
40
+ title: 'Check Auth Status',
41
+ },
35
42
  description: 'Checks authentication status for the current user.',
36
43
  input: z.object({
37
44
  headers: z
38
- .string()
39
- .describe(
40
- 'Optional JSON string containing custom headers to send with the authentication request',
41
- )
45
+ .record(z.string(), z.string())
46
+ .describe('Optional custom headers to send with the authentication request')
42
47
  .optional(),
43
48
  }),
44
49
  }).handler(async ({ collectionSlug, input, req }) => {
@@ -46,11 +51,7 @@ export const authCollectionTool = defineCollectionTool({
46
51
  try {
47
52
  let authHeaders = new Headers()
48
53
  if (input.headers) {
49
- try {
50
- authHeaders = new Headers(JSON.parse(input.headers) as Record<string, string>)
51
- } catch {
52
- logger.warn(`Invalid headers JSON for auth: ${input.headers}, using empty headers`)
53
- }
54
+ authHeaders = new Headers(input.headers)
54
55
  }
55
56
  const result = await req.payload.auth({ headers: authHeaders })
56
57
  return {
@@ -70,6 +71,13 @@ export const authCollectionTool = defineCollectionTool({
70
71
  })
71
72
 
72
73
  export const forgotPasswordCollectionTool = defineCollectionTool({
74
+ annotations: {
75
+ destructiveHint: false,
76
+ idempotentHint: false,
77
+ openWorldHint: true,
78
+ readOnlyHint: false,
79
+ title: 'Forgot Password',
80
+ },
73
81
  description: 'Sends a password reset email to a user.',
74
82
  input: z.object({
75
83
  disableEmail: z
@@ -104,6 +112,13 @@ export const forgotPasswordCollectionTool = defineCollectionTool({
104
112
  })
105
113
 
106
114
  export const loginCollectionTool = defineCollectionTool({
115
+ annotations: {
116
+ destructiveHint: false,
117
+ idempotentHint: false,
118
+ openWorldHint: false,
119
+ readOnlyHint: false,
120
+ title: 'User Login',
121
+ },
107
122
  description: 'Authenticates a user with email and password.',
108
123
  input: z.object({
109
124
  depth: z
@@ -148,6 +163,13 @@ export const loginCollectionTool = defineCollectionTool({
148
163
  })
149
164
 
150
165
  export const resetPasswordCollectionTool = defineCollectionTool({
166
+ annotations: {
167
+ destructiveHint: false,
168
+ idempotentHint: false,
169
+ openWorldHint: false,
170
+ readOnlyHint: false,
171
+ title: 'Reset Password',
172
+ },
151
173
  description: 'Resets a user password with a reset token.',
152
174
  input: z.object({
153
175
  password: z.string().describe('The new password for the user'),
@@ -178,6 +200,13 @@ export const resetPasswordCollectionTool = defineCollectionTool({
178
200
  })
179
201
 
180
202
  export const unlockCollectionTool = defineCollectionTool({
203
+ annotations: {
204
+ destructiveHint: false,
205
+ idempotentHint: true,
206
+ openWorldHint: false,
207
+ readOnlyHint: false,
208
+ title: 'Unlock Account',
209
+ },
181
210
  description: 'Unlocks a user account that has been locked due to failed login attempts.',
182
211
  input: z.object({ email: emailSchema }),
183
212
  }).handler(async ({ collectionSlug, input, req }) => {
@@ -205,6 +234,13 @@ export const unlockCollectionTool = defineCollectionTool({
205
234
  })
206
235
 
207
236
  export const verifyCollectionTool = defineCollectionTool({
237
+ annotations: {
238
+ destructiveHint: false,
239
+ idempotentHint: false,
240
+ openWorldHint: false,
241
+ readOnlyHint: false,
242
+ title: 'Email Verification',
243
+ },
208
244
  description: 'Verifies a user email with a verification token.',
209
245
  input: z.object({
210
246
  token: z.string().describe('The verification token sent to the user email'),
@@ -0,0 +1,73 @@
1
+ import { z } from 'zod'
2
+
3
+ import { defaultAccess } from '../../../defaultAccess.js'
4
+ import { defineCollectionTool } from '../../../defineTool.js'
5
+ import { getLogger } from '../../../utils/getLogger.js'
6
+ import { whereSchema } from '../../../utils/whereSchema.js'
7
+
8
+ const DEFAULT_DESCRIPTION =
9
+ 'Count documents in any collection by passing the collection slug and optional where clause.'
10
+
11
+ export const countDocumentsTool = defineCollectionTool({
12
+ access: (args) =>
13
+ defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),
14
+ annotations: {
15
+ destructiveHint: false,
16
+ idempotentHint: true,
17
+ openWorldHint: false,
18
+ readOnlyHint: true,
19
+ title: 'Count Documents',
20
+ },
21
+ description: DEFAULT_DESCRIPTION,
22
+ input: z.object({
23
+ locale: z.string().describe('Optional: locale code to count documents in').optional(),
24
+ trash: z
25
+ .boolean()
26
+ .describe('Optional: include soft-deleted documents when trash is enabled on the collection')
27
+ .optional(),
28
+ where: whereSchema
29
+ .describe(
30
+ 'Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}',
31
+ )
32
+ .optional(),
33
+ }),
34
+ }).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
35
+ const payload = req.payload
36
+ const logger = getLogger({ payload })
37
+ const { locale, trash, where } = input
38
+
39
+ logger.info(`Counting documents in collection: ${collectionSlug}`)
40
+
41
+ try {
42
+ const result = await payload.count({
43
+ collection: collectionSlug,
44
+ overrideAccess: authorizedMCP.overrideAccess,
45
+ req,
46
+ ...(locale ? { locale } : {}),
47
+ ...(trash !== undefined ? { trash } : {}),
48
+ ...(where ? { where } : {}),
49
+ })
50
+
51
+ return {
52
+ content: [
53
+ {
54
+ type: 'text',
55
+ text: `Collection "${collectionSlug}" contains ${result.totalDocs} matching documents.\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
56
+ },
57
+ ],
58
+ doc: result,
59
+ }
60
+ } catch (error) {
61
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error'
62
+ logger.error(`Error counting documents in ${collectionSlug}: ${errorMessage}`)
63
+ return {
64
+ content: [
65
+ {
66
+ type: 'text',
67
+ text: `❌ **Error counting documents in collection "${collectionSlug}":** ${errorMessage}`,
68
+ },
69
+ ],
70
+ isError: true,
71
+ }
72
+ }
73
+ })