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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/bin.js +0 -7
  2. package/dist/endpoint/access.d.ts.map +1 -1
  3. package/dist/endpoint/access.js +17 -5
  4. package/dist/endpoint/access.js.map +1 -1
  5. package/dist/endpoint/index.d.ts.map +1 -1
  6. package/dist/endpoint/index.js +46 -4
  7. package/dist/endpoint/index.js.map +1 -1
  8. package/dist/endpoint/oauth.d.ts +39 -0
  9. package/dist/endpoint/oauth.d.ts.map +1 -0
  10. package/dist/endpoint/oauth.js +94 -0
  11. package/dist/endpoint/oauth.js.map +1 -0
  12. package/dist/endpoint/oauthLoginToken.d.ts +15 -0
  13. package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
  14. package/dist/endpoint/oauthLoginToken.js +45 -0
  15. package/dist/endpoint/oauthLoginToken.js.map +1 -0
  16. package/dist/endpoint/oauthServer.d.ts +12 -0
  17. package/dist/endpoint/oauthServer.d.ts.map +1 -0
  18. package/dist/endpoint/oauthServer.js +386 -0
  19. package/dist/endpoint/oauthServer.js.map +1 -0
  20. package/dist/index.d.ts +10 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +15 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/mcp/buildMcpServer.d.ts +2 -2
  25. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  26. package/dist/mcp/buildMcpServer.js +36 -24
  27. package/dist/mcp/buildMcpServer.js.map +1 -1
  28. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  29. package/dist/mcp/builtin/collections/authTools.js +80 -56
  30. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  31. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  32. package/dist/mcp/builtin/collections/countTool.js +9 -14
  33. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  34. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  35. package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
  36. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  37. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  38. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  39. package/dist/mcp/builtin/collections/createTool.js +103 -62
  40. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  41. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  42. package/dist/mcp/builtin/collections/deleteTool.js +44 -43
  43. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  44. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/duplicateTool.js +31 -37
  46. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  47. package/dist/mcp/builtin/collections/fileInput.d.ts +21 -21
  48. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  49. package/dist/mcp/builtin/collections/fileInput.js +43 -72
  50. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  51. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  52. package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
  53. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  54. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  55. package/dist/mcp/builtin/collections/findTool.js +28 -46
  56. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  57. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  58. package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
  59. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  60. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  61. package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
  62. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  63. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  64. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +30 -14
  65. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  66. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  67. package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
  68. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  69. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  70. package/dist/mcp/builtin/collections/updateTool.js +56 -88
  71. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  72. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +13 -13
  73. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
  74. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  75. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  76. package/dist/mcp/builtin/formatEntityError.js +55 -0
  77. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  78. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  79. package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
  80. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  81. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  82. package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
  83. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  84. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  85. package/dist/mcp/builtin/globals/findTool.js +10 -16
  86. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  87. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  88. package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
  89. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  90. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  91. package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
  92. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  93. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  94. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +29 -13
  95. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  96. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  97. package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
  98. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  99. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  100. package/dist/mcp/builtin/globals/updateTool.js +27 -36
  101. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  102. package/dist/mcp/builtinTools.d.ts.map +1 -1
  103. package/dist/mcp/builtinTools.js +3 -3
  104. package/dist/mcp/builtinTools.js.map +1 -1
  105. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  106. package/dist/mcp/sanitizeMCPConfig.js +3 -0
  107. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  108. package/dist/stdio.js +4 -3
  109. package/dist/stdio.js.map +1 -1
  110. package/dist/types.d.ts +95 -7
  111. package/dist/types.d.ts.map +1 -1
  112. package/dist/types.js.map +1 -1
  113. package/dist/utils/toStandardSchema.js.map +1 -1
  114. package/package.json +23 -28
  115. package/src/endpoint/access.ts +14 -6
  116. package/src/endpoint/index.ts +41 -3
  117. package/src/endpoint/oauth.ts +92 -0
  118. package/src/endpoint/oauthLoginToken.ts +59 -0
  119. package/src/endpoint/oauthServer.ts +440 -0
  120. package/src/index.ts +40 -5
  121. package/src/mcp/buildMcpServer.ts +40 -30
  122. package/src/mcp/builtin/collections/authTools.ts +82 -71
  123. package/src/mcp/builtin/collections/countTool.ts +9 -21
  124. package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
  125. package/src/mcp/builtin/collections/createTool.ts +107 -85
  126. package/src/mcp/builtin/collections/deleteTool.ts +37 -65
  127. package/src/mcp/builtin/collections/duplicateTool.ts +36 -86
  128. package/src/mcp/builtin/collections/fileInput.spec.ts +2 -2
  129. package/src/mcp/builtin/collections/fileInput.ts +54 -81
  130. package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
  131. package/src/mcp/builtin/collections/findTool.ts +24 -106
  132. package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
  133. package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
  134. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +23 -12
  135. package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -57
  136. package/src/mcp/builtin/collections/updateTool.ts +56 -110
  137. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +15 -15
  138. package/src/mcp/builtin/formatEntityError.ts +77 -0
  139. package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
  140. package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
  141. package/src/mcp/builtin/globals/findTool.ts +13 -52
  142. package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
  143. package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
  144. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +21 -11
  145. package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
  146. package/src/mcp/builtin/globals/updateTool.ts +38 -61
  147. package/src/mcp/builtinTools.ts +2 -2
  148. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  149. package/src/stdio.ts +2 -2
  150. package/src/types.ts +97 -7
  151. package/src/utils/toStandardSchema.ts +1 -1
  152. package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
  153. package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
  154. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  155. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  156. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  157. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  158. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  159. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  160. package/dist/mcp/builtin/validateEntityData.js +0 -82
  161. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  162. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  163. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  164. package/dist/utils/getVirtualFieldNames.js +0 -35
  165. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  166. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
  167. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
  168. package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
  169. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
  170. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
  171. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  172. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
  173. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  174. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
  175. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  176. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
  177. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  178. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
  179. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  180. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  181. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  182. package/dist/utils/transformPointDataToPayload.js +0 -28
  183. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  184. package/dist/utils/whereSchema.d.ts +0 -9
  185. package/dist/utils/whereSchema.d.ts.map +0 -1
  186. package/dist/utils/whereSchema.js +0 -13
  187. package/dist/utils/whereSchema.js.map +0 -1
  188. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  189. package/src/mcp/builtin/validateEntityData.ts +0 -132
  190. package/src/utils/getVirtualFieldNames.ts +0 -53
  191. package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
  192. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
  193. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
  194. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
  195. package/src/utils/transformPointDataToPayload.ts +0 -40
  196. package/src/utils/whereSchema.ts +0 -24
package/dist/stdio.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stdio.ts"],"sourcesContent":["import type { Config, Plugin, SanitizedConfig } from 'payload'\n\n/* eslint-disable no-console */\nimport { serveStdio } from '@modelcontextprotocol/server/stdio'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { createLocalReq, getPayload } from 'payload'\nimport { findConfig, loadEnv } from 'payload/node'\n\nimport type { SanitizedMCPPluginConfig } from './types.js'\n\nimport { getAuthorizedMCP } from './endpoint/access.js'\nimport { buildMcpServer } from './mcp/buildMcpServer.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\nimport { getPluginConfig } from './utils/getPluginConfig.js'\nimport { resolveProjectRoot } from './utils/resolveProjectRoot.js'\n\n/**\n * Starts Payload's MCP server over stdin and stdout.\n *\n * Set `PAYLOAD_MCP_AUTHORIZATION` to authenticate. In development,\n * `PAYLOAD_MCP_OVERRIDE_ACCESS=true` skips access checks.\n */\nexport const runMcpStdio = async (): Promise<void> => {\n // MCP clients may start this command from another folder. Move to the Payload\n // project so findConfig() can find the config.\n const projectRoot = resolveProjectRoot(fileURLToPath(import.meta.url))\n if (projectRoot) {\n process.chdir(projectRoot)\n }\n\n loadEnv()\n const configPath = findConfig()\n const configModule = await import(pathToFileURL(configPath).toString())\n const config = (await (configModule.default ?? configModule)) as SanitizedConfig\n\n /**\n * stdout is only for MCP messages. The spec says the server must not write\n * logs there and may write them to stderr instead.\n *\n * The 2.0 client library recovers from stray stdout logs, but that behavior is not\n * guaranteed. Move Payload logs to stderr so Payload does not add invalid data\n * to stdout. Keep options from configurable loggers. Replace pre-built loggers\n * because their output cannot be redirected.\n *\n * @see https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio\n */\n const loggerConfig: { logger?: Config['logger'] } = config\n if (\n loggerConfig.logger &&\n typeof loggerConfig.logger === 'object' &&\n 'options' in loggerConfig.logger\n ) {\n loggerConfig.logger.destination = process.stderr\n } else {\n loggerConfig.logger = { destination: process.stderr, options: {} }\n }\n\n const payload = await getPayload({ config, cron: false, disableOnInit: true })\n\n let pluginConfig: SanitizedMCPPluginConfig\n try {\n pluginConfig = getPluginConfig({ config: payload.config })\n } catch {\n // The command also works when mcpPlugin() is not in the Payload config.\n pluginConfig = sanitizeMCPConfig({ config: payload.config, pluginConfig: {} })\n\n const fallbackPlugin: Plugin = (config) => config\n Object.assign(fallbackPlugin, {\n slug: '@payloadcms/plugin-mcp',\n sanitizedOptions: pluginConfig,\n })\n payload.config.plugins ??= []\n payload.config.plugins.push(fallbackPlugin)\n }\n\n const overrideAccessEnv = process.env.PAYLOAD_MCP_OVERRIDE_ACCESS\n let overrideAccess = false\n\n if (overrideAccessEnv === 'true') {\n overrideAccess = true\n } else if (overrideAccessEnv && overrideAccessEnv !== 'false') {\n throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS must be \"true\" or \"false\".')\n }\n\n if (overrideAccess && process.env.NODE_ENV !== 'development') {\n throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS is only available in development.')\n }\n\n const headers = new Headers()\n if (process.env.PAYLOAD_MCP_AUTHORIZATION) {\n headers.set('Authorization', process.env.PAYLOAD_MCP_AUTHORIZATION)\n }\n\n const req = await createLocalReq({ req: { headers } }, payload)\n req.payloadAPI = 'MCP' as const\n const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })\n\n const stdioServer = serveStdio(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {\n onerror: (err) => {\n // MCP messages use stdout, so write SDK errors to stderr.\n console.error('[payload-mcp] error serving MCP over stdio:', err)\n },\n })\n\n // Close the MCP server and Payload when the client disconnects or the process stops.\n let isShuttingDown = false\n const shutdown = async () => {\n if (isShuttingDown) {\n return\n }\n isShuttingDown = true\n\n try {\n await stdioServer.close()\n } catch (err) {\n console.error('[payload-mcp] error closing server:', err)\n }\n\n try {\n await payload.destroy()\n } catch (err) {\n console.error('[payload-mcp] error destroying payload:', err)\n }\n\n process.exit(0)\n }\n\n process.once('SIGINT', () => void shutdown())\n process.once('SIGTERM', () => void shutdown())\n process.stdin.once('close', () => void shutdown())\n}\n"],"names":["serveStdio","fileURLToPath","pathToFileURL","createLocalReq","getPayload","findConfig","loadEnv","getAuthorizedMCP","buildMcpServer","sanitizeMCPConfig","getPluginConfig","resolveProjectRoot","runMcpStdio","projectRoot","url","process","chdir","configPath","configModule","toString","config","default","loggerConfig","logger","destination","stderr","options","payload","cron","disableOnInit","pluginConfig","fallbackPlugin","Object","assign","slug","sanitizedOptions","plugins","push","overrideAccessEnv","env","PAYLOAD_MCP_OVERRIDE_ACCESS","overrideAccess","Error","NODE_ENV","headers","Headers","PAYLOAD_MCP_AUTHORIZATION","set","req","payloadAPI","authorizedMCP","stdioServer","onerror","err","console","error","isShuttingDown","shutdown","close","destroy","exit","once","stdin"],"mappings":"AAEA,6BAA6B,GAC7B,SAASA,UAAU,QAAQ,qCAAoC;AAC/D,SAASC,aAAa,EAAEC,aAAa,QAAQ,WAAU;AACvD,SAASC,cAAc,EAAEC,UAAU,QAAQ,UAAS;AACpD,SAASC,UAAU,EAAEC,OAAO,QAAQ,eAAc;AAIlD,SAASC,gBAAgB,QAAQ,uBAAsB;AACvD,SAASC,cAAc,QAAQ,0BAAyB;AACxD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,kBAAkB,QAAQ,gCAA+B;AAElE;;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AS;QAC7D,MAAM,IAAII,MAAM;IAClB;IAEA,IAAID,kBAAkB1B,QAAQwB,GAAG,CAACI,QAAQ,KAAK,eAAe;QAC5D,MAAM,IAAID,MAAM;IAClB;IAEA,MAAME,UAAU,IAAIC;IACpB,IAAI9B,QAAQwB,GAAG,CAACO,yBAAyB,EAAE;QACzCF,QAAQG,GAAG,CAAC,iBAAiBhC,QAAQwB,GAAG,CAACO,yBAAyB;IACpE;IAEA,MAAME,MAAM,MAAM7C,eAAe;QAAE6C,KAAK;YAAEJ;QAAQ;IAAE,GAAGjB;IACvDqB,IAAIC,UAAU,GAAG;IACjB,MAAMC,gBAAgB,MAAM3C,iBAAiB;QAAEkC;QAAgBO;IAAI;IAEnE,MAAMG,cAAcnD,WAAW,IAAMQ,eAAe;YAAE0C;YAAepB;YAAckB;QAAI,IAAI;QACzFI,SAAS,CAACC;YACR,0DAA0D;YAC1DC,QAAQC,KAAK,CAAC,+CAA+CF;QAC/D;IACF;IAEA,qFAAqF;IACrF,IAAIG,iBAAiB;IACrB,MAAMC,WAAW;QACf,IAAID,gBAAgB;YAClB;QACF;QACAA,iBAAiB;QAEjB,IAAI;YACF,MAAML,YAAYO,KAAK;QACzB,EAAE,OAAOL,KAAK;YACZC,QAAQC,KAAK,CAAC,uCAAuCF;QACvD;QAEA,IAAI;YACF,MAAM1B,QAAQgC,OAAO;QACvB,EAAE,OAAON,KAAK;YACZC,QAAQC,KAAK,CAAC,2CAA2CF;QAC3D;QAEAtC,QAAQ6C,IAAI,CAAC;IACf;IAEA7C,QAAQ8C,IAAI,CAAC,UAAU,IAAM,KAAKJ;IAClC1C,QAAQ8C,IAAI,CAAC,WAAW,IAAM,KAAKJ;IACnC1C,QAAQ+C,KAAK,CAACD,IAAI,CAAC,SAAS,IAAM,KAAKJ;AACzC,EAAC"}
1
+ {"version":3,"sources":["../src/stdio.ts"],"sourcesContent":["import type { Config, Plugin, SanitizedConfig } from 'payload'\n\n/* eslint-disable no-console */\nimport { serveStdio } from '@modelcontextprotocol/server/stdio'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { createPayloadRequest, getPayload } from 'payload'\nimport { findConfig, loadEnv } from 'payload/node'\n\nimport type { SanitizedMCPPluginConfig } from './types.js'\n\nimport { getAuthorizedMCP } from './endpoint/access.js'\nimport { buildMcpServer } from './mcp/buildMcpServer.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\nimport { getPluginConfig } from './utils/getPluginConfig.js'\nimport { resolveProjectRoot } from './utils/resolveProjectRoot.js'\n\n/**\n * Starts Payload's MCP server over stdin and stdout.\n *\n * Set `PAYLOAD_MCP_AUTHORIZATION` to authenticate. In development,\n * `PAYLOAD_MCP_OVERRIDE_ACCESS=true` skips access checks.\n */\nexport const runMcpStdio = async (): Promise<void> => {\n // MCP clients may start this command from another folder. Move to the Payload\n // project so findConfig() can find the config.\n const projectRoot = resolveProjectRoot(fileURLToPath(import.meta.url))\n if (projectRoot) {\n process.chdir(projectRoot)\n }\n\n loadEnv()\n const configPath = findConfig()\n const configModule = await import(pathToFileURL(configPath).toString())\n const config = (await (configModule.default ?? configModule)) as SanitizedConfig\n\n /**\n * stdout is only for MCP messages. The spec says the server must not write\n * logs there and may write them to stderr instead.\n *\n * The 2.0 client library recovers from stray stdout logs, but that behavior is not\n * guaranteed. Move Payload logs to stderr so Payload does not add invalid data\n * to stdout. Keep options from configurable loggers. Replace pre-built loggers\n * because their output cannot be redirected.\n *\n * @see https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio\n */\n const loggerConfig: { logger?: Config['logger'] } = config\n if (\n loggerConfig.logger &&\n typeof loggerConfig.logger === 'object' &&\n 'options' in loggerConfig.logger\n ) {\n loggerConfig.logger.destination = process.stderr\n } else {\n loggerConfig.logger = { destination: process.stderr, options: {} }\n }\n\n const payload = await getPayload({ config, cron: false, disableOnInit: true })\n\n let pluginConfig: SanitizedMCPPluginConfig\n try {\n pluginConfig = getPluginConfig({ config: payload.config })\n } catch {\n // The command also works when mcpPlugin() is not in the Payload config.\n pluginConfig = sanitizeMCPConfig({ config: payload.config, pluginConfig: {} })\n\n const fallbackPlugin: Plugin = (config) => config\n Object.assign(fallbackPlugin, {\n slug: '@payloadcms/plugin-mcp',\n sanitizedOptions: pluginConfig,\n })\n payload.config.plugins ??= []\n payload.config.plugins.push(fallbackPlugin)\n }\n\n const overrideAccessEnv = process.env.PAYLOAD_MCP_OVERRIDE_ACCESS\n let overrideAccess = false\n\n if (overrideAccessEnv === 'true') {\n overrideAccess = true\n } else if (overrideAccessEnv && overrideAccessEnv !== 'false') {\n throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS must be \"true\" or \"false\".')\n }\n\n if (overrideAccess && process.env.NODE_ENV !== 'development') {\n throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS is only available in development.')\n }\n\n const headers = new Headers()\n if (process.env.PAYLOAD_MCP_AUTHORIZATION) {\n headers.set('Authorization', process.env.PAYLOAD_MCP_AUTHORIZATION)\n }\n\n const req = await createPayloadRequest({ payload, req: { headers } })\n req.payloadAPI = 'MCP' as const\n const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })\n\n const stdioServer = serveStdio(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {\n onerror: (err) => {\n // MCP messages use stdout, so write SDK errors to stderr.\n console.error('[payload-mcp] error serving MCP over stdio:', err)\n },\n })\n\n // Close the MCP server and Payload when the client disconnects or the process stops.\n let isShuttingDown = false\n const shutdown = async () => {\n if (isShuttingDown) {\n return\n }\n isShuttingDown = true\n\n try {\n await stdioServer.close()\n } catch (err) {\n console.error('[payload-mcp] error closing server:', err)\n }\n\n try {\n await payload.destroy()\n } catch (err) {\n console.error('[payload-mcp] error destroying payload:', err)\n }\n\n process.exit(0)\n }\n\n process.once('SIGINT', () => void shutdown())\n process.once('SIGTERM', () => void shutdown())\n process.stdin.once('close', () => void shutdown())\n}\n"],"names":["serveStdio","fileURLToPath","pathToFileURL","createPayloadRequest","getPayload","findConfig","loadEnv","getAuthorizedMCP","buildMcpServer","sanitizeMCPConfig","getPluginConfig","resolveProjectRoot","runMcpStdio","projectRoot","url","process","chdir","configPath","configModule","toString","config","default","loggerConfig","logger","destination","stderr","options","payload","cron","disableOnInit","pluginConfig","fallbackPlugin","Object","assign","slug","sanitizedOptions","plugins","push","overrideAccessEnv","env","PAYLOAD_MCP_OVERRIDE_ACCESS","overrideAccess","Error","NODE_ENV","headers","Headers","PAYLOAD_MCP_AUTHORIZATION","set","req","payloadAPI","authorizedMCP","stdioServer","onerror","err","console","error","isShuttingDown","shutdown","close","destroy","exit","once","stdin"],"mappings":"AAEA,6BAA6B,GAC7B,SAASA,UAAU,QAAQ,qCAAoC;AAC/D,SAASC,aAAa,EAAEC,aAAa,QAAQ,WAAU;AACvD,SAASC,oBAAoB,EAAEC,UAAU,QAAQ,UAAS;AAC1D,SAASC,UAAU,EAAEC,OAAO,QAAQ,eAAc;AAIlD,SAASC,gBAAgB,QAAQ,uBAAsB;AACvD,SAASC,cAAc,QAAQ,0BAAyB;AACxD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,kBAAkB,QAAQ,gCAA+B;AAElE;;;;;CAKC,GACD,OAAO,MAAMC,cAAc;IACzB,8EAA8E;IAC9E,+CAA+C;IAC/C,MAAMC,cAAcF,mBAAmBV,cAAc,YAAYa,GAAG;IACpE,IAAID,aAAa;QACfE,QAAQC,KAAK,CAACH;IAChB;IAEAP;IACA,MAAMW,aAAaZ;IACnB,MAAMa,eAAe,MAAM,MAAM,CAAChB,cAAce,YAAYE,QAAQ;IACpE,MAAMC,SAAU,MAAOF,CAAAA,aAAaG,OAAO,IAAIH,YAAW;IAE1D;;;;;;;;;;GAUC,GACD,MAAMI,eAA8CF;IACpD,IACEE,aAAaC,MAAM,IACnB,OAAOD,aAAaC,MAAM,KAAK,YAC/B,aAAaD,aAAaC,MAAM,EAChC;QACAD,aAAaC,MAAM,CAACC,WAAW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,eAAe;YAAE0C;YAAepB;YAAckB;QAAI,IAAI;QACzFI,SAAS,CAACC;YACR,0DAA0D;YAC1DC,QAAQC,KAAK,CAAC,+CAA+CF;QAC/D;IACF;IAEA,qFAAqF;IACrF,IAAIG,iBAAiB;IACrB,MAAMC,WAAW;QACf,IAAID,gBAAgB;YAClB;QACF;QACAA,iBAAiB;QAEjB,IAAI;YACF,MAAML,YAAYO,KAAK;QACzB,EAAE,OAAOL,KAAK;YACZC,QAAQC,KAAK,CAAC,uCAAuCF;QACvD;QAEA,IAAI;YACF,MAAM1B,QAAQgC,OAAO;QACvB,EAAE,OAAON,KAAK;YACZC,QAAQC,KAAK,CAAC,2CAA2CF;QAC3D;QAEAtC,QAAQ6C,IAAI,CAAC;IACf;IAEA7C,QAAQ8C,IAAI,CAAC,UAAU,IAAM,KAAKJ;IAClC1C,QAAQ8C,IAAI,CAAC,WAAW,IAAM,KAAKJ;IACnC1C,QAAQ+C,KAAK,CAACD,IAAI,CAAC,SAAS,IAAM,KAAKJ;AACzC,EAAC"}
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CallToolResult, ContentBlock, JsonSchemaType, McpServer, ResourceTemplate, ServerContext, StandardSchemaWithJSON, ToolAnnotations } from '@modelcontextprotocol/server';
1
+ import type { CallToolResult, ContentBlock, Implementation, JsonSchemaType, McpServerOptions, ResourceTemplate, ServerContext, StandardSchemaWithJSON, ToolAnnotations } from '@modelcontextprotocol/server';
2
2
  import type { AuthCollectionSlug, CollectionSlug, GlobalSlug, MaybePromise, PayloadRequest, SanitizedPermissions } from 'payload';
3
3
  import type { GetAuthorizedMCPArgs } from './endpoint/access.js';
4
4
  import type { MCPCollectionAuthToolName, MCPCollectionBuiltinName, MCPGlobalBuiltinName } from './mcp/builtinTools.js';
@@ -37,10 +37,10 @@ export type MCPAccessArgs = {
37
37
  req: PayloadRequest;
38
38
  };
39
39
  export type CollectionMCPAccessArgs = {
40
- collectionSlug: CollectionSlug;
40
+ slug: CollectionSlug;
41
41
  } & MCPAccessArgs;
42
42
  export type GlobalMCPAccessArgs = {
43
- globalSlug: GlobalSlug;
43
+ slug: GlobalSlug;
44
44
  } & MCPAccessArgs;
45
45
  export type ToolHandlerArgs<TSchema = undefined> = {
46
46
  authorizedMCP: AuthorizedMCP;
@@ -49,10 +49,10 @@ export type ToolHandlerArgs<TSchema = undefined> = {
49
49
  serverContext: ServerContext;
50
50
  };
51
51
  export type CollectionToolHandlerArgs<TSchema = undefined> = {
52
- collectionSlug: CollectionSlug;
52
+ slug: CollectionSlug;
53
53
  } & ToolHandlerArgs<TSchema>;
54
54
  export type GlobalToolHandlerArgs<TSchema = undefined> = {
55
- globalSlug: GlobalSlug;
55
+ slug: GlobalSlug;
56
56
  } & ToolHandlerArgs<TSchema>;
57
57
  export type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {
58
58
  /**
@@ -223,9 +223,24 @@ export type MCPPluginConfig = {
223
223
  afterToolCall?: MCPAfterToolCallHook[];
224
224
  };
225
225
  mcp?: {
226
+ /**
227
+ * Largest HTTP request body, in bytes, that the MCP endpoint accepts. Larger requests
228
+ * are answered with `413`. Base64 file uploads count toward this limit.
229
+ *
230
+ * @default 4194304 (4 MiB, the MCP SDK default)
231
+ */
232
+ maxRequestBodySize?: number;
226
233
  serverOptions?: MCPServerOptions;
227
234
  verboseLogs?: boolean;
228
235
  };
236
+ /**
237
+ * How MCP clients sign in. MCP requests without an authenticated user get a `401` that points
238
+ * to the protected resource metadata (RFC 9728). Set to `false` to only accept API keys and
239
+ * anonymous requests.
240
+ *
241
+ * @default { type: 'builtin' }
242
+ */
243
+ oauth?: false | MCPOAuthConfig;
229
244
  /**
230
245
  * Replace the default MCP authorization resolver.
231
246
  *
@@ -240,12 +255,85 @@ export type MCPPluginConfig = {
240
255
  /** Cross-cutting tools (not scoped to any collection or global). */
241
256
  tools?: MCPTopLevelToolsMap;
242
257
  };
258
+ export type MCPOAuthConfig = MCPBuiltinOAuthConfig | MCPExternalOAuthConfig;
259
+ /**
260
+ * This Payload app is the authorization server. Users sign in to the admin panel and allow the
261
+ * MCP client, which then gets an access token for them.
262
+ */
263
+ export type MCPBuiltinOAuthConfig = {
264
+ /**
265
+ * Creates the tokens the MCP client gets when the user clicks Allow. `req` is the user's own
266
+ * browser request, so `req.user` is the user who allowed it. Pass `authenticate` too if
267
+ * Payload's auth strategies don't accept the access token.
268
+ *
269
+ * @default a Payload login token for that user, with a refresh token when the collection uses sessions
270
+ */
271
+ issueToken?: (args: {
272
+ req: PayloadRequest;
273
+ }) => MaybePromise<MCPOAuthTokens>;
274
+ /**
275
+ * Trades a refresh token from `issueToken`, or from an earlier refresh, for new tokens. Return
276
+ * `null` when it's no longer valid, and the client sends the user through sign-in again. `req`
277
+ * is the MCP client's request, without a user. Only used together with `issueToken`.
278
+ *
279
+ * OAuth requires noticing copied refresh tokens: return a new refresh token every time, and
280
+ * revoke the tokens when an already used refresh token comes back.
281
+ */
282
+ refreshToken?: (args: {
283
+ refreshToken: string;
284
+ req: PayloadRequest;
285
+ }) => MaybePromise<MCPOAuthTokens | null>;
286
+ type: 'builtin';
287
+ } & MCPOAuthSharedConfig;
288
+ export type MCPOAuthTokens = {
289
+ accessToken: string;
290
+ /** Seconds until the access token expires. */
291
+ expiresIn?: number;
292
+ /** Lets the client get new tokens without the user, through `refreshToken`. */
293
+ refreshToken?: string;
294
+ };
295
+ /** Another service, e.g. your identity provider, is the authorization server. */
296
+ export type MCPExternalOAuthConfig = {
297
+ /**
298
+ * The authorization servers that issue access tokens for MCP clients. Clients require each one
299
+ * to exactly match the `issuer` in that server's metadata, so pass a function when the exact
300
+ * value is only known at runtime, e.g. from the server's OpenID configuration or per host.
301
+ */
302
+ authorizationServers: ((args: {
303
+ req: PayloadRequest;
304
+ }) => MaybePromise<string[]>) | string[];
305
+ /**
306
+ * Scopes MCP clients should request, e.g. `['openid', 'email', 'profile']`. Without them,
307
+ * clients request none, which some authorization servers reject or answer with a token that
308
+ * doesn't identify the user.
309
+ */
310
+ scopes?: string[];
311
+ type: 'external';
312
+ } & MCPOAuthSharedConfig;
313
+ type MCPOAuthSharedConfig = {
314
+ /**
315
+ * Called on MCP requests with a bearer token that Payload's auth strategies didn't accept.
316
+ * Return the Payload user, including its `collection`, or `null` to answer with the OAuth challenge.
317
+ */
318
+ authenticate?: (args: {
319
+ req: PayloadRequest;
320
+ token: string;
321
+ }) => MaybePromise<PayloadRequest['user']>;
322
+ /**
323
+ * The URL clients call to reach the MCP endpoint.
324
+ *
325
+ * @default the absolute URL of `/api/mcp`, based on `serverURL` or the request URL
326
+ */
327
+ resource?: string;
328
+ };
243
329
  export type SanitizedMCPPluginConfig = {
244
330
  items: MCPItem[];
331
+ /** `undefined` when OAuth is turned off. */
332
+ oauth?: MCPOAuthConfig;
245
333
  } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>;
246
334
  export type MCPServerOptions = {
247
- options?: ConstructorParameters<typeof McpServer>[1];
248
- serverInfo?: Partial<ConstructorParameters<typeof McpServer>[0]>;
335
+ options?: McpServerOptions;
336
+ serverInfo?: Partial<Implementation>;
249
337
  };
250
338
  /**
251
339
  * One MCP primitive plus the metadata needed for config-driven filtering and
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,cAAc,EACd,SAAS,EACT,gBAAgB,EAChB,aAAa,EACb,sBAAsB,EACtB,eAAe,EAChB,MAAM,8BAA8B,CAAA;AACrC,OAAO,KAAK,EACV,kBAAkB,EAClB,cAAc,EACd,UAAU,EACV,YAAY,EACZ,cAAc,EACd,oBAAoB,EACrB,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAChE,OAAO,KAAK,EACV,yBAAyB,EACzB,wBAAwB,EACxB,oBAAoB,EACrB,MAAM,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B,iBAAiB,GACjB,aAAa,CAAA;AAEjB;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,OAAO,EAAE,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;CACxB,CAAA"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CallToolResult,\n ContentBlock,\n JsonSchemaType,\n McpServer,\n ResourceTemplate,\n ServerContext,\n StandardSchemaWithJSON,\n ToolAnnotations,\n} from '@modelcontextprotocol/server'\nimport type {\n AuthCollectionSlug,\n CollectionSlug,\n GlobalSlug,\n MaybePromise,\n PayloadRequest,\n SanitizedPermissions,\n} from 'payload'\n\nimport type { GetAuthorizedMCPArgs } from './endpoint/access.js'\nimport type {\n MCPCollectionAuthToolName,\n MCPCollectionBuiltinName,\n MCPGlobalBuiltinName,\n} from './mcp/builtinTools.js'\n\nexport type { MCPCollectionAuthToolName, MCPCollectionBuiltinName, MCPGlobalBuiltinName }\n\n/** Re-exported from `@modelcontextprotocol/server` — common MCP types used in plugin config. */\nexport type { JsonSchemaType, StandardSchemaWithJSON, ToolAnnotations }\n\n/**\n * What a tool's `input` (or a prompt's `argsSchema`) can be — either a raw\n * JSON Schema 2020-12 literal, or a Standard Schema instance (Zod, Valibot, …).\n * Raw schemas may omit `$schema`; when present it must declare the 2020-12 dialect.\n */\nexport type ToolInputSchema = JsonSchemaType | StandardSchemaWithJSON\n\nexport type MCPToolResponse = {\n content: ContentBlock[]\n /**\n * If available, return the document fetched within the\n * mcp tool. This is threaded as an additional argument to\n * overrideResponse functions and stripped before going on the wire.\n */\n doc?: Record<string, unknown>\n} & Pick<CallToolResult, '_meta' | 'isError' | 'structuredContent'>\n\nexport type MCPResponseOverride = (\n response: MCPToolResponse,\n doc: Record<string, unknown>,\n req: PayloadRequest,\n) => MCPToolResponse\n\nexport type MCPAfterToolCallHook = (args: {\n input: unknown\n req: PayloadRequest\n response: MCPToolResponse\n toolName: string\n}) => MaybePromise<MCPToolResponse>\n\n/**\n * The handler's `input` type. A specific Standard Schema (Zod, Valibot, …) gets\n * its inferred output; anything else falls back to `Record<string, unknown>`.\n */\nexport type TypedInput<TSchema> = TSchema extends StandardSchemaWithJSON\n ? StandardSchemaWithJSON extends TSchema\n ? Record<string, unknown>\n : StandardSchemaWithJSON.InferOutput<TSchema>\n : Record<string, unknown>\n\nexport type MCPAccessArgs = {\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}\n\nexport type CollectionMCPAccessArgs = {\n collectionSlug: CollectionSlug\n} & MCPAccessArgs\n\nexport type GlobalMCPAccessArgs = {\n globalSlug: GlobalSlug\n} & MCPAccessArgs\n\nexport type ToolHandlerArgs<TSchema = undefined> = {\n authorizedMCP: AuthorizedMCP\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type CollectionToolHandlerArgs<TSchema = undefined> = {\n collectionSlug: CollectionSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type GlobalToolHandlerArgs<TSchema = undefined> = {\n globalSlug: GlobalSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {\n /**\n * Runs while authorizing each MCP request, before the tool is advertised or called. Return\n * `false` to make the tool unavailable for that request. This is skipped when `overrideAccess`\n * is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description: string\n handler: (args: ToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n /**\n * Override the return value of the tool handler\n */\n overrideResponse?: MCPResponseOverride\n}\n\nexport type CollectionTool<\n TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined,\n> = {\n /**\n * Runs while authorizing each MCP request for this collection. Return `false` to reject calls\n * to this tool for the collection. The shared tool is not advertised when no collections allow\n * it, but can remain advertised when it is available for another collection. This is skipped\n * when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: CollectionToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n} & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\nexport type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> =\n {\n /**\n * Runs while authorizing each MCP request for this global. Return `false` to reject calls to\n * this tool for the global. The shared tool is not advertised when no globals allow it, but\n * can remain advertised when it is available for another global. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: GlobalToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n } & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\n/**\n * Configures (or disables) a built-in tool without replacing it.\n * `handler?: never` prevents a full `CollectionTool`/`GlobalTool` (which has a\n * required handler) from being silently accepted at a built-in key slot.\n */\nexport type MCPBuiltInCollectionToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this collection. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\nexport type MCPBuiltInGlobalToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this global. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\n/**\n * Value at a custom (non-built-in) tool key. Either the tool itself, or `false`\n * to disable it (useful when one plugin defines a custom tool and another\n * wants to opt out per-collection).\n */\nexport type MCPTopLevelToolEntry = Tool\n\nexport type MCPCollectionToolsMap = {\n [customToolName: string]: boolean | CollectionTool | MCPBuiltInCollectionToolOverride | undefined\n} & {\n [K in MCPCollectionBuiltinName]?: false | MCPBuiltInCollectionToolOverride\n}\n\nexport type MCPAuthCollectionToolsMap = {\n [K in MCPCollectionAuthToolName]?: MCPBuiltInCollectionToolOverride | true\n} & MCPCollectionToolsMap\n\n/** Auth-enabled collections get auth-tool name autocomplete; others get CRUD-only. */\nexport type MCPToolsMapForCollection<Slug extends CollectionSlug> = Slug extends AuthCollectionSlug\n ? MCPAuthCollectionToolsMap\n : MCPCollectionToolsMap\n\nexport type MCPGlobalToolsMap = {\n [customToolName: string]: boolean | GlobalTool | MCPBuiltInGlobalToolOverride | undefined\n} & {\n [K in MCPGlobalBuiltinName]?: false | MCPBuiltInGlobalToolOverride\n}\n\nexport type MCPTopLevelToolsMap = Record<string, Tool>\n\nexport type PromptHandlerArgs<TSchema = undefined> = {\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type Prompt<TSchema extends ToolInputSchema = ToolInputSchema> = {\n /**\n * Runs while authorizing each MCP request, before the prompt is advertised or used. Return\n * `false` to make the prompt unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n argsSchema: TSchema\n description: string\n handler: (args: PromptHandlerArgs<TSchema>) => MaybePromise<{\n messages: Array<{ content: { text: string; type: 'text' }; role: 'assistant' | 'user' }>\n }>\n title: string\n}\n\nexport type ResourceHandlerArgs = {\n /** Variables extracted from a `ResourceTemplate` URI. Empty for static-URI resources. */\n params: Record<string, string>\n req: PayloadRequest\n serverContext: ServerContext\n uri: URL\n}\n\nexport type Resource = {\n /**\n * Runs while authorizing each MCP request, before the resource is advertised or read. Return\n * `false` to make the resource unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n description: string\n handler: (args: ResourceHandlerArgs) => MaybePromise<{\n contents: Array<{ text: string; uri: string }>\n }>\n mimeType: string\n title: string\n uri: ResourceTemplate | string\n}\n\nexport type MCPPluginCollectionConfig<TSlug extends CollectionSlug> = {\n description?: string\n /** Fallback for built-in tools that don't set their own `overrideResponse`. */\n overrideResponse?: MCPResponseOverride\n tools?: MCPToolsMapForCollection<TSlug>\n}\n\nexport type MCPPluginGlobalConfig = {\n description?: string\n overrideResponse?: MCPResponseOverride\n tools?: MCPGlobalToolsMap\n}\n\n/**\n * The user-facing config shape passed to `mcpPlugin({ ... })`. Tools, prompts,\n * resources, and per-collection/global tool maps live in their own nested\n * fields. `sanitizeMCPConfig` flattens those into `items` and applies defaults\n * to produce a `SanitizedMCPPluginConfig` — the form every internal consumer\n * actually works with.\n */\nexport type MCPPluginConfig = {\n collections?: {\n [Slug in CollectionSlug]?: MCPPluginCollectionConfig<Slug>\n }\n /** Skip MCP endpoint registration. */\n disabled?: boolean\n globals?: {\n [Slug in GlobalSlug]?: MCPPluginGlobalConfig\n }\n hooks?: {\n /** Transform a tool response after its handler returns */\n afterToolCall?: MCPAfterToolCallHook[]\n }\n mcp?: {\n serverOptions?: MCPServerOptions\n verboseLogs?: boolean\n }\n /**\n * Replace the default MCP authorization resolver.\n *\n * This hook replaces the default authentication flow. It must set `req.user` to the\n * authenticated Payload user, or to `null` for an anonymous caller, before returning.\n */\n overrideGetAuthorizedMCP?: (\n args: {\n pluginConfig: SanitizedMCPPluginConfig\n } & GetAuthorizedMCPArgs,\n ) => MaybePromise<AuthorizedMCP>\n prompts?: Record<string, Prompt>\n resources?: Record<string, Resource>\n /** Cross-cutting tools (not scoped to any collection or global). */\n tools?: MCPTopLevelToolsMap\n}\n\nexport type SanitizedMCPPluginConfig = {\n items: MCPItem[]\n} & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>\n\nexport type MCPServerOptions = {\n options?: ConstructorParameters<typeof McpServer>[1]\n serverInfo?: Partial<ConstructorParameters<typeof McpServer>[0]>\n}\n\n/**\n * One MCP primitive plus the metadata needed for config-driven filtering and\n * registration.\n *\n * - `configKey`: the config identifier, e.g. `find` or `echo`.\n * - `mcpName`: the MCP wire name, e.g. `findDocuments` or `echo`.\n * - `label`: human-readable display text.\n */\nexport type MCPItemBase = {\n configKey: string\n label: string\n mcpName: string\n}\n\nexport type CollectionMCPItem = {\n collectionSlug: CollectionSlug\n tool: CollectionTool\n type: 'collectionTool'\n} & MCPItemBase\n\nexport type GlobalMCPItem = {\n globalSlug: GlobalSlug\n tool: GlobalTool\n type: 'globalTool'\n} & MCPItemBase\n\nexport type MCPItem =\n | ({\n prompt: Prompt\n type: 'prompt'\n } & MCPItemBase)\n | ({\n resource: Resource\n type: 'resource'\n } & MCPItemBase)\n | ({\n tool: Tool\n type: 'tool'\n } & MCPItemBase)\n | CollectionMCPItem\n | GlobalMCPItem\n\n/**\n * The MCP items and access mode authorized for this request. The authenticated user is available\n * as `req.user`.\n */\nexport type AuthorizedMCP = {\n items: MCPItem[]\n overrideAccess: boolean\n}\n"],"names":[],"mappings":"AAgWA;;;CAGC,GACD,WAGC"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CallToolResult,\n ContentBlock,\n Implementation,\n JsonSchemaType,\n McpServerOptions,\n ResourceTemplate,\n ServerContext,\n StandardSchemaWithJSON,\n ToolAnnotations,\n} from '@modelcontextprotocol/server'\nimport type {\n AuthCollectionSlug,\n CollectionSlug,\n GlobalSlug,\n MaybePromise,\n PayloadRequest,\n SanitizedPermissions,\n} from 'payload'\n\nimport type { GetAuthorizedMCPArgs } from './endpoint/access.js'\nimport type {\n MCPCollectionAuthToolName,\n MCPCollectionBuiltinName,\n MCPGlobalBuiltinName,\n} from './mcp/builtinTools.js'\n\nexport type { MCPCollectionAuthToolName, MCPCollectionBuiltinName, MCPGlobalBuiltinName }\n\n/** Re-exported from `@modelcontextprotocol/server` — common MCP types used in plugin config. */\nexport type { JsonSchemaType, StandardSchemaWithJSON, ToolAnnotations }\n\n/**\n * What a tool's `input` (or a prompt's `argsSchema`) can be — either a raw\n * JSON Schema 2020-12 literal, or a Standard Schema instance (Zod, Valibot, …).\n * Raw schemas may omit `$schema`; when present it must declare the 2020-12 dialect.\n */\nexport type ToolInputSchema = JsonSchemaType | StandardSchemaWithJSON\n\nexport type MCPToolResponse = {\n content: ContentBlock[]\n /**\n * If available, return the document fetched within the\n * mcp tool. This is threaded as an additional argument to\n * overrideResponse functions and stripped before going on the wire.\n */\n doc?: Record<string, unknown>\n} & Pick<CallToolResult, '_meta' | 'isError' | 'structuredContent'>\n\nexport type MCPResponseOverride = (\n response: MCPToolResponse,\n doc: Record<string, unknown>,\n req: PayloadRequest,\n) => MCPToolResponse\n\nexport type MCPAfterToolCallHook = (args: {\n input: unknown\n req: PayloadRequest\n response: MCPToolResponse\n toolName: string\n}) => MaybePromise<MCPToolResponse>\n\n/**\n * The handler's `input` type. A specific Standard Schema (Zod, Valibot, …) gets\n * its inferred output; anything else falls back to `Record<string, unknown>`.\n */\nexport type TypedInput<TSchema> = TSchema extends StandardSchemaWithJSON\n ? StandardSchemaWithJSON extends TSchema\n ? Record<string, unknown>\n : StandardSchemaWithJSON.InferOutput<TSchema>\n : Record<string, unknown>\n\nexport type MCPAccessArgs = {\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}\n\nexport type CollectionMCPAccessArgs = {\n slug: CollectionSlug\n} & MCPAccessArgs\n\nexport type GlobalMCPAccessArgs = {\n slug: GlobalSlug\n} & MCPAccessArgs\n\nexport type ToolHandlerArgs<TSchema = undefined> = {\n authorizedMCP: AuthorizedMCP\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type CollectionToolHandlerArgs<TSchema = undefined> = {\n slug: CollectionSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type GlobalToolHandlerArgs<TSchema = undefined> = {\n slug: GlobalSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {\n /**\n * Runs while authorizing each MCP request, before the tool is advertised or called. Return\n * `false` to make the tool unavailable for that request. This is skipped when `overrideAccess`\n * is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description: string\n handler: (args: ToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n /**\n * Override the return value of the tool handler\n */\n overrideResponse?: MCPResponseOverride\n}\n\nexport type CollectionTool<\n TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined,\n> = {\n /**\n * Runs while authorizing each MCP request for this collection. Return `false` to reject calls\n * to this tool for the collection. The shared tool is not advertised when no collections allow\n * it, but can remain advertised when it is available for another collection. This is skipped\n * when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: CollectionToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n} & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\nexport type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> =\n {\n /**\n * Runs while authorizing each MCP request for this global. Return `false` to reject calls to\n * this tool for the global. The shared tool is not advertised when no globals allow it, but\n * can remain advertised when it is available for another global. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: GlobalToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n } & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\n/**\n * Configures (or disables) a built-in tool without replacing it.\n * `handler?: never` prevents a full `CollectionTool`/`GlobalTool` (which has a\n * required handler) from being silently accepted at a built-in key slot.\n */\nexport type MCPBuiltInCollectionToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this collection. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\nexport type MCPBuiltInGlobalToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this global. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\n/**\n * Value at a custom (non-built-in) tool key. Either the tool itself, or `false`\n * to disable it (useful when one plugin defines a custom tool and another\n * wants to opt out per-collection).\n */\nexport type MCPTopLevelToolEntry = Tool\n\nexport type MCPCollectionToolsMap = {\n [customToolName: string]: boolean | CollectionTool | MCPBuiltInCollectionToolOverride | undefined\n} & {\n [K in MCPCollectionBuiltinName]?: false | MCPBuiltInCollectionToolOverride\n}\n\nexport type MCPAuthCollectionToolsMap = {\n [K in MCPCollectionAuthToolName]?: MCPBuiltInCollectionToolOverride | true\n} & MCPCollectionToolsMap\n\n/** Auth-enabled collections get auth-tool name autocomplete; others get CRUD-only. */\nexport type MCPToolsMapForCollection<Slug extends CollectionSlug> = Slug extends AuthCollectionSlug\n ? MCPAuthCollectionToolsMap\n : MCPCollectionToolsMap\n\nexport type MCPGlobalToolsMap = {\n [customToolName: string]: boolean | GlobalTool | MCPBuiltInGlobalToolOverride | undefined\n} & {\n [K in MCPGlobalBuiltinName]?: false | MCPBuiltInGlobalToolOverride\n}\n\nexport type MCPTopLevelToolsMap = Record<string, Tool>\n\nexport type PromptHandlerArgs<TSchema = undefined> = {\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type Prompt<TSchema extends ToolInputSchema = ToolInputSchema> = {\n /**\n * Runs while authorizing each MCP request, before the prompt is advertised or used. Return\n * `false` to make the prompt unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n argsSchema: TSchema\n description: string\n handler: (args: PromptHandlerArgs<TSchema>) => MaybePromise<{\n messages: Array<{ content: { text: string; type: 'text' }; role: 'assistant' | 'user' }>\n }>\n title: string\n}\n\nexport type ResourceHandlerArgs = {\n /** Variables extracted from a `ResourceTemplate` URI. Empty for static-URI resources. */\n params: Record<string, string>\n req: PayloadRequest\n serverContext: ServerContext\n uri: URL\n}\n\nexport type Resource = {\n /**\n * Runs while authorizing each MCP request, before the resource is advertised or read. Return\n * `false` to make the resource unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n description: string\n handler: (args: ResourceHandlerArgs) => MaybePromise<{\n contents: Array<{ text: string; uri: string }>\n }>\n mimeType: string\n title: string\n uri: ResourceTemplate | string\n}\n\nexport type MCPPluginCollectionConfig<TSlug extends CollectionSlug> = {\n description?: string\n /** Fallback for built-in tools that don't set their own `overrideResponse`. */\n overrideResponse?: MCPResponseOverride\n tools?: MCPToolsMapForCollection<TSlug>\n}\n\nexport type MCPPluginGlobalConfig = {\n description?: string\n overrideResponse?: MCPResponseOverride\n tools?: MCPGlobalToolsMap\n}\n\n/**\n * The user-facing config shape passed to `mcpPlugin({ ... })`. Tools, prompts,\n * resources, and per-collection/global tool maps live in their own nested\n * fields. `sanitizeMCPConfig` flattens those into `items` and applies defaults\n * to produce a `SanitizedMCPPluginConfig` — the form every internal consumer\n * actually works with.\n */\nexport type MCPPluginConfig = {\n collections?: {\n [Slug in CollectionSlug]?: MCPPluginCollectionConfig<Slug>\n }\n /** Skip MCP endpoint registration. */\n disabled?: boolean\n globals?: {\n [Slug in GlobalSlug]?: MCPPluginGlobalConfig\n }\n hooks?: {\n /** Transform a tool response after its handler returns */\n afterToolCall?: MCPAfterToolCallHook[]\n }\n mcp?: {\n /**\n * Largest HTTP request body, in bytes, that the MCP endpoint accepts. Larger requests\n * are answered with `413`. Base64 file uploads count toward this limit.\n *\n * @default 4194304 (4 MiB, the MCP SDK default)\n */\n maxRequestBodySize?: number\n serverOptions?: MCPServerOptions\n verboseLogs?: boolean\n }\n /**\n * How MCP clients sign in. MCP requests without an authenticated user get a `401` that points\n * to the protected resource metadata (RFC 9728). Set to `false` to only accept API keys and\n * anonymous requests.\n *\n * @default { type: 'builtin' }\n */\n oauth?: false | MCPOAuthConfig\n /**\n * Replace the default MCP authorization resolver.\n *\n * This hook replaces the default authentication flow. It must set `req.user` to the\n * authenticated Payload user, or to `null` for an anonymous caller, before returning.\n */\n overrideGetAuthorizedMCP?: (\n args: {\n pluginConfig: SanitizedMCPPluginConfig\n } & GetAuthorizedMCPArgs,\n ) => MaybePromise<AuthorizedMCP>\n prompts?: Record<string, Prompt>\n resources?: Record<string, Resource>\n /** Cross-cutting tools (not scoped to any collection or global). */\n tools?: MCPTopLevelToolsMap\n}\n\nexport type MCPOAuthConfig = MCPBuiltinOAuthConfig | MCPExternalOAuthConfig\n\n/**\n * This Payload app is the authorization server. Users sign in to the admin panel and allow the\n * MCP client, which then gets an access token for them.\n */\nexport type MCPBuiltinOAuthConfig = {\n /**\n * Creates the tokens the MCP client gets when the user clicks Allow. `req` is the user's own\n * browser request, so `req.user` is the user who allowed it. Pass `authenticate` too if\n * Payload's auth strategies don't accept the access token.\n *\n * @default a Payload login token for that user, with a refresh token when the collection uses sessions\n */\n issueToken?: (args: { req: PayloadRequest }) => MaybePromise<MCPOAuthTokens>\n /**\n * Trades a refresh token from `issueToken`, or from an earlier refresh, for new tokens. Return\n * `null` when it's no longer valid, and the client sends the user through sign-in again. `req`\n * is the MCP client's request, without a user. Only used together with `issueToken`.\n *\n * OAuth requires noticing copied refresh tokens: return a new refresh token every time, and\n * revoke the tokens when an already used refresh token comes back.\n */\n refreshToken?: (args: {\n refreshToken: string\n req: PayloadRequest\n }) => MaybePromise<MCPOAuthTokens | null>\n type: 'builtin'\n} & MCPOAuthSharedConfig\n\nexport type MCPOAuthTokens = {\n accessToken: string\n /** Seconds until the access token expires. */\n expiresIn?: number\n /** Lets the client get new tokens without the user, through `refreshToken`. */\n refreshToken?: string\n}\n\n/** Another service, e.g. your identity provider, is the authorization server. */\nexport type MCPExternalOAuthConfig = {\n /**\n * The authorization servers that issue access tokens for MCP clients. Clients require each one\n * to exactly match the `issuer` in that server's metadata, so pass a function when the exact\n * value is only known at runtime, e.g. from the server's OpenID configuration or per host.\n */\n authorizationServers: ((args: { req: PayloadRequest }) => MaybePromise<string[]>) | string[]\n /**\n * Scopes MCP clients should request, e.g. `['openid', 'email', 'profile']`. Without them,\n * clients request none, which some authorization servers reject or answer with a token that\n * doesn't identify the user.\n */\n scopes?: string[]\n type: 'external'\n} & MCPOAuthSharedConfig\n\ntype MCPOAuthSharedConfig = {\n /**\n * Called on MCP requests with a bearer token that Payload's auth strategies didn't accept.\n * Return the Payload user, including its `collection`, or `null` to answer with the OAuth challenge.\n */\n authenticate?: (args: {\n req: PayloadRequest\n token: string\n }) => MaybePromise<PayloadRequest['user']>\n /**\n * The URL clients call to reach the MCP endpoint.\n *\n * @default the absolute URL of `/api/mcp`, based on `serverURL` or the request URL\n */\n resource?: string\n}\n\nexport type SanitizedMCPPluginConfig = {\n items: MCPItem[]\n /** `undefined` when OAuth is turned off. */\n oauth?: MCPOAuthConfig\n} & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>\n\nexport type MCPServerOptions = {\n options?: McpServerOptions\n serverInfo?: Partial<Implementation>\n}\n\n/**\n * One MCP primitive plus the metadata needed for config-driven filtering and\n * registration.\n *\n * - `configKey`: the config identifier, e.g. `find` or `echo`.\n * - `mcpName`: the MCP wire name, e.g. `findDocuments` or `echo`.\n * - `label`: human-readable display text.\n */\nexport type MCPItemBase = {\n configKey: string\n label: string\n mcpName: string\n}\n\nexport type CollectionMCPItem = {\n collectionSlug: CollectionSlug\n tool: CollectionTool\n type: 'collectionTool'\n} & MCPItemBase\n\nexport type GlobalMCPItem = {\n globalSlug: GlobalSlug\n tool: GlobalTool\n type: 'globalTool'\n} & MCPItemBase\n\nexport type MCPItem =\n | ({\n prompt: Prompt\n type: 'prompt'\n } & MCPItemBase)\n | ({\n resource: Resource\n type: 'resource'\n } & MCPItemBase)\n | ({\n tool: Tool\n type: 'tool'\n } & MCPItemBase)\n | CollectionMCPItem\n | GlobalMCPItem\n\n/**\n * The MCP items and access mode authorized for this request. The authenticated user is available\n * as `req.user`.\n */\nexport type AuthorizedMCP = {\n items: MCPItem[]\n overrideAccess: boolean\n}\n"],"names":[],"mappings":"AA0bA;;;CAGC,GACD,WAGC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/toStandardSchema.ts"],"sourcesContent":["import { fromJsonSchema, type StandardSchemaWithJSON } from '@modelcontextprotocol/server'\n\nimport type { ToolInputSchema } from '../types.js'\n\n/** Normalize a tool/prompt input to a Standard Schema. Raw JSON Schema gets wrapped; Standard Schema instances pass through. */\nexport const toStandardSchema = (schema: ToolInputSchema): StandardSchemaWithJSON =>\n typeof schema === 'object' && schema !== null && '~standard' in schema\n ? (schema as StandardSchemaWithJSON)\n : fromJsonSchema(schema)\n"],"names":["fromJsonSchema","toStandardSchema","schema"],"mappings":"AAAA,SAASA,cAAc,QAAqC,+BAA8B;AAI1F,8HAA8H,GAC9H,OAAO,MAAMC,mBAAmB,CAACC,SAC/B,OAAOA,WAAW,YAAYA,WAAW,QAAQ,eAAeA,SAC3DA,SACDF,eAAeE,QAAO"}
1
+ {"version":3,"sources":["../../src/utils/toStandardSchema.ts"],"sourcesContent":["import { fromJsonSchema, type StandardSchemaWithJSON } from '@modelcontextprotocol/server'\n\nimport type { ToolInputSchema } from '../types.js'\n\n/** Normalize a tool/prompt input to a Standard Schema. Raw JSON Schema gets wrapped; Standard Schema instances pass through. */\nexport const toStandardSchema = (schema: ToolInputSchema): StandardSchemaWithJSON =>\n typeof schema === 'object' && schema !== null && '~standard' in schema\n ? schema\n : fromJsonSchema(schema)\n"],"names":["fromJsonSchema","toStandardSchema","schema"],"mappings":"AAAA,SAASA,cAAc,QAAqC,+BAA8B;AAI1F,8HAA8H,GAC9H,OAAO,MAAMC,mBAAmB,CAACC,SAC/B,OAAOA,WAAW,YAAYA,WAAW,QAAQ,eAAeA,SAC5DA,SACAF,eAAeE,QAAO"}
package/package.json CHANGED
@@ -1,17 +1,12 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "4.0.0-internal.e7d4ebc",
3
+ "version": "4.0.0-internal.ee5d8bd",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
- "plugin",
7
6
  "mcp",
8
- "model context protocol"
7
+ "model context protocol",
8
+ "plugin"
9
9
  ],
10
- "repository": {
11
- "type": "git",
12
- "url": "https://github.com/payloadcms/payload.git",
13
- "directory": "packages/plugin-mcp"
14
- },
15
10
  "license": "MIT",
16
11
  "author": "Payload <dev@payloadcms.com> (https://payloadcms.com)",
17
12
  "maintainers": [
@@ -21,7 +16,22 @@
21
16
  "url": "https://payloadcms.com"
22
17
  }
23
18
  ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/payloadcms/payload.git",
22
+ "directory": "packages/plugin-mcp"
23
+ },
24
+ "bin": {
25
+ "payload-mcp": "./bin.js"
26
+ },
27
+ "files": [
28
+ "src",
29
+ "dist",
30
+ "bin.js"
31
+ ],
24
32
  "type": "module",
33
+ "main": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
25
35
  "exports": {
26
36
  ".": {
27
37
  "import": "./dist/index.js",
@@ -44,30 +54,17 @@
44
54
  "default": "./dist/exports/internal.js"
45
55
  }
46
56
  },
47
- "main": "./dist/index.js",
48
- "types": "./dist/index.d.ts",
49
- "bin": {
50
- "payload-mcp": "./bin.js"
51
- },
52
- "files": [
53
- "src",
54
- "dist",
55
- "bin.js"
56
- ],
57
57
  "dependencies": {
58
- "@modelcontextprotocol/server": "2.0.0-beta.3",
59
- "tsx": "4.22.4",
60
- "zod": "^4.2.0"
58
+ "@modelcontextprotocol/server": "2.3.1",
59
+ "tsx": "4.23.15"
61
60
  },
62
61
  "devDependencies": {
63
- "@payloadcms/eslint-config": "3.28.0",
64
- "payload": "4.0.0-internal.e7d4ebc"
62
+ "payload": "4.0.0-internal.ee5d8bd"
65
63
  },
66
64
  "peerDependencies": {
67
- "payload": "4.0.0-internal.e7d4ebc"
65
+ "payload": "4.0.0-internal.ee5d8bd"
68
66
  },
69
67
  "//deps_notes": {
70
- "zod": "zod is a hard dependency of @modelcontextprotocol/server, thus we can safely use it without it impacting bundle size. Make extra sure the zod version here matches exactly what's defined in the dependencies of @modelcontextprotocol/server to avoid duplicate versions being installed.",
71
68
  "tsx": "Required by the `bin.js` stdio mcp. Keep the version pinned to whatever `payload` ships to avoid duplicate installs."
72
69
  },
73
70
  "homepage:": "https://payloadcms.com",
@@ -77,9 +74,7 @@
77
74
  "build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
78
75
  "build:types": "tsc --emitDeclarationOnly --outDir dist",
79
76
  "clean": "rimraf {dist,*.tsbuildinfo}",
80
- "copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
81
- "lint": "eslint .",
82
- "lint:fix": "eslint . --fix",
77
+ "copyfiles": "copyfiles -u 1 -e \"**/*.spec.*\" \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
83
78
  "pack:plugin": "pnpm build && pnpm pack"
84
79
  }
85
80
  }
@@ -1,6 +1,6 @@
1
1
  import type { PayloadRequest, SanitizedPermissions } from 'payload'
2
2
 
3
- import { getAccessResults, UnauthorizedError } from 'payload'
3
+ import { executeAuthStrategies, getAccessResults, UnauthorizedError } from 'payload'
4
4
 
5
5
  import type { AuthorizedMCP, MCPItem } from '../types.js'
6
6
 
@@ -34,9 +34,18 @@ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<Authorize
34
34
  const hasAuthorization = headers.has('Authorization')
35
35
 
36
36
  headers.set('DisableAutologin', 'true')
37
- req.user = (await req.payload.auth({ headers, req })).user
37
+ // Not `payload.auth()`, which also computes permissions that filterMCPItems computes anyway
38
+ req.user = (await executeAuthStrategies({ headers, payload: req.payload, req })).user
39
+
40
+ // Only bearer tokens that no auth strategy accepted reach the hook, e.g. an OAuth access token.
41
+ // API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
42
+ const bearerToken = headers.get('Authorization')?.match(/^Bearer (.+)$/)?.[1]
43
+ if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
44
+ req.user = await pluginConfig.oauth.authenticate({ req, token: bearerToken })
45
+ }
38
46
 
39
- if (hasAuthorization && !req.user) {
47
+ // With OAuth, the endpoint answers with a challenge that starts the client's sign-in
48
+ if (hasAuthorization && !req.user && !pluginConfig.oauth) {
40
49
  throw new UnauthorizedError(req.t)
41
50
  }
42
51
  }
@@ -95,12 +104,11 @@ const checkItemAccess = async ({
95
104
  case 'collectionTool':
96
105
  return (
97
106
  !item.tool.access ||
98
- (await item.tool.access({ collectionSlug: item.collectionSlug, permissions, req }))
107
+ (await item.tool.access({ slug: item.collectionSlug, permissions, req }))
99
108
  )
100
109
  case 'globalTool':
101
110
  return (
102
- !item.tool.access ||
103
- (await item.tool.access({ globalSlug: item.globalSlug, permissions, req }))
111
+ !item.tool.access || (await item.tool.access({ slug: item.globalSlug, permissions, req }))
104
112
  )
105
113
  case 'prompt':
106
114
  return !item.prompt.access || (await item.prompt.access({ permissions, req }))
@@ -3,6 +3,7 @@ import type { PayloadHandler, PayloadRequest } from 'payload'
3
3
  import {
4
4
  createMcpHandler,
5
5
  isLegacyRequest,
6
+ readRequestBody,
6
7
  WebStandardStreamableHTTPServerTransport,
7
8
  } from '@modelcontextprotocol/server'
8
9
  import { APIError } from 'payload'
@@ -10,6 +11,7 @@ import { APIError } from 'payload'
10
11
  import { buildMcpServer } from '../mcp/buildMcpServer.js'
11
12
  import { getPluginConfig } from '../utils/getPluginConfig.js'
12
13
  import { getAuthorizedMCP } from './access.js'
14
+ import { getMCPResource, oauthChallenge } from './oauth.js'
13
15
 
14
16
  export const mcpEndpoint: PayloadHandler = async (req) => {
15
17
  if (!req.url) {
@@ -17,6 +19,8 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
17
19
  }
18
20
 
19
21
  req.payloadAPI = 'MCP' as const
22
+ // Lets auth strategies check that an OAuth access token was issued for this MCP server
23
+ req.context.mcp = { resource: getMCPResource({ config: req.payload.config, url: req.url }) }
20
24
 
21
25
  const pluginConfig = getPluginConfig({ config: req.payload.config })
22
26
  const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')
@@ -33,14 +37,22 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
33
37
  }
34
38
 
35
39
  const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
40
+
41
+ if (pluginConfig.oauth && !req.user) {
42
+ return oauthChallenge({ req })
43
+ }
44
+
45
+ const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
36
46
  // Payload augments the original web-standard Request in place.
37
47
  const mcpRequest = req as PayloadRequest & Request
48
+ const parsedBody = await parseRequestBody({ maxRequestBodySize, request: mcpRequest })
38
49
 
39
50
  // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
40
- if (await isLegacyRequest(mcpRequest)) {
51
+ if (await isLegacyRequest(mcpRequest, parsedBody, { maxRequestBodySize })) {
41
52
  const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
42
53
  const transport = new WebStandardStreamableHTTPServerTransport({
43
54
  enableJsonResponse: true,
55
+ maxRequestBodySize,
44
56
  sessionIdGenerator: undefined, // stateless mode
45
57
  })
46
58
  transport.onerror = (err) => {
@@ -49,7 +61,7 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
49
61
 
50
62
  try {
51
63
  await server.connect(transport)
52
- return await transport.handleRequest(mcpRequest)
64
+ return await transport.handleRequest(mcpRequest, { parsedBody })
53
65
  } finally {
54
66
  await server.close().catch((err) => {
55
67
  req.payload.logger.error({ err, msg: 'Error closing MCP server' })
@@ -59,6 +71,7 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
59
71
 
60
72
  const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
61
73
  legacy: 'reject',
74
+ maxRequestBodySize,
62
75
  // SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
63
76
  maxSubscriptions: 0,
64
77
  onerror: (err) => {
@@ -68,10 +81,35 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
68
81
  })
69
82
 
70
83
  try {
71
- return await handler.fetch(mcpRequest)
84
+ return await handler.fetch(mcpRequest, { parsedBody })
72
85
  } finally {
73
86
  await handler.close().catch((err) => {
74
87
  req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })
75
88
  })
76
89
  }
77
90
  }
91
+
92
+ /**
93
+ * Parses a POST body once so the era check and the SDK handler can share it. The SDK
94
+ * skips its size limit for a pre-parsed body, so this reads with the same limit. It reads
95
+ * a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,
96
+ * or not JSON), leaving the original request for the SDK to read and answer.
97
+ */
98
+ const parseRequestBody = async ({
99
+ maxRequestBodySize,
100
+ request,
101
+ }: {
102
+ maxRequestBodySize?: number
103
+ request: Request
104
+ }): Promise<unknown> => {
105
+ if (request.method.toUpperCase() !== 'POST') {
106
+ return undefined
107
+ }
108
+
109
+ try {
110
+ const body = await readRequestBody(request.clone(), maxRequestBodySize)
111
+ return body.tooLarge ? undefined : JSON.parse(body.text)
112
+ } catch {
113
+ return undefined
114
+ }
115
+ }
@@ -0,0 +1,92 @@
1
+ import type { OAuthProtectedResourceMetadata } from '@modelcontextprotocol/server'
2
+ import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'
3
+
4
+ import {
5
+ bearerAuthChallengeResponse,
6
+ OAuthError,
7
+ OAuthErrorCode,
8
+ } from '@modelcontextprotocol/server'
9
+ import { createPayloadRequest, getPayload } from 'payload'
10
+
11
+ import { getPluginConfig } from '../utils/getPluginConfig.js'
12
+
13
+ /**
14
+ * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
15
+ * The OAuth challenge links here, so MCP clients find the authorization server without setup.
16
+ */
17
+ export const oauthProtectedResourceEndpoint: PayloadHandler = (req) => getMetadataResponse({ req })
18
+
19
+ /**
20
+ * Serves the same metadata for clients that ignore the challenge's link and only look at
21
+ * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
22
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
23
+ *
24
+ * ```ts
25
+ * import config from '@payload-config'
26
+ * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
27
+ *
28
+ * export const GET = oauthProtectedResourceHandler(config)
29
+ * ```
30
+ */
31
+ export const oauthProtectedResourceHandler =
32
+ (config: Promise<SanitizedConfig> | SanitizedConfig) =>
33
+ async (request: Request): Promise<Response> =>
34
+ getMetadataResponse({
35
+ req: await createPayloadRequest({ payload: await getPayload({ config }), req: request }),
36
+ })
37
+
38
+ /**
39
+ * Answers an unauthenticated MCP request with a challenge linking to the protected resource
40
+ * metadata, which starts the client's OAuth flow.
41
+ */
42
+ export const oauthChallenge = ({ req }: { req: PayloadRequest }): Response => {
43
+ const { oauth } = getPluginConfig({ config: req.payload.config })
44
+ const response = bearerAuthChallengeResponse(
45
+ new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),
46
+ {
47
+ requiredScopes: oauth?.type === 'external' ? oauth.scopes : undefined,
48
+ resourceMetadataUrl: `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth-protected-resource`,
49
+ },
50
+ )
51
+
52
+ // Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them
53
+ response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate')
54
+
55
+ return response
56
+ }
57
+
58
+ /**
59
+ * The MCP endpoint's address, as advertised in the metadata's `resource`. Clients send it when
60
+ * they sign in, and authorization servers that support it put it in the access token's audience.
61
+ */
62
+ export const getMCPResource = ({ config, url }: { config: SanitizedConfig; url: string }): string =>
63
+ getPluginConfig({ config }).oauth?.resource ?? getMCPURL({ config, url })
64
+
65
+ export const getMCPURL = ({ config, url }: { config: SanitizedConfig; url: string }): string =>
66
+ new URL(`${config.routes.api}/mcp`, config.serverURL || url).href
67
+
68
+ const getMetadataResponse = async ({ req }: { req: PayloadRequest }): Promise<Response> => {
69
+ const { config } = req.payload
70
+ const { oauth } = getPluginConfig({ config })
71
+
72
+ if (!oauth) {
73
+ return new Response(null, { status: 404 })
74
+ }
75
+
76
+ return Response.json(
77
+ {
78
+ authorization_servers:
79
+ oauth.type === 'builtin'
80
+ ? [`${getMCPURL({ config, url: req.url! })}/oauth`]
81
+ : typeof oauth.authorizationServers === 'function'
82
+ ? await oauth.authorizationServers({ req })
83
+ : oauth.authorizationServers,
84
+ bearer_methods_supported: ['header'],
85
+ resource: getMCPResource({ config, url: req.url! }),
86
+ scopes_supported: oauth.type === 'external' ? oauth.scopes : undefined,
87
+ } satisfies OAuthProtectedResourceMetadata,
88
+ // Public document, readable by browser-based MCP clients on any origin. Not cached, since
89
+ // without `serverURL` its URLs come from the request.
90
+ { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },
91
+ )
92
+ }