@payloadcms/plugin-mcp 4.0.0-internal.cd69eef → 4.0.0-internal.ce66a41
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.
- package/bin.js +0 -7
- package/dist/endpoint/access.js +2 -2
- package/dist/endpoint/access.js.map +1 -1
- package/dist/endpoint/index.d.ts.map +1 -1
- package/dist/endpoint/index.js +33 -4
- package/dist/endpoint/index.js.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts +2 -2
- package/dist/mcp/buildMcpServer.d.ts.map +1 -1
- package/dist/mcp/buildMcpServer.js +36 -24
- package/dist/mcp/buildMcpServer.js.map +1 -1
- package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/authTools.js +80 -56
- package/dist/mcp/builtin/collections/authTools.js.map +1 -1
- package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/countTool.js +9 -14
- package/dist/mcp/builtin/collections/countTool.js.map +1 -1
- package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
- package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.js +104 -63
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.js +44 -43
- package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.js +31 -37
- package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.d.ts +21 -13
- package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.js +52 -64
- package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
- package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
- package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findTool.js +27 -45
- package/dist/mcp/builtin/collections/findTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
- package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
- package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +33 -16
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
- package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +58 -90
- package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
- package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
- package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
- package/dist/mcp/builtin/formatEntityError.js +55 -0
- package/dist/mcp/builtin/formatEntityError.js.map +1 -0
- package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
- package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
- package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
- package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
- package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findTool.js +10 -16
- package/dist/mcp/builtin/globals/findTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
- package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
- package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +29 -13
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
- package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.js +27 -36
- package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
- package/dist/mcp/builtinTools.d.ts +6 -0
- package/dist/mcp/builtinTools.d.ts.map +1 -1
- package/dist/mcp/builtinTools.js +9 -3
- package/dist/mcp/builtinTools.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +4 -1
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/stdio.d.ts.map +1 -1
- package/dist/stdio.js +6 -4
- package/dist/stdio.js.map +1 -1
- package/dist/types.d.ts +14 -7
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +7 -9
- package/src/endpoint/access.ts +2 -3
- package/src/endpoint/index.ts +33 -3
- package/src/mcp/buildMcpServer.ts +40 -30
- package/src/mcp/builtin/collections/authTools.ts +80 -69
- package/src/mcp/builtin/collections/countTool.ts +9 -21
- package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
- package/src/mcp/builtin/collections/createTool.ts +110 -86
- package/src/mcp/builtin/collections/deleteTool.ts +36 -64
- package/src/mcp/builtin/collections/duplicateTool.ts +35 -85
- package/src/mcp/builtin/collections/fileInput.spec.ts +20 -6
- package/src/mcp/builtin/collections/fileInput.ts +64 -76
- package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
- package/src/mcp/builtin/collections/findTool.ts +23 -105
- package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
- package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +28 -13
- package/src/mcp/builtin/collections/restoreVersionTool.ts +14 -56
- package/src/mcp/builtin/collections/updateTool.ts +57 -111
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
- package/src/mcp/builtin/formatEntityError.ts +77 -0
- package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
- package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
- package/src/mcp/builtin/globals/findTool.ts +12 -51
- package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
- package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +21 -11
- package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
- package/src/mcp/builtin/globals/updateTool.ts +37 -60
- package/src/mcp/builtinTools.ts +9 -2
- package/src/mcp/sanitizeMCPConfig.ts +4 -1
- package/src/stdio.ts +4 -3
- package/src/types.ts +15 -7
- package/dist/mcp/builtin/collections/fileInput.spec.js +0 -72
- package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
- package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
- package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
- package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
- package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
- package/dist/mcp/builtin/validateEntityData.js +0 -82
- package/dist/mcp/builtin/validateEntityData.js.map +0 -1
- package/dist/utils/getVirtualFieldNames.d.ts +0 -14
- package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
- package/dist/utils/getVirtualFieldNames.js +0 -35
- package/dist/utils/getVirtualFieldNames.js.map +0 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
- package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
- package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
- package/dist/utils/transformPointDataToPayload.d.ts +0 -7
- package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
- package/dist/utils/transformPointDataToPayload.js +0 -28
- package/dist/utils/transformPointDataToPayload.js.map +0 -1
- package/dist/utils/whereSchema.d.ts +0 -9
- package/dist/utils/whereSchema.d.ts.map +0 -1
- package/dist/utils/whereSchema.js +0 -13
- package/dist/utils/whereSchema.js.map +0 -1
- package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
- package/src/mcp/builtin/validateEntityData.ts +0 -132
- package/src/utils/getVirtualFieldNames.ts +0 -53
- package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
- package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
- package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
- package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
- package/src/utils/transformPointDataToPayload.ts +0 -40
- 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} 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 * 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?: 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":"AAwWA;;;CAGC,GACD,WAGC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/plugin-mcp",
|
|
3
|
-
"version": "4.0.0-internal.
|
|
3
|
+
"version": "4.0.0-internal.ce66a41",
|
|
4
4
|
"description": "MCP (Model Context Protocol) capabilities with Payload",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"plugin",
|
|
@@ -55,19 +55,17 @@
|
|
|
55
55
|
"bin.js"
|
|
56
56
|
],
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@modelcontextprotocol/server": "2.
|
|
59
|
-
"tsx": "4.
|
|
60
|
-
"zod": "^4.2.0"
|
|
58
|
+
"@modelcontextprotocol/server": "2.3.1",
|
|
59
|
+
"tsx": "4.23.15"
|
|
61
60
|
},
|
|
62
61
|
"devDependencies": {
|
|
63
|
-
"
|
|
64
|
-
"
|
|
62
|
+
"@payloadcms/eslint-config": "3.28.0",
|
|
63
|
+
"payload": "4.0.0-internal.ce66a41"
|
|
65
64
|
},
|
|
66
65
|
"peerDependencies": {
|
|
67
|
-
"payload": "4.0.0-internal.
|
|
66
|
+
"payload": "4.0.0-internal.ce66a41"
|
|
68
67
|
},
|
|
69
68
|
"//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
69
|
"tsx": "Required by the `bin.js` stdio mcp. Keep the version pinned to whatever `payload` ships to avoid duplicate installs."
|
|
72
70
|
},
|
|
73
71
|
"homepage:": "https://payloadcms.com",
|
|
@@ -77,7 +75,7 @@
|
|
|
77
75
|
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
|
|
78
76
|
"build:types": "tsc --emitDeclarationOnly --outDir dist",
|
|
79
77
|
"clean": "rimraf {dist,*.tsbuildinfo}",
|
|
80
|
-
"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/",
|
|
81
79
|
"lint": "eslint .",
|
|
82
80
|
"lint:fix": "eslint . --fix",
|
|
83
81
|
"pack:plugin": "pnpm build && pnpm pack"
|
package/src/endpoint/access.ts
CHANGED
|
@@ -95,12 +95,11 @@ const checkItemAccess = async ({
|
|
|
95
95
|
case 'collectionTool':
|
|
96
96
|
return (
|
|
97
97
|
!item.tool.access ||
|
|
98
|
-
(await item.tool.access({
|
|
98
|
+
(await item.tool.access({ slug: item.collectionSlug, permissions, req }))
|
|
99
99
|
)
|
|
100
100
|
case 'globalTool':
|
|
101
101
|
return (
|
|
102
|
-
!item.tool.access ||
|
|
103
|
-
(await item.tool.access({ globalSlug: item.globalSlug, permissions, req }))
|
|
102
|
+
!item.tool.access || (await item.tool.access({ slug: item.globalSlug, permissions, req }))
|
|
104
103
|
)
|
|
105
104
|
case 'prompt':
|
|
106
105
|
return !item.prompt.access || (await item.prompt.access({ permissions, req }))
|
package/src/endpoint/index.ts
CHANGED
|
@@ -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'
|
|
@@ -33,14 +34,17 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
33
34
|
}
|
|
34
35
|
|
|
35
36
|
const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
|
|
37
|
+
const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
|
|
36
38
|
// Payload augments the original web-standard Request in place.
|
|
37
39
|
const mcpRequest = req as PayloadRequest & Request
|
|
40
|
+
const parsedBody = await parseRequestBody({ maxRequestBodySize, request: mcpRequest })
|
|
38
41
|
|
|
39
42
|
// Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
|
|
40
|
-
if (await isLegacyRequest(mcpRequest)) {
|
|
43
|
+
if (await isLegacyRequest(mcpRequest, parsedBody, { maxRequestBodySize })) {
|
|
41
44
|
const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
|
|
42
45
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
43
46
|
enableJsonResponse: true,
|
|
47
|
+
maxRequestBodySize,
|
|
44
48
|
sessionIdGenerator: undefined, // stateless mode
|
|
45
49
|
})
|
|
46
50
|
transport.onerror = (err) => {
|
|
@@ -49,7 +53,7 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
49
53
|
|
|
50
54
|
try {
|
|
51
55
|
await server.connect(transport)
|
|
52
|
-
return await transport.handleRequest(mcpRequest)
|
|
56
|
+
return await transport.handleRequest(mcpRequest, { parsedBody })
|
|
53
57
|
} finally {
|
|
54
58
|
await server.close().catch((err) => {
|
|
55
59
|
req.payload.logger.error({ err, msg: 'Error closing MCP server' })
|
|
@@ -59,6 +63,7 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
59
63
|
|
|
60
64
|
const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
|
|
61
65
|
legacy: 'reject',
|
|
66
|
+
maxRequestBodySize,
|
|
62
67
|
// SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
|
|
63
68
|
maxSubscriptions: 0,
|
|
64
69
|
onerror: (err) => {
|
|
@@ -68,10 +73,35 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
68
73
|
})
|
|
69
74
|
|
|
70
75
|
try {
|
|
71
|
-
return await handler.fetch(mcpRequest)
|
|
76
|
+
return await handler.fetch(mcpRequest, { parsedBody })
|
|
72
77
|
} finally {
|
|
73
78
|
await handler.close().catch((err) => {
|
|
74
79
|
req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })
|
|
75
80
|
})
|
|
76
81
|
}
|
|
77
82
|
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Parses a POST body once so the era check and the SDK handler can share it. The SDK
|
|
86
|
+
* skips its size limit for a pre-parsed body, so this reads with the same limit. It reads
|
|
87
|
+
* a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,
|
|
88
|
+
* or not JSON), leaving the original request for the SDK to read and answer.
|
|
89
|
+
*/
|
|
90
|
+
const parseRequestBody = async ({
|
|
91
|
+
maxRequestBodySize,
|
|
92
|
+
request,
|
|
93
|
+
}: {
|
|
94
|
+
maxRequestBodySize?: number
|
|
95
|
+
request: Request
|
|
96
|
+
}): Promise<unknown> => {
|
|
97
|
+
if (request.method.toUpperCase() !== 'POST') {
|
|
98
|
+
return undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
try {
|
|
102
|
+
const body = await readRequestBody(request.clone(), maxRequestBodySize)
|
|
103
|
+
return body.tooLarge ? undefined : JSON.parse(body.text)
|
|
104
|
+
} catch {
|
|
105
|
+
return undefined
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload'
|
|
2
|
+
|
|
1
3
|
import { McpServer, type ServerContext } from '@modelcontextprotocol/server'
|
|
2
|
-
import { APIError,
|
|
3
|
-
import { z } from 'zod'
|
|
4
|
+
import { APIError, strictObject, z } from 'payload'
|
|
4
5
|
|
|
5
6
|
import type {
|
|
6
7
|
AuthorizedMCP,
|
|
@@ -24,7 +25,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js'
|
|
|
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 `
|
|
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 },
|
|
@@ -68,7 +71,7 @@ export const buildMcpServer = ({
|
|
|
68
71
|
|
|
69
72
|
/**
|
|
70
73
|
* Runs a collection/global tool call:
|
|
71
|
-
* - reads `
|
|
74
|
+
* - reads `slug` from the input
|
|
72
75
|
* - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug
|
|
73
76
|
* - runs the tool handler and finalizes its response
|
|
74
77
|
*/
|
|
@@ -82,16 +85,15 @@ export const buildMcpServer = ({
|
|
|
82
85
|
serverContext: ServerContext
|
|
83
86
|
}): Promise<MCPToolResponse> => {
|
|
84
87
|
const entity = item.type === 'collectionTool' ? 'collection' : 'global'
|
|
85
|
-
const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'
|
|
86
88
|
const toolInput = (input ?? {}) as Record<string, unknown>
|
|
87
|
-
const slug = toolInput
|
|
89
|
+
const slug = toolInput.slug as string | undefined
|
|
88
90
|
|
|
89
91
|
if (!slug) {
|
|
90
92
|
return {
|
|
91
93
|
content: [
|
|
92
94
|
{
|
|
93
95
|
type: 'text',
|
|
94
|
-
text: `Error: "${item.mcpName}" requires
|
|
96
|
+
text: `Error: "${item.mcpName}" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,
|
|
95
97
|
},
|
|
96
98
|
],
|
|
97
99
|
isError: true,
|
|
@@ -126,8 +128,8 @@ export const buildMcpServer = ({
|
|
|
126
128
|
serverContext,
|
|
127
129
|
}
|
|
128
130
|
const response = await (match.type === 'collectionTool'
|
|
129
|
-
? match.tool.handler({ ...handlerArgs,
|
|
130
|
-
: match.tool.handler({ ...handlerArgs,
|
|
131
|
+
? match.tool.handler({ ...handlerArgs, slug })
|
|
132
|
+
: match.tool.handler({ ...handlerArgs, slug }))
|
|
131
133
|
|
|
132
134
|
return finalizeToolResponse({
|
|
133
135
|
input: toolInput,
|
|
@@ -149,10 +151,7 @@ export const buildMcpServer = ({
|
|
|
149
151
|
}
|
|
150
152
|
registeredEntityTools.add(item.mcpName)
|
|
151
153
|
|
|
152
|
-
const inputSchema = withSlugInput({
|
|
153
|
-
name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',
|
|
154
|
-
input: item.tool.input,
|
|
155
|
-
})
|
|
154
|
+
const inputSchema = withSlugInput({ input: item.tool.input })
|
|
156
155
|
|
|
157
156
|
server.registerTool(
|
|
158
157
|
item.mcpName,
|
|
@@ -246,39 +245,50 @@ export const buildMcpServer = ({
|
|
|
246
245
|
return server
|
|
247
246
|
}
|
|
248
247
|
|
|
249
|
-
const withSlugInput = ({
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
}: {
|
|
253
|
-
input?: ToolInputSchema
|
|
254
|
-
name: 'collectionSlug' | 'globalSlug'
|
|
255
|
-
}): ToolInputSchema => {
|
|
256
|
-
const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'
|
|
257
|
-
const slugSchema = z.string().describe(description)
|
|
248
|
+
const withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {
|
|
249
|
+
const description = 'The target slug.'
|
|
250
|
+
const slugSchema = z.string().check(z.describe(description))
|
|
258
251
|
|
|
259
252
|
if (!input) {
|
|
260
|
-
return
|
|
253
|
+
return strictObject({ slug: slugSchema }) as unknown as ToolInputSchema
|
|
261
254
|
}
|
|
262
255
|
|
|
263
|
-
if (input
|
|
264
|
-
|
|
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 })
|
|
265
265
|
}
|
|
266
266
|
|
|
267
|
-
|
|
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 {
|
|
268
278
|
properties?: Record<string, JsonSchemaType>
|
|
269
279
|
required?: string[]
|
|
270
280
|
} & JsonSchemaType
|
|
271
281
|
|
|
272
282
|
return {
|
|
273
|
-
...
|
|
283
|
+
...objectSchema,
|
|
274
284
|
type: 'object',
|
|
275
285
|
properties: {
|
|
276
|
-
...
|
|
277
|
-
|
|
286
|
+
...objectSchema.properties,
|
|
287
|
+
slug: {
|
|
278
288
|
type: 'string',
|
|
279
289
|
description,
|
|
280
290
|
},
|
|
281
291
|
},
|
|
282
|
-
required: Array.from(new Set([
|
|
292
|
+
required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),
|
|
283
293
|
}
|
|
284
294
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { z } from '
|
|
1
|
+
import { createPayloadRequest, strictObject, z } from 'payload'
|
|
2
2
|
|
|
3
3
|
import type { MCPToolResponse } from '../../../types.js'
|
|
4
4
|
|
|
5
|
+
import { defaultAccess } from '../../../defaultAccess.js'
|
|
5
6
|
import { defineCollectionTool } from '../../../defineTool.js'
|
|
6
7
|
import { getLogger } from '../../../utils/getLogger.js'
|
|
7
8
|
|
|
@@ -16,16 +17,16 @@ import { getLogger } from '../../../utils/getLogger.js'
|
|
|
16
17
|
* users collection so all auth-shaped tools live in one place.
|
|
17
18
|
*/
|
|
18
19
|
|
|
19
|
-
const emailSchema = z.
|
|
20
|
+
const emailSchema = z.email().check(z.describe('The user email address.'))
|
|
20
21
|
|
|
21
22
|
const wrapError =
|
|
22
23
|
(name: string) =>
|
|
23
|
-
({
|
|
24
|
+
({ slug, message }: { message: string; slug: string }): MCPToolResponse => {
|
|
24
25
|
return {
|
|
25
26
|
content: [
|
|
26
27
|
{
|
|
27
28
|
type: 'text',
|
|
28
|
-
text: `❌ **Error in ${name}** on ${
|
|
29
|
+
text: `❌ **Error in ${name}** on ${slug}: ${message}`,
|
|
29
30
|
},
|
|
30
31
|
],
|
|
31
32
|
}
|
|
@@ -40,20 +41,41 @@ export const authCollectionTool = defineCollectionTool({
|
|
|
40
41
|
title: 'Check Auth Status',
|
|
41
42
|
},
|
|
42
43
|
description: 'Checks authentication status for the current user.',
|
|
43
|
-
input:
|
|
44
|
+
input: strictObject({
|
|
44
45
|
headers: z
|
|
45
|
-
.record(z.string(), z.string())
|
|
46
|
-
.describe('
|
|
47
|
-
.optional(),
|
|
46
|
+
.optional(z.record(z.string(), z.string()))
|
|
47
|
+
.check(z.describe('Custom headers to send with the authentication request.')),
|
|
48
48
|
}),
|
|
49
|
-
}).handler(async ({
|
|
49
|
+
}).handler(async ({ slug, authorizedMCP, input, req }) => {
|
|
50
50
|
const logger = getLogger({ payload: req.payload })
|
|
51
51
|
try {
|
|
52
52
|
let authHeaders = new Headers()
|
|
53
53
|
if (input.headers) {
|
|
54
54
|
authHeaders = new Headers(input.headers)
|
|
55
55
|
}
|
|
56
|
-
const
|
|
56
|
+
const authReq = await createPayloadRequest({
|
|
57
|
+
payload: req.payload,
|
|
58
|
+
req: { headers: authHeaders },
|
|
59
|
+
})
|
|
60
|
+
const result = await req.payload.auth({ headers: authHeaders, req: authReq })
|
|
61
|
+
|
|
62
|
+
if (result.user) {
|
|
63
|
+
const authenticatedUser = result.user
|
|
64
|
+
// Auth strategies read users with trusted Local API access. Re-read the user with the MCP
|
|
65
|
+
// caller's access level before returning it to the client.
|
|
66
|
+
const user = await req.payload.findByID({
|
|
67
|
+
id: authenticatedUser.id,
|
|
68
|
+
collection: authenticatedUser.collection,
|
|
69
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
70
|
+
req: authReq,
|
|
71
|
+
})
|
|
72
|
+
result.user = {
|
|
73
|
+
...user,
|
|
74
|
+
_sid: authenticatedUser._sid,
|
|
75
|
+
_strategy: authenticatedUser._strategy,
|
|
76
|
+
collection: authenticatedUser.collection,
|
|
77
|
+
}
|
|
78
|
+
}
|
|
57
79
|
return {
|
|
58
80
|
content: [
|
|
59
81
|
{
|
|
@@ -65,8 +87,8 @@ export const authCollectionTool = defineCollectionTool({
|
|
|
65
87
|
}
|
|
66
88
|
} catch (error) {
|
|
67
89
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
|
68
|
-
logger.error(`Error in auth tool on ${
|
|
69
|
-
return wrapError('auth')({
|
|
90
|
+
logger.error(`Error in auth tool on ${slug}: ${errorMessage}`)
|
|
91
|
+
return wrapError('auth')({ slug, message: errorMessage })
|
|
70
92
|
}
|
|
71
93
|
})
|
|
72
94
|
|
|
@@ -79,35 +101,31 @@ export const forgotPasswordCollectionTool = defineCollectionTool({
|
|
|
79
101
|
title: 'Forgot Password',
|
|
80
102
|
},
|
|
81
103
|
description: 'Sends a password reset email to a user.',
|
|
82
|
-
input:
|
|
83
|
-
disableEmail: z
|
|
84
|
-
.boolean()
|
|
85
|
-
.describe('Whether to disable sending the email (for testing)')
|
|
86
|
-
.optional()
|
|
87
|
-
.default(false),
|
|
104
|
+
input: strictObject({
|
|
88
105
|
email: emailSchema,
|
|
89
106
|
}),
|
|
90
|
-
}).handler(async ({
|
|
107
|
+
}).handler(async ({ slug, input, req }) => {
|
|
91
108
|
const logger = getLogger({ payload: req.payload })
|
|
92
109
|
try {
|
|
93
|
-
|
|
94
|
-
collection:
|
|
110
|
+
await req.payload.forgotPassword({
|
|
111
|
+
collection: slug,
|
|
95
112
|
data: { email: input.email },
|
|
96
|
-
disableEmail:
|
|
113
|
+
disableEmail: false,
|
|
114
|
+
overrideAccess: false,
|
|
115
|
+
req,
|
|
97
116
|
})
|
|
98
117
|
return {
|
|
99
118
|
content: [
|
|
100
119
|
{
|
|
101
120
|
type: 'text',
|
|
102
|
-
text:
|
|
121
|
+
text: 'If an account matches that email, password reset instructions have been sent.',
|
|
103
122
|
},
|
|
104
123
|
],
|
|
105
|
-
doc: { result } as Record<string, unknown>,
|
|
106
124
|
}
|
|
107
125
|
} catch (error) {
|
|
108
126
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
|
109
|
-
logger.error(`Error in forgotPassword tool on ${
|
|
110
|
-
return wrapError('forgotPassword')({
|
|
127
|
+
logger.error(`Error in forgotPassword tool on ${slug}: ${errorMessage}`)
|
|
128
|
+
return wrapError('forgotPassword')({ slug, message: errorMessage })
|
|
111
129
|
}
|
|
112
130
|
})
|
|
113
131
|
|
|
@@ -120,45 +138,35 @@ export const loginCollectionTool = defineCollectionTool({
|
|
|
120
138
|
title: 'User Login',
|
|
121
139
|
},
|
|
122
140
|
description: 'Authenticates a user with email and password.',
|
|
123
|
-
input:
|
|
141
|
+
input: strictObject({
|
|
124
142
|
depth: z
|
|
125
|
-
.
|
|
126
|
-
.
|
|
127
|
-
.min(0)
|
|
128
|
-
.max(10)
|
|
129
|
-
.describe('Depth of population for relationships')
|
|
130
|
-
.optional()
|
|
131
|
-
.default(0),
|
|
143
|
+
._default(z.int().check(z.minimum(0), z.maximum(10)), 0)
|
|
144
|
+
.check(z.describe('Depth of population for relationships.')),
|
|
132
145
|
email: emailSchema,
|
|
133
|
-
password: z.string().describe('The user password'),
|
|
134
|
-
showHiddenFields: z
|
|
135
|
-
.boolean()
|
|
136
|
-
.describe('Whether to show hidden fields in the response')
|
|
137
|
-
.optional()
|
|
138
|
-
.default(false),
|
|
146
|
+
password: z.string().check(z.describe('The user password.')),
|
|
139
147
|
}),
|
|
140
|
-
}).handler(async ({
|
|
148
|
+
}).handler(async ({ slug, authorizedMCP, input, req }) => {
|
|
141
149
|
const logger = getLogger({ payload: req.payload })
|
|
142
150
|
try {
|
|
143
151
|
const result = await req.payload.login({
|
|
144
|
-
collection:
|
|
152
|
+
collection: slug,
|
|
145
153
|
data: { email: input.email, password: input.password },
|
|
146
154
|
depth: input.depth,
|
|
147
|
-
|
|
155
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
148
156
|
})
|
|
149
157
|
return {
|
|
150
158
|
content: [
|
|
151
159
|
{
|
|
152
160
|
type: 'text',
|
|
153
|
-
text: `# Login Successful\n\n**User:** ${input.email}\n**Collection:** ${
|
|
161
|
+
text: `# Login Successful\n\n**User:** ${input.email}\n**Collection:** ${slug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
|
|
154
162
|
},
|
|
155
163
|
],
|
|
156
164
|
doc: result as unknown as Record<string, unknown>,
|
|
157
165
|
}
|
|
158
166
|
} catch (error) {
|
|
159
167
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
|
160
|
-
logger.error(`Error in login tool on ${
|
|
161
|
-
return wrapError('login')({
|
|
168
|
+
logger.error(`Error in login tool on ${slug}: ${errorMessage}`)
|
|
169
|
+
return wrapError('login')({ slug, message: errorMessage })
|
|
162
170
|
}
|
|
163
171
|
})
|
|
164
172
|
|
|
@@ -171,35 +179,37 @@ export const resetPasswordCollectionTool = defineCollectionTool({
|
|
|
171
179
|
title: 'Reset Password',
|
|
172
180
|
},
|
|
173
181
|
description: 'Resets a user password with a reset token.',
|
|
174
|
-
input:
|
|
175
|
-
password: z.string().describe('The new password for the user'),
|
|
176
|
-
token: z.string().describe('The password reset token sent to the user email'),
|
|
182
|
+
input: strictObject({
|
|
183
|
+
password: z.string().check(z.describe('The new password for the user.')),
|
|
184
|
+
token: z.string().check(z.describe('The password reset token sent to the user email.')),
|
|
177
185
|
}),
|
|
178
|
-
}).handler(async ({
|
|
186
|
+
}).handler(async ({ slug, authorizedMCP, input, req }) => {
|
|
179
187
|
const logger = getLogger({ payload: req.payload })
|
|
180
188
|
try {
|
|
181
189
|
const result = await req.payload.resetPassword({
|
|
182
|
-
collection:
|
|
190
|
+
collection: slug,
|
|
183
191
|
data: { password: input.password, token: input.token },
|
|
184
|
-
overrideAccess:
|
|
192
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
185
193
|
})
|
|
186
194
|
return {
|
|
187
195
|
content: [
|
|
188
196
|
{
|
|
189
197
|
type: 'text',
|
|
190
|
-
text: `# Password Reset Successful\n\n**Collection:** ${
|
|
198
|
+
text: `# Password Reset Successful\n\n**Collection:** ${slug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
|
|
191
199
|
},
|
|
192
200
|
],
|
|
193
201
|
doc: result as unknown as Record<string, unknown>,
|
|
194
202
|
}
|
|
195
203
|
} catch (error) {
|
|
196
204
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
|
197
|
-
logger.error(`Error in resetPassword tool on ${
|
|
198
|
-
return wrapError('resetPassword')({
|
|
205
|
+
logger.error(`Error in resetPassword tool on ${slug}: ${errorMessage}`)
|
|
206
|
+
return wrapError('resetPassword')({ slug, message: errorMessage })
|
|
199
207
|
}
|
|
200
208
|
})
|
|
201
209
|
|
|
202
210
|
export const unlockCollectionTool = defineCollectionTool({
|
|
211
|
+
access: (args) =>
|
|
212
|
+
defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.unlock),
|
|
203
213
|
annotations: {
|
|
204
214
|
destructiveHint: false,
|
|
205
215
|
idempotentHint: true,
|
|
@@ -208,28 +218,29 @@ export const unlockCollectionTool = defineCollectionTool({
|
|
|
208
218
|
title: 'Unlock Account',
|
|
209
219
|
},
|
|
210
220
|
description: 'Unlocks a user account that has been locked due to failed login attempts.',
|
|
211
|
-
input:
|
|
212
|
-
}).handler(async ({
|
|
221
|
+
input: strictObject({ email: emailSchema }),
|
|
222
|
+
}).handler(async ({ slug, authorizedMCP, input, req }) => {
|
|
213
223
|
const logger = getLogger({ payload: req.payload })
|
|
214
224
|
try {
|
|
215
225
|
const result = await req.payload.unlock({
|
|
216
|
-
collection:
|
|
226
|
+
collection: slug,
|
|
217
227
|
data: { email: input.email },
|
|
218
|
-
overrideAccess:
|
|
228
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
229
|
+
req,
|
|
219
230
|
})
|
|
220
231
|
return {
|
|
221
232
|
content: [
|
|
222
233
|
{
|
|
223
234
|
type: 'text',
|
|
224
|
-
text: `# Account Unlocked\n\n**Collection:** ${
|
|
235
|
+
text: `# Account Unlocked\n\n**Collection:** ${slug}\n**Email:** ${input.email}\n**Result:** ${result ? 'Success' : 'Failed'}`,
|
|
225
236
|
},
|
|
226
237
|
],
|
|
227
238
|
doc: { result } as Record<string, unknown>,
|
|
228
239
|
}
|
|
229
240
|
} catch (error) {
|
|
230
241
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
|
231
|
-
logger.error(`Error in unlock tool on ${
|
|
232
|
-
return wrapError('unlock')({
|
|
242
|
+
logger.error(`Error in unlock tool on ${slug}: ${errorMessage}`)
|
|
243
|
+
return wrapError('unlock')({ slug, message: errorMessage })
|
|
233
244
|
}
|
|
234
245
|
})
|
|
235
246
|
|
|
@@ -242,28 +253,28 @@ export const verifyCollectionTool = defineCollectionTool({
|
|
|
242
253
|
title: 'Email Verification',
|
|
243
254
|
},
|
|
244
255
|
description: 'Verifies a user email with a verification token.',
|
|
245
|
-
input:
|
|
246
|
-
token: z.string().describe('The verification token sent to the user email'),
|
|
256
|
+
input: strictObject({
|
|
257
|
+
token: z.string().check(z.describe('The verification token sent to the user email.')),
|
|
247
258
|
}),
|
|
248
|
-
}).handler(async ({
|
|
259
|
+
}).handler(async ({ slug, input, req }) => {
|
|
249
260
|
const logger = getLogger({ payload: req.payload })
|
|
250
261
|
try {
|
|
251
262
|
const result = await req.payload.verifyEmail({
|
|
252
|
-
collection:
|
|
263
|
+
collection: slug,
|
|
253
264
|
token: input.token,
|
|
254
265
|
})
|
|
255
266
|
return {
|
|
256
267
|
content: [
|
|
257
268
|
{
|
|
258
269
|
type: 'text',
|
|
259
|
-
text: `# Email Verification Successful\n\n**Collection:** ${
|
|
270
|
+
text: `# Email Verification Successful\n\n**Collection:** ${slug}\n**Result:** ${result ? 'Success' : 'Failed'}`,
|
|
260
271
|
},
|
|
261
272
|
],
|
|
262
273
|
doc: { result } as Record<string, unknown>,
|
|
263
274
|
}
|
|
264
275
|
} catch (error) {
|
|
265
276
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
|
266
|
-
logger.error(`Error in verify tool on ${
|
|
267
|
-
return wrapError('verify')({
|
|
277
|
+
logger.error(`Error in verify tool on ${slug}: ${errorMessage}`)
|
|
278
|
+
return wrapError('verify')({ slug, message: errorMessage })
|
|
268
279
|
}
|
|
269
280
|
})
|