@payloadcms/plugin-mcp 4.0.0-internal.5f0cd13 → 4.0.0-internal.656159a

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 (257) 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 -73
  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 -41
  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 +20 -0
  57. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  58. package/dist/mcp/builtin/collections/fileInput.js +100 -0
  59. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  60. package/dist/mcp/builtin/collections/fileInput.spec.js +72 -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 +86 -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 -89
  93. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  94. package/dist/mcp/builtin/getConfigInfoTool.d.ts +2 -0
  95. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -0
  96. package/dist/mcp/builtin/getConfigInfoTool.js +68 -0
  97. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -0
  98. package/dist/mcp/builtin/globals/countVersionsTool.d.ts +2 -0
  99. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -0
  100. package/dist/mcp/builtin/globals/countVersionsTool.js +64 -0
  101. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -0
  102. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  103. package/dist/mcp/builtin/globals/findTool.js +20 -23
  104. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  105. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts +2 -0
  106. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -0
  107. package/dist/mcp/builtin/globals/findVersionByIDTool.js +79 -0
  108. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -0
  109. package/dist/mcp/builtin/globals/findVersionsTool.d.ts +2 -0
  110. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -0
  111. package/dist/mcp/builtin/globals/findVersionsTool.js +94 -0
  112. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -0
  113. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts +2 -0
  114. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -0
  115. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +65 -0
  116. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -0
  117. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts +2 -0
  118. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -0
  119. package/dist/mcp/builtin/globals/restoreVersionTool.js +77 -0
  120. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -0
  121. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  122. package/dist/mcp/builtin/globals/updateTool.js +33 -38
  123. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  124. package/dist/mcp/builtin/validateEntityData.d.ts +14 -0
  125. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -0
  126. package/dist/mcp/builtin/validateEntityData.js +82 -0
  127. package/dist/mcp/builtin/validateEntityData.js.map +1 -0
  128. package/dist/mcp/builtinTools.d.ts +144 -19
  129. package/dist/mcp/builtinTools.d.ts.map +1 -1
  130. package/dist/mcp/builtinTools.js +119 -20
  131. package/dist/mcp/builtinTools.js.map +1 -1
  132. package/dist/mcp/sanitizeMCPConfig.d.ts +0 -1
  133. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  134. package/dist/mcp/sanitizeMCPConfig.js +121 -58
  135. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  136. package/dist/stdio.d.ts +3 -3
  137. package/dist/stdio.d.ts.map +1 -1
  138. package/dist/stdio.js +82 -45
  139. package/dist/stdio.js.map +1 -1
  140. package/dist/types.d.ts +112 -110
  141. package/dist/types.d.ts.map +1 -1
  142. package/dist/types.js +2 -4
  143. package/dist/types.js.map +1 -1
  144. package/dist/utils/camelCase.d.ts.map +1 -1
  145. package/dist/utils/getPluginConfig.d.ts +1 -1
  146. package/dist/utils/getPluginConfig.js +1 -1
  147. package/dist/utils/getPluginConfig.js.map +1 -1
  148. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  149. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  150. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  151. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  152. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  153. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +13 -0
  154. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -0
  155. package/dist/utils/schemaConversion/getEntityInputSchema.js +66 -0
  156. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -0
  157. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +10 -0
  158. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -0
  159. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +384 -0
  160. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -0
  161. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +133 -0
  162. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -0
  163. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  164. package/dist/utils/whereSchema.d.ts +9 -0
  165. package/dist/utils/whereSchema.d.ts.map +1 -0
  166. package/dist/utils/whereSchema.js +13 -0
  167. package/dist/utils/whereSchema.js.map +1 -0
  168. package/package.json +11 -16
  169. package/src/defaultAccess.ts +3 -0
  170. package/src/endpoint/access.ts +81 -101
  171. package/src/endpoint/index.ts +58 -16
  172. package/src/exports/client.ts +2 -1
  173. package/src/exports/internal.ts +1 -0
  174. package/src/index.ts +12 -20
  175. package/src/mcp/buildMcpServer.ts +169 -109
  176. package/src/mcp/builtin/collections/authTools.ts +45 -9
  177. package/src/mcp/builtin/collections/countTool.ts +73 -0
  178. package/src/mcp/builtin/collections/countVersionsTool.ts +69 -0
  179. package/src/mcp/builtin/collections/createTool.ts +67 -62
  180. package/src/mcp/builtin/collections/deleteTool.ts +20 -18
  181. package/src/mcp/builtin/collections/duplicateTool.ts +134 -0
  182. package/src/mcp/builtin/collections/fileInput.spec.ts +79 -0
  183. package/src/mcp/builtin/collections/fileInput.ts +139 -0
  184. package/src/mcp/builtin/collections/findDistinctTool.ts +119 -0
  185. package/src/mcp/builtin/collections/findTool.ts +66 -37
  186. package/src/mcp/builtin/collections/findVersionByIDTool.ts +109 -0
  187. package/src/mcp/builtin/collections/findVersionsTool.ts +154 -0
  188. package/src/mcp/builtin/collections/formatCollectionError.ts +84 -0
  189. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +76 -0
  190. package/src/mcp/builtin/collections/restoreVersionTool.ts +107 -0
  191. package/src/mcp/builtin/collections/updateTool.ts +132 -110
  192. package/src/mcp/builtin/getConfigInfoTool.ts +67 -0
  193. package/src/mcp/builtin/globals/countVersionsTool.ts +68 -0
  194. package/src/mcp/builtin/globals/findTool.ts +28 -19
  195. package/src/mcp/builtin/globals/findVersionByIDTool.ts +103 -0
  196. package/src/mcp/builtin/globals/findVersionsTool.ts +147 -0
  197. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +63 -0
  198. package/src/mcp/builtin/globals/restoreVersionTool.ts +99 -0
  199. package/src/mcp/builtin/globals/updateTool.ts +52 -55
  200. package/src/mcp/builtin/validateEntityData.ts +132 -0
  201. package/src/mcp/builtinTools.ts +111 -41
  202. package/src/mcp/sanitizeMCPConfig.ts +117 -78
  203. package/src/stdio.ts +77 -45
  204. package/src/types.ts +128 -115
  205. package/src/utils/getPluginConfig.ts +1 -1
  206. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  207. package/src/utils/schemaConversion/getEntityInputSchema.ts +96 -0
  208. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +96 -0
  209. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +432 -0
  210. package/src/utils/whereSchema.ts +24 -0
  211. package/dist/collection/getAccessField.d.ts +0 -12
  212. package/dist/collection/getAccessField.d.ts.map +0 -1
  213. package/dist/collection/getAccessField.js +0 -57
  214. package/dist/collection/getAccessField.js.map +0 -1
  215. package/dist/collection/index.d.ts +0 -6
  216. package/dist/collection/index.d.ts.map +0 -1
  217. package/dist/collection/index.js +0 -59
  218. package/dist/collection/index.js.map +0 -1
  219. package/dist/components/AccessField/index.client.d.ts +0 -10
  220. package/dist/components/AccessField/index.client.d.ts.map +0 -1
  221. package/dist/components/AccessField/index.client.js +0 -305
  222. package/dist/components/AccessField/index.client.js.map +0 -1
  223. package/dist/components/AccessField/index.css +0 -93
  224. package/dist/utils/localAPIDefaults.d.ts +0 -20
  225. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  226. package/dist/utils/localAPIDefaults.js +0 -19
  227. package/dist/utils/localAPIDefaults.js.map +0 -1
  228. package/dist/utils/schemaConversion/prepareCollectionSchema.d.ts +0 -7
  229. package/dist/utils/schemaConversion/prepareCollectionSchema.d.ts.map +0 -1
  230. package/dist/utils/schemaConversion/prepareCollectionSchema.js +0 -37
  231. package/dist/utils/schemaConversion/prepareCollectionSchema.js.map +0 -1
  232. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  233. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  234. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  235. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  236. package/dist/utils/schemaConversion/sanitizeJsonSchema.d.ts +0 -13
  237. package/dist/utils/schemaConversion/sanitizeJsonSchema.d.ts.map +0 -1
  238. package/dist/utils/schemaConversion/sanitizeJsonSchema.js +0 -56
  239. package/dist/utils/schemaConversion/sanitizeJsonSchema.js.map +0 -1
  240. package/dist/utils/schemaConversion/simplifyRelationshipFields.d.ts +0 -20
  241. package/dist/utils/schemaConversion/simplifyRelationshipFields.d.ts.map +0 -1
  242. package/dist/utils/schemaConversion/simplifyRelationshipFields.js +0 -56
  243. package/dist/utils/schemaConversion/simplifyRelationshipFields.js.map +0 -1
  244. package/dist/utils/schemaConversion/transformPointFields.d.ts +0 -3
  245. package/dist/utils/schemaConversion/transformPointFields.d.ts.map +0 -1
  246. package/dist/utils/schemaConversion/transformPointFields.js +0 -57
  247. package/dist/utils/schemaConversion/transformPointFields.js.map +0 -1
  248. package/src/collection/getAccessField.ts +0 -64
  249. package/src/collection/index.ts +0 -63
  250. package/src/components/AccessField/index.client.tsx +0 -344
  251. package/src/components/AccessField/index.css +0 -93
  252. package/src/utils/localAPIDefaults.ts +0 -22
  253. package/src/utils/schemaConversion/prepareCollectionSchema.ts +0 -39
  254. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
  255. package/src/utils/schemaConversion/sanitizeJsonSchema.ts +0 -62
  256. package/src/utils/schemaConversion/simplifyRelationshipFields.ts +0 -70
  257. package/src/utils/schemaConversion/transformPointFields.ts +0 -56
package/src/stdio.ts CHANGED
@@ -1,35 +1,28 @@
1
- import type { MaybePromise, Plugin, SanitizedConfig } from 'payload'
1
+ import type { Config, Plugin, SanitizedConfig } from 'payload'
2
2
 
3
3
  /* eslint-disable no-console */
4
- import { StdioServerTransport } from '@modelcontextprotocol/server'
4
+ import { serveStdio } from '@modelcontextprotocol/server/stdio'
5
5
  import { fileURLToPath, pathToFileURL } from 'node:url'
6
6
  import { createLocalReq, getPayload } from 'payload'
7
7
  import { findConfig } from 'payload/node'
8
8
 
9
- import type { AuthorizedMCP, SanitizedMCPPluginConfig } from './types.js'
9
+ import type { SanitizedMCPPluginConfig } from './types.js'
10
10
 
11
+ import { getAuthorizedMCP } from './endpoint/access.js'
11
12
  import { buildMcpServer } from './mcp/buildMcpServer.js'
12
13
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
13
14
  import { getPluginConfig } from './utils/getPluginConfig.js'
14
15
  import { resolveProjectRoot } from './utils/resolveProjectRoot.js'
15
16
 
16
17
  /**
17
- * Stdio adapter for the Payload MCP server.
18
+ * Starts Payload's MCP server over stdin and stdout.
18
19
  *
19
- * Do not use in production. There's no auth; whoever can spawn the process gets
20
- * full access to your local data.
20
+ * Set `PAYLOAD_MCP_AUTHORIZATION` to authenticate. In development,
21
+ * `PAYLOAD_MCP_OVERRIDE_ACCESS=true` skips access checks.
21
22
  */
22
23
  export const runMcpStdio = async (): Promise<void> => {
23
- /**
24
- * If MCP clients spawn stdio servers from an arbitrary working directory,
25
- * Payload's cwd-anchored `findConfig()` can't locate the project on
26
- * its own. This module always lives inside the project's `node_modules`, so
27
- * we derive the project root from its own path and `chdir` into it.
28
- *
29
- * An absolute `PAYLOAD_CONFIG_PATH` still overrides everything; unusual
30
- * layouts (e.g. a monorepo where the package is hoisted above the app) can
31
- * fall back to it. See the implementation of findConfig for details.
32
- */
24
+ // MCP clients may start this command from another folder. Move to the Payload
25
+ // project so findConfig() can find the config.
33
26
  const projectRoot = resolveProjectRoot(fileURLToPath(import.meta.url))
34
27
  if (projectRoot) {
35
28
  process.chdir(projectRoot)
@@ -37,62 +30,101 @@ export const runMcpStdio = async (): Promise<void> => {
37
30
 
38
31
  const configPath = findConfig()
39
32
  const configModule = await import(pathToFileURL(configPath).toString())
40
- const config = (await (configModule.default ?? configModule)) as MaybePromise<SanitizedConfig>
41
-
42
- const payload = await getPayload({ config })
33
+ const config = (await (configModule.default ?? configModule)) as SanitizedConfig
43
34
 
44
35
  /**
45
- * If the user added `mcpPlugin({...})` to their `plugins` array, read the
46
- * sanitized config they registered. Otherwise fall back to the defaults. That way,
47
- * the mcp works on any project that has `@payloadcms/plugin-mcp` installed,
48
- * even if the plugin is not added to the plugins array.
36
+ * stdout is only for MCP messages. The spec says the server must not write
37
+ * logs there and may write them to stderr instead.
38
+ *
39
+ * The 2.0 client library recovers from stray stdout logs, but that behavior is not
40
+ * guaranteed. Move Payload logs to stderr so Payload does not add invalid data
41
+ * to stdout. Keep options from configurable loggers. Replace pre-built loggers
42
+ * because their output cannot be redirected.
43
+ *
44
+ * @see https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio
49
45
  */
46
+ const loggerConfig: { logger?: Config['logger'] } = config
47
+ if (
48
+ loggerConfig.logger &&
49
+ typeof loggerConfig.logger === 'object' &&
50
+ 'options' in loggerConfig.logger
51
+ ) {
52
+ loggerConfig.logger.destination = process.stderr
53
+ } else {
54
+ loggerConfig.logger = { destination: process.stderr, options: {} }
55
+ }
56
+
57
+ const payload = await getPayload({ config, cron: false, disableOnInit: true })
58
+
50
59
  let pluginConfig: SanitizedMCPPluginConfig
51
60
  try {
52
61
  pluginConfig = getPluginConfig({ config: payload.config })
53
62
  } catch {
63
+ // The command also works when mcpPlugin() is not in the Payload config.
54
64
  pluginConfig = sanitizeMCPConfig({ config: payload.config, pluginConfig: {} })
55
65
 
56
- const fakePluginFn: Plugin = (config) => config
57
- fakePluginFn.slug = '@payloadcms/plugin-mcp'
58
- // @ts-expect-error
59
- fakePluginFn.sanitizedOptions = pluginConfig
66
+ const fallbackPlugin: Plugin = (config) => config
67
+ Object.assign(fallbackPlugin, {
68
+ slug: '@payloadcms/plugin-mcp',
69
+ sanitizedOptions: pluginConfig,
70
+ })
71
+ payload.config.plugins ??= []
72
+ payload.config.plugins.push(fallbackPlugin)
73
+ }
74
+
75
+ const overrideAccessEnv = process.env.PAYLOAD_MCP_OVERRIDE_ACCESS
76
+ let overrideAccess = false
77
+
78
+ if (overrideAccessEnv === 'true') {
79
+ overrideAccess = true
80
+ } else if (overrideAccessEnv && overrideAccessEnv !== 'false') {
81
+ throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS must be "true" or "false".')
82
+ }
60
83
 
61
- // Push to payload config, to ensure consecutive calls to `getPluginConfig()` work
62
- ;(payload.config.plugins ??= []).push(fakePluginFn)
84
+ if (overrideAccess && process.env.NODE_ENV !== 'development') {
85
+ throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS is only available in development.')
63
86
  }
64
87
 
65
- const authorizedMCP: AuthorizedMCP = {
66
- items: pluginConfig.items,
67
- overrideAccess: true,
68
- user: null,
88
+ const headers = new Headers()
89
+ if (process.env.PAYLOAD_MCP_AUTHORIZATION) {
90
+ headers.set('Authorization', process.env.PAYLOAD_MCP_AUTHORIZATION)
69
91
  }
70
92
 
71
- const req = await createLocalReq({}, payload)
93
+ const req = await createLocalReq({ req: { headers } }, payload)
72
94
  req.payloadAPI = 'MCP' as const
95
+ const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
73
96
 
74
- const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
97
+ const stdioServer = serveStdio(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
98
+ onerror: (err) => {
99
+ // MCP messages use stdout, so write SDK errors to stderr.
100
+ console.error('[payload-mcp] error serving MCP over stdio:', err)
101
+ },
102
+ })
75
103
 
76
- const transport = new StdioServerTransport()
77
- await server.connect(transport)
104
+ // Close the MCP server and Payload when the client disconnects or the process stops.
105
+ let isShuttingDown = false
106
+ const shutdown = async () => {
107
+ if (isShuttingDown) {
108
+ return
109
+ }
110
+ isShuttingDown = true
78
111
 
79
- // Process now lives until stdin closes. Wire graceful shutdown so DB
80
- // connections (and any other Payload-managed resources) get released.
81
- const shutdown = async (code = 0) => {
82
112
  try {
83
- await server.close()
113
+ await stdioServer.close()
84
114
  } catch (err) {
85
115
  console.error('[payload-mcp] error closing server:', err)
86
116
  }
117
+
87
118
  try {
88
119
  await payload.destroy()
89
120
  } catch (err) {
90
121
  console.error('[payload-mcp] error destroying payload:', err)
91
122
  }
92
- process.exit(code)
123
+
124
+ process.exit(0)
93
125
  }
94
126
 
95
- process.on('SIGINT', () => void shutdown(0))
96
- process.on('SIGTERM', () => void shutdown(0))
97
- process.stdin.on('close', () => void shutdown(0))
127
+ process.once('SIGINT', () => void shutdown())
128
+ process.once('SIGTERM', () => void shutdown())
129
+ process.stdin.once('close', () => void shutdown())
98
130
  }
package/src/types.ts CHANGED
@@ -6,18 +6,18 @@ import type {
6
6
  ResourceTemplate,
7
7
  ServerContext,
8
8
  StandardSchemaWithJSON,
9
+ ToolAnnotations,
9
10
  } from '@modelcontextprotocol/server'
10
11
  import type {
11
12
  AuthCollectionSlug,
12
- CollectionConfig,
13
13
  CollectionSlug,
14
- DefaultDocumentIDType,
15
14
  GlobalSlug,
16
15
  MaybePromise,
17
16
  PayloadRequest,
18
- TypedUser,
17
+ SanitizedPermissions,
19
18
  } from 'payload'
20
19
 
20
+ import type { GetAuthorizedMCPArgs } from './endpoint/access.js'
21
21
  import type {
22
22
  MCPCollectionAuthToolName,
23
23
  MCPCollectionBuiltinName,
@@ -26,34 +26,16 @@ import type {
26
26
 
27
27
  export type { MCPCollectionAuthToolName, MCPCollectionBuiltinName, MCPGlobalBuiltinName }
28
28
 
29
- /** Re-exported from `@modelcontextprotocol/server` — the JSON Schema shape the MCP runtime validates against. */
30
- export type { JsonSchemaType, StandardSchemaWithJSON }
29
+ /** Re-exported from `@modelcontextprotocol/server` — common MCP types used in plugin config. */
30
+ export type { JsonSchemaType, StandardSchemaWithJSON, ToolAnnotations }
31
31
 
32
32
  /**
33
33
  * What a tool's `input` (or a prompt's `argsSchema`) can be — either a raw
34
- * JSON Schema literal, or a Standard Schema instance (Zod, Valibot, …).
34
+ * JSON Schema 2020-12 literal, or a Standard Schema instance (Zod, Valibot, …).
35
+ * Raw schemas may omit `$schema`; when present it must declare the 2020-12 dialect.
35
36
  */
36
37
  export type ToolInputSchema = JsonSchemaType | StandardSchemaWithJSON
37
38
 
38
- /**
39
- * Serializable mirror of `SanitizedMCPPluginConfig` for client components —
40
- * the full sanitized config carries functions (tool handlers, etc.) that can't
41
- * cross the server→client boundary. Built by `sanitizeClientPluginConfig` and
42
- * passed to the `AccessField` component via `clientProps`.
43
- *
44
- * @internal
45
- */
46
- export type ClientMCPPluginConfig = {
47
- items: Array<{
48
- collectionSlug?: string
49
- description: string
50
- globalSlug?: string
51
- key: string
52
- label: string
53
- type: 'collectionTool' | 'globalTool' | 'prompt' | 'resource' | 'tool'
54
- }>
55
- }
56
-
57
39
  export type MCPToolResponse = {
58
40
  content: ContentBlock[]
59
41
  /**
@@ -70,6 +52,13 @@ export type MCPResponseOverride = (
70
52
  req: PayloadRequest,
71
53
  ) => MCPToolResponse
72
54
 
55
+ export type MCPAfterToolCallHook = (args: {
56
+ input: unknown
57
+ req: PayloadRequest
58
+ response: MCPToolResponse
59
+ toolName: string
60
+ }) => MaybePromise<MCPToolResponse>
61
+
73
62
  /**
74
63
  * The handler's `input` type. A specific Standard Schema (Zod, Valibot, …) gets
75
64
  * its inferred output; anything else falls back to `Record<string, unknown>`.
@@ -80,6 +69,19 @@ export type TypedInput<TSchema> = TSchema extends StandardSchemaWithJSON
80
69
  : StandardSchemaWithJSON.InferOutput<TSchema>
81
70
  : Record<string, unknown>
82
71
 
72
+ export type MCPAccessArgs = {
73
+ permissions?: SanitizedPermissions
74
+ req: PayloadRequest
75
+ }
76
+
77
+ export type CollectionMCPAccessArgs = {
78
+ collectionSlug: CollectionSlug
79
+ } & MCPAccessArgs
80
+
81
+ export type GlobalMCPAccessArgs = {
82
+ globalSlug: GlobalSlug
83
+ } & MCPAccessArgs
84
+
83
85
  export type ToolHandlerArgs<TSchema = undefined> = {
84
86
  authorizedMCP: AuthorizedMCP
85
87
  input: TypedInput<TSchema>
@@ -96,6 +98,13 @@ export type GlobalToolHandlerArgs<TSchema = undefined> = {
96
98
  } & ToolHandlerArgs<TSchema>
97
99
 
98
100
  export type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {
101
+ /**
102
+ * Runs while authorizing each MCP request, before the tool is advertised or called. Return
103
+ * `false` to make the tool unavailable for that request. This is skipped when `overrideAccess`
104
+ * is enabled.
105
+ */
106
+ access?: (args: MCPAccessArgs) => MaybePromise<boolean>
107
+ annotations?: ToolAnnotations
99
108
  description: string
100
109
  handler: (args: ToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>
101
110
  input?: TSchema
@@ -105,30 +114,57 @@ export type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema |
105
114
  overrideResponse?: MCPResponseOverride
106
115
  }
107
116
 
108
- /**
109
- * `TSchema` is the schema itself (Standard Schema, raw JSON Schema, or undefined).
110
- * The function-form variant of `input` carries a concrete `{ collectionSchema: JsonSchemaType }`
111
- * parameter type so callers can write `({ collectionSchema }) => …` without annotating it.
112
- */
113
117
  export type CollectionTool<
114
118
  TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined,
115
119
  > = {
120
+ /**
121
+ * Runs while authorizing each MCP request for this collection. Return `false` to reject calls
122
+ * to this tool for the collection. The shared tool is not advertised when no collections allow
123
+ * it, but can remain advertised when it is available for another collection. This is skipped
124
+ * when `overrideAccess` is enabled.
125
+ */
126
+ access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>
116
127
  handler: (args: CollectionToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>
117
- input?: ((args: { collectionSchema: JsonSchemaType }) => TSchema) | TSchema
118
- } & Pick<Tool, 'description' | 'overrideResponse'>
128
+ input?: TSchema
129
+ } & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>
119
130
 
120
131
  export type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> =
121
132
  {
133
+ /**
134
+ * Runs while authorizing each MCP request for this global. Return `false` to reject calls to
135
+ * this tool for the global. The shared tool is not advertised when no globals allow it, but
136
+ * can remain advertised when it is available for another global. This is skipped when
137
+ * `overrideAccess` is enabled.
138
+ */
139
+ access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>
122
140
  handler: (args: GlobalToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>
123
- input?: ((args: { globalSchema: JsonSchemaType }) => TSchema) | TSchema
124
- } & Pick<Tool, 'description' | 'overrideResponse'>
141
+ input?: TSchema
142
+ } & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>
125
143
 
126
144
  /**
127
145
  * Configures (or disables) a built-in tool without replacing it.
128
146
  * `handler?: never` prevents a full `CollectionTool`/`GlobalTool` (which has a
129
147
  * required handler) from being silently accepted at a built-in key slot.
130
148
  */
131
- export type MCPBuiltInToolOverride = {
149
+ export type MCPBuiltInCollectionToolOverride = {
150
+ /**
151
+ * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for
152
+ * this collection. This is skipped when `overrideAccess` is enabled.
153
+ */
154
+ access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>
155
+ annotations?: ToolAnnotations
156
+ description?: string
157
+ handler?: never
158
+ overrideResponse?: MCPResponseOverride
159
+ }
160
+
161
+ export type MCPBuiltInGlobalToolOverride = {
162
+ /**
163
+ * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for
164
+ * this global. This is skipped when `overrideAccess` is enabled.
165
+ */
166
+ access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>
167
+ annotations?: ToolAnnotations
132
168
  description?: string
133
169
  handler?: never
134
170
  overrideResponse?: MCPResponseOverride
@@ -142,13 +178,13 @@ export type MCPBuiltInToolOverride = {
142
178
  export type MCPTopLevelToolEntry = Tool
143
179
 
144
180
  export type MCPCollectionToolsMap = {
145
- [customToolName: string]: boolean | CollectionTool | MCPBuiltInToolOverride | undefined
181
+ [customToolName: string]: boolean | CollectionTool | MCPBuiltInCollectionToolOverride | undefined
146
182
  } & {
147
- [K in MCPCollectionBuiltinName]?: false | MCPBuiltInToolOverride
183
+ [K in MCPCollectionBuiltinName]?: false | MCPBuiltInCollectionToolOverride
148
184
  }
149
185
 
150
186
  export type MCPAuthCollectionToolsMap = {
151
- [K in MCPCollectionAuthToolName]?: MCPBuiltInToolOverride | true
187
+ [K in MCPCollectionAuthToolName]?: MCPBuiltInCollectionToolOverride | true
152
188
  } & MCPCollectionToolsMap
153
189
 
154
190
  /** Auth-enabled collections get auth-tool name autocomplete; others get CRUD-only. */
@@ -157,9 +193,9 @@ export type MCPToolsMapForCollection<Slug extends CollectionSlug> = Slug extends
157
193
  : MCPCollectionToolsMap
158
194
 
159
195
  export type MCPGlobalToolsMap = {
160
- [customToolName: string]: boolean | GlobalTool | MCPBuiltInToolOverride | undefined
196
+ [customToolName: string]: boolean | GlobalTool | MCPBuiltInGlobalToolOverride | undefined
161
197
  } & {
162
- [K in MCPGlobalBuiltinName]?: false | MCPBuiltInToolOverride
198
+ [K in MCPGlobalBuiltinName]?: false | MCPBuiltInGlobalToolOverride
163
199
  }
164
200
 
165
201
  export type MCPTopLevelToolsMap = Record<string, Tool>
@@ -171,6 +207,12 @@ export type PromptHandlerArgs<TSchema = undefined> = {
171
207
  }
172
208
 
173
209
  export type Prompt<TSchema extends ToolInputSchema = ToolInputSchema> = {
210
+ /**
211
+ * Runs while authorizing each MCP request, before the prompt is advertised or used. Return
212
+ * `false` to make the prompt unavailable for that request. This is skipped when
213
+ * `overrideAccess` is enabled.
214
+ */
215
+ access?: (args: MCPAccessArgs) => MaybePromise<boolean>
174
216
  argsSchema: TSchema
175
217
  description: string
176
218
  handler: (args: PromptHandlerArgs<TSchema>) => MaybePromise<{
@@ -188,6 +230,12 @@ export type ResourceHandlerArgs = {
188
230
  }
189
231
 
190
232
  export type Resource = {
233
+ /**
234
+ * Runs while authorizing each MCP request, before the resource is advertised or read. Return
235
+ * `false` to make the resource unavailable for that request. This is skipped when
236
+ * `overrideAccess` is enabled.
237
+ */
238
+ access?: (args: MCPAccessArgs) => MaybePromise<boolean>
191
239
  description: string
192
240
  handler: (args: ResourceHandlerArgs) => MaybePromise<{
193
241
  contents: Array<{ text: string; uri: string }>
@@ -221,34 +269,39 @@ export type MCPPluginConfig = {
221
269
  collections?: {
222
270
  [Slug in CollectionSlug]?: MCPPluginCollectionConfig<Slug>
223
271
  }
224
- /** Skip MCP registration. The API key collection is still added (so DB / types stay stable). */
272
+ /** Skip MCP endpoint registration. */
225
273
  disabled?: boolean
226
274
  globals?: {
227
275
  [Slug in GlobalSlug]?: MCPPluginGlobalConfig
228
276
  }
277
+ hooks?: {
278
+ /** Transform a tool response after its handler returns */
279
+ afterToolCall?: MCPAfterToolCallHook[]
280
+ }
229
281
  mcp?: {
230
282
  serverOptions?: MCPServerOptions
231
283
  verboseLogs?: boolean
232
284
  }
233
- overrideApiKeyCollection?: (collection: CollectionConfig) => CollectionConfig
234
- /** Replace the default API-key auth with a custom resolver. */
235
- overrideAuth?: (args: {
236
- getAPIKeyDoc: (overrideApiKey?: string) => Promise<MCPAPIKeysDoc>
237
- getAuthorizedMCP: (args: { apiKeyDoc: MCPAPIKeysDoc }) => AuthorizedMCP
238
- pluginConfig: SanitizedMCPPluginConfig
239
- req: PayloadRequest
240
- }) => MaybePromise<AuthorizedMCP>
285
+ /**
286
+ * Replace the default MCP authorization resolver.
287
+ *
288
+ * This hook replaces the default authentication flow. It must set `req.user` to the
289
+ * authenticated Payload user, or to `null` for an anonymous caller, before returning.
290
+ */
291
+ overrideGetAuthorizedMCP?: (
292
+ args: {
293
+ pluginConfig: SanitizedMCPPluginConfig
294
+ } & GetAuthorizedMCPArgs,
295
+ ) => MaybePromise<AuthorizedMCP>
241
296
  prompts?: Record<string, Prompt>
242
297
  resources?: Record<string, Resource>
243
298
  /** Cross-cutting tools (not scoped to any collection or global). */
244
299
  tools?: MCPTopLevelToolsMap
245
- userCollection?: CollectionSlug
246
300
  }
247
301
 
248
302
  export type SanitizedMCPPluginConfig = {
249
303
  items: MCPItem[]
250
- userCollection: CollectionSlug
251
- } & Pick<MCPPluginConfig, 'disabled' | 'mcp' | 'overrideApiKeyCollection' | 'overrideAuth'>
304
+ } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>
252
305
 
253
306
  export type MCPServerOptions = {
254
307
  options?: ConstructorParameters<typeof McpServer>[1]
@@ -256,71 +309,32 @@ export type MCPServerOptions = {
256
309
  }
257
310
 
258
311
  /**
259
- * Nested access tree as stored in the collection.
260
- * A `false` leaf disables that tool; missing keys defer to
261
- * defaults (built-in CRUD is on, opt-in tools are off).
262
- */
263
- export type MCPAPIKeysDocAccessTree = {
264
- collections?: {
265
- [CollectionSlug: CollectionSlug]: {
266
- [ToolKey: string]: boolean
267
- }
268
- }
269
- globals?: {
270
- [GlobalSlug: GlobalSlug]: {
271
- [ToolKey: string]: boolean
272
- }
273
- }
274
- prompts?: {
275
- [PromptKey: string]: boolean
276
- }
277
- resources?: {
278
- [ResourceKey: string]: boolean
279
- }
280
- tools?: {
281
- [ToolKey: string]: boolean
282
- }
283
- }
284
-
285
- /**
286
- * Stored on `payload-mcp-api-keys` docs
287
- */
288
- export type MCPAPIKeysDoc = {
289
- access: MCPAPIKeysDocAccessTree
290
- id: DefaultDocumentIDType
291
- overrideAccess?: boolean
292
- user: null | TypedUser
293
- }
294
-
295
- /**
296
- * One MCP primitive — tool, prompt, or resource — paired with the metadata both
297
- * the endpoint and the API key collection need. Built by `sanitizeMCPConfig`,
298
- * filtered by `getAuthorizedMCP`, registered by the MCP endpoint.
312
+ * One MCP primitive plus the metadata needed for config-driven filtering and
313
+ * registration.
299
314
  *
300
- * - `key`: the config identifier (`find`, `echo`). Used for the API-key deny
301
- * lookup and as the admin checkbox field name. For collection/global tools,
302
- * the MCP wire name (`findPosts`) is derived from `key + slug` at
303
- * registration time.
304
- * - `label`: human-readable admin-UI display text for the checkbox.
305
- * - `tool` / `prompt` / `resource`: the live primitive (its own
306
- * `description` is what both MCP clients and the admin UI surface).
315
+ * - `configKey`: the config identifier, e.g. `find` or `echo`.
316
+ * - `mcpName`: the MCP wire name, e.g. `findDocuments` or `echo`.
317
+ * - `label`: human-readable display text.
307
318
  */
308
319
  export type MCPItemBase = {
309
- key: string
320
+ configKey: string
310
321
  label: string
322
+ mcpName: string
311
323
  }
312
324
 
325
+ export type CollectionMCPItem = {
326
+ collectionSlug: CollectionSlug
327
+ tool: CollectionTool
328
+ type: 'collectionTool'
329
+ } & MCPItemBase
330
+
331
+ export type GlobalMCPItem = {
332
+ globalSlug: GlobalSlug
333
+ tool: GlobalTool
334
+ type: 'globalTool'
335
+ } & MCPItemBase
336
+
313
337
  export type MCPItem =
314
- | ({
315
- collectionSlug: CollectionSlug
316
- tool: CollectionTool
317
- type: 'collectionTool'
318
- } & MCPItemBase)
319
- | ({
320
- globalSlug: GlobalSlug
321
- tool: GlobalTool
322
- type: 'globalTool'
323
- } & MCPItemBase)
324
338
  | ({
325
339
  prompt: Prompt
326
340
  type: 'prompt'
@@ -333,15 +347,14 @@ export type MCPItem =
333
347
  tool: Tool
334
348
  type: 'tool'
335
349
  } & MCPItemBase)
350
+ | CollectionMCPItem
351
+ | GlobalMCPItem
336
352
 
337
353
  /**
338
- * The caller's identity + the MCP items they can use for this request. Returned
339
- * by `getAuthorizedMCP`; denied items are simply absent from `items`. Handlers
340
- * receive this via `args.authorizedMCP` so they can spread
341
- * `localAPIDefaults(authorizedMCP)` into every local API call.
354
+ * The MCP items and access mode authorized for this request. The authenticated user is available
355
+ * as `req.user`.
342
356
  */
343
357
  export type AuthorizedMCP = {
344
358
  items: MCPItem[]
345
359
  overrideAccess: boolean
346
- user: null | TypedUser
347
360
  }
@@ -5,7 +5,7 @@ import type { SanitizedMCPPluginConfig } from '../types.js'
5
5
  /**
6
6
  * Returns the sanitized plugin config — the form produced by
7
7
  * `sanitizeMCPConfig` and stashed back on the plugin's `options` during init.
8
- * Callers downstream of plugin init can rely on `items`, `userCollection`, etc.
8
+ * Callers downstream of plugin init can rely on `items` and other defaults
9
9
  * being fully resolved.
10
10
  */
11
11
  export const getPluginConfig: (args: { config: SanitizedConfig }) => SanitizedMCPPluginConfig = ({