@payloadcms/plugin-mcp 4.0.0-internal.bc5cf8c → 4.0.0-internal.bf4bcce

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 (204) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/defaultAccess.d.ts.map +1 -1
  3. package/dist/defineTool.d.ts +8 -8
  4. package/dist/defineTool.d.ts.map +1 -1
  5. package/dist/endpoint/access.d.ts +2 -7
  6. package/dist/endpoint/access.d.ts.map +1 -1
  7. package/dist/endpoint/access.js +17 -14
  8. package/dist/endpoint/access.js.map +1 -1
  9. package/dist/endpoint/index.d.ts +1 -1
  10. package/dist/endpoint/index.d.ts.map +1 -1
  11. package/dist/endpoint/index.js +91 -16
  12. package/dist/endpoint/index.js.map +1 -1
  13. package/dist/endpoint/oauth.d.ts +27 -0
  14. package/dist/endpoint/oauth.d.ts.map +1 -0
  15. package/dist/endpoint/oauth.js +61 -0
  16. package/dist/endpoint/oauth.js.map +1 -0
  17. package/dist/index.d.ts +3 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +9 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/mcp/buildMcpServer.d.ts +6 -6
  22. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  23. package/dist/mcp/buildMcpServer.js +68 -34
  24. package/dist/mcp/buildMcpServer.js.map +1 -1
  25. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  26. package/dist/mcp/builtin/collections/authTools.js +80 -56
  27. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  28. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  29. package/dist/mcp/builtin/collections/countTool.js +10 -16
  30. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  31. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  32. package/dist/mcp/builtin/collections/countVersionsTool.js +10 -15
  33. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  34. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  35. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  36. package/dist/mcp/builtin/collections/createTool.js +104 -54
  37. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  38. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  39. package/dist/mcp/builtin/collections/deleteTool.js +45 -45
  40. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  41. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  42. package/dist/mcp/builtin/collections/duplicateTool.js +32 -39
  43. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  44. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  45. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  46. package/dist/mcp/builtin/collections/fileInput.js +88 -0
  47. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  48. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  49. package/dist/mcp/builtin/collections/findDistinctTool.js +12 -28
  50. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  51. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  52. package/dist/mcp/builtin/collections/findTool.js +29 -48
  53. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  54. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  55. package/dist/mcp/builtin/collections/findVersionByIDTool.js +18 -28
  56. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  57. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  58. package/dist/mcp/builtin/collections/findVersionsTool.js +17 -32
  59. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  60. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  61. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +68 -12
  62. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  63. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  64. package/dist/mcp/builtin/collections/restoreVersionTool.js +15 -28
  65. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  66. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  67. package/dist/mcp/builtin/collections/updateTool.js +67 -87
  68. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  69. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  70. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  71. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  72. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  73. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  74. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  75. package/dist/mcp/builtin/formatEntityError.js +55 -0
  76. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  77. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  78. package/dist/mcp/builtin/getConfigInfoTool.js +5 -7
  79. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  80. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  81. package/dist/mcp/builtin/globals/countVersionsTool.js +10 -15
  82. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  83. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  84. package/dist/mcp/builtin/globals/findTool.js +12 -18
  85. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  86. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  87. package/dist/mcp/builtin/globals/findVersionByIDTool.js +14 -26
  88. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  89. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  90. package/dist/mcp/builtin/globals/findVersionsTool.js +14 -31
  91. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  92. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  93. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +46 -12
  94. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  95. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  96. package/dist/mcp/builtin/globals/restoreVersionTool.js +16 -24
  97. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  98. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  99. package/dist/mcp/builtin/globals/updateTool.js +28 -37
  100. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  101. package/dist/mcp/builtinTools.d.ts +6 -0
  102. package/dist/mcp/builtinTools.d.ts.map +1 -1
  103. package/dist/mcp/builtinTools.js +9 -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 +6 -1
  107. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  108. package/dist/stdio.d.ts +3 -4
  109. package/dist/stdio.d.ts.map +1 -1
  110. package/dist/stdio.js +65 -45
  111. package/dist/stdio.js.map +1 -1
  112. package/dist/types.d.ts +94 -16
  113. package/dist/types.d.ts.map +1 -1
  114. package/dist/types.js +2 -4
  115. package/dist/types.js.map +1 -1
  116. package/dist/utils/camelCase.d.ts.map +1 -1
  117. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  118. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  119. package/package.json +9 -13
  120. package/src/endpoint/access.ts +14 -14
  121. package/src/endpoint/index.ts +79 -14
  122. package/src/endpoint/oauth.ts +72 -0
  123. package/src/index.ts +11 -4
  124. package/src/mcp/buildMcpServer.ts +80 -50
  125. package/src/mcp/builtin/collections/authTools.ts +80 -69
  126. package/src/mcp/builtin/collections/countTool.ts +10 -23
  127. package/src/mcp/builtin/collections/countVersionsTool.ts +10 -20
  128. package/src/mcp/builtin/collections/createTool.ts +110 -77
  129. package/src/mcp/builtin/collections/deleteTool.ts +36 -65
  130. package/src/mcp/builtin/collections/duplicateTool.ts +36 -87
  131. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  132. package/src/mcp/builtin/collections/fileInput.ts +127 -0
  133. package/src/mcp/builtin/collections/findDistinctTool.ts +12 -65
  134. package/src/mcp/builtin/collections/findTool.ts +25 -108
  135. package/src/mcp/builtin/collections/findVersionByIDTool.ts +16 -60
  136. package/src/mcp/builtin/collections/findVersionsTool.ts +15 -87
  137. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +60 -15
  138. package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -58
  139. package/src/mcp/builtin/collections/updateTool.ts +63 -101
  140. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  141. package/src/mcp/builtin/formatEntityError.ts +77 -0
  142. package/src/mcp/builtin/getConfigInfoTool.ts +4 -5
  143. package/src/mcp/builtin/globals/countVersionsTool.ts +10 -19
  144. package/src/mcp/builtin/globals/findTool.ts +14 -53
  145. package/src/mcp/builtin/globals/findVersionByIDTool.ts +14 -54
  146. package/src/mcp/builtin/globals/findVersionsTool.ts +15 -94
  147. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +41 -9
  148. package/src/mcp/builtin/globals/restoreVersionTool.ts +15 -47
  149. package/src/mcp/builtin/globals/updateTool.ts +39 -62
  150. package/src/mcp/builtinTools.ts +9 -2
  151. package/src/mcp/sanitizeMCPConfig.ts +6 -1
  152. package/src/stdio.ts +63 -45
  153. package/src/types.ts +95 -16
  154. package/dist/@types/assets.d.js +0 -2
  155. package/dist/@types/assets.d.js.map +0 -1
  156. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  157. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  158. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  159. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  160. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  161. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  162. package/dist/mcp/builtin/validateEntityData.js +0 -82
  163. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  164. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  165. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  166. package/dist/utils/getVirtualFieldNames.js +0 -35
  167. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  168. package/dist/utils/localAPIDefaults.d.ts +0 -20
  169. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  170. package/dist/utils/localAPIDefaults.js +0 -19
  171. package/dist/utils/localAPIDefaults.js.map +0 -1
  172. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -11
  173. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  174. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -34
  175. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  176. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  177. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  178. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  179. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  180. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -15
  181. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  182. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -464
  183. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  184. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -158
  185. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  186. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  187. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  188. package/dist/utils/transformPointDataToPayload.js +0 -28
  189. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  190. package/dist/utils/whereSchema.d.ts +0 -9
  191. package/dist/utils/whereSchema.d.ts.map +0 -1
  192. package/dist/utils/whereSchema.js +0 -13
  193. package/dist/utils/whereSchema.js.map +0 -1
  194. package/src/@types/assets.d.ts +0 -3
  195. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  196. package/src/mcp/builtin/validateEntityData.ts +0 -132
  197. package/src/utils/getVirtualFieldNames.ts +0 -53
  198. package/src/utils/localAPIDefaults.ts +0 -22
  199. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -78
  200. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
  201. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -103
  202. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -529
  203. package/src/utils/transformPointDataToPayload.ts +0 -40
  204. package/src/utils/whereSchema.ts +0 -24
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 TypedUser,\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 literal, or a Standard Schema instance (Zod, Valibot, …).\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\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 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 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 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 access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\nexport type MCPBuiltInGlobalToolOverride = {\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 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 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 mcp?: {\n serverOptions?: MCPServerOptions\n verboseLogs?: boolean\n }\n /** Replace the default MCP authorization resolver. */\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' | '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 caller's identity + the MCP items authorized for this request. Disabled\n * items and items blocked by access callbacks or Payload operation access are\n * absent from `items`. Tool handlers receive this via `args.authorizedMCP` so\n * they can spread `localAPIDefaults(authorizedMCP)` into every local API call.\n */\nexport type AuthorizedMCP = {\n items: MCPItem[]\n overrideAccess: boolean\n user: null | TypedUser\n}\n"],"names":[],"mappings":"AA6SA;;;;;CAKC,GACD,WAIC"}
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 * Lets MCP clients sign in through an OAuth authorization server. MCP requests without an\n * authenticated user get a `401` that points to the protected resource metadata (RFC 9728),\n * served by `oauthProtectedResourceHandler`. Payload's auth strategies must accept the\n * issued access tokens.\n */\n oauth?: {\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 authorizationServers: string[]\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 /**\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' | 'oauth' | '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":"AA+XA;;;CAGC,GACD,WAGC"}
@@ -1 +1 @@
1
- {"version":3,"file":"camelCase.d.ts","sourceRoot":"","sources":["../../src/utils/camelCase.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,WAAW,GAAI,KAAK,MAAM,KAAG,MAIzC,CAAA"}
1
+ {"version":3,"file":"camelCase.d.ts","sourceRoot":"","sources":["../../src/utils/camelCase.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,WAAW,QAAS,MAAM,KAAG,MAIzC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolveProjectRoot.d.ts","sourceRoot":"","sources":["../../src/utils/resolveProjectRoot.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,GAAI,UAAU,MAAM,KAAG,IAAI,GAAG,MAS5D,CAAA"}
1
+ {"version":3,"file":"resolveProjectRoot.d.ts","sourceRoot":"","sources":["../../src/utils/resolveProjectRoot.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,aAAc,MAAM,KAAG,IAAI,GAAG,MAS5D,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"toStandardSchema.d.ts","sourceRoot":"","sources":["../../src/utils/toStandardSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,sBAAsB,EAAE,MAAM,8BAA8B,CAAA;AAE1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,gIAAgI;AAChI,eAAO,MAAM,gBAAgB,GAAI,QAAQ,eAAe,KAAG,sBAG/B,CAAA"}
1
+ {"version":3,"file":"toStandardSchema.d.ts","sourceRoot":"","sources":["../../src/utils/toStandardSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,sBAAsB,EAAE,MAAM,8BAA8B,CAAA;AAE1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,gIAAgI;AAChI,eAAO,MAAM,gBAAgB,WAAY,eAAe,KAAG,sBAG/B,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "4.0.0-internal.bc5cf8c",
3
+ "version": "4.0.0-internal.bf4bcce",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
6
  "plugin",
@@ -39,9 +39,9 @@
39
39
  "default": "./dist/stdio.js"
40
40
  },
41
41
  "./internal": {
42
- "import": "./dist/internal.js",
43
- "types": "./dist/internal.d.ts",
44
- "default": "./dist/internal.js"
42
+ "import": "./dist/exports/internal.js",
43
+ "types": "./dist/exports/internal.d.ts",
44
+ "default": "./dist/exports/internal.js"
45
45
  }
46
46
  },
47
47
  "main": "./dist/index.js",
@@ -55,21 +55,17 @@
55
55
  "bin.js"
56
56
  ],
57
57
  "dependencies": {
58
- "@cfworker/json-schema": "^4.1.1",
59
- "@modelcontextprotocol/server": "2.0.0-alpha.2",
60
- "tsx": "4.22.4",
61
- "zod": "^4.0.0"
58
+ "@modelcontextprotocol/server": "2.3.1",
59
+ "tsx": "4.23.15"
62
60
  },
63
61
  "devDependencies": {
64
62
  "@payloadcms/eslint-config": "3.28.0",
65
- "payload": "4.0.0-internal.bc5cf8c"
63
+ "payload": "4.0.0-internal.bf4bcce"
66
64
  },
67
65
  "peerDependencies": {
68
- "payload": "4.0.0-internal.bc5cf8c"
66
+ "payload": "4.0.0-internal.bf4bcce"
69
67
  },
70
68
  "//deps_notes": {
71
- "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.",
72
- "@cfworker/json-schema": "Should be able to remove in next @modelcontextprotocol/server alpha release. Marked as an optional peer of @modelcontextprotocol/server, but its bundle does an eager top-level `import { Validator } from '@cfworker/json-schema'`, so it must be installed even when only zod-registered tools are used. Drop once upstream lazy-loads the validator. See: https://github.com/modelcontextprotocol/typescript-sdk",
73
69
  "tsx": "Required by the `bin.js` stdio mcp. Keep the version pinned to whatever `payload` ships to avoid duplicate installs."
74
70
  },
75
71
  "homepage:": "https://payloadcms.com",
@@ -79,7 +75,7 @@
79
75
  "build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
80
76
  "build:types": "tsc --emitDeclarationOnly --outDir dist",
81
77
  "clean": "rimraf {dist,*.tsbuildinfo}",
82
- "copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
78
+ "copyfiles": "copyfiles -u 1 -e \"**/*.spec.*\" \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
83
79
  "lint": "eslint .",
84
80
  "lint:fix": "eslint . --fix",
85
81
  "pack:plugin": "pnpm build && pnpm pack"
@@ -12,13 +12,8 @@ export type GetAuthorizedMCPArgs = {
12
12
  }
13
13
 
14
14
  /**
15
- * Resolves the MCP caller and returns the MCP surface authorized for that request.
16
- *
17
- * Authorization has two layers:
18
- * 1. Payload collection/global permissions determine whether built-in operation tools are shown.
19
- * 2. MCP `access` callbacks can further hide any configured tool, prompt, or resource.
20
- *
21
- * Like Payload core operations, `overrideAccess` skips both layers.
15
+ * Authenticates an MCP request and removes items the user cannot access.
16
+ * `overrideAccess` skips Payload and MCP item access checks.
22
17
  */
23
18
  export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP> = async ({
24
19
  overrideAccess,
@@ -41,7 +36,15 @@ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<Authorize
41
36
  headers.set('DisableAutologin', 'true')
42
37
  req.user = (await req.payload.auth({ headers, req })).user
43
38
 
44
- if (hasAuthorization && !req.user) {
39
+ // Only bearer tokens that no auth strategy accepted reach the hook, e.g. an OAuth access token.
40
+ // API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
41
+ const bearerToken = headers.get('Authorization')?.match(/^Bearer (.+)$/)?.[1]
42
+ if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
43
+ req.user = await pluginConfig.oauth.authenticate({ req, token: bearerToken })
44
+ }
45
+
46
+ // With OAuth, the endpoint answers with a challenge that starts the client's sign-in
47
+ if (hasAuthorization && !req.user && !pluginConfig.oauth) {
45
48
  throw new UnauthorizedError(req.t)
46
49
  }
47
50
  }
@@ -53,7 +56,6 @@ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<Authorize
53
56
  req,
54
57
  }),
55
58
  overrideAccess,
56
- user: req.user,
57
59
  }
58
60
  }
59
61
 
@@ -66,8 +68,7 @@ export const filterMCPItems = async ({
66
68
  overrideAccess: boolean
67
69
  req: PayloadRequest
68
70
  }): Promise<MCPItem[]> => {
69
- // Match Payload core: overrideAccess bypasses access evaluation instead of
70
- // forcing each access function to return true.
71
+ // Match Payload core: overrideAccess bypasses access evaluation
71
72
  if (overrideAccess) {
72
73
  return items
73
74
  }
@@ -102,12 +103,11 @@ const checkItemAccess = async ({
102
103
  case 'collectionTool':
103
104
  return (
104
105
  !item.tool.access ||
105
- (await item.tool.access({ collectionSlug: item.collectionSlug, permissions, req }))
106
+ (await item.tool.access({ slug: item.collectionSlug, permissions, req }))
106
107
  )
107
108
  case 'globalTool':
108
109
  return (
109
- !item.tool.access ||
110
- (await item.tool.access({ globalSlug: item.globalSlug, permissions, req }))
110
+ !item.tool.access || (await item.tool.access({ slug: item.globalSlug, permissions, req }))
111
111
  )
112
112
  case 'prompt':
113
113
  return !item.prompt.access || (await item.prompt.access({ permissions, req }))
@@ -1,9 +1,17 @@
1
- import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'
2
- import { APIError, type PayloadHandler } from 'payload'
1
+ import type { PayloadHandler, PayloadRequest } from 'payload'
2
+
3
+ import {
4
+ createMcpHandler,
5
+ isLegacyRequest,
6
+ readRequestBody,
7
+ WebStandardStreamableHTTPServerTransport,
8
+ } from '@modelcontextprotocol/server'
9
+ import { APIError } from 'payload'
3
10
 
4
11
  import { buildMcpServer } from '../mcp/buildMcpServer.js'
5
12
  import { getPluginConfig } from '../utils/getPluginConfig.js'
6
13
  import { getAuthorizedMCP } from './access.js'
14
+ import { oauthChallenge } from './oauth.js'
7
15
 
8
16
  export const mcpEndpoint: PayloadHandler = async (req) => {
9
17
  if (!req.url) {
@@ -28,21 +36,78 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
28
36
 
29
37
  const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
30
38
 
31
- const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
39
+ if (pluginConfig.oauth && !req.user) {
40
+ return oauthChallenge({ req })
41
+ }
42
+
43
+ const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
44
+ // Payload augments the original web-standard Request in place.
45
+ const mcpRequest = req as PayloadRequest & Request
46
+ const parsedBody = await parseRequestBody({ maxRequestBodySize, request: mcpRequest })
47
+
48
+ // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
49
+ if (await isLegacyRequest(mcpRequest, parsedBody, { maxRequestBodySize })) {
50
+ const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
51
+ const transport = new WebStandardStreamableHTTPServerTransport({
52
+ enableJsonResponse: true,
53
+ maxRequestBodySize,
54
+ sessionIdGenerator: undefined, // stateless mode
55
+ })
56
+ transport.onerror = (err) => {
57
+ req.payload.logger.error({ err, msg: 'Error serving legacy MCP request' })
58
+ }
59
+
60
+ try {
61
+ await server.connect(transport)
62
+ return await transport.handleRequest(mcpRequest, { parsedBody })
63
+ } finally {
64
+ await server.close().catch((err) => {
65
+ req.payload.logger.error({ err, msg: 'Error closing MCP server' })
66
+ })
67
+ }
68
+ }
32
69
 
33
- const transport = new WebStandardStreamableHTTPServerTransport({
34
- enableJsonResponse: true,
35
- sessionIdGenerator: undefined, // stateless mode
70
+ const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
71
+ legacy: 'reject',
72
+ maxRequestBodySize,
73
+ // SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
74
+ maxSubscriptions: 0,
75
+ onerror: (err) => {
76
+ req.payload.logger.error({ err, msg: 'Error serving modern MCP request' })
77
+ },
78
+ responseMode: 'json',
36
79
  })
37
80
 
38
- await server.connect(transport)
81
+ try {
82
+ return await handler.fetch(mcpRequest, { parsedBody })
83
+ } finally {
84
+ await handler.close().catch((err) => {
85
+ req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })
86
+ })
87
+ }
88
+ }
39
89
 
40
- const mcpRequest = new Request(req.url, {
41
- body: req.body,
42
- duplex: 'half',
43
- headers: req.headers,
44
- method: req.method,
45
- } as { duplex: 'half' } & RequestInit)
90
+ /**
91
+ * Parses a POST body once so the era check and the SDK handler can share it. The SDK
92
+ * skips its size limit for a pre-parsed body, so this reads with the same limit. It reads
93
+ * a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,
94
+ * or not JSON), leaving the original request for the SDK to read and answer.
95
+ */
96
+ const parseRequestBody = async ({
97
+ maxRequestBodySize,
98
+ request,
99
+ }: {
100
+ maxRequestBodySize?: number
101
+ request: Request
102
+ }): Promise<unknown> => {
103
+ if (request.method.toUpperCase() !== 'POST') {
104
+ return undefined
105
+ }
46
106
 
47
- return await transport.handleRequest(mcpRequest)
107
+ try {
108
+ const body = await readRequestBody(request.clone(), maxRequestBodySize)
109
+ return body.tooLarge ? undefined : JSON.parse(body.text)
110
+ } catch {
111
+ return undefined
112
+ }
48
113
  }
@@ -0,0 +1,72 @@
1
+ import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'
2
+
3
+ import {
4
+ bearerAuthChallengeResponse,
5
+ OAuthError,
6
+ OAuthErrorCode,
7
+ } from '@modelcontextprotocol/server'
8
+
9
+ import { getPluginConfig } from '../utils/getPluginConfig.js'
10
+
11
+ /**
12
+ * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
13
+ * The OAuth challenge links here, so MCP clients find the authorization server without setup.
14
+ */
15
+ export const oauthProtectedResourceEndpoint: PayloadHandler = (req) =>
16
+ getMetadataResponse({ config: req.payload.config, url: req.url! })
17
+
18
+ /**
19
+ * Serves the same metadata for clients that ignore the challenge's link and only look at
20
+ * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
21
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
22
+ *
23
+ * ```ts
24
+ * import config from '@payload-config'
25
+ * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
26
+ *
27
+ * export const GET = oauthProtectedResourceHandler(config)
28
+ * ```
29
+ */
30
+ export const oauthProtectedResourceHandler =
31
+ (config: Promise<SanitizedConfig> | SanitizedConfig) =>
32
+ async (request: Request): Promise<Response> =>
33
+ getMetadataResponse({ config: await config, url: request.url })
34
+
35
+ /**
36
+ * Answers an unauthenticated MCP request with a challenge linking to the protected resource
37
+ * metadata, which starts the client's OAuth flow.
38
+ */
39
+ export const oauthChallenge = ({ req }: { req: PayloadRequest }): Response =>
40
+ bearerAuthChallengeResponse(
41
+ new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),
42
+ {
43
+ resourceMetadataUrl: `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth-protected-resource`,
44
+ },
45
+ )
46
+
47
+ const getMCPURL = ({ config, url }: { config: SanitizedConfig; url: string }): string =>
48
+ new URL(`${config.routes.api}/mcp`, config.serverURL || url).href
49
+
50
+ const getMetadataResponse = ({
51
+ config,
52
+ url,
53
+ }: {
54
+ config: SanitizedConfig
55
+ url: string
56
+ }): Response => {
57
+ const pluginConfig = getPluginConfig({ config })
58
+
59
+ if (!pluginConfig.oauth) {
60
+ return new Response(null, { status: 404 })
61
+ }
62
+
63
+ return Response.json(
64
+ {
65
+ authorization_servers: pluginConfig.oauth.authorizationServers,
66
+ bearer_methods_supported: ['header'],
67
+ resource: pluginConfig.oauth.resource ?? getMCPURL({ config, url }),
68
+ },
69
+ // Public document, readable by browser-based MCP clients on any origin
70
+ { headers: { 'Access-Control-Allow-Origin': '*' } },
71
+ )
72
+ }
package/src/index.ts CHANGED
@@ -3,11 +3,12 @@ import { definePlugin } from 'payload'
3
3
  import type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'
4
4
 
5
5
  import { mcpEndpoint } from './endpoint/index.js'
6
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'
6
7
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
7
8
 
8
9
  declare module 'payload' {
9
- export interface PayloadRequest {
10
- payloadAPI: 'GraphQL' | 'local' | 'MCP' | 'REST'
10
+ export interface PayloadRequestAPI {
11
+ MCP: true
11
12
  }
12
13
  interface RegisteredPlugins {
13
14
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
@@ -18,12 +19,13 @@ declare module 'payload' {
18
19
  export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }
19
20
 
20
21
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'
22
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js'
21
23
 
22
24
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
23
25
  slug: '@payloadcms/plugin-mcp',
24
26
  order: 10,
25
- plugin: ({ config, plugins, ...rawConfig }) => {
26
- const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: rawConfig })
27
+ plugin: ({ config, options, plugins }) => {
28
+ const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })
27
29
 
28
30
  // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.
29
31
  const registered = plugins['@payloadcms/plugin-mcp']
@@ -49,6 +51,11 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
49
51
  method: 'get',
50
52
  path: '/mcp',
51
53
  },
54
+ {
55
+ handler: oauthProtectedResourceEndpoint,
56
+ method: 'get',
57
+ path: '/mcp/oauth-protected-resource',
58
+ },
52
59
  ],
53
60
  }
54
61
  },
@@ -1,6 +1,7 @@
1
+ import type { PayloadRequest } from 'payload'
2
+
1
3
  import { McpServer, type ServerContext } from '@modelcontextprotocol/server'
2
- import { APIError, type PayloadRequest } from 'payload'
3
- import { z } from 'zod'
4
+ import { APIError, strictObject, z } from 'payload'
4
5
 
5
6
  import type {
6
7
  AuthorizedMCP,
@@ -17,14 +18,14 @@ import { getLogger } from '../utils/getLogger.js'
17
18
  import { toStandardSchema } from '../utils/toStandardSchema.js'
18
19
 
19
20
  /**
20
- * Transport-agnostic core: registers every authorized MCP item onto a fresh
21
- * `McpServer` and returns it. The caller is responsible for picking a transport
22
- * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and
23
- * calling `server.connect(transport)`.
21
+ * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh
22
+ * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh
23
+ * instances from this builder while they own the transport and protocol-era
24
+ * decision.
24
25
  *
25
26
  * `req` is the request context handlers see. For HTTP it's the live
26
27
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
27
- * synthesized one built via `createLocalReq`.
28
+ * synthesized one built via `createPayloadRequest`.
28
29
  */
29
30
  export const buildMcpServer = ({
30
31
  authorizedMCP,
@@ -35,6 +36,8 @@ export const buildMcpServer = ({
35
36
  pluginConfig: SanitizedMCPPluginConfig
36
37
  req: PayloadRequest
37
38
  }): McpServer => {
39
+ z.config(z.locales.en())
40
+
38
41
  const serverOptions = pluginConfig.mcp?.serverOptions || {}
39
42
  const server = new McpServer(
40
43
  { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },
@@ -47,18 +50,28 @@ export const buildMcpServer = ({
47
50
  * Wrap a tool handler's response with the tool's `overrideResponse`, then
48
51
  * strip the internal `doc` field so it doesn't leak onto the wire.
49
52
  */
50
- const finalizeToolResponse = (
51
- response: MCPToolResponse,
52
- overrideResponse?: MCPResponseOverride,
53
- ): MCPToolResponse => {
54
- const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response
53
+ const finalizeToolResponse = async ({
54
+ input,
55
+ overrideResponse,
56
+ response,
57
+ toolName,
58
+ }: {
59
+ input: unknown
60
+ overrideResponse?: MCPResponseOverride
61
+ response: MCPToolResponse
62
+ toolName: string
63
+ }): Promise<MCPToolResponse> => {
64
+ let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response
65
+ for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {
66
+ overridden = await hook({ input, req, response: overridden, toolName })
67
+ }
55
68
  const { doc: _doc, ...rest } = overridden
56
69
  return rest
57
70
  }
58
71
 
59
72
  /**
60
73
  * Runs a collection/global tool call:
61
- * - reads `collectionSlug` / `globalSlug` from the input
74
+ * - reads `slug` from the input
62
75
  * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug
63
76
  * - runs the tool handler and finalizes its response
64
77
  */
@@ -72,16 +85,15 @@ export const buildMcpServer = ({
72
85
  serverContext: ServerContext
73
86
  }): Promise<MCPToolResponse> => {
74
87
  const entity = item.type === 'collectionTool' ? 'collection' : 'global'
75
- const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'
76
88
  const toolInput = (input ?? {}) as Record<string, unknown>
77
- const slug = toolInput[slugKey] as string | undefined
89
+ const slug = toolInput.slug as string | undefined
78
90
 
79
91
  if (!slug) {
80
92
  return {
81
93
  content: [
82
94
  {
83
95
  type: 'text',
84
- text: `Error: "${item.mcpName}" requires ${slugKey}. Use getConfigInfo to inspect ${entity} slugs.`,
96
+ text: `Error: "${item.mcpName}" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,
85
97
  },
86
98
  ],
87
99
  isError: true,
@@ -116,10 +128,15 @@ export const buildMcpServer = ({
116
128
  serverContext,
117
129
  }
118
130
  const response = await (match.type === 'collectionTool'
119
- ? match.tool.handler({ ...handlerArgs, collectionSlug: slug })
120
- : match.tool.handler({ ...handlerArgs, globalSlug: slug }))
131
+ ? match.tool.handler({ ...handlerArgs, slug })
132
+ : match.tool.handler({ ...handlerArgs, slug }))
121
133
 
122
- return finalizeToolResponse(response, match.tool.overrideResponse)
134
+ return finalizeToolResponse({
135
+ input: toolInput,
136
+ overrideResponse: match.tool.overrideResponse,
137
+ response,
138
+ toolName: match.mcpName,
139
+ })
123
140
  }
124
141
 
125
142
  try {
@@ -134,10 +151,7 @@ export const buildMcpServer = ({
134
151
  }
135
152
  registeredEntityTools.add(item.mcpName)
136
153
 
137
- const inputSchema = withSlugInput({
138
- name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',
139
- input: item.tool.input,
140
- })
154
+ const inputSchema = withSlugInput({ input: item.tool.input })
141
155
 
142
156
  server.registerTool(
143
157
  item.mcpName,
@@ -203,16 +217,21 @@ export const buildMcpServer = ({
203
217
  description: tool.description,
204
218
  inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,
205
219
  },
206
- async (input: unknown, ctx: ServerContext) =>
207
- finalizeToolResponse(
208
- await tool.handler({
209
- authorizedMCP,
210
- input: (input ?? {}) as Record<string, unknown>,
211
- req,
212
- serverContext: ctx,
213
- }),
214
- tool.overrideResponse,
215
- ),
220
+ async (input: unknown, ctx: ServerContext) => {
221
+ const toolInput = (input ?? {}) as Record<string, unknown>
222
+ const response = await tool.handler({
223
+ authorizedMCP,
224
+ input: toolInput,
225
+ req,
226
+ serverContext: ctx,
227
+ })
228
+ return finalizeToolResponse({
229
+ input: toolInput,
230
+ overrideResponse: tool.overrideResponse,
231
+ response,
232
+ toolName: item.mcpName,
233
+ })
234
+ },
216
235
  )
217
236
  logger.info(`✅ Tool: ${item.mcpName} Registered.`)
218
237
  break
@@ -226,39 +245,50 @@ export const buildMcpServer = ({
226
245
  return server
227
246
  }
228
247
 
229
- const withSlugInput = ({
230
- name,
231
- input,
232
- }: {
233
- input?: ToolInputSchema
234
- name: 'collectionSlug' | 'globalSlug'
235
- }): ToolInputSchema => {
236
- const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'
237
- const slugSchema = z.string().describe(description)
248
+ const withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {
249
+ const description = 'The target slug.'
250
+ const slugSchema = z.string().check(z.describe(description))
238
251
 
239
252
  if (!input) {
240
- return z.object({ [name]: slugSchema })
253
+ return strictObject({ slug: slugSchema }) as unknown as ToolInputSchema
241
254
  }
242
255
 
243
- if (input instanceof z.ZodObject) {
244
- return input.extend({ [name]: slugSchema })
256
+ if (typeof input === 'object' && input !== null && '~standard' in input) {
257
+ const schema = input['~standard'].jsonSchema.input({ target: 'draft-2020-12' })
258
+ const properties = schema.properties as Record<string, unknown> | undefined
259
+
260
+ if (properties?.slug) {
261
+ return input
262
+ }
263
+
264
+ return addSlugToJSONSchema({ description, schema: schema as JsonSchemaType })
245
265
  }
246
266
 
247
- const schema = input as {
267
+ return addSlugToJSONSchema({ description, schema: input })
268
+ }
269
+
270
+ const addSlugToJSONSchema = ({
271
+ description,
272
+ schema,
273
+ }: {
274
+ description: string
275
+ schema: JsonSchemaType
276
+ }): JsonSchemaType => {
277
+ const objectSchema = schema as {
248
278
  properties?: Record<string, JsonSchemaType>
249
279
  required?: string[]
250
280
  } & JsonSchemaType
251
281
 
252
282
  return {
253
- ...schema,
283
+ ...objectSchema,
254
284
  type: 'object',
255
285
  properties: {
256
- ...schema.properties,
257
- [name]: {
286
+ ...objectSchema.properties,
287
+ slug: {
258
288
  type: 'string',
259
289
  description,
260
290
  },
261
291
  },
262
- required: Array.from(new Set([name, ...(schema.required ?? [])])),
292
+ required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),
263
293
  }
264
294
  }